qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
279,473
<p>currently I have the following code:</p> <pre><code>String select = qry.substring("select ".length(),qry2.indexOf(" from ")); String[] attrs = select.split(","); </code></pre> <p>which works for the most parts but fails if given the following:</p> <pre><code>qry = "select a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy') from tbl_a"; </code></pre> <p>what I'm looking for is the regex to feed to String.split() which will hande that situation, and for that matter any other special cases you might be able to think of that I'm missing.</p>
[ { "answer_id": 279499, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": true, "text": "[^,]+\\([^\\)]+\\)|[^,]+,\n a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff\n a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff,\n EXP(arg1, EXP2(ARG11,ARG22), ARG2)\n [^,]+\\([^\\)]+\\)|[^,]), attrs" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
279,475
<p>On a web page that is to be displayed on an iPhone, is there a way to get the number pad to come up when the user taps in the field, instead of the qwerty keypad? </p> <p><a href="http://www.bennadel.com/blog/1197-Defaulting-To-The-Numeric-Keyboard-On-The-iPhone.htm" rel="nofollow noreferrer">This guy says here's how to do it</a>, but as of 2.0, this "feature" was disabled. </p> <p>I'm guessing there's some fancy javascript to employ to get around this limitation? </p>
[ { "answer_id": 6951937, "author": "icktoofay", "author_id": 200291, "author_profile": "https://Stackoverflow.com/users/200291", "pm_score": 2, "selected": false, "text": "number text" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21447/" ]
279,478
<p>Given a model</p> <pre><code>class BaseModel &lt; ActiveRecord::Base validates_presence_of :parent_id before_save :frobnicate_widgets end </code></pre> <p>and a derived model (the underlying database table has a <code>type</code> field - this is simple rails STI)</p> <pre><code>class DerivedModel &lt; BaseModel end </code></pre> <p><code>DerivedModel</code> will in good OO fashion inherit all the behaviour from <code>BaseModel</code>, including the <code>validates_presence_of :parent_id</code>. I would like to turn the validation off for <code>DerivedModel</code>, and prevent the callback methods from firing, preferably without modifying or otherwise breaking <code>BaseModel</code></p> <p>What's the easiest and most robust way to do this?</p>
[ { "answer_id": 279584, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "before_validation_on_create before_save before_save.clear\n" }, { "answer_id": 279591, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": ":validate :validate_on_create :validate_on_update write_inheritable_attribute write_inheritable_attribute :validate, nil\n" }, { "answer_id": 692448, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "class Parent < ActiveRecord::Base\n validate_uniqueness_of :column_name, :if => :validate_uniqueness_of_column_name?\n def validate_uniqueness_of_column_name?\n true\n end\nend\n\nclass Child < Parent\n def validate_uniqueness_of_column_name?\n false\n end\nend\n" }, { "answer_id": 10208075, "author": "Chandresh Pant", "author_id": 713152, "author_profile": "https://Stackoverflow.com/users/713152", "pm_score": 3, "selected": false, "text": "class Parent < ActiveRecord::Base\n validate_uniqueness_of :column_name, :unless => :child?\n def child?\n is_a? Child\n end\nend\n\nclass Child < Parent\nend\n" }, { "answer_id": 14598740, "author": "hadees", "author_id": 325068, "author_profile": "https://Stackoverflow.com/users/325068", "pm_score": 0, "selected": false, "text": "class Parent\n include Mongoid::Document\n validates :column_name , uniqueness: true, unless: Proc.new {|r| r._type == \"Child\"}\nend\n\nclass Child < Parent\nend\n" }, { "answer_id": 28729135, "author": "phlegx", "author_id": 132235, "author_profile": "https://Stackoverflow.com/users/132235", "pm_score": 2, "selected": false, "text": "class Parent < ActiveRecord::Base\n validate :column_name, uniqueness: true, if: 'self.class == Parent'\nend\n\n\nclass Child < Parent\nend\n class Parent < ActiveRecord::Base\n validate :column_name, uniqueness: true, if: :check_base\n\n private\n\n def check_base\n self.class == Parent\n end\nend\n\n\nclass Child < Parent\nend\n Parent Child Child Parent Parent Parent Parent" }, { "answer_id": 46213250, "author": "ulferts", "author_id": 3206935, "author_profile": "https://Stackoverflow.com/users/3206935", "pm_score": 2, "selected": false, "text": "validators _validators class Child < Parent\n # add additional conditions if necessary\n _validators.reject! { |attribute, _| attribute == :parent_id } \nend\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
279,491
<p>I'm experiencing some problems with CSS and/or tables on my newly redesigned <a href="http://www.artinthepicture.com" rel="nofollow noreferrer">website</a>. Because of the well known "100% div height"-issue, I have resorted to using tables as a structural element of the website. So it looks something like this:</p> <p>HTML MARKUP:</p> <pre><code>&lt;div id="header"&gt;...&lt;/div&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;div id="main"&gt;...&lt;/div&gt;&lt;/td&gt; &lt;td class="crighttd"&gt;&lt;div id="cright"&gt;...&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div id="footer"&gt;...&lt;/div&gt; </code></pre> <p>AND CORRESPONDING CSS</p> <pre><code>table { border-top: 1px solid #6A6A6A; padding: 0; margin-top: 20px; border-spacing: 0 } td { vertical-align: top; padding:0; margin:0 } .crighttd { background: #4F4F4F; vertical-align:top; margin: 0 } #cright { width: 185px; float: right; background: #4F4F4F; height: 100%; line-height: 1.2em; margin: 0; padding: 25px 0 25px 20px; } </code></pre> <p>The issue here is that apparently the td on the right will not display at all in certain browsers (have seen this on Mac as well as on old instances of IE). Is this a CSS problem or something with the tables ?</p>
[ { "answer_id": 279517, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 0, "selected": false, "text": "border: 1px solid red;\n position: relative;\n" }, { "answer_id": 279518, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "html, body {\n height: 100%;\n}\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
279,493
<p>What is the way to avoid phpunit having to call the constructor for a mock object? Otherwise I would need a mock object as constructor argument, another one for that etc. The api seems to be like this:</p> <pre><code>getMock($className, $methods = array(), array $arguments = array(), $mockClassName = '', $callOriginalConstructor = TRUE, $callOriginalClone = TRUE, $callAutoload = TRUE) </code></pre> <p>I don't get it to work. It still complains about the constructor argument, even with <code>$callOriginalConstructor</code> set to false.</p> <p>I only have one object in the constructor and it is a dependency injection. So I don't think I have a design problem there.</p>
[ { "answer_id": 628308, "author": "Matthew Purdon", "author_id": 75873, "author_profile": "https://Stackoverflow.com/users/75873", "pm_score": 5, "selected": false, "text": " // Get a Mock Soap Client object to work with.\n $classToMock = 'SoapClient';\n $methodsToMock = array('__getFunctions');\n $mockConstructorParams = array('fake wsdl url', array());\n $mockClassName = 'MyMockSoapClient';\n $callMockConstructor = false;\n $mockSoapClient = $this->getMock($classToMock,\n $methodsToMock,\n $mockConstructorParams,\n $mockClassName,\n $callMockConstructor);\n" }, { "answer_id": 6277201, "author": "dave1010", "author_id": 315435, "author_profile": "https://Stackoverflow.com/users/315435", "pm_score": 7, "selected": false, "text": "getMockBuilder getMock $mock = $this->getMockBuilder('class_name')\n ->disableOriginalConstructor()\n ->getMock();\n" }, { "answer_id": 15285625, "author": "Steve Tauber", "author_id": 825364, "author_profile": "https://Stackoverflow.com/users/825364", "pm_score": 3, "selected": false, "text": "expects() disableOriginalConstructor() // Use a trick to create a new object of a class\n// without invoking its constructor.\n$object = unserialize(\nsprintf('O:%d:\"%s\":0:{}', strlen($className), $className)\n $mock = $this->getMockBuilder('class_name')\n ->disableOriginalConstructor()\n ->getMock();\n\n$mock->expect($this->once())\n ->method('functionCallFromConstructor')\n ->with($this->equalTo('someValue'));\n\n$reflectedClass = new ReflectionClass('class_name');\n$constructor = $reflectedClass->getConstructor();\n$constructor->invoke($mock);\n functionCallFromConstruct protected setMethods() $mock->setMethods(array('functionCallFromConstructor'));\n setMethods() expect() disableOriginalConstructor() getMock()" }, { "answer_id": 24859834, "author": "Hans Wouters", "author_id": 2581587, "author_profile": "https://Stackoverflow.com/users/2581587", "pm_score": 2, "selected": false, "text": "$mock = $this->getMock(class_name, methods = array(), args = array(), \n mockClassName = '', callOriginalConstructor = FALSE);\n" }, { "answer_id": 61595920, "author": "Wesley Gonçalves", "author_id": 8522818, "author_profile": "https://Stackoverflow.com/users/8522818", "pm_score": 3, "selected": false, "text": "createMock createTestDouble $mock = $this->createMock($className);\n PHPUnit\\Framework\\TestCase phpunit/src/framework/TestCase.php /** PHPUnit\\Framework\\TestCase::createMock method */\nprotected function createMock(string $originalClassName): MockObject\n{\n return $this->getMockBuilder($originalClassName)\n ->disableOriginalConstructor()\n ->disableOriginalClone()\n ->disableArgumentCloning()\n ->disallowMockingUnknownTypes()\n ->getMock();\n}\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
279,495
<p>This is a C# console application. I have a function that does something like this:</p> <pre><code>static void foo() { Application powerpointApp; Presentation presentation = null; powerpointApp = new Microsoft.Office.Interop.PowerPoint.ApplicationClass(); } </code></pre> <p>That's all it does. When it is called there is a fifteen second delay before the function gets hit. I added something like this:</p> <pre><code>static void MyAssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args) { Console.WriteLine(DateTime.Now.ToString() + " ASSEMBLY LOADED: " + args.LoadedAssembly.FullName); Console.WriteLine(); } </code></pre> <p>This gets fired telling me that my interop assemblies have been loaded about 10 milliseconds before my foo function gets hit. What can I do about this? The program needs to call this function (and eventually do something else) once and then exit so I need for these assemblies to be cached or something. Ideas?</p>
[ { "answer_id": 2505375, "author": "Anonymous Type", "author_id": 141720, "author_profile": "https://Stackoverflow.com/users/141720", "pm_score": 1, "selected": false, "text": "<runtime>\n\n <generatePublisherEvidence enabled=\"false\"/>\n\n</runtime>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12261/" ]
279,500
<p>I have a program that I need to run under *nix and windows. because the program takes file paths from files the issue is what to do about the <code>\</code> vs <code>/</code> issue. </p> <p>My current thought is to put in a regex that converts the wrong one to the right one depending on what system I'm on. This will have the effect of letting either type work on either system. Aside from the fact that <a href="http://fishbowl.pastiche.org/2003/08/18/beware_regular_expressions/" rel="nofollow noreferrer">now I have two problems</a>, does anyone see any other problems?</p> <p>(Other better solutions are more than welcome)</p> <p>Edit: the primary issue is getting windows paths to work on unix rather than the other way around.</p>
[ { "answer_id": 279511, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 1, "selected": false, "text": "LoadApplicationData(FileManager.GetDataFilePath)\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
279,507
<p>This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie. </p> <ol> <li>Can somebody clarify what is meant by <em>immutable</em>? </li> <li>Why is a <code>String</code> immutable?</li> <li>What are the advantages/disadvantages of the immutable objects?</li> <li>Why should a mutable object such as <code>StringBuilder</code> be preferred over String and vice-verse?</li> </ol> <p>A nice example (in Java) will be really appreciated.</p>
[ { "answer_id": 279515, "author": "eishay", "author_id": 16201, "author_profile": "https://Stackoverflow.com/users/16201", "pm_score": 2, "selected": false, "text": "String String s1 = \" abc \";\nString s2 = s1.trim();\n s2 s1" }, { "answer_id": 279516, "author": "Georgy Bolyuba", "author_id": 4052, "author_profile": "https://Stackoverflow.com/users/4052", "pm_score": 4, "selected": false, "text": "String foo = \"Hello\";\nfoo.substring(3);\n<-- foo here still has the same value \"Hello\"\n equals hashCode" }, { "answer_id": 279522, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 9, "selected": true, "text": "class Foo\n{\n private final String myvar;\n\n public Foo(final String initialValue)\n {\n this.myvar = initialValue;\n }\n\n public String getValue()\n {\n return this.myvar;\n }\n}\n Foo getValue() Foo StringBuilder String getValue() StringBuilder Foo" }, { "answer_id": 279537, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 5, "selected": false, "text": "public class ColoredString {\n\n private String color;\n private String string;\n\n public ColoredString(String color, String string) {\n this.color = color;\n this.string = string;\n }\n\n public String getColor() { return this.color; }\n public String getString() { return this.string; }\n\n public void setColor(String newColor) {\n this.color = newColor;\n }\n\n}\n new ColoredString(\"Blue\", \"This is a blue string!\");\n blueString.setColor(\"Red\");\n" }, { "answer_id": 1253519, "author": "Imagist", "author_id": 130640, "author_profile": "https://Stackoverflow.com/users/130640", "pm_score": 6, "selected": false, "text": "String substring = fullstring.substring(x,y);\n // Assume string is stored like this:\nstruct String { char* characters; unsigned int length; };\n\n// Passing pointers because Java is pass-by-reference\nstruct String* substring(struct String* in, unsigned int begin, unsigned int end)\n{\n struct String* out = malloc(sizeof(struct String));\n out->characters = in->characters + begin;\n out->length = end - begin;\n return out;\n}\n foo = foo.substring(0,4) + \"a\" + foo.substring(5); // foo is a String\nbar.replace(4,5,\"a\"); // bar is a StringBuilder\n struct String* concatenate(struct String* first, struct String* second)\n{\n struct String* new = malloc(sizeof(struct String));\n new->length = first->length + second->length;\n\n new->characters = malloc(new->length);\n \n int i;\n\n for(i = 0; i < first->length; i++)\n new->characters[i] = first->characters[i];\n\n for(; i - first->length < second->length; i++)\n new->characters[i] = second->characters[i - first->length];\n\n return new;\n}\n\n// The code that executes\nstruct String* astring;\nchar a = 'a';\nastring->characters = &a;\nastring->length = 1;\nfoo = concatenate(concatenate(slice(foo,0,4),astring),slice(foo,5,foo->length));\n bar bar->characters[4] = 'a';\n // This will have awful performance if you don't use mutable strings\nString join(String[] strings, String separator)\n{\n StringBuilder mutable;\n boolean first = true;\n\n for(int i = 0; i < strings.length; i++)\n {\n if(first) first = false;\n else mutable.append(separator);\n\n mutable.append(strings[i]);\n }\n\n return mutable.toString();\n}\n mutable" }, { "answer_id": 31493491, "author": "Shanaka Jayalath", "author_id": 5043154, "author_profile": "https://Stackoverflow.com/users/5043154", "pm_score": 5, "selected": false, "text": "//s1 variable, refers to string in memory\n reference | MEMORY |\n variables | |\n\n [s1] --------------->| \"Old String\" |\n //s2 refers to same string as s1\n | |\n [s1] --------------->| \"Old String\" |\n [s2] ------------------------^\n //s1 deletes reference to old string and points to the newly created one\n [s1] -----|--------->| \"New String\" |\n | | |\n |~~~~~~~~~X| \"Old String\" |\n [s2] ------------------------^\n" }, { "answer_id": 37776140, "author": "george", "author_id": 3793865, "author_profile": "https://Stackoverflow.com/users/3793865", "pm_score": 4, "selected": false, "text": "LocalDate date = LocalDate.of(2014, 3, 18); \ndate.plusYears(2);\nSystem.out.println(date);\n plusYears(2) plusYears LocalDate date = LocalDate.of(2014, 3, 18); \nLocalDate dateAfterTwoYears = date.plusYears(2);\n" }, { "answer_id": 43604612, "author": "Ayub", "author_id": 579381, "author_profile": "https://Stackoverflow.com/users/579381", "pm_score": 3, "selected": false, "text": "String s1=\"Hi\";\nString s2=s1;\ns1=\"Bye\";\n\nSystem.out.println(s2); //Hi (if String was mutable output would be: Bye)\nSystem.out.println(s1); //Bye\n s1=\"Hi\" s1 s2=s1 s2 s1=\"Bye\" s1 s1 s1 s2 s2 s1" }, { "answer_id": 51376068, "author": "Priyantha", "author_id": 7467246, "author_profile": "https://Stackoverflow.com/users/7467246", "pm_score": 2, "selected": false, "text": "class Testimmutablestring{ \n public static void main(String args[]){ \n String s=\"Future\"; \n s.concat(\" World\");//concat() method appends the string at the end \n System.out.println(s);//will print Future because strings are immutable objects \n } \n } \n Because String is immutable s String s=\"Future\"; \ns=s.concat(\" World\"); \nSystem.out.println(s);//print Future World\n" }, { "answer_id": 61648791, "author": "TooCool", "author_id": 3672184, "author_profile": "https://Stackoverflow.com/users/3672184", "pm_score": 1, "selected": false, "text": "String String s = \"\";\nfor (int i = 0; i < n; ++i) {\n s = s + n;\n}\n StringBuilder sb = new StringBuilder();\nfor (int i = 0; i < n; ++i) {\n sb.append(String.valueOf(n));\n}\nString s = sb.toString();\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33203/" ]
279,523
<p>I have written an installation class that extends Installer and overrides afterInstall, but I'm getting a null pointer exception. How can I go about debugging my class?</p>
[ { "answer_id": 280161, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 6, "selected": false, "text": "System.Diagnostics.Debugger.Break()\n" }, { "answer_id": 2702598, "author": "Timex", "author_id": 179333, "author_profile": "https://Stackoverflow.com/users/179333", "pm_score": 3, "selected": false, "text": "[TestClass] public class InstallerTest {\n[TestMethod]\npublic void InstallTest() {\n // substitute with your installer component here\n DataWarehouseInstall installer = new DataWarehouseInstall();\n\n string assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\n\n string installLogFilePath = Path.Combine(assemblyDirectory, \"install.log\");\n installer.Context = new System.Configuration.Install.InstallContext(installLogFilePath, null); \n\n // Refactor to set any parameters for your installer here\n installer.Context.Parameters.Add(\"Server\", \".\");\n //installer.Context.Parameters.Add(\"User\", \"\");\n //installer.Context.Parameters.Add(\"Password\", \"\");\n installer.Context.Parameters.Add(\"DatabaseName\", \"MyDatabaseInstallMsiTest\");\n //installer.Context.Parameters.Add(\"DatabasePath\", \"\");\n\n // Our test isn't injecting any save state so we give a default instance for the stateSaver\n installer.Install(new Hashtable());\n} }\n" }, { "answer_id": 3277186, "author": "Wayne Bloss", "author_id": 16387, "author_profile": "https://Stackoverflow.com/users/16387", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\n\nnamespace MyCompany.Deployment\n{\n /// <summary>\n /// Enables a quick and easy method of debugging custom actions.\n /// </summary>\n class LogFile\n {\n const string FileName = \"MyCompany.Deployment.log\";\n readonly string _filePath;\n\n public LogFile(string primaryOutputPath)\n {\n var dir = Path.GetDirectoryName(primaryOutputPath);\n _filePath = Path.Combine(dir, FileName);\n }\n\n public void Print(Exception ex)\n {\n File.AppendAllText(_filePath, \"Error: \" + ex.Message + Environment.NewLine +\n \"Stack Trace: \" + Environment.NewLine + ex.StackTrace + Environment.NewLine);\n }\n\n public void Print(string format, params object[] args)\n {\n var text = String.Format(format, args) + Environment.NewLine;\n\n File.AppendAllText(_filePath, text);\n }\n\n public void PrintLine() { Print(\"\"); }\n }\n}\n" }, { "answer_id": 5216966, "author": "Almund", "author_id": 479632, "author_profile": "https://Stackoverflow.com/users/479632", "pm_score": 1, "selected": false, "text": "Context.LogMessage(\"My message\");\n" }, { "answer_id": 15110940, "author": "Muhammad Mubashir", "author_id": 878106, "author_profile": "https://Stackoverflow.com/users/878106", "pm_score": 2, "selected": false, "text": "public override void Install(System.Collections.IDictionary stateSaver)\n{\n Debugger.Launch();\n base.Install(stateSaver);\n\n}\n" }, { "answer_id": 15598697, "author": "Adith", "author_id": 2196739, "author_profile": "https://Stackoverflow.com/users/2196739", "pm_score": 1, "selected": false, "text": "#if DEBUG\nMessageBox.Show(Process.GetCurrentProcess().Id.ToString());\n#endif\n" }, { "answer_id": 27704181, "author": "Peter", "author_id": 1123360, "author_profile": "https://Stackoverflow.com/users/1123360", "pm_score": 0, "selected": false, "text": "<PropertyGroup Condition=\"'$(Configuration)' == 'Debug'\">\n <StartAction>Program</StartAction>\n <StartProgram>$(MSBuildBinPath)\\installutil.exe</StartProgram>\n <StartArguments>$(AssemblyName).dll</StartArguments>\n</PropertyGroup>\n" }, { "answer_id": 31651133, "author": "Sriwantha Attanayake", "author_id": 215336, "author_profile": "https://Stackoverflow.com/users/215336", "pm_score": 2, "selected": false, "text": "using System.Diagnostics;\n\nMessageBox.Show(\"Test is about to begin\");\nDebugger.Launch();\n" }, { "answer_id": 45438534, "author": "Ahmed Sabry", "author_id": 4707576, "author_profile": "https://Stackoverflow.com/users/4707576", "pm_score": 2, "selected": false, "text": "System.Diagnostics.Debugger.Launch();\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16684/" ]
279,524
<p>I have a class that maintans a reference to a Hashtable and serializes/deserializes that Hashtable. After the call to SerializationInfo.GetValue, the Hashtable is not fully deserialized because the deserialization happens during the IDeserialization calback.</p> <pre><code>Hashtable hashtable = (Hashtable) info.GetValue("hash", typeof(Hashtable)); </code></pre> <p>I also implemented the IDeserialization callback in the parent class, but there too the Hashtable is not fully deserialized yet. I expected it to be if the deserialization is happening from the inside out.</p> <p>My question is, is it safe to explicitely call Hashtable.OnDeserialization from the OnDeserialization method of my parent class, so that I can enumerate it at that point?</p> <pre><code>public virtual void OnDeserialization(object sender) { hashtable.OnDeserialization(sender); } </code></pre>
[ { "answer_id": 287887, "author": "Brian Adams", "author_id": 32992, "author_profile": "https://Stackoverflow.com/users/32992", "pm_score": 2, "selected": false, "text": "public BoringClass(SerializationInfo info, StreamingContext context)\n{\n Hashtable hashtable = (Hashtable) info.GetValue(\"hash\", typeof(Hashtable));\n hashtable.OnDeserialization(this);\n\n Console.WriteLine(\"Value is: \" + hashtable[\"testItem\"]);\n\n}\n" }, { "answer_id": 301444, "author": "Gaspar Nagy", "author_id": 26530, "author_profile": "https://Stackoverflow.com/users/26530", "pm_score": 4, "selected": true, "text": "Class1: [OnDeserializing]\nClass2: [OnDeserializing]\nClass2: [OnDeserialized]\nClass1: [OnDeserialized]\nClass1: IDeserializationCallback.OnDeserialization\nClass2: IDeserializationCallback.OnDeserialization\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36373/" ]
279,534
<p>Once a programmer decides to implement <code>IXmlSerializable</code>, what are the rules and best practices for implementing it? I've heard that <code>GetSchema()</code> should return <code>null</code> and <code>ReadXml</code> should move to the next element before returning. Is this true? And what about <code>WriteXml</code> - should it write a root element for the object or is it assumed that the root is already written? How should child objects be treated and written?</p> <p>Here's a sample of what I have now. I'll update it as I get good responses.</p> <pre><code>public class MyCalendar : IXmlSerializable { private string _name; private bool _enabled; private Color _color; private List&lt;MyEvent&gt; _events = new List&lt;MyEvent&gt;(); public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element &amp;&amp; reader.LocalName == "MyCalendar") { _name = reader["Name"]; _enabled = Boolean.Parse(reader["Enabled"]); _color = Color.FromArgb(Int32.Parse(reader["Color"])); if (reader.ReadToDescendant("MyEvent")) { while (reader.MoveToContent() == XmlNodeType.Element &amp;&amp; reader.LocalName == "MyEvent") { MyEvent evt = new MyEvent(); evt.ReadXml(reader); _events.Add(evt); } } reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Name", _name); writer.WriteAttributeString("Enabled", _enabled.ToString()); writer.WriteAttributeString("Color", _color.ToArgb().ToString()); foreach (MyEvent evt in _events) { writer.WriteStartElement("MyEvent"); evt.WriteXml(writer); writer.WriteEndElement(); } } } public class MyEvent : IXmlSerializable { private string _title; private DateTime _start; private DateTime _stop; public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element &amp;&amp; reader.LocalName == "MyEvent") { _title = reader["Title"]; _start = DateTime.FromBinary(Int64.Parse(reader["Start"])); _stop = DateTime.FromBinary(Int64.Parse(reader["Stop"])); reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Title", _title); writer.WriteAttributeString("Start", _start.ToBinary().ToString()); writer.WriteAttributeString("Stop", _stop.ToBinary().ToString()); } } </code></pre> <p>Corresponding Sample XML</p> <pre><code>&lt;MyCalendar Name="Master Plan" Enabled="True" Color="-14069085"&gt; &lt;MyEvent Title="Write Code" Start="-8589241828854775808" Stop="-8589241756854775808" /&gt; &lt;MyEvent Title="???" Start="-8589241828854775808" Stop="-8589241756854775808" /&gt; &lt;MyEvent Title="Profit!" Start="-8589247048854775808" Stop="-8589246976854775808" /&gt; &lt;/MyCalendar&gt; </code></pre>
[ { "answer_id": 280077, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "Read()" }, { "answer_id": 2665097, "author": "EMP", "author_id": 20336, "author_profile": "https://Stackoverflow.com/users/20336", "pm_score": 3, "selected": false, "text": "IXmlSerializable WriteOuterXml() WriteXml() ReadContentXml()" }, { "answer_id": 22806275, "author": "Thijs Dalhuijsen", "author_id": 2250352, "author_profile": "https://Stackoverflow.com/users/2250352", "pm_score": 2, "selected": false, "text": "class ExampleBaseClass : IXmlSerializable { \n public XmlDocument xmlDocument { get; set; }\n public XmlSchema GetSchema()\n {\n return null;\n }\n public void ReadXml(XmlReader reader)\n {\n xmlDocument.Load(reader);\n }\n\n public void WriteXml(XmlWriter writer)\n {\n xmlDocument.WriteTo(writer);\n }\n}\n" }, { "answer_id": 61872634, "author": "VoteCoffee", "author_id": 848419, "author_profile": "https://Stackoverflow.com/users/848419", "pm_score": 2, "selected": false, "text": "using System.Collections.Generic;\n\n[System.Xml.Serialization.XmlRoot(\"dictionary\")]\npublic partial class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, System.Xml.Serialization.IXmlSerializable\n{\n public virtual System.Xml.Schema.XmlSchema GetSchema()\n {\n return null;\n }\n\n public virtual void ReadXml(System.Xml.XmlReader reader)\n {\n var keySerializer = new System.Xml.Serialization.XmlSerializer(typeof(TKey));\n var valueSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TValue));\n bool wasEmpty = reader.IsEmptyElement;\n reader.Read();\n if (wasEmpty)\n return;\n while (reader.NodeType != System.Xml.XmlNodeType.EndElement)\n {\n reader.ReadStartElement(\"item\");\n reader.ReadStartElement(\"key\");\n TKey key = (TKey)keySerializer.Deserialize(reader);\n reader.ReadEndElement();\n reader.ReadStartElement(\"value\");\n TValue value = (TValue)valueSerializer.Deserialize(reader);\n reader.ReadEndElement();\n Add(key, value);\n reader.ReadEndElement();\n reader.MoveToContent();\n }\n\n reader.ReadEndElement();\n }\n\n public virtual void WriteXml(System.Xml.XmlWriter writer)\n {\n var keySerializer = new System.Xml.Serialization.XmlSerializer(typeof(TKey));\n var valueSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TValue));\n foreach (TKey key in Keys)\n {\n writer.WriteStartElement(\"item\");\n writer.WriteStartElement(\"key\");\n keySerializer.Serialize(writer, key);\n writer.WriteEndElement();\n writer.WriteStartElement(\"value\");\n var value = this[key];\n valueSerializer.Serialize(writer, value);\n writer.WriteEndElement();\n writer.WriteEndElement();\n }\n }\n\n public SerializableDictionary() : base()\n {\n }\n\n public SerializableDictionary(IDictionary<TKey, TValue> dictionary) : base(dictionary)\n {\n }\n\n public SerializableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : base(dictionary, comparer)\n {\n }\n\n public SerializableDictionary(IEqualityComparer<TKey> comparer) : base(comparer)\n {\n }\n\n public SerializableDictionary(int capacity) : base(capacity)\n {\n }\n\n public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer) : base(capacity, comparer)\n {\n }\n\n}\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12971/" ]
279,546
<p>How could you calculate the minimum width needed to display a string in X lines, given that text should break on whitespace?</p>
[ { "answer_id": 279654, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 0, "selected": false, "text": "public SizeF CalculateWidth(Font font, Graphics graphics, int numOfLines,\n string text)\n{\n SizeF sizeFull = graphics.MeasureString(text, font,\n new SizeF(\n float.PositiveInfinity,\n float.PositiveInfinity),\n StringFormat.\n GenericTypographic);\n\n float width = sizeFull.Width/numOfLines;\n float averageWidth = sizeFull.Width/text.Length;\n int charsFitted;\n int linesFilled;\n\n SizeF needed = graphics.MeasureString(text, font,\n new SizeF(width,\n float.\n PositiveInfinity),\n StringFormat.\n GenericTypographic,\n out charsFitted,\n out linesFilled);\n\n while (linesFilled > numOfLines)\n {\n width += averageWidth;\n needed = graphics.MeasureString(text, font,\n new SizeF(width,\n float.PositiveInfinity),\n StringFormat.GenericTypographic,\n out charsFitted, out linesFilled);\n }\n\n return needed;\n}\n Font font = new Font(\"Arial\", 12, FontStyle.Regular,\n GraphicsUnit.Pixel);\nGraphics g = Graphics.FromImage(new Bitmap(1, 1));\nstring text = \"Some random text with words in it.\";\n\nSizeF size = CalculateWidth(font, g, 3, text);\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
279,552
<p>I am using the Ajax Control Toolkit Calendar Extender control. In some fields though I want to display the time along with the date. I have tried just setting the Format to "dd/MM/yyyy hh:mm:ss" but the time section gets wiped off. If the user wants to change the time section they can do it manually, the calendar drop down is only used for changing the date part. </p> <p>Are there any workarounds or alternatives to get this working? </p>
[ { "answer_id": 18371967, "author": "Rajkumar", "author_id": 2705954, "author_profile": "https://Stackoverflow.com/users/2705954", "pm_score": 1, "selected": false, "text": " function dateselect(ev)\n {\n var calendarBehavior1 = $find(\"Calendar1\");\n var d = calendarBehavior1._selectedDate;\n var now = new Date();\n calendarBehavior1.get_element().value = d.format(\"MM/dd/yyyy\") + \" \"+now.format(\"HH:mm:ss\")\n }\n" }, { "answer_id": 36353615, "author": "anandd360", "author_id": 4575768, "author_profile": "https://Stackoverflow.com/users/4575768", "pm_score": 0, "selected": false, "text": "<ajaxToolkit:CalendarExtender ID=\"ce1\" runat=\"server\" PopupButtonID=\"calImg\" Enabled=\"true\" Format=\"dd/MM/yyyy\" TargetControlID=\"txtLeft\" PopupPosition=\"TopRight\" OnClientDateSelectionChanged=\"AppendTime\"></ajaxToolkit:CalendarExtender>\n <script language=\"javascript\" type=\"text/javascript\">\n //this script will get the date selected from the given calendarextender (ie: \"sender\") and append the\n //current time to it.\n function AppendTime(sender, args) {\n var selectedDate = new Date();\n selectedDate = sender.get_selectedDate();\n var now = new Date();\n sender.get_element().value = selectedDate.format(\"dd/MM/yyyy\") + \" \" + now.format(\"hh:mm tt\");\n }\n </script>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27294/" ]
279,557
<p>WPF GridSplitter makes my Grid wider than my Window!</p> <p>I've got a WPF Grid with a GridSplitter. If I resize my columns, then I can make my grid wider than my window and non-viewable.</p> <p>It starts like this: </p> <p><a href="http://img201.imageshack.us/img201/9505/onehg6.jpg" rel="nofollow noreferrer">WPF Grid http://img201.imageshack.us/img201/9505/onehg6.jpg</a></p> <p>But after widening the left column, I can no longer see the right column (green): </p> <p><a href="http://img201.imageshack.us/img201/1804/twomy6.jpg" rel="nofollow noreferrer">WPF GridSplitter http://img201.imageshack.us/img201/1804/twomy6.jpg</a></p> <p>What am I doing wrong? How do I keep the GridSplitter from changing the size of my Grid?</p> <hr> <p>Update:</p> <p>I'm still struggling with this. I've now tried nesting grids within grids. That didn't help. Here's my XAML ColumnDefinitions, RowDefinitions, and GridSplitters...</p> <pre><code>&lt;Window ... &gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*" MinWidth="150" /&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;ColumnDefinition Width="*" MinWidth="400" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;GridSplitter ResizeDirection="Columns" ResizeBehavior="BasedOnAlignment" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="2" Margin="0,5,0,5" Panel.ZIndex="1"/&gt; &lt;Grid Grid.Column="0"&gt; ... &lt;/Grid&gt; &lt;Grid Grid.Column="2"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*" MinWidth="150" /&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;ColumnDefinition Width="*" MinWidth="200" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;GridSplitter ResizeDirection="Columns" ResizeBehavior="PreviousAndNext" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="2" Margin="0,5,0,5" Panel.ZIndex="1"/&gt; &lt;Grid Grid.Column="0"&gt; ... &lt;/Grid&gt; &lt;Grid Grid.Column="2"&gt; ... &lt;/Grid&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <hr> <p>Update:</p> <p>I think the problem is with the WebBrowser control. See new question:</p> <p><a href="https://stackoverflow.com/questions/375841/wpf-gridsplitter-doesnt-work-with-webbrowser-control">WPF GridSplitter Doesn't Work With WebBrowser Control?</a></p>
[ { "answer_id": 281317, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 3, "selected": false, "text": "<Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"2*\" MinWidth=\"100\" />\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition Width=\"*\" MinWidth=\"50\" />\n <ColumnDefinition Width=\"2*\" MinWidth=\"100\" />\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition Width=\"3*\" MinWidth=\"150\" />\n </Grid.ColumnDefinitions>\n <GridSplitter \n ResizeDirection=\"Columns\"\n Grid.Column=\"1\"\n Grid.RowSpan=\"8\"\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Stretch\"\n Width=\"2\"\n Margin=\"0,5,0,5\"\n Panel.ZIndex=\"1\"/>\n ...\n</Grid>\n" }, { "answer_id": 375754, "author": "Robert Macnee", "author_id": 19273, "author_profile": "https://Stackoverflow.com/users/19273", "pm_score": 3, "selected": true, "text": "<Window xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:sys=\"clr-namespace:System;assembly=mscorlib\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition MinWidth=\"150\" Width=\"*\"/>\n <ColumnDefinition Width=\"Auto\"/>\n <ColumnDefinition MinWidth=\"400\" Width=\"*\"/>\n </Grid.ColumnDefinitions>\n <GridSplitter\n Width=\"2\"\n Grid.Column=\"1\"\n HorizontalAlignment=\"Center\"\n Margin=\"0,5,0,5\"\n Panel.ZIndex=\"1\"\n VerticalAlignment=\"Stretch\"\n ResizeBehavior=\"BasedOnAlignment\"\n ResizeDirection=\"Columns\"/>\n <Grid Grid.Column=\"0\">\n <Border Background=\"Red\" Margin=\"5\"/>\n </Grid>\n <Grid Grid.Column=\"2\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition MinWidth=\"150\" Width=\"*\"/>\n <ColumnDefinition Width=\"Auto\"/>\n <ColumnDefinition MinWidth=\"200\" Width=\"*\"/>\n </Grid.ColumnDefinitions>\n <GridSplitter\n Width=\"2\"\n Grid.Column=\"1\"\n HorizontalAlignment=\"Center\"\n Margin=\"0,5,0,5\"\n Panel.ZIndex=\"1\"\n VerticalAlignment=\"Stretch\"\n ResizeBehavior=\"PreviousAndNext\"\n ResizeDirection=\"Columns\"/>\n <Grid Grid.Column=\"0\">\n <Border Background=\"Green\" Margin=\"5\"/>\n </Grid>\n <Grid Grid.Column=\"2\">\n <Border Background=\"Blue\" Margin=\"5\"/>\n </Grid>\n </Grid>\n </Grid>\n</Window>\n" }, { "answer_id": 4225454, "author": "Nestor", "author_id": 122732, "author_profile": "https://Stackoverflow.com/users/122732", "pm_score": 2, "selected": false, "text": " private void VerticalGridSplitter_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)\n {\n if (GridName.ColumnDefinitions[2].Width.Value < 400)\n {\n GridName.ColumnDefinitions[2].Width = new GridLength(400);\n }\n }\n" }, { "answer_id": 9885851, "author": "user958933", "author_id": 958933, "author_profile": "https://Stackoverflow.com/users/958933", "pm_score": 2, "selected": false, "text": "<Grid >\n<Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"20*\" MinWidth=\"50\" MaxWidth=\"500\" />\n <ColumnDefinition Width=\"Auto\"/> <!-- Remove such columns /-->\n <ColumnDefinition Width=\"100*\" MinWidth=\"850\"/>\n <ColumnDefinition Width=\"30*\" MinWidth=\"50\" MaxWidth=\"800\" />\n</Grid.ColumnDefinitions>\n...\n<GridSplitter HorizontalAlignment=\"Right\" Width=\"3\"/>\n...\n<GridSplitter Grid.Column=\"3\" HorizontalAlignment=\"Left\" Width=\"3\" />\n<!-- Assign Grid.Column to 2 if you remove the auto width column /-->\n...\n</Grid>\n" }, { "answer_id": 58877141, "author": "Jan Willem B", "author_id": 167266, "author_profile": "https://Stackoverflow.com/users/167266", "pm_score": 1, "selected": false, "text": "Grid * *" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
279,561
<p>What is the idiomatic Python equivalent of this C/C++ code?</p> <pre class="lang-cpp prettyprint-override"><code>void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } </code></pre> <p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
[ { "answer_id": 279568, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 4, "selected": false, "text": "def foo_gen():\n n = 0\n while True:\n n+=1\n yield n\n foo = foo_gen().next\nfor i in range(0,10):\n print foo()\n def foo_gen(limit=100000):\n n = 0\n while n < limit:\n n+=1\n yield n\n for i in foo_gen(20):\n print i\n" }, { "answer_id": 279586, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 11, "selected": true, "text": "def foo():\n foo.counter += 1\n print \"Counter is %d\" % foo.counter\nfoo.counter = 0\n def static_vars(**kwargs):\n def decorate(func):\n for k in kwargs:\n setattr(func, k, kwargs[k])\n return func\n return decorate\n @static_vars(counter=0)\ndef foo():\n foo.counter += 1\n print \"Counter is %d\" % foo.counter\n foo." }, { "answer_id": 279592, "author": "Jeremy", "author_id": 1114, "author_profile": "https://Stackoverflow.com/users/1114", "pm_score": 6, "selected": false, "text": ">>> def foo(counter=[0]):\n... counter[0] += 1\n... print(\"Counter is %i.\" % counter[0]);\n... \n>>> foo()\nCounter is 1.\n>>> foo()\nCounter is 2.\n>>> \n" }, { "answer_id": 279597, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 8, "selected": false, "text": "def myfunc():\n myfunc.counter += 1\n print myfunc.counter\n\n# attribute must be initialized\nmyfunc.counter = 0\n hasattr() AttributeError def myfunc():\n if not hasattr(myfunc, \"counter\"):\n myfunc.counter = 0 # it doesn't exist yet, so initialize it\n myfunc.counter += 1\n" }, { "answer_id": 279598, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 5, "selected": false, "text": "class Foo(object):\n # Class variable, shared by all instances of this class\n counter = 0\n\n def __call__(self):\n Foo.counter += 1\n print Foo.counter\n\n# Create an object instance of class \"Foo,\" called \"foo\"\nfoo = Foo()\n\n# Make calls to the \"__call__\" method, via the object's name itself\nfoo() #prints 1\nfoo() #prints 2\nfoo() #prints 3\n __call__ foo() __call__ __call__()" }, { "answer_id": 10941940, "author": "spenthil", "author_id": 158897, "author_profile": "https://Stackoverflow.com/users/158897", "pm_score": 1, "selected": false, "text": "def staticize(name, factory):\n \"\"\"Makes a pseudo-static variable in calling function.\n\n If name `name` exists in calling function, return it. \n Otherwise, saves return value of `factory()` in \n name `name` of calling function and return it.\n\n :param name: name to use to store static object \n in calling function\n :type name: String\n :param factory: used to initialize name `name` \n in calling function\n :type factory: function\n :rtype: `type(factory())`\n\n >>> def steveholt(z):\n ... a = staticize('a', list)\n ... a.append(z)\n >>> steveholt.a\n Traceback (most recent call last):\n ...\n AttributeError: 'function' object has no attribute 'a'\n >>> steveholt(1)\n >>> steveholt.a\n [1]\n >>> steveholt('a')\n >>> steveholt.a\n [1, 'a']\n >>> steveholt.a = []\n >>> steveholt.a\n []\n >>> steveholt('zzz')\n >>> steveholt.a\n ['zzz']\n\n \"\"\"\n from inspect import stack\n # get scope enclosing calling function\n calling_fn_scope = stack()[2][0]\n # get calling function\n calling_fn_name = stack()[1][3]\n calling_fn = calling_fn_scope.f_locals[calling_fn_name]\n if not hasattr(calling_fn, name):\n setattr(calling_fn, name, factory())\n return getattr(calling_fn, name)\n" }, { "answer_id": 12270415, "author": "Riaz Rizvi", "author_id": 213307, "author_profile": "https://Stackoverflow.com/users/213307", "pm_score": 5, "selected": false, "text": "def fn():\n fn.counter=vars(fn).setdefault('counter',-1)\n fn.counter+=1\n print (fn.counter)\n __dict__ vars() __dict__ try:except AttributeError try:except AttributeError def Fibonacci(n):\n if n<2: return n\n Fibonacci.memo=vars(Fibonacci).setdefault('memo',{}) # use static variable to hold a results cache\n return Fibonacci.memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2)) # lookup result in cache, if not available then calculate and store it\n nonlocal def TheOnlyPlaceStaticFunctionIsCalled():\n memo={}\n def Fibonacci(n):\n nonlocal memo # required in Python3. Python2 can see memo\n if n<2: return n\n return memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2))\n ...\n print (Fibonacci(200))\n ...\n" }, { "answer_id": 16214510, "author": "rav", "author_id": 1661491, "author_profile": "https://Stackoverflow.com/users/1661491", "pm_score": 8, "selected": false, "text": "def foo():\n try:\n foo.counter += 1\n except AttributeError:\n foo.counter = 1\n if" }, { "answer_id": 19125990, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "@static_var2('seed',0)\ndef funccounter(statics, add=1):\n statics.seed += add\n return statics.seed\n\nprint funccounter() #1\nprint funccounter(add=2) #3\nprint funccounter() #4\n\nclass ACircle(object):\n @static_var2('seed',0)\n def counter(statics, self, add=1):\n statics.seed += add\n return statics.seed\n\nc = ACircle()\nprint c.counter() #1\nprint c.counter(add=2) #3\nprint c.counter() #4\nd = ACircle()\nprint d.counter() #5\nprint d.counter(add=2) #7\nprint d.counter() #8    \n class StaticMan(object):\n def __init__(self):\n self.__dict__['_d'] = {}\n\n def __getattr__(self, name):\n return self.__dict__['_d'][name]\n def __getitem__(self, name):\n return self.__dict__['_d'][name]\n def __setattr__(self, name, val):\n self.__dict__['_d'][name] = val\n def __setitem__(self, name, val):\n self.__dict__['_d'][name] = val\n\ndef static_var2(name, val):\n def decorator(original):\n if not hasattr(original, ':staticman'): \n def wrapped(*args, **kwargs):\n return original(getattr(wrapped, ':staticman'), *args, **kwargs)\n setattr(wrapped, ':staticman', StaticMan())\n f = wrapped\n else:\n f = original #already wrapped\n\n getattr(f, ':staticman')[name] = val\n return f\n return decorator\n" }, { "answer_id": 27783657, "author": "Jonathan", "author_id": 448460, "author_profile": "https://Stackoverflow.com/users/448460", "pm_score": 6, "selected": false, "text": "def func():\n func.counter = getattr(func, 'counter', 0) + 1\n" }, { "answer_id": 27914651, "author": "wannik", "author_id": 639616, "author_profile": "https://Stackoverflow.com/users/639616", "pm_score": 2, "selected": false, "text": "class Count:\n def foo(self):\n try: \n self.foo.__func__.counter += 1\n except AttributeError: \n self.foo.__func__.counter = 1\n\n print self.foo.__func__.counter\n\nm = Count()\nm.foo() # 1\nm.foo() # 2\nm.foo() # 3\n" }, { "answer_id": 28401932, "author": "Giorgian Borca-Tasciuc", "author_id": 4459923, "author_profile": "https://Stackoverflow.com/users/4459923", "pm_score": 3, "selected": false, "text": "def staticvariables(**variables):\n def decorate(function):\n for variable in variables:\n setattr(function, variable, variables[variable])\n return function\n return decorate\n\n@staticvariables(counter=0, bar=1)\ndef foo():\n print(foo.counter)\n print(foo.bar)\n" }, { "answer_id": 31784304, "author": "kdb", "author_id": 2075630, "author_profile": "https://Stackoverflow.com/users/2075630", "pm_score": 4, "selected": false, "text": "nonlocal def make_counter():\n i = 0\n def counter():\n nonlocal i\n i = i + 1\n return i\n return counter\ncounter = make_counter()\n def counter(*, _i=[0]):\n _i[0] += 1\n return _i[0]\n def counter(*, _i = Mutable(0)):\n _i.value += 1\n return _i.value\n" }, { "answer_id": 34023168, "author": "lost", "author_id": 916373, "author_profile": "https://Stackoverflow.com/users/916373", "pm_score": 2, "selected": false, "text": "class foo(object):\n counter = 0;\n @staticmethod\n def __call__():\n foo.counter += 1\n print \"counter is %i\" % foo.counter\n >>> foo()()\ncounter is 1\n>>> foo()()\ncounter is 2\n" }, { "answer_id": 35020271, "author": "Keji Li", "author_id": 5112950, "author_profile": "https://Stackoverflow.com/users/5112950", "pm_score": -1, "selected": false, "text": "isInt_try: 0.3690\nisInt_str: 0.3981\nisInt_re: 0.5870\nisInt_re2: 0.3632\n" }, { "answer_id": 38712809, "author": "warvariuc", "author_id": 248296, "author_profile": "https://Stackoverflow.com/users/248296", "pm_score": 3, "selected": false, "text": ">>> def func(_static={'counter': 0}):\n... _static['counter'] += 1\n... print _static['counter']\n...\n>>> func()\n1\n>>> func()\n2\n>>>\n" }, { "answer_id": 46942953, "author": "IdleCustard", "author_id": 8827807, "author_profile": "https://Stackoverflow.com/users/8827807", "pm_score": 2, "selected": false, "text": "operator() int x = square(5); square operator() # C++ function object\nclass Foo_class {\n private:\n int counter; \n public:\n Foo_class() {\n counter = 0;\n }\n void operator() () { \n counter++;\n printf(\"counter is %d\\n\", counter);\n } \n };\n Foo_class foo;\n operator() __call__ class Foo_class:\n def __init__(self): # __init__ is similair to a C++ class constructor\n self.counter = 0\n # self.counter is like a static member\n # variable of a function named \"foo\"\n def __call__(self): # overload operator()\n self.counter += 1\n print(\"counter is %d\" % self.counter);\nfoo = Foo_class() # call the constructor\n from foo import foo\n\nfor i in range(0, 5):\n foo() # function call\n counter is 1\ncounter is 2\ncounter is 3\ncounter is 4\ncounter is 5\n __call__ # FILE: foo.py - - - - - - - - - - - - - - - - - - - - - - - - -\n\nclass Foo_class:\n def __init__(self):\n self.counter = 0\n def __call__(self, x, y, z): # overload operator()\n self.counter += 1\n print(\"counter is %d\" % self.counter);\n print(\"x, y, z, are %d, %d, %d\" % (x, y, z));\nfoo = Foo_class() # call the constructor\n\n# FILE: main.py - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\nfrom foo import foo\n\nfor i in range(0, 5):\n foo(7, 8, 9) # function call\n\n# Console Output - - - - - - - - - - - - - - - - - - - - - - - - - - \n\ncounter is 1\nx, y, z, are 7, 8, 9\ncounter is 2\nx, y, z, are 7, 8, 9\ncounter is 3\nx, y, z, are 7, 8, 9\ncounter is 4\nx, y, z, are 7, 8, 9\ncounter is 5\nx, y, z, are 7, 8, 9\n" }, { "answer_id": 49347152, "author": "Pascal T.", "author_id": 19816, "author_profile": "https://Stackoverflow.com/users/19816", "pm_score": 2, "selected": false, "text": "print(statics.foo)\n print(my_function_name.foo)\n statics statics my_function.statics from bunch import *\n\ndef static_vars(**kwargs):\n def decorate(func):\n statics = Bunch(**kwargs)\n setattr(func, \"statics\", statics)\n return func\n return decorate\n\n@static_vars(name = \"Martin\")\ndef my_function():\n statics = my_function.statics\n print(\"Hello, {0}\".format(statics.name))\n Bunch pip install bunch class Bunch(dict):\n def __init__(self, **kw):\n dict.__init__(self,kw)\n self.__dict__ = self\n" }, { "answer_id": 49501693, "author": "Feca", "author_id": 9548882, "author_profile": "https://Stackoverflow.com/users/9548882", "pm_score": 2, "selected": false, "text": "def foo():\n foo.__dict__.setdefault('count', 0)\n foo.count += 1\n return foo.count\n" }, { "answer_id": 49719596, "author": "cbarrick", "author_id": 1078465, "author_profile": "https://Stackoverflow.com/users/1078465", "pm_score": 4, "selected": false, "text": "nonlocal counter = 0\ndef foo():\n nonlocal counter\n counter += 1\n print(f'counter is {counter}')\n nonlocal _counter" }, { "answer_id": 51437838, "author": "VPfB", "author_id": 5378816, "author_profile": "https://Stackoverflow.com/users/5378816", "pm_score": 3, "selected": false, "text": "import types\n\ndef func(_static=types.SimpleNamespace(counter=0)):\n _static.counter += 1\n print(_static.counter)\n" }, { "answer_id": 51931792, "author": "yash", "author_id": 9908518, "author_profile": "https://Stackoverflow.com/users/9908518", "pm_score": 0, "selected": false, "text": "class Foo(object): \n counter = 0 \n\ndef __call__(self, inc_value=0):\n Foo.counter += inc_value\n return Foo.counter\n\nfoo = Foo()\n\ndef use_foo(x,y):\n if(x==5):\n foo(2)\n elif(y==7):\n foo(3)\n if(foo() == 10):\n print(\"yello\")\n\n\nuse_foo(5,1)\nuse_foo(5,1)\nuse_foo(1,7)\nuse_foo(1,7)\nuse_foo(1,1)\n stat_c +=9; // in c++\nfoo(9) #python equiv\n\nif(stat_c==10){ //do something} // c++\n\nif(foo() == 10): # python equiv\n #add code here # python equiv \n\nOutput :\nyello\nyello\n" }, { "answer_id": 52430571, "author": "Richard Merren", "author_id": 10392796, "author_profile": "https://Stackoverflow.com/users/10392796", "pm_score": 2, "selected": false, "text": "counter = 0\n\ndef foo():\n global counter\n counter += 1\n print(\"counter is {}\".format(counter))\n\nfoo() #output: \"counter is 1\"\nfoo() #output: \"counter is 2\"\nfoo() #output: \"counter is 3\"\n" }, { "answer_id": 63131227, "author": "0x262f", "author_id": 9129714, "author_profile": "https://Stackoverflow.com/users/9129714", "pm_score": 0, "selected": false, "text": "def Static():\n ### get the func object by which Static() is called.\n from inspect import currentframe, getframeinfo\n caller = currentframe().f_back\n func_name = getframeinfo(caller)[2]\n # print(func_name)\n caller = caller.f_back\n func = caller.f_locals.get(\n func_name, caller.f_globals.get(\n func_name\n )\n )\n \n class StaticVars:\n def has(self, varName):\n return hasattr(self, varName)\n def declare(self, varName, value):\n if not self.has(varName):\n setattr(self, varName, value)\n\n if hasattr(func, \"staticVars\"):\n return func.staticVars\n else:\n # add an attribute to func\n func.staticVars = StaticVars()\n return func.staticVars\n def myfunc(arg):\n if Static().has('test1'):\n Static().test += 1\n else:\n Static().test = 1\n print(Static().test)\n\n # declare() only takes effect in the first time for each static variable.\n Static().declare('test2', 1)\n print(Static().test2)\n Static().test2 += 1\n" }, { "answer_id": 68307083, "author": "Miguel Angelo", "author_id": 195417, "author_profile": "https://Stackoverflow.com/users/195417", "pm_score": 2, "selected": false, "text": "def static_inner_self(func):\n return func()\n @static_inner_self\ndef foo():\n counter = 0\n def foo():\n nonlocal counter\n counter += 1\n print(f\"counter is {counter}\")\n return foo\n nonlocal counter counter += 1 nonlocal nonlocal @static_inner_self\ndef indent_lines():\n import re\n re_start_line = re.compile(r'^', flags=re.MULTILINE)\n def indent_lines(text, indent=2):\n return re_start_line.sub(\" \"*indent, text)\n return indent_lines\n" }, { "answer_id": 74668335, "author": "Meindert Meindertsma", "author_id": 1683835, "author_profile": "https://Stackoverflow.com/users/1683835", "pm_score": 0, "selected": false, "text": "def fun(increment=1):\n global fun\n counter = 0\n def fun(increment=1):\n nonlocal counter\n counter += increment\n print(counter)\n fun(increment)\n\nfun() #=> 1\nfun() #=> 2\nfun(10) #=> 12\n def outerfun():\n def innerfun(increment=1):\n nonlocal innerfun\n counter = 0\n def innerfun(increment=1):\n nonlocal counter\n counter += increment\n print(counter)\n innerfun(increment)\n\n innerfun() #=> 1\n innerfun() #=> 2\n innerfun(10) #=> 12\n\nouterfun()\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10569/" ]
279,572
<p>I have a database where one of the common queries is has a "where blobCol is null", I think that this is getting bad performance (as in a full table scan). I have no need to index the contents of the blobCol. </p> <p>What indexes would improve this? Can an index be built on an expression (blobCol is not null) rather than just a column?</p>
[ { "answer_id": 279580, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "CREATE INDEX notNullblob ON myTable (blobCol is not NULL);\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
279,575
<p>HI All,</p> <p>I have a piece of javaScript that removes commas from a provided string (in my case currency values)</p> <p>It is:</p> <pre><code> function replaceCommaInCurrency(myField, val) { var re = /,/g; document.net1003Form.myField.value=val.replace(re, ''); } </code></pre> <p>'MyField' was my attempt to dynamically have this work on any field that I pass in, but it doesn't work, I get errors saying 'MyField' is not valid. I sort of get my, but I thought this was valid.</p> <p>I am calling by using: onBlur="replaceCommaInCurrency(this.name, this.value);return false;"</p> <p>this.name and this.value are passing in the right values...field name and its value.</p> <p>How do I do this dynamically?</p> <p>-Jason</p>
[ { "answer_id": 279604, "author": "flatline", "author_id": 20846, "author_profile": "https://Stackoverflow.com/users/20846", "pm_score": 2, "selected": false, "text": "myField.value = myField.value.replace(re, '');\n var jqField = $(myField);\njqField.val(jqField.val().replace(re, '')); \n" }, { "answer_id": 279607, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 3, "selected": true, "text": "eval(\"document.net1003Form.\" + myField + \".value=val.replace(re, '');\");\n document.net1003Form[myField].value=val.replace(re, '');\n function replaceCommaInCurrency(field){\n var re = /,/g;\n field.value = field.value.replace(re, '');\n}\n onBlur=\"replaceCommaInCurrency(this); return false\";\n $(function(){\n $(\"input.currency\").bind('blur', function(){\n this.value = $(this).val().replace(',', '');\n })\n});\n" }, { "answer_id": 279614, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": " function removeCommaInCurrency(myField)\n {\n var re = /,/g;\n\n myField.value=myField.value.replace(re, '');\n }\n <input type=\"text\" name=\"...\" onchange=\"removeCommaInCurrency(this);\">\n" }, { "answer_id": 279621, "author": "FriendOfFuture", "author_id": 1169746, "author_profile": "https://Stackoverflow.com/users/1169746", "pm_score": 1, "selected": false, "text": "function replaceCommaInCurrency( myField, val)\n{\n var re = /,/g;\n\n document.net1003Form[myField].value=val.replace(re, '');\n}\n" }, { "answer_id": 279760, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "<input type=\"text\" class=\"number\" name=\"something\" />\n...\n<script type=\"text/javascript\"> // external script is best, linked after all forms\n function numberfield_bind() {\n var inputs= document.getElementsByTagName('input');\n for (var inputi= inputs.length; inputi-->0;)\n if (inputs[inputi].className=='number')\n inputs[inputi].onchange= numberfield_change;\n }\n function numberfield_change() {\n this.value= this.value.split(',').join('');\n }\n numberfield_bind();\n</script>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
279,583
<p>I have a very basic app that I believe should change the width of an image, but it does nothing... can anyone tell me why, when I click on the image, nothing happens to the image? </p> <p><em>(note, the image itself doesnt really matter, Im just trying to figure out how to shrink and grow and image in JavaFX)</em></p> <pre><code>import javafx.application.Frame; import javafx.application.Stage; import javafx.scene.image.ImageView; import javafx.scene.image.Image; import javafx.input.MouseEvent; var w:Number = 250; Frame { title: "Image View Sample" width: 500 height: 500 closeAction: function() { java.lang.System.exit( 0 ); } visible: true stage: Stage { content: [ ImageView { x: 200; y: 200; image: Image { url: "{__DIR__}/c1.png" width: bind w; } onMouseClicked: function( e: MouseEvent ):Void { w = 100; } } ] } } </code></pre> <p>Thanks heaps!</p>
[ { "answer_id": 279604, "author": "flatline", "author_id": 20846, "author_profile": "https://Stackoverflow.com/users/20846", "pm_score": 2, "selected": false, "text": "myField.value = myField.value.replace(re, '');\n var jqField = $(myField);\njqField.val(jqField.val().replace(re, '')); \n" }, { "answer_id": 279607, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 3, "selected": true, "text": "eval(\"document.net1003Form.\" + myField + \".value=val.replace(re, '');\");\n document.net1003Form[myField].value=val.replace(re, '');\n function replaceCommaInCurrency(field){\n var re = /,/g;\n field.value = field.value.replace(re, '');\n}\n onBlur=\"replaceCommaInCurrency(this); return false\";\n $(function(){\n $(\"input.currency\").bind('blur', function(){\n this.value = $(this).val().replace(',', '');\n })\n});\n" }, { "answer_id": 279614, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": " function removeCommaInCurrency(myField)\n {\n var re = /,/g;\n\n myField.value=myField.value.replace(re, '');\n }\n <input type=\"text\" name=\"...\" onchange=\"removeCommaInCurrency(this);\">\n" }, { "answer_id": 279621, "author": "FriendOfFuture", "author_id": 1169746, "author_profile": "https://Stackoverflow.com/users/1169746", "pm_score": 1, "selected": false, "text": "function replaceCommaInCurrency( myField, val)\n{\n var re = /,/g;\n\n document.net1003Form[myField].value=val.replace(re, '');\n}\n" }, { "answer_id": 279760, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "<input type=\"text\" class=\"number\" name=\"something\" />\n...\n<script type=\"text/javascript\"> // external script is best, linked after all forms\n function numberfield_bind() {\n var inputs= document.getElementsByTagName('input');\n for (var inputi= inputs.length; inputi-->0;)\n if (inputs[inputi].className=='number')\n inputs[inputi].onchange= numberfield_change;\n }\n function numberfield_change() {\n this.value= this.value.split(',').join('');\n }\n numberfield_bind();\n</script>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26310/" ]
279,601
<p>I have a <code>vector</code> that I want to insert into a <code>set</code>. This is one of three different calls (the other two are more complex, involving <code>boost::lambda::if_()</code>), but solving this simple case will help me solve the others.</p> <pre><code>std::vector&lt;std::string&gt; s_vector; std::set&lt;std::string&gt; s_set; std::for_each(s_vector.begin(), s_vector.end(), s_set.insert(boost::lambda::_1)); </code></pre> <p>Unfortunately, this fails with a conversion error message (trying to convert <code>boost::lambda::placeholder1_type</code> to <code>std::string</code>).</p> <p>So... what's wrong with this?</p>
[ { "answer_id": 279649, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "for_each() vector<string>::insert() for_each() for_each(s_vector.begin(), s_vector.end(),\n boost::bind(set<string>::insert, s_set, boost::lambda::_1));\n" }, { "answer_id": 279677, "author": "Austin Ziegler", "author_id": 36378, "author_profile": "https://Stackoverflow.com/users/36378", "pm_score": 0, "selected": false, "text": "std::for_each(s_vector.begin(), s_vector.end(),\n lambda::bind(&std::set<std::string>::insert, s_set, lambda::_1));\n" }, { "answer_id": 279689, "author": "Mic", "author_id": 35656, "author_profile": "https://Stackoverflow.com/users/35656", "pm_score": 3, "selected": true, "text": "typedef std::set<std::string> s_type;\ntypedef std::pair<s_type::iterator, bool>(s_type::*insert_fp)(const s_type::value_type&);\nstd::for_each(s_vector.begin(), s_vector.end(), boost::bind(static_cast<insert_fp>(&s_type::insert), &s_set, _1));\n" }, { "answer_id": 279850, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 2, "selected": false, "text": "std::copy(s_vector.begin(), s_vector.end(), std::inserter(s_set, s_set.end()));\n #include <boost/assign/list_of.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/test/minimal.hpp>\n\n#include <set>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\nusing namespace boost::lambda;\nusing namespace boost::assign;\n\nint test_main(int argc, char* argv[])\n{\n vector<string> s_vector = list_of(\"red\")(\"orange\")(\"yellow\")(\"blue\")(\"indigo\")(\"violet\");\n set<string> s_set;\n\n // Copy only strings length<=4 into set:\n\n std::remove_copy_if(s_vector.begin(), s_vector.end(), std::inserter(s_set, s_set.end()),\n bind(&string::length, _1) > 4u);\n\n BOOST_CHECK(s_set.size() == 2);\n BOOST_CHECK(s_set.count(\"red\"));\n BOOST_CHECK(s_set.count(\"blue\"));\n\n return 0;\n}\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36378/" ]
279,610
<p>I want to create a history table to track field changes across a number of tables in DB2. </p> <p>I know history is usually done with copying an entire table's structure and giving it a suffixed name (e.g. user --> user_history). Then you can use a pretty simple trigger to copy the old record into the history table on an UPDATE.</p> <p>However, for my application this would use too much space. It doesn't seem like a good idea (to me at least) to copy an entire record to another table every time a field changes. So I thought I could have a generic 'history' table which would track individual field changes:</p> <pre><code>CREATE TABLE history ( history_id LONG GENERATED ALWAYS AS IDENTITY, record_id INTEGER NOT NULL, table_name VARCHAR(32) NOT NULL, field_name VARCHAR(64) NOT NULL, field_value VARCHAR(1024), change_time TIMESTAMP, PRIMARY KEY (history_id) ); </code></pre> <p>OK, so every table that I want to track has a single, auto-generated id field as the primary key, which would be put into the 'record_id' field. And the maximum VARCHAR size in the tables is 1024. Obviously if a non-VARCHAR field changes, it would have to be converted into a VARCHAR before inserting the record into the history table.</p> <p>Now, this could be a completely retarded way to do things (hey, let me know why if it is), but I think it it's a good way of tracking changes that need to be pulled up rarely and need to be stored for a significant amount of time. </p> <p>Anyway, I need help with writing the trigger to add records to the history table on an update. Let's for example take a hypothetical user table:</p> <pre><code>CREATE TABLE user ( user_id INTEGER GENERATED ALWAYS AS IDENTITY, username VARCHAR(32) NOT NULL, first_name VARCHAR(64) NOT NULL, last_name VARCHAR(64) NOT NULL, email_address VARCHAR(256) NOT NULL PRIMARY KEY(user_id) ); </code></pre> <p>So, can anyone help me with a trigger on an update of the user table to insert the changes into the history table? My guess is that some procedural SQL will need to be used to loop through the fields in the old record, compare them with the fields in the new record and if they don't match, then add a new entry into the history table. </p> <p>It'd be preferable to use the same trigger action SQL for every table, regardless of its fields, if it's possible.</p> <p>Thanks!</p>
[ { "answer_id": 279649, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "for_each() vector<string>::insert() for_each() for_each(s_vector.begin(), s_vector.end(),\n boost::bind(set<string>::insert, s_set, boost::lambda::_1));\n" }, { "answer_id": 279677, "author": "Austin Ziegler", "author_id": 36378, "author_profile": "https://Stackoverflow.com/users/36378", "pm_score": 0, "selected": false, "text": "std::for_each(s_vector.begin(), s_vector.end(),\n lambda::bind(&std::set<std::string>::insert, s_set, lambda::_1));\n" }, { "answer_id": 279689, "author": "Mic", "author_id": 35656, "author_profile": "https://Stackoverflow.com/users/35656", "pm_score": 3, "selected": true, "text": "typedef std::set<std::string> s_type;\ntypedef std::pair<s_type::iterator, bool>(s_type::*insert_fp)(const s_type::value_type&);\nstd::for_each(s_vector.begin(), s_vector.end(), boost::bind(static_cast<insert_fp>(&s_type::insert), &s_set, _1));\n" }, { "answer_id": 279850, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 2, "selected": false, "text": "std::copy(s_vector.begin(), s_vector.end(), std::inserter(s_set, s_set.end()));\n #include <boost/assign/list_of.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/test/minimal.hpp>\n\n#include <set>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\nusing namespace boost::lambda;\nusing namespace boost::assign;\n\nint test_main(int argc, char* argv[])\n{\n vector<string> s_vector = list_of(\"red\")(\"orange\")(\"yellow\")(\"blue\")(\"indigo\")(\"violet\");\n set<string> s_set;\n\n // Copy only strings length<=4 into set:\n\n std::remove_copy_if(s_vector.begin(), s_vector.end(), std::inserter(s_set, s_set.end()),\n bind(&string::length, _1) > 4u);\n\n BOOST_CHECK(s_set.size() == 2);\n BOOST_CHECK(s_set.count(\"red\"));\n BOOST_CHECK(s_set.count(\"blue\"));\n\n return 0;\n}\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
279,615
<p>I've got an NSArrayController, and I'm using KVO to observe the Old/New values of it's selection method.</p> <p>This works perfectly (triggers when the selection changes, the usual) except that the items in the change dictionary are all null instead of being the old/new selected object. [arrayController selection] still returns the proper object, but I'd like to be able to access the previously selected object as well if possible (my workaround will probably be to observe the selected index instead and see if that works).</p> <p>The only possible reason for this I've come up with is perhaps it's because the NSArrayController is a proxy object.</p> <p>So is this the expected behavior, or is something weird going on?</p> <p>EDIT: I tried observing just the Indexes, but that didn't work either. Both old and new keys still show up as null.</p>
[ { "answer_id": 1220907, "author": "Tom Dalling", "author_id": 108105, "author_profile": "https://Stackoverflow.com/users/108105", "pm_score": 0, "selected": false, "text": "NSKeyValueObservingOptionNew NSKeyValueObservingOptionOld addObserver:forKeyPath:options:context:" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
279,631
<p>I'm trying to load an external swf movie then adding the ability to drag it around the stage, however whenever I try to do this I just hit a dead end. Are there any limitations on what you can set be draggable or clickable? An example of what I'm doing is below:</p> <pre><code>public function loadSwf(url:String, swfUniqueName:String) { var ldr:Loader = new Loader(); var url:String = "Swfs/Label.swf"; var urlReq:URLRequest = new URLRequest(url); ldr.load(urlReq); ldr.contentLoaderInfo.addEventListener("complete", loadCompleteHandler); } private function loadCompleteHandler(event):void{ var ldr = event.currentTarget; // These are only here because I can't seem to get the drag to work ldr.content.doubleClickEnabled = true; ldr.content.buttonMode = true; ldr.content.useHandCursor = true; ldr.content.mouseEnabled = true; ldr.content.txtLabel.mouseEnabled = true; this.addChild(ldr.content); ldr.content.addEventListener(MouseEvent.MOUSE_DOWN, mouse_down); } mouse_down = function(event) { trace(event.target); } </code></pre> <p>Using the code above i can only get it to recognise a click on the movie itself if it is over a click on the textfield, but this really needs to work on any part of the movie. Any ideas?</p>
[ { "answer_id": 282050, "author": "Iain", "author_id": 11911, "author_profile": "https://Stackoverflow.com/users/11911", "pm_score": 2, "selected": false, "text": "ldr.content.mouseChildren = false;" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26081/" ]
279,634
<p>I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the <code>&lt;head&gt;</code></p> <p>note: I am working with a local server, so pageload in instant.</p> <pre><code>function changeVisibility() { var a = document.getElementById('invisible'); a.style.display = 'block'; } var changed = document.getElementById('click1'); changed.onchange = changeVisibility; </code></pre> <p>This here is the corresponding HTML</p> <pre><code>&lt;input type="file" name="click[]" size="35" id="click1" /&gt; &lt;div id="invisible" style="display: none;"&gt; &lt;a href="javascript:addFileInput();"&gt;Attach another File&lt;/a&gt; &lt;/div&gt; </code></pre> <p>So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block.</p> <p>Problem is, I keep getting this error:</p> <p>"changed is null: changed.onchange = changeVisibility;"</p> <p>i don't get it, I seriously don't get what I'm overlooking here.</p> <hr> <p>EDIT: question answered, thank you Mercutio for your help and everyone else too of course. Final code: </p> <pre><code>function loadEvents() { var changed = document.getElementById('click1'); var a = document.getElementById('invisible'); document.getElementById('addField').onclick = addFileInput; changed.onchange = function() { a.style.display = 'block'; } } if (document.getElementById) window.onload = loadEvents; </code></pre> <p>This here is the corresponding HTML:</p> <pre><code>&lt;input type="file" name="click[]" size="35" id="click1" /&gt; &lt;div id="invisible" style="display: none;"&gt; &lt;a href="#"&gt;Attach another File&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Also, thanks for the link to <a href="http://www.jsbin.com" rel="nofollow noreferrer">JSbin</a>, didn't know about that, looks nifty. </p>
[ { "answer_id": 279637, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 4, "selected": true, "text": "document.getElementById('addField').onclick = addFileInput;\n a.firstChild.onclick = addFileInput;\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11795/" ]
279,655
<p>I need some help with what is probably a newbie question in terms of modifying phpBB.</p> <p>I have a whole system developed in PHP, and I would like to integrate phpBB so that people can navigate into the forums and post seamlessly, without logging in again.</p> <p>Now, using the phpBB users table as the users table for my system (and having people register in phpBB instead of in my website) is not possible unfortunately (it'd take more work to redo our system than to build our own basic forum).<br> I'm assuming I can hack my way into making phpBB believe that a certain user ID has logged in, however, that user won't exist in phpBB's users table (which I'm assuming will cause it to error out pretty much everywhere).</p> <p>All the tutorials and forum posts I could find implied having phpBB as the primary. I couldn't find anything to do it the other way around.</p> <p>I'm guessing the only possible way to solve this is by having both tables relatively synchronized.</p> <p>Now, provided that I can have both users table synchronized, what is the best way to integrate both sites, keeping my site's login and users table as the "primary" ones?<br> Also, is there anything in particular I should keep in mind when creating records in phpBB's users table? Or is it relatively straightforward to figure out? What tables should I be writing to, if there is more than one?</p>
[ { "answer_id": 282181, "author": "Murat Ayfer", "author_id": 25910, "author_profile": "https://Stackoverflow.com/users/25910", "pm_score": 3, "selected": false, "text": "profile_fields profile_fields_data phpbb_hash($password) phpbb/includes/functions.php phpbb/includes/functions.php" }, { "answer_id": 423604, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$result=$auth->login($username, $password);\n\nif ($result['status'] == LOGIN_SUCCESS) {\n\n echo \"You're logged in\";\n\n} else {\n\n echo $user->lang[$result['error_msg']];\n\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
279,665
<p>How can I return the result of a different action or move the user to a different action if there is an error in my <code>ModelState</code> without losing my <code>ModelState</code> information?</p> <p>The scenario is; <code>Delete</code> action accepts a POST from a DELETE form rendered by my <code>Index</code> Action/View. If there is an error in the <code>Delete</code> I want to move the user back to the <code>Index</code> Action/View and show the errors that are stored by the <code>Delete</code> action in the <code>ViewData.ModelState</code>. How can this be done in ASP.NET MVC?</p> <pre><code>[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Delete)] public ActionResult Delete([ModelBinder(typeof(RdfUriBinder))] RdfUri graphUri) { if (!ModelState.IsValid) return Index(); //this needs to be replaced with something that works :) return RedirectToAction(&quot;Index&quot;); } </code></pre>
[ { "answer_id": 279680, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": -1, "selected": false, "text": "return View(\"Index\");\n return Index();\n" }, { "answer_id": 279740, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 8, "selected": true, "text": "TempData Index ...\n if (!ModelState.IsValid)\n TempData[\"ViewData\"] = ViewData;\n\n RedirectToAction( \"Index\" );\n}\n\n public ActionResult Index()\n {\n if (TempData[\"ViewData\"] != null)\n {\n ViewData = (ViewDataDictionary)TempData[\"ViewData\"];\n }\n\n ...\n }\n ViewData ViewData ModelState" }, { "answer_id": 18323394, "author": "Matthew", "author_id": 1803682, "author_profile": "https://Stackoverflow.com/users/1803682", "pm_score": 3, "selected": false, "text": "RedirectToAction(\"Action\") [AcceptVerbs(HttpVerbs.Post)]\n [ExportModelStateToTempData]\n public ActionResult ChangePassword(ProfileViewModel pVM) {\n bool result = MyChangePasswordCode(pVM.ChangePasswordViewModel);\n if (result) {\n ViewBag.Message = \"Password change success\";\n else {\n ModelState.AddModelError(\"ChangePassword\", \"Some password error\");\n }\n return RedirectToAction(\"Index\");\n }\n [ImportModelStateFromTempData]\npublic ActionResult Index() {\n ProfileViewModel pVM = new ProfileViewModel { //setup }\n return View(pVM);\n}\n // Following best practices as listed here for storing / restoring model data:\n// http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg\npublic abstract class ModelStateTempDataTransfer : ActionFilterAttribute {\n protected static readonly string Key = typeof(ModelStateTempDataTransfer).FullName;\n}\n public class ExportModelStateToTempData : ModelStateTempDataTransfer {\n public override void OnActionExecuted(ActionExecutedContext filterContext) {\n //Only export when ModelState is not valid\n if (!filterContext.Controller.ViewData.ModelState.IsValid) {\n //Export if we are redirecting\n if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult)) {\n filterContext.Controller.TempData[Key] = filterContext.Controller.ViewData.ModelState;\n }\n }\n // Added to pull message from ViewBag\n if (!string.IsNullOrEmpty(filterContext.Controller.ViewBag.Message)) {\n filterContext.Controller.TempData[\"Message\"] = filterContext.Controller.ViewBag.Message;\n }\n\n base.OnActionExecuted(filterContext);\n }\n}\n public class ImportModelStateFromTempData : ModelStateTempDataTransfer {\n public override void OnActionExecuted(ActionExecutedContext filterContext) {\n ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;\n\n if (modelState != null) {\n //Only Import if we are viewing\n if (filterContext.Result is ViewResult) {\n filterContext.Controller.ViewData.ModelState.Merge(modelState);\n } else {\n //Otherwise remove it.\n filterContext.Controller.TempData.Remove(Key);\n }\n }\n // Restore Viewbag message\n if (!string.IsNullOrEmpty((string)filterContext.Controller.TempData[\"Message\"])) {\n filterContext.Controller.ViewBag.Message = filterContext.Controller.TempData[\"Message\"];\n }\n\n base.OnActionExecuted(filterContext);\n }\n}\n" }, { "answer_id": 60775107, "author": "Jess", "author_id": 1804678, "author_profile": "https://Stackoverflow.com/users/1804678", "pm_score": 0, "selected": false, "text": "(function ($) {\n\n $(function () {\n\n // For forms marked with data-ajax=\"#container\",\n // on submit,\n // post the form data via AJAX\n // and if #container is specified, replace the #container with the response.\n var postAjaxForm = function (event) {\n\n event.preventDefault(); // Prevent the actual submit of the form.\n\n var $this = $(this);\n var containerId = $this.attr(\"data-ajax\");\n var $container = $(containerId);\n var url = $this.attr('action');\n\n console.log(\"Post ajax form to \" + url + \" and replace html in \" + containerId);\n\n $.ajax({\n type: \"POST\",\n url: url,\n data: $this.serialize()\n })\n .done(function (result) {\n if ($container) {\n $container.html(result);\n // re-apply this event since it would have been lost by the form getting recreated above.\n var $newForm = $container.find(\"[data-ajax]\");\n $newForm.submit(postAjaxForm);\n $newForm.trigger(\"data-ajax-done\");\n }\n })\n .fail(function (error) {\n alert(error);\n });\n };\n $(\"[data-ajax]\").submit(postAjaxForm);\n });\n\n})(jQuery);\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
279,673
<p>I wonder if it's possible to save all files in a Visual Studio 2008 project into a specific character encoding. I got a solution with mixed encodings and I want to make them all the same (UTF-8 with signature).</p> <p>I know how to save single files, but how about all files in a project?</p>
[ { "answer_id": 280325, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 3, "selected": false, "text": "import glob, codecs\n\nfor f in glob.glob(\"*.py\"):\n data = open(\"f\", \"rb\").read()\n if data.startswith(codecs.BOM_UTF8):\n # Already UTF-8\n continue\n # else assume ANSI code page\n data = data.decode(\"mbcs\")\n data = codecs.BOM_UTF8 + data.encode(\"utf-8\")\n open(\"f\", \"wb\").write(data)\n" }, { "answer_id": 850751, "author": "Timwi", "author_id": 33225, "author_profile": "https://Stackoverflow.com/users/33225", "pm_score": 7, "selected": true, "text": "foreach (var f in new DirectoryInfo(@\"...\").GetFiles(\"*.cs\", SearchOption.AllDirectories)) {\n string s = File.ReadAllText(f.FullName);\n File.WriteAllText (f.FullName, s, Encoding.UTF8);\n}\n" }, { "answer_id": 1326157, "author": "rasx", "author_id": 22944, "author_profile": "https://Stackoverflow.com/users/22944", "pm_score": 4, "selected": false, "text": "Function Write-Utf8([string] $path, [string] $filter='*.*')\n{\n [IO.SearchOption] $option = [IO.SearchOption]::AllDirectories;\n [String[]] $files = [IO.Directory]::GetFiles((Get-Item $path).FullName, $filter, $option);\n foreach($file in $files)\n {\n \"Writing $file...\";\n [String]$s = [IO.File]::ReadAllText($file);\n [IO.File]::WriteAllText($file, $s, [Text.Encoding]::UTF8);\n }\n}\n" }, { "answer_id": 2313200, "author": "Ehsan", "author_id": 278915, "author_profile": "https://Stackoverflow.com/users/278915", "pm_score": 1, "selected": false, "text": "Dim s As String = \"\"\nDim direc As DirectoryInfo = New DirectoryInfo(\"Your Directory path\")\n\nFor Each fi As FileInfo In direc.GetFiles(\"*.vb\", SearchOption.AllDirectories)\n s = File.ReadAllText(fi.FullName, System.Text.Encoding.Default)\n File.WriteAllText(fi.FullName, s, System.Text.Encoding.Unicode)\nNext\n" }, { "answer_id": 8799737, "author": "podcast", "author_id": 1140289, "author_profile": "https://Stackoverflow.com/users/1140289", "pm_score": 1, "selected": false, "text": " Function ChangeFileEncoding(pPathFolder As String, pExtension As String, pDirOption As IO.SearchOption) As Integer\n\n Dim Counter As Integer\n Dim s As String\n Dim reader As IO.StreamReader\n Dim gEnc As Text.Encoding\n Dim direc As IO.DirectoryInfo = New IO.DirectoryInfo(pPathFolder)\n For Each fi As IO.FileInfo In direc.GetFiles(pExtension, pDirOption)\n s = \"\"\n reader = New IO.StreamReader(fi.FullName, Text.Encoding.Default, True)\n s = reader.ReadToEnd\n gEnc = reader.CurrentEncoding\n reader.Close()\n\n If (gEnc.EncodingName <> Text.Encoding.UTF8.EncodingName) Then\n s = IO.File.ReadAllText(fi.FullName, gEnc)\n IO.File.WriteAllText(fi.FullName, s, System.Text.Encoding.UTF8)\n Counter += 1\n Response.Write(\"<br>Saved #\" & Counter & \": \" & fi.FullName & \" - <i>Encoding was: \" & gEnc.EncodingName & \"</i>\")\n End If\n Next\n\n Return Counter\nEnd Function\n ChangeFileEncoding(\"C:\\temp\\test\", \"*.ascx\", IO.SearchOption.TopDirectoryOnly)\n" }, { "answer_id": 18206763, "author": "Mase", "author_id": 2678184, "author_profile": "https://Stackoverflow.com/users/2678184", "pm_score": 1, "selected": false, "text": "tf checkout -r -type:utf-8 src/*.aspx\n" }, { "answer_id": 29138903, "author": "Bruce", "author_id": 1745885, "author_profile": "https://Stackoverflow.com/users/1745885", "pm_score": 3, "selected": false, "text": "static void Main(string[] args)\n{\n const string targetEncoding = \"utf-8\";\n foreach (var f in new DirectoryInfo(@\"<your project's path>\").GetFiles(\"*.cs\", SearchOption.AllDirectories))\n {\n var fileEnc = GetEncoding(f.FullName);\n if (fileEnc != null && !string.Equals(fileEnc, targetEncoding, StringComparison.OrdinalIgnoreCase))\n {\n var str = File.ReadAllText(f.FullName, Encoding.GetEncoding(fileEnc));\n File.WriteAllText(f.FullName, str, Encoding.GetEncoding(targetEncoding));\n }\n }\n Console.WriteLine(\"Done.\");\n Console.ReadKey();\n}\n\nprivate static string GetEncoding(string filename)\n{\n using (var fs = File.OpenRead(filename))\n {\n var cdet = new Ude.CharsetDetector();\n cdet.Feed(fs);\n cdet.DataEnd();\n if (cdet.Charset != null)\n Console.WriteLine(\"Charset: {0}, confidence: {1} : \" + filename, cdet.Charset, cdet.Confidence);\n else\n Console.WriteLine(\"Detection failed: \" + filename);\n return cdet.Charset;\n }\n}\n" }, { "answer_id": 32265184, "author": "Janis Rudovskis", "author_id": 1503576, "author_profile": "https://Stackoverflow.com/users/1503576", "pm_score": 0, "selected": false, "text": " Encoding encoding = Encoding.Default;\n String original = String.Empty;\n foreach (var f in new DirectoryInfo(path).GetFiles(\"*.cs\", SearchOption.AllDirectories))\n {\n using (StreamReader sr = new StreamReader(f.FullName, Encoding.Default))\n {\n original = sr.ReadToEnd();\n encoding = sr.CurrentEncoding;\n sr.Close();\n }\n if (encoding == Encoding.UTF8)\n continue;\n byte[] encBytes = encoding.GetBytes(original);\n byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encBytes);\n var utf8Text = Encoding.UTF8.GetString(utf8Bytes);\n\n File.WriteAllText(f.FullName, utf8Text, Encoding.UTF8);\n }\n" }, { "answer_id": 42143222, "author": "Maxime Esprit", "author_id": 4965913, "author_profile": "https://Stackoverflow.com/users/4965913", "pm_score": 1, "selected": false, "text": "foreach (var f in new DirectoryInfo(@\"....\").GetFiles(\"*.cs\", SearchOption.AllDirectories))\n {\n string s = File.ReadAllText(f.FullName, Encoding.GetEncoding(1252));\n File.WriteAllText(f.FullName, s, Encoding.UTF8);\n }\n" }, { "answer_id": 58287056, "author": "Bruno Zell", "author_id": 5185376, "author_profile": "https://Stackoverflow.com/users/5185376", "pm_score": 1, "selected": false, "text": "Function Write-Utf8([string] $path, [string] $filter='*')\n{\n [IO.SearchOption] $option = [IO.SearchOption]::AllDirectories;\n [String[]] $files = [IO.Directory]::GetFiles((Get-Item $path).FullName, $filter, $option);\n foreach($file in $files)\n {\n \"Writing $file...\";\n [String]$s = [IO.File]::ReadAllText($file, [Text.Encoding]::UTF8);\n [Text.Encoding]$e = New-Object -TypeName Text.UTF8Encoding -ArgumentList ($false);\n [IO.File]::WriteAllText($file, $s, $e);\n }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33349/" ]
279,693
<p>I'm new to cryptography and modular arithmetic. So, I'm sure it's a silly question, but I can't help it. </p> <p>How do I calculate <em>a</em> from <br> &nbsp;&nbsp;&nbsp;&nbsp; pow(<em>a</em>,<strong>q</strong>) = 1 (mod <strong>p</strong>), <br> where <strong>p</strong> and <strong>q</strong> are known? I don't get the "1 (mod <strong>p</strong>)" part, it equals to 1, doesn't it? If so, than what is "mod <strong>p</strong>" about? <br> Is this the same as <br> &nbsp;&nbsp;&nbsp;&nbsp; pow(<em>a</em>,<strong>-q</strong>) (mod <strong>p</strong>) = 1?</p>
[ { "answer_id": 279700, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": false, "text": "p q p q p a q q a q p a q p a q p n p n p a q np a a np q n a" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24622/" ]
279,696
<p>Still struggling to understand what best practices are with respect to macros. I'm attempting to write a macro which defines packages on the fly.</p> <pre><code>(defmacro def-dynamic-package (name) `(defpackage ,(intern (string-upcase name) "KEYWORD") (:use :common-lisp))) </code></pre> <p>This works fine only for expressions such as:</p> <pre><code>(def-dynamic-package "helloworld") </code></pre> <p>But fails miserably for something like this:</p> <pre><code>(defun make-package-from-path (path) (def-dynamic-package (pathname-name path))) </code></pre> <p>or</p> <pre><code>(defun make-package-from-path (path) (let ((filename (pathname-path))) (def-dynamic-package filename))) </code></pre> <p>I understand how most basic macros work but how to implement this one escapes me.</p>
[ { "answer_id": 279725, "author": "Nowhere man", "author_id": 400277, "author_profile": "https://Stackoverflow.com/users/400277", "pm_score": 0, "selected": false, "text": "(list 'pathname-name 'path)\n (defun def-dynamic-package (name)\n (defpackage (string-upcase name)\n (:use :common-lisp)))\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32797/" ]
279,701
<p>I'm trying to get a handle on if there's a good time to use standard linq keywords or linq extension methods with lambda expressions. They seems to do the same thing, just are written differently. Is it purely a matter of style?</p> <pre><code>var query = from p in Products where p.Name.Contains("foo") orderby c.Name select p; // or with extension methods: var query = Products .Where(p =&gt; p.Name.Contains("foo")) .OrderBy(p =&gt; p.Name); </code></pre> <p>They're very similar with the second example being a bit more terse, but perhaps less expressive if you don't know what the => is doing.</p> <p><strong>Other than writing terse code, are there other advantages to using the extension methods as opposed to the LINQ syntax?</strong></p>
[ { "answer_id": 279738, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 5, "selected": false, "text": "Into var query = (from p in Products\n where p.Name.Contains(\"foo\")\n orderby c.Name\n select p).Into(\"MyTable\");\n var query = Products\n .Where(p => p.Name.Contains(\"foo\"))\n .OrderBy(p => p.Name)\n .Into(\"MyTable\");\n" }, { "answer_id": 284313, "author": "Programmin Tool", "author_id": 21691, "author_profile": "https://Stackoverflow.com/users/21691", "pm_score": 6, "selected": true, "text": " Func<DataClasses.User, String> userName = user => user.UserName;\n Func<DataClasses.User, Boolean> userIDOverTen = user => user.UserID < 10;\n Func<DataClasses.User, Boolean> userIDUnderTen = user => user.UserID > 10;\n var userList = \n from user in userList\n where userIDOverTen(user)\n select userName;\n var otherList =\n userList\n .Where(IDIsBelowNumber)\n .Select(userName)\n private Boolean IDIsBelowNumber(DataClasses.User user, \n Int32 someNumber, Boolean doSomething)\n {\n return user.UserID < someNumber;\n }\n var completeList =\n from user in userList\n where IDIsBelowNumber(user, 10, true)\n select userName;\n var otherList =\n userList\n .Where(IDIsBelowNumber????)\n .Select(userName)\n private Func<DataClasses.User, Boolean> IDIsBelowNumberFunc(Int32 number)\n {\n return user => IDIsBelowNumber(user, number, true);\n }\n var otherList =\n userList\n .Where(IDIsBelowNumberFunc(10))\n .Select(userName)\n" }, { "answer_id": 4322017, "author": "Rodi", "author_id": 526176, "author_profile": "https://Stackoverflow.com/users/526176", "pm_score": 4, "selected": false, "text": "\n.Where(user => IDIsBelowNumber(user, 10, true))\n" }, { "answer_id": 22231539, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": -1, "selected": false, "text": "var query = from p in Products\n where p.Name.Contains(\"foo\")\n orderby p.Name\n select p;\n\nvar result = query.ToList(); //extension method syntax\n var nonQuery = Products.Where(p => p.Name.Contains(\"foo\"))\n .OrderBy(p => p.Name)\n .ToList();\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26931/" ]
279,705
<p>My shared host did not provide git, so I built and installed it into ~/bin. When I ran it, I got the following error on most commands, although they were successful. </p> <blockquote> <p><code>stdin: is not a tty</code></p> </blockquote> <p>I can solve that problem by adding: </p> <blockquote> <p><code>default_run_options[:pty] = true</code></p> </blockquote> <p>to my deploy.rb, but then I get this error, which blocks deployment:</p> <blockquote> <p><code>sh: git: command not found</code></p> </blockquote> <p>How can I resolve both errors?</p> <p>I tried adding a ~/.ssh/environment file with <code>"PATH=$PATH:$HOME/bin"</code> (and changing sshd_config to use it) but it did nothing.</p> <p>It seems whatever shell is being used by capistrano is not using the ~/.bashrc or ~/.bash_profile on the remote server.</p> <p>Any ideas how to set the path on the remote machine?</p> <p>other info: I'm using OS X locally, and the shared server is linux on Site5.</p>
[ { "answer_id": 279746, "author": "Denis Hennessy", "author_id": 35958, "author_profile": "https://Stackoverflow.com/users/35958", "pm_score": 2, "selected": false, "text": "set :deploy_via, :copy\n" }, { "answer_id": 281124, "author": "Chu Yeow", "author_id": 25226, "author_profile": "https://Stackoverflow.com/users/25226", "pm_score": 2, "selected": false, "text": "set :scm_command, \"/home/your_cap_runner_user/bin/git\"" }, { "answer_id": 281873, "author": "Matt Van Horn", "author_id": 12651, "author_profile": "https://Stackoverflow.com/users/12651", "pm_score": 4, "selected": false, "text": "set :scm_command, \"~/bin/git\" set :scm_command, \"~/bin/git\"\nset :local_scm_command, \"/usr/local/bin/git\"" }, { "answer_id": 1993985, "author": "ckim", "author_id": 242556, "author_profile": "https://Stackoverflow.com/users/242556", "pm_score": 3, "selected": false, "text": "default_run_options[:pty] = true\n default_environment['PATH'] = \"/your/path/to/git:/and/any/other/path/you/need\"\n" }, { "answer_id": 2158557, "author": "Sergei Morozov", "author_id": 146187, "author_profile": "https://Stackoverflow.com/users/146187", "pm_score": 2, "selected": false, "text": "stdin: is not a tty\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
279,729
<p>I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment.</p> <p>Here is as a code I use:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;sys/time.h&gt; #include &lt;sys/wait.h&gt; using namespace std; struct timeval first, second, lapsed; struct timezone tzp; int main(int argc, char* argv[])// query, file, num. of processes. { int pCount = 5; // process count gettimeofday (&amp;first, &amp;tzp); //start time pid_t* pID = new pid_t[pCount]; for(int indexOfProcess=0; indexOfProcess&lt;pCount; indexOfProcess++) { pID[indexOfProcess]= fork(); if (pID[indexOfProcess] == 0) // child { // code only executed by child process // magic here // The End exit(0); } else if (pID[indexOfProcess] &lt; 0) // failed to fork { cerr &lt;&lt; "Failed to fork" &lt;&lt; endl; exit(1); } else // parent { // if(indexOfProcess==pCount-1) and a loop with waitpid?? gettimeofday (&amp;second, &amp;tzp); //stop time if (first.tv_usec &gt; second.tv_usec) { second.tv_usec += 1000000; second.tv_sec--; } lapsed.tv_usec = second.tv_usec - first.tv_usec; lapsed.tv_sec = second.tv_sec - first.tv_sec; cout &lt;&lt; "Job performed in " &lt;&lt;lapsed.tv_sec &lt;&lt; " sec and " &lt;&lt; lapsed.tv_usec &lt;&lt; " usec"&lt;&lt; endl &lt;&lt; endl; } }//for }//main </code></pre>
[ { "answer_id": 279744, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 4, "selected": false, "text": "while(wait() > 0) { /* no-op */ ; }\n wait() int status;\n[...]\ndo {\n status = wait();\n if(status == -1 && errno != ECHILD) {\n perror(\"Error during wait()\");\n abort();\n }\n} while (status > 0);\n wait(2)" }, { "answer_id": 279745, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "for (int i = 0; i < pidCount; i++) {\n while (waitpid(pids[i], NULL, 0) > 0);\n}\n" }, { "answer_id": 279761, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 6, "selected": true, "text": "for (int i = 0; i < pidCount; ++i) {\n int status;\n while (-1 == waitpid(pids[i], &status, 0));\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {\n cerr << \"Process \" << i << \" (pid \" << pids[i] << \") failed\" << endl;\n exit(1);\n }\n}\n\ngettimeofday (&second, &tzp); //stop time\n while (true) {\n int status;\n pid_t done = wait(&status);\n if (done == -1) {\n if (errno == ECHILD) break; // no more child processes\n } else {\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {\n cerr << \"pid \" << done << \" failed\" << endl;\n exit(1);\n }\n }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3515/" ]
279,748
<p>I have some code like this:</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult Save([Bind(Prefix="")]Person person) { String s = person.property; /* ... */ } </code></pre> <p>But it throws the error: "Cannot use local variable 'person' before it is declared".</p> <p>What simple thing am I missing?</p>
[ { "answer_id": 18253246, "author": "Frankie Lee", "author_id": 2685909, "author_profile": "https://Stackoverflow.com/users/2685909", "pm_score": 2, "selected": false, "text": " public ChartData(MetricInfo metricInfo, MetricItem[] metricItems) : this()\n {\n int endingYear = 0;\n endingYear = endingDate.Year;\n case \"QRTR_LAST_FULL_QRTR\":\n if (metricInfo.CalendarType == \"CALENDAR\")\n {\n switch (endingDate.Month)\n {\n case 1:\n case 2:\n case 3:\n loopControl = 4;\n endingYear = endingDate.Year - 1;\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
279,749
<p>I'm working on a kind of unique app which needs to generate images at specific resolutions according to the device they are displayed on. So the output is different on a regular Windows browser (96ppi), iPhone (163ppi), Android G1 (180ppi), and other devices. I'm wondering if there's a way to detect this automatically.</p> <p>My initial research seems to say no. The only suggestion I've seen is to make an element whose width is specified as "1in" in CSS, then check its offsetWidth (see also <a href="https://stackoverflow.com/q/476815/698168">How to access screen display’s DPI settings via javascript?</a>). Makes sense, but iPhone is lying to me with that technique, saying it's 96ppi.</p> <p>Another approach might be to get the dimensions of the display in inches and then divide by the width in pixels, but I'm not sure how to do that either.</p>
[ { "answer_id": 4472024, "author": "john", "author_id": 488480, "author_profile": "https://Stackoverflow.com/users/488480", "pm_score": 2, "selected": false, "text": "<body><div id=\"ppitest\" style=\"width:1in;visible:hidden;padding:0px\"></div></body>\n screenPPI = document.getElementById('ppitest').offsetWidth;" }, { "answer_id": 8212989, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 4, "selected": false, "text": "resolution" }, { "answer_id": 21577144, "author": "TJS101", "author_id": 1150866, "author_profile": "https://Stackoverflow.com/users/1150866", "pm_score": 2, "selected": false, "text": "function getPPI(){\n // create an empty element\n var div = document.createElement(\"div\");\n // give it an absolute size of one inch\n div.style.width=\"1in\";\n // append it to the body\n var body = document.getElementsByTagName(\"body\")[0];\n body.appendChild(div);\n // read the computed width\n var ppi = document.defaultView.getComputedStyle(div, null).getPropertyValue('width');\n // remove it again\n body.removeChild(div);\n // and return the value\n return parseFloat(ppi);\n} \n" }, { "answer_id": 26004882, "author": "MaxXx1313", "author_id": 1269984, "author_profile": "https://Stackoverflow.com/users/1269984", "pm_score": 4, "selected": false, "text": "<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>\n<script type='text/javascript'>\n var devicePixelRatio = window.devicePixelRatio || 1;\n dpi_x = document.getElementById('testdiv').offsetWidth * devicePixelRatio;\n dpi_y = document.getElementById('testdiv').offsetHeight * devicePixelRatio;\n \n console.log(dpi_x, dpi_y);\n</script>" }, { "answer_id": 35941703, "author": "Endless", "author_id": 1008999, "author_profile": "https://Stackoverflow.com/users/1008999", "pm_score": 4, "selected": false, "text": "width: x !important /**\n * Binary search for a max value without knowing the exact value, only that it can be under or over\n * It dose not test every number but instead looks for 1,2,4,8,16,32,64,128,96,95 to figure out that\n * you thought about #96 from 0-infinity\n *\n * @example findFirstPositive(x => matchMedia(`(max-resolution: ${x}dpi)`).matches)\n * @author Jimmy Wärting\n * @see {@link https://stackoverflow.com/a/35941703/1008999}\n * @param {function} fn The function to run the test on (should return truthy or falsy values)\n * @param {number} start=1 Where to start looking from\n * @param {function} _ (private)\n * @returns {number} Intenger\n */\nfunction findFirstPositive (f,b=1,d=(e,g,c)=>g<e?-1:0<f(c=e+g>>>1)?c==e||0>=f(c-1)?c:d(e,c-1):d(c+1,g)) {\n for (;0>=f(b);b<<=1);return d(b>>>1,b)|0\n}\n\nvar dpi = findFirstPositive(x => matchMedia(`(max-resolution: ${x}dpi)`).matches)\n\nconsole.log(dpi)" }, { "answer_id": 39795416, "author": "jrmgx", "author_id": 696517, "author_profile": "https://Stackoverflow.com/users/696517", "pm_score": 2, "selected": false, "text": "var dpi = (function () {\n for (var i = 56; i < 2000; i++) {\n if (matchMedia(\"(max-resolution: \" + i + \"dpi)\").matches === true) {\n return i;\n }\n }\n return i;\n})();\n" }, { "answer_id": 50284385, "author": "haelmic", "author_id": 5092123, "author_profile": "https://Stackoverflow.com/users/5092123", "pm_score": -1, "selected": false, "text": "navigator.userAgent.toLowerCase();\n window.isMobile=/iphone|ipod|ipad|android|blackberry|opera mini|opera mobi|skyfire|maemo|windows phone|palm|iemobile|symbian|symbianos|fennec/i.test(navigator.userAgent.toLowerCase());\n" }, { "answer_id": 66735827, "author": "Алексей Жуков", "author_id": 15007931, "author_profile": "https://Stackoverflow.com/users/15007931", "pm_score": -1, "selected": false, "text": "const dpi = (function () {\n let i = 1;\n while ( !hasMatch(i) ) i *= 2;\n\n function getValue(start, end) {\n if (start > end) return -1;\n let average = (start + end) / 2;\n if ( hasMatch(average) ) {\n if ( start == average || !hasMatch(average - 1) ) {\n return average;\n } else {\n return getValue(start, average - 1);\n }\n } else {\n return getValue(average + 1, end);\n }\n }\n\n function hasMatch(x) {\n return matchMedia(`(max-resolution: ${x}dpi)`).matches;\n }\n\n return getValue(i / 2, i) | 0;\n})();\n" }, { "answer_id": 71447234, "author": "rookie", "author_id": 18436745, "author_profile": "https://Stackoverflow.com/users/18436745", "pm_score": -1, "selected": false, "text": "const canvas = document.getElementById(\"canvas\");\nfunction findFirstPositive(b, a, i, c) {\n c=(d,e)=>e>=d?(a=d+(e-d)/2,0<b(a)&&(a==d||0>=b(a-1))?a:0>=b(a)?c(a+1,e):c(d,a-1)):-1\n for (i = 1; 0 >= b(i);) i *= 2\n return c(i / 2, i)|0\n}\nconst dpi = findFirstPositive(x => matchMedia(`(max-resolution: ${x}dpi)`).matches)\nlet w = 198 * dpi / 25.4;\nlet h = 280 * dpi / 25.4;\ncanvas.width = w;\ncanvas.height = h;\n let [w,h] = [748,1058];\ncanvas.width = w;\ncanvas.height = h;\n" }, { "answer_id": 72385005, "author": "cdauth", "author_id": 242365, "author_profile": "https://Stackoverflow.com/users/242365", "pm_score": 1, "selected": false, "text": "1in devicePixelRatio 1" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
279,753
<p>I have written code that automatically creates CSS sprites based on the IMG tags in a page and replaces them with DIV's with (what I thought was) appropriate CSS to position the sprite image as a background letting the appropriate part show through -- the problem is that I cannot get DIVs to behave as drop in replacements for IMGs. </p> <p>If I leave the default 'display' value set to 'block' then if the original IMG was positioned at the end of some text, the replacement DIV will jump down to the next line after text (which of course is what I would expect something with display: block to do).</p> <p>If I change the 'display' to inline, then the DIV stays on the same line as the text but it ignores the 'width' and 'height' I have set and collapses. I've tried putting &nbsp;'s inside the DIV but it then only takes up enough width to contain the nbsp.</p> <p>I've tried experimenting with setting display to all possible values (including the "obscure" ones like 'table-row', 'run-in', 'compact', etc) but all with no luck. Is it even possible to create a DIV with the same layout behavior as an IMG?</p> <p>I am open to having something more complicated than just a single DIV, however I've tried the obvious things there (one DIV inside another where the inner DIV is set to display: block with the outer set to display: inline) but I haven't found a combination there that works either.</p> <p>There are always specific things I can do outside of the replaced IMG/DIV to get the layout I want, but my goal is to have a generic auto-CSS-sprite mechanism that works regardless of the rest of the HTML.</p>
[ { "answer_id": 279777, "author": "Andy Ford", "author_id": 17252, "author_profile": "https://Stackoverflow.com/users/17252", "pm_score": 5, "selected": true, "text": "display: inline-block; display: -moz-inline-block;" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2168/" ]
279,763
<p>I am trying to write a C program that uses <code>dlysm</code>, and I keep getting an undefined reference to dlysm. I think I need to set my <code>-ldl</code> flags but I have no idea how to do this. </p> <p>I am very new to linux and setting variables. If this is what I need to do can someone help me out with the commands?</p>
[ { "answer_id": 279767, "author": "Kknd", "author_id": 18403, "author_profile": "https://Stackoverflow.com/users/18403", "pm_score": 1, "selected": false, "text": "-ldl gcc myprog.c -o app -ldl\n" }, { "answer_id": 279771, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 2, "selected": false, "text": "-l gcc -o program program.c -ldl *.o -ldl ld man ld man cc" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
279,769
<p>How do you convert between a DateTime and a Time object in Ruby?</p>
[ { "answer_id": 279785, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 7, "selected": true, "text": " Time DateTime require 'date'\nclass Time\n def to_datetime\n # Convert seconds + microseconds into a fractional number of seconds\n seconds = sec + Rational(usec, 10**6)\n\n # Convert a UTC offset measured in minutes to one measured in a\n # fraction of a day.\n offset = Rational(utc_offset, 60 * 60 * 24)\n DateTime.new(year, month, day, hour, min, seconds, offset)\n end\nend\n DateTime Time class Date\n def to_gm_time\n to_time(new_offset, :gm)\n end\n\n def to_local_time\n to_time(new_offset(DateTime.now.offset-offset), :local)\n end\n\n private\n def to_time(dest, method)\n #Convert a fraction of a day to a number of microseconds\n usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i\n Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,\n dest.sec, usec)\n end\nend\n" }, { "answer_id": 280464, "author": "anshul", "author_id": 17674, "author_profile": "https://Stackoverflow.com/users/17674", "pm_score": 8, "selected": false, "text": "require 'time'\nrequire 'date'\n\nt = Time.now\nd = DateTime.now\n\ndd = DateTime.parse(t.to_s)\ntt = Time.parse(d.to_s)\n" }, { "answer_id": 3513247, "author": "Bernard", "author_id": 1556338, "author_profile": "https://Stackoverflow.com/users/1556338", "pm_score": 4, "selected": false, "text": "DateTime.to_time, Time.to_datetime Time.parse require 'date'\n\n# Create a date in some foreign time zone (middle of the Atlantic)\nd = DateTime.new(2010,01,01, 10,00,00, Rational(-2, 24))\nputs d\n\n# Convert DateTime to Time, keeping the original timezone\nt = Time.new(d.year, d.month, d.day, d.hour, d.min, d.sec, d.zone)\nputs t\n\n# Convert Time to DateTime, keeping the original timezone\nd = DateTime.new(t.year, t.month, t.day, t.hour, t.min, t.sec, Rational(t.gmt_offset / 3600, 24))\nputs d\n 2010-01-01T10:00:00-02:00\n2010-01-01 10:00:00 -0200\n2010-01-01T10:00:00-02:00\n" }, { "answer_id": 8511699, "author": "the Tin Man", "author_id": 128421, "author_profile": "https://Stackoverflow.com/users/128421", "pm_score": 6, "selected": false, "text": "Date DateTime Time pry\n[1] pry(main)> ts = 'Jan 1, 2000 12:01:01'\n=> \"Jan 1, 2000 12:01:01\"\n[2] pry(main)> require 'time'\n=> true\n[3] pry(main)> require 'date'\n=> true\n[4] pry(main)> ds = Date.parse(ts)\n=> #<Date: 2000-01-01 (4903089/2,0,2299161)>\n[5] pry(main)> ds.to_date\n=> #<Date: 2000-01-01 (4903089/2,0,2299161)>\n[6] pry(main)> ds.to_datetime\n=> #<DateTime: 2000-01-01T00:00:00+00:00 (4903089/2,0,2299161)>\n[7] pry(main)> ds.to_time\n=> 2000-01-01 00:00:00 -0700\n[8] pry(main)> ds.to_time.class\n=> Time\n[9] pry(main)> ds.to_datetime.class\n=> DateTime\n[10] pry(main)> ts = Time.parse(ts)\n=> 2000-01-01 12:01:01 -0700\n[11] pry(main)> ts.class\n=> Time\n[12] pry(main)> ts.to_date\n=> #<Date: 2000-01-01 (4903089/2,0,2299161)>\n[13] pry(main)> ts.to_date.class\n=> Date\n[14] pry(main)> ts.to_datetime\n=> #<DateTime: 2000-01-01T12:01:01-07:00 (211813513261/86400,-7/24,2299161)>\n[15] pry(main)> ts.to_datetime.class\n=> DateTime\n" }, { "answer_id": 11138360, "author": "Mildred", "author_id": 174011, "author_profile": "https://Stackoverflow.com/users/174011", "pm_score": 1, "selected": false, "text": "def to_time\n #Convert a fraction of a day to a number of microseconds\n usec = (sec_fraction * 60 * 60 * 24 * (10**6)).to_i\n t = Time.gm(year, month, day, hour, min, sec, usec)\n t - offset.abs.div(SECONDS_IN_DAY)\nend\n to_time" }, { "answer_id": 65582221, "author": "Dorian", "author_id": 12544391, "author_profile": "https://Stackoverflow.com/users/12544391", "pm_score": 0, "selected": false, "text": "to_date > Event.last.starts_at\n=> Wed, 13 Jan 2021 16:49:36.292979000 CET +01:00\n> Event.last.starts_at.to_date\n=> Wed, 13 Jan 2021\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
279,779
<p>I know in the MVC Framework, you have the Html Class to create URLs:</p> <pre><code>Html.ActionLink(&quot;About us&quot;, &quot;about&quot;, &quot;home&quot;); </code></pre> <p>But what if you want to generate Urls in Webforms?</p> <p>I haven't found a really good resource on the details on generating URLs with Webforms.</p> <p>For example, if I'm generating routes like so:</p> <pre><code>Route r = new Route(&quot;{country}/{lang}/articles/{id}/{title}&quot;, new ArticleRouteHandler(&quot;~/Forms/Article.aspx&quot;)); Route r2 = new Route(&quot;{country}/{lang}/articles/&quot;, new ArticleRouteHandler(&quot;~/Forms/ArticlesList.aspx&quot;)); Routes.Add(r); Routes.Add(r2); </code></pre> <p>How would i generate URLs using the Routing table data.</p> <h2>How do I generate URLS based on my routes?</h2> <p>eg. /ca/en/articles/123/Article-Title without</p>
[ { "answer_id": 281340, "author": "MikeO", "author_id": 36616, "author_profile": "https://Stackoverflow.com/users/36616", "pm_score": 3, "selected": true, "text": "Dim routedurl = RouteTable.Routes.GetVirtualPath(context, rvd).VirtualPath\n requestContext.HttpContext.Items(\"RequestContext\") = requestContext\n Dim rvd = \n New RouteValueDictionary(New With {.country = \"UK\", .lang = \"EN-GB\"})\nDim routedurl = \n RouteTable.Routes.GetVirtualPath(context.Items(\"RequestContext\"), rvd).VirtualPath\n" }, { "answer_id": 285882, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 3, "selected": false, "text": "RouteValueDictionary rvdSiteDefaults \n = new RouteValueDictionary { { \"country\", \"ca\" }, { \"lang\", \"en\" } };\n\nRoute oneArticle \n = new Route(\"{country}/{lang}/articles/a{id}/{title}\",\n rvdSiteDefaults,\n rvdConstrainID,\n new ArticleRouteHandler(\"~/Articles/Details.aspx\"));\n\nRoutes.Add( \"Article\", oneArticle); \n public static string CreateUrl(Article a) {\n // Note, Article comes from Database, has properties of ArticleID, Title, etc.\n RouteValueDictionary parameters;\n\n string routeName = \"Article\"; // Set in Global.asax\n\n parameters \n = new RouteValueDictionary { \n { \"id\", a.ArticleID }, \n { \"title\", a.Title.CleanUrl() } \n }; \n VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, routeName, parameters);\n\n string url = vpd.VirtualPath; \n return url; // eg. /ca/en/1/The-Article-Title\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26931/" ]
279,781
<p>Hey everyone, I am trying to run the following program, but am getting a NullPointerException. I am new to the Java swing library so I could be doing something very dumb. Either way here are my two classes I am just playing around for now and all i want to do is draw a damn circle (ill want to draw a gallow, with a hangman on it in the end).</p> <pre><code>package hangman2; import java.awt.*; import javax.swing.*; public class Hangman2 extends JFrame{ private GridLayout alphabetLayout = new GridLayout(2,2,5,5); private Gallow gallow = new Gallow(); public Hangman2() { setLayout(alphabetLayout); setSize(1000,500); setVisible( true ); } public static void main( String args[] ) { Hangman2 application = new Hangman2(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } package hangman2; import java.awt.*; import javax.swing.*; public class Gallow extends JPanel { private Graphics g; public Gallow(){ g.fillOval(10, 20, 40, 25); } } </code></pre> <p>The NullPointerException comes in at the g.fillOval line.</p> <p>Thanks in advance,</p> <p>Tomek</p>
[ { "answer_id": 279798, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": true, "text": "g null paintComponent(Graphics g) public class Gallow extends JPanel {\n public paintComponent(Graphics g){\n g.fillOval(10, 20, 40, 25); \n }\n}\n" }, { "answer_id": 279851, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 0, "selected": false, "text": "JFrame paint() JPanel JPanel package hangman2;\n\nimport java.awt.*;\nimport javax.swing.*;\n\npublic class Hangman2 extends JFrame{\n private GridLayout alphabetLayout = new GridLayout(2,2,5,5);\n private Gallow gallow = new Gallow();\n\n public Hangman2() {\n\n setLayout(alphabetLayout);\n add(gallow, BorderLayout.CENTER);//here\n setSize(1000,500);\n setVisible( true );\n\n }\n\n public static void main( String args[] ) { \n Hangman2 application = new Hangman2();\n application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n }\n}\n\n\npackage hangman2;\n\nimport java.awt.*;\nimport javax.swing.*;\n\npublic class Gallow extends JPanel {\n\n public Gallow(){\n super();\n }\n\n public void paint(Graphics g){\n g.fillOval(10, 20, 40, 25); \n }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
279,782
<p>Given:</p> <pre><code>from django.db import models class Food(models.Model): """Food, by name.""" name = models.CharField(max_length=25) class Cat(models.Model): """A cat eats one type of food""" food = models.ForeignKey(Food) class Cow(models.Model): """A cow eats one type of food""" food = models.ForeignKey(Food) class Human(models.Model): """A human may eat lots of types of food""" food = models.ManyToManyField(Food) </code></pre> <p>How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class <strong>Food</strong>, how can one get the classes <strong>Cat</strong>, <strong>Cow</strong> and <strong>Human</strong>.</p> <p>I would think it's possible because Food has the three "reverse relations": <em>Food.cat_set</em>, <em>Food.cow_set</em>, and <em>Food.human_set</em>.</p> <p>Help's appreciated &amp; thank you!</p>
[ { "answer_id": 279809, "author": "Brian M. Hunt", "author_id": 19212, "author_profile": "https://Stackoverflow.com/users/19212", "pm_score": 4, "selected": false, "text": "def get_all_related_objects(self, local_only=False):\n\ndef get_all_related_many_to_many_objects(self, local_only=False)\n >>> Food._meta.get_all_related_objects()\n[<RelatedObject: app_label:cow related to food>,\n <RelatedObject: app_label:cat related to food>,]\n\n>>> Food._meta.get_all_related_many_to_many_objects()\n[<RelatedObject: app_label:human related to food>,]\n\n# and, per django/db/models/related.py\n# you can retrieve the model with\n>>> Food._meta.get_all_related_objects()[0].model\n<class 'app_label.models.Cow'>\n" }, { "answer_id": 279952, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 4, "selected": true, "text": "from django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\nclass Food(models.Model):\n \"\"\"Food, by name.\"\"\"\n name = models.CharField(max_length=25)\n\n# ConsumedFood has a foreign key to Food, and a \"eaten_by\" generic relation\nclass ConsumedFood(models.Model):\n food = models.ForeignKey(Food, related_name=\"eaters\")\n content_type = models.ForeignKey(ContentType, null=True)\n object_id = models.PositiveIntegerField(null=True)\n eaten_by = generic.GenericForeignKey('content_type', 'object_id')\n\nclass Person(models.Model):\n first_name = models.CharField(max_length=50)\n last_name = models.CharField(max_length=50)\n birth_date = models.DateField()\n address = models.CharField(max_length=100)\n city = models.CharField(max_length=50)\n foods = generic.GenericRelation(ConsumedFood)\n\nclass Cat(models.Model):\n name = models.CharField(max_length=50)\n foods = generic.GenericRelation(ConsumedFood) \n\nclass Cow(models.Model):\n farmer = models.ForeignKey(Person)\n foods = generic.GenericRelation(ConsumedFood) \n \"\"\"\n>>> from models import *\n\nCreate some food records\n\n>>> weed = Food(name=\"weed\")\n>>> weed.save()\n\n>>> burger = Food(name=\"burger\")\n>>> burger.save()\n\n>>> pet_food = Food(name=\"Pet food\")\n>>> pet_food.save()\n\nJohn the farmer likes burgers\n\n>>> john = Person(first_name=\"John\", last_name=\"Farmer\", birth_date=\"1960-10-12\")\n>>> john.save()\n>>> john.foods.create(food=burger)\n<ConsumedFood: ConsumedFood object>\n\nWilma the cow eats weed\n\n>>> wilma = Cow(farmer=john)\n>>> wilma.save()\n>>> wilma.foods.create(food=weed)\n<ConsumedFood: ConsumedFood object>\n\nFelix the cat likes pet food\n\n>>> felix = Cat(name=\"felix\")\n>>> felix.save()\n>>> pet_food.eaters.create(eaten_by=felix)\n<ConsumedFood: ConsumedFood object>\n\nWhat food john likes again ?\n>>> john.foods.all()[0].food.name\nu'burger'\n\nWho's getting pet food ?\n>>> living_thing = pet_food.eaters.all()[0].eaten_by\n>>> isinstance(living_thing,Cow)\nFalse\n>>> isinstance(living_thing,Cat)\nTrue\n\nJohn's farm is in fire ! He looses his cow.\n>>> wilma.delete()\n\nJohn is a lot poorer right now\n>>> john.foods.clear()\n>>> john.foods.create(food=pet_food)\n<ConsumedFood: ConsumedFood object>\n\nWho's eating pet food now ?\n>>> for consumed_food in pet_food.eaters.all():\n... consumed_food.eaten_by\n<Cat: Cat object>\n<Person: Person object>\n\nGet the second pet food eater\n>>> living_thing = pet_food.eaters.all()[1].eaten_by\n\nTry to find if it's a person and reveal his name\n>>> if isinstance(living_thing,Person): living_thing.first_name\nu'John'\n\n\"\"\"\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
279,791
<p>Suppose the following data schema:</p> <pre><code>Usage ====== client_id resource type amount Billing ====== client_id usage_resource usage_type rate </code></pre> <p>In this example, suppose I have multiple resources, each of which can be used in many ways. For example, one resource is a <code>widget</code>. <code>Widgets</code> can be <code>foo</code>ed and they can be <code>bar</code>ed. <code>Gizmo</code>s can also be <code>foo</code>ed and <code>bar</code>ed. These usage types are billed at different rates, possibly even different rates for different clients. Each occurence of a usage (of a resource) is recorded in the Usage table. Each billing rate (for client, resource, and type combination) is stored in the billing table.</p> <p><em>(By the way, if this data schema is not the right way to approach this problem, please make suggestions.)</em></p> <p>Is it possible, using Ruby on Rails and ActiveRecord, to create a <code>has_many</code> relationship from Billings to Usages so that I can get a list of usage instances for a given billing rate? Is there a syntax of the <code>has_many, :through</code> that I don't know?</p> <p>Once again, I may be approaching this problem from the wrong angle, so if you can think of a better way, please speak up!</p>
[ { "answer_id": 279838, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "id Billing Billing Usage Usage Billing" }, { "answer_id": 1081092, "author": "Michael Sofaer", "author_id": 132613, "author_profile": "https://Stackoverflow.com/users/132613", "pm_score": 1, "selected": false, "text": "class Billing\n def usages\n Usage.find(:all, :conditions => [\"x = ? and y = ?\", self.x, self.y])\n end\nend\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ]
279,822
<p>I'm looking for a (preferably free) component for Delphi for users to easily select about 100 different colours.</p> <p>I've currently got one as part of DevExpress's editors, but it only has about 20 proper colours to choose, with a bunch of other 'Windows' colours like clHighlight, clBtnFace, etc.</p> <p>It's for regular users, so would like to avoid requiring them to manually select RGB values. </p> <p>Something similar to the colour picker in MS Paint might work, or something that lists X11/web colours:</p> <p><a href="http://en.wikipedia.org/wiki/Web_Colors" rel="noreferrer">http://en.wikipedia.org/wiki/Web_Colors</a></p> <p>So, please let me know if you got any recommendations.</p> <p><strong>Thanks for the suggestions from everyone</strong></p> <p>All of the suggestions were good, I didn't realise the MS Paint colour dialog can be called, that's all I needed and is the simplest solution. Thanks</p>
[ { "answer_id": 280103, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 5, "selected": true, "text": "object ColorDialog1: TColorDialog\n Options = [cdFullOpen, cdAnyColor]\nend\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26305/" ]
279,833
<p>I am not looking for links to information on hashing.</p> <p>I am not looking for the worlds greatest hash function.</p> <p>I am interested in mini-stories describing</p> <ul> <li>The problem domain you were working in</li> <li>The nature of the data you were working with</li> <li>What your thought process was in designing a hash function for your data.</li> <li>How happy were you with your result.</li> <li>What you learned from the experience that might be of value to others.</li> </ul>
[ { "answer_id": 279893, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": true, "text": "{ \n ( (col1, col2), (col3, col4) ) : [ aRow, anotherRow, row3, ... ],\n ( (col1, col2), (col3, col4) ) : [ row1, row2, row3. row4, ... ],\n}\n" }, { "answer_id": 280043, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 1, "selected": false, "text": "steal" }, { "answer_id": 14053157, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 1, "selected": false, "text": "int32" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
279,837
<p>It's kind of a C puzzle. You have to tell if the program finish its execution, if so, how much time it takes to run and what it returns to the OS.</p> <pre><code>static unsigned char buffer[256]; int main(void) { unsigned char *p, *q; q = (p = buffer) + sizeof(buffer); while (q - p) { p = buffer; while (!++*p++); } return p - q; } </code></pre> <p>[EDIT] I removed the interview-questions tag since that seems to be the primary thing people are objecting to. This is a great little puzzle but as everyone has already pointed out, not a great interview question.</p>
[ { "answer_id": 279855, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": false, "text": "static unsigned char buffer[256];\nint main(void)\n{\n unsigned char *p, *q;\n q = (p = buffer) + sizeof(buffer); //p=buffer, q=buffer+256\n while (q - p) //q-p = 256 on first iteration\n { \n p = buffer; //p=buffer again\n while (!++*p++); //increment the value pointed at by p+1 and check for !0\n }\n return p - q; //will return zero if loop ever terminates\n}\n" }, { "answer_id": 279954, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 5, "selected": true, "text": "static unsigned char buffer[256];\n\nint main(void)\n{\n unsigned char *p, *q;\n q = (p = buffer) + sizeof(buffer);\n /* This statement will set p to point to the beginning of buffer and will\n set q to point to one past the last element of buffer (this is legal) */\n while (q - p)\n /* q - p will start out being 256 and will decrease at an inversely \n exponential rate: */\n { \n p = buffer;\n while (!++*p++);\n /* This is where the interesting part comes in; the prefix increment,\n dereference, and logical negation operators all have the same\n precedence and are evaluated **right-to-left**. The postfix\n operator has a higher precedence. *p starts out at zero, is\n incremented to 1 by the prefix, and is negated by !.\n p is incremented by the postfix operator, the condition\n evaluates to false and the loop terminates with buffer[0] = 1.\n\n p is then set to point to buffer[0] again and the loop continues \n until buffer[0] = 255. This time, the loop succeeds when *p is\n incremented, becomes 0 and is negated. This causes the loop to\n run again immediately after p is incremented to point to buffer[1],\n which is increased to 1. The value 1 is of course negated,\n p is incremented which doesn't matter because the loop terminates\n and p is reset to point to buffer[0] again.\n\n This process will continue to increment buffer[0] every time,\n increasing buffer[1] every 256 runs. After 256*255 runs,\n buffer[0] and buffer[1] will both be 255, the loop will succeed\n *twice* and buffer[2] will be incremented once, etc.\n\n The loop will terminate after about 256^256 runs when all the values\n in the buffer array are 255 allowing p to be incremented to the end\n of the array. This will happen sometime after the universe ends,\n maybe a little sooner on the new Intels ;)\n */\n }\n return p - q;\n /* Returns 0 as p == q now */\n}\n" }, { "answer_id": 280028, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": -1, "selected": false, "text": "unsigned char *p, *q;\n char* p;\nchar* q;\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1876/" ]
279,854
<p>If I have a vector of pairs:</p> <pre><code>std::vector&lt;std::pair&lt;int, int&gt; &gt; vec; </code></pre> <p>Is there and easy way to sort the list in <strong>increasing</strong> order based on the second element of the pair?</p> <p>I know I can write a little function object that will do the work, but is there a way to use existing parts of the <em>STL</em> and <code>std::less</code> to do the work directly?</p> <p>EDIT: I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like:</p> <pre><code>std::sort(vec.begin(), vec.end(), std::something_magic&lt;int, int, std::less&gt;()); </code></pre>
[ { "answer_id": 279878, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 9, "selected": true, "text": "auto std::sort(v.begin(), v.end(), [](auto &left, auto &right) {\n return left.second < right.second;\n});\n std::sort struct sort_pred {\n bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {\n return left.second < right.second;\n }\n};\n\nstd::sort(v.begin(), v.end(), sort_pred());\n std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {\n return left.second < right.second;\n});\n template <class T1, class T2, class Pred = std::less<T2> >\nstruct sort_pair_second {\n bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {\n Pred p;\n return p(left.second, right.second);\n }\n};\n std::sort(v.begin(), v.end(), sort_pair_second<int, int>());\n std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());\n" }, { "answer_id": 280128, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": false, "text": "std::sort(a.begin(), a.end(), \n boost::bind(&std::pair<int, int>::second, _1) <\n boost::bind(&std::pair<int, int>::second, _2));\n boost::bind" }, { "answer_id": 280662, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "template<template <typename> class P = std::less >\nstruct compare_pair_second {\n template<class T1, class T2> bool operator()(const std::pair<T1, T2>& left, const std::pair<T1, T2>& right) {\n return P<T2>()(left.second, right.second);\n }\n};\n std::sort(foo.begin(), foo.end(), compare_pair_second<>());\n std::sort(foo.begin(), foo.end(), compare_pair_second<std::less>());\n" }, { "answer_id": 8002277, "author": "Andreas Spindler", "author_id": 887771, "author_profile": "https://Stackoverflow.com/users/887771", "pm_score": 5, "selected": false, "text": "using namespace std;\nvector<pair<int, int>> v;\n .\n .\nsort(v.begin(), v.end(),\n [](const pair<int, int>& lhs, const pair<int, int>& rhs) {\n return lhs.second < rhs.second; } );\n bool { return expression ; } void []() -> Type { } sort(v.begin(), v.end(),\n [](const pair<int, int>& lhs, const pair<int, int>& rhs) -> bool {\n if (lhs.second == 0)\n return true;\n return lhs.second < rhs.second; } );\n" }, { "answer_id": 33649456, "author": "Ezio", "author_id": 3782306, "author_profile": "https://Stackoverflow.com/users/3782306", "pm_score": 5, "selected": false, "text": "vector< pair<int,int > > v;\nsort(v.begin(),v.end(),myComparison);\n bool myComparison(const pair<int,int> &a,const pair<int,int> &b)\n{\n return a.second<b.second;\n}\n" }, { "answer_id": 41607852, "author": "hadizadeh.ali", "author_id": 5389810, "author_profile": "https://Stackoverflow.com/users/5389810", "pm_score": -1, "selected": false, "text": "std::sort()" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34502/" ]
279,860
<h2>Background</h2> <p>I'm trying out Scons by setting up a basic C++ sample project that has two sub-projects: </p> <ul> <li>Prj1 is an EXE that depends on Prj2</li> <li>Prj2 is a DLL that exports some functions</li> </ul> <p>The problem I'm running into is that the library builds its .obj, .pdb, .lib, .dll, etc. files in the same directory as it's SConscript file while the EXE builds its files in the same directory as its SConscript. The application successfully builds both the Prj2 dependency and itself. However, you cannot run the resulting EXE because it can't find the library it needs because it is in the other directory.</p> <h2>Question</h2> <p>How can I get multiple projects that have dependences to output their binaries and debug information into a common directory so that they can be executed and debugged?</p> <h2>Potential Solutions</h2> <p>This is what I have thought of so far:</p> <ul> <li>I tried using VariantDir (previously called BuildDir) however this doesn't seem to work. Perhaps I'm messing something up here.</li> <li>I could potentially tell the compiler and the linker explicitly (via Fo/Fd for example) where to drop their files (is this the best or only solution???)</li> <li>Execute a copy command on the resulting binaries (this seems like a hack and quite a pain to manage/maintain)</li> </ul> <h2>Update</h2> <p>I updated the File Structure and file contents below to reflect the working solution in it's entirety. Thanks to grieve for his insight.</p> <h2>Command</h2> <p>With this configuration, you must unfortunately execute the build by cd'ing to the build directory and then running the command below. I need to get a properly working alias setup to get around this.</p> <pre><code> build> scons ../bin/project1.exe </code></pre> <h2>File Structure</h2> <pre><code> /scons-sample /bin /release /debug /build SConstruct scons_helper.py /prj1 SConscript /include /src main.cpp /prj2 SConscript /include functions.h /src functions.cpp </code></pre> <h2>SConstruct</h2> <pre><code> import os.path BIN_DIR = '../bin' OBJ_DIR = './obj' #-------------------------------------- # CxxTest Options #-------------------------------------- CXXTEST_DIR = '../extern/CxxTest/CxxTest-latest' PERL = 'perl -w' TESTS = '*.h' TESTGEN = PERL + CXXTEST_DIR + '/cxxtestgen.pl' CXXTESTGEN_FLAGS = '--runner=ParenPrinter \ --abort-on-fail \ --have-eh' #-------------------------------------- # Options #-------------------------------------- SetOption( 'implicit_cache', 1 ) # command line options opts = Options() opts.AddOptions( EnumOption( 'debug', 'Debug version (useful for developers only)', 'no', allowed_values = ('yes', 'no'), map = { }, ignorecase = 1 ) ) #-------------------------------------- # Environment #-------------------------------------- env = Environment( options = opts, #-------------------------------------- # Linker Options #-------------------------------------- LIBPATH = [ '../extern/wxWidgets/wxWidgets-latest/lib/vc_dll' ], LIBS = [ # 'wxmsw28d_core.lib', # 'wxbase28d.lib', # 'wxbase28d_odbc.lib', # 'wxbase28d_net.lib', 'kernel32.lib', 'user32.lib', 'gdi32.lib', 'winspool.lib', 'comdlg32.lib', 'advapi32.lib', 'shell32.lib', 'ole32.lib', 'oleaut32.lib', 'uuid.lib', 'odbc32.lib', 'odbccp32.lib' ], LINKFLAGS = '/nologo /subsystem:console /incremental:yes /debug /machine:I386', #-------------------------------------- # Compiler Options #-------------------------------------- CPPPATH = [ './include/', '../extern/wxWidgets/wxWidgets-latest/include', '../extern/wxWidgets/wxWidgets-latest/vc_dll/mswd' ], CPPDEFINES = [ 'WIN32', '_DEBUG', '_CONSOLE', '_MBCS', 'WXUSINGDLL', '__WXDEBUG__' ], CCFLAGS = '/W4 /EHsc /RTC1 /MDd /nologo /Zi /TP /errorReport:prompt' ) env.Decider( 'MD5-timestamp' ) # For speed, use timestamps for change, followed by MD5 Export( 'env', 'BIN_DIR' ) # Export this environment for use by the SConscript files #-------------------------------------- # Builders #-------------------------------------- SConscript( '../prj1/SConscript' ) SConscript( '../prj2/SConscript' ) Default( 'prj1' ) </code></pre> <h2>scons_helper.py</h2> <pre><code> import os.path #-------------------------------------- # Functions #-------------------------------------- # Prepends the full path information to the output directory so that the build # files are dropped into the directory specified by trgt rather than in the # same directory as the SConscript file. # # Parameters: # env - The environment to assign the Program value for # outdir - The relative path to the location you want the Program binary to be placed # trgt - The target application name (without extension) # srcs - The list of source files # Ref: # Credit grieve and his local SCons guru for this: # http://stackoverflow.com/questions/279860/how-do-i-get-projects-to-place-their-build-output-into-the-same-directory-with def PrefixProgram(env, outdir, trgt, srcs): env.Program(target = os.path.join(outdir, trgt), source = srcs) # Similar to PrefixProgram above, except for SharedLibrary def PrefixSharedLibrary(env, outdir, trgt, srcs): env.SharedLibrary(target = os.path.join(outdir, trgt), source = srcs) def PrefixFilename(filename, extensions): return [(filename + ext) for ext in extensions] # Prefix the source files names with the source directory def PrefixSources(srcdir, srcs): return [os.path.join(srcdir, x) for x in srcs] </code></pre> <h2>SConscript for Prj1</h2> <pre><code> import os.path import sys sys.path.append( '../build' ) from scons_helper import * Import( 'env', 'BIN_DIR' ) # Import the common environment prj1_env = env.Clone() # Clone it so we don't make changes to the global one #-------------------------------------- # Project Options #-------------------------------------- PROG = 'project1' #-------------------------------------- # Header Files #-------------------------------------- INC_DIR = [ '../prj2/include' ] HEADERS = [ '' ] #-------------------------------------- # Source Files #-------------------------------------- SRC_DIR = './src' SOURCES = [ 'main.cpp' ] # Prefix the source files names with the source directory SOURCES = PrefixSources( SRC_DIR, SOURCES ) #-------------------------------------- # Compiler and Linker Overrides #-------------------------------------- prj1_env.Append( CPPPATH = INC_DIR, LIBS = 'project2', LIBPATH = BIN_DIR, # Microsoft Visual Studio Specific PDB = os.path.join( BIN_DIR, PROG + '.pdb' ) ) #-------------------------------------- # Builders #-------------------------------------- PrefixProgram( prj1_env, BIN_DIR, PROG, SOURCES ) </code></pre> <h2>SConscript for Prj2</h2> <pre><code> import os.path import sys sys.path.append( '../build' ) from scons_helper import * Import( 'env', 'BIN_DIR' ) # Import the common environment prj2_env = env.Clone() # Clone it so we don't make changes to the global one #-------------------------------------- # Project Options #-------------------------------------- PROG = 'project2' #-------------------------------------- # Header Files #-------------------------------------- INC_DIR = [ '' ] HEADERS = [ 'functions.h' ] #-------------------------------------- # Source Files #-------------------------------------- SRC_DIR = './src/' SOURCES = [ 'functions.cpp' ] # Prefix the source files names with the source directory SOURCES = PrefixSources( SRC_DIR, SOURCES ) #-------------------------------------- # Compiler and Linker Overrides #-------------------------------------- # Update the environment with the project specific information prj2_env.Append( CPPPATH = INC_DIR, # Microsoft Visual Studio Specific PDB = os.path.join( BIN_DIR, PROG + '.pdb' ) ) #-------------------------------------- # Builders #-------------------------------------- PrefixSharedLibrary( prj2_env, BIN_DIR, PROG, SOURCES ) </code></pre>
[ { "answer_id": 279883, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 2, "selected": false, "text": "env.Install(\"../bin\", <your target exe or dll>)\n env.Alias('install', \"../bin\")\nDefault('install')\n" }, { "answer_id": 281103, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 4, "selected": true, "text": "prj2_env.Program(target = os.path.join(BIN_DIR,PROG), source = SOURCES )\n def PrefixProgram(env, trgt, srcs):\n env.Program(target = os.path.join(env.[\"MY_OUTPUT_DIR\"], trgt), source = srcs)\n import ('PrefixProgram')\n# stuff ...\nPrefixProgram(prj2_env, PROG, SOURCES)\n env[\"MY_OUTPUT_DIR\"]\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2233/" ]
279,902
<p>Or better said: When to use array as a field data type in a table?</p> <p>Which solution provides better search results?</p>
[ { "answer_id": 59516125, "author": "mattdlockyer", "author_id": 1060487, "author_profile": "https://Stackoverflow.com/users/1060487", "pm_score": 3, "selected": false, "text": "create table data (\n id serial primary key,\n tags int[],\n data jsonb\n);\n\ncreate table tags (\n id serial primary key,\n data_id int references data(id)\n);\n\nCREATE INDEX gin_tags ON data USING GIN(tags gin__int_ops); \n\nSET enable_seqscan to off;\n\nwith rand as (SELECT generate_series(1,100000) AS id)\ninsert into data (tags) select '{5}' from rand;\n\nupdate data set tags = '{1}' where id = 47300;\n\nwith rand as (SELECT generate_series(1,100000) AS id)\nINSERT INTO tags(data_id) select id from rand;\n select data.id, data.data, data.tags\n from data, tags where tags.data_id = data.id and tags.id = 47300;\n select data.id, data.data, data.tags\n from data where data.tags && '{1}';\n Record Count: 1; Execution Time: 3ms\nQUERY PLAN\nNested Loop (cost=0.58..16.63 rows=1 width=61)\n-> Index Scan using tags_pkey on tags (cost=0.29..8.31 rows=1 width=4)\nIndex Cond: (id = 47300)\n-> Index Scan using data_pkey on data (cost=0.29..8.31 rows=1 width=61)\nIndex Cond: (id = tags.data_id)\n Record Count: 1; Execution Time: 1ms\nQUERY PLAN\nBitmap Heap Scan on data (cost=15.88..718.31 rows=500 width=61)\nRecheck Cond: (tags && '{1}'::integer[])\n-> Bitmap Index Scan on gin_tags (cost=0.00..15.75 rows=500 width=0)\nIndex Cond: (tags && '{1}'::integer[])\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34565/" ]
279,907
<p>What is the best way to display a checkbox in a Crystal Report?</p> <p>Example: My report has a box for "Male" and "Female", and one should be checked.</p> <p>My current workaround is to draw a small graphical square, and line it up with a formula which goes like this:</p> <pre><code>if {table.gender} = "M" then "X" else " " </code></pre> <p>This is a poor solution, because changing the font misaligns my "X" and the box around it, and it is absurdly tedious to squint at the screen and get a pixel-perfect alignment for every box (there are dozens).</p> <p>Does anyone have a better solution? I've thought about using the old-style terminal characters, but I'm not sure if they display properly in Crystal.</p> <p><em>Edit: I'm using Crystal XI.</em></p>
[ { "answer_id": 281304, "author": "jons911", "author_id": 34375, "author_profile": "https://Stackoverflow.com/users/34375", "pm_score": 2, "selected": false, "text": "0xFE 0xA8" }, { "answer_id": 2891048, "author": "hatem gamil", "author_id": 298416, "author_profile": "https://Stackoverflow.com/users/298416", "pm_score": 3, "selected": false, "text": "If {Table.Field} = True Then\n\n'Display the checkbox of your choice here\n\nFormula = Chr(254)\n\nElse\n\n'Display empty checkbox\n\nFormula = Chr(168)\n\nEnd If\n" }, { "answer_id": 9060100, "author": "am2", "author_id": 1177465, "author_profile": "https://Stackoverflow.com/users/1177465", "pm_score": 2, "selected": false, "text": "If {Table.Field} = True Then\n\n'Display the checkbox of your choice here\n\nFormula = Chr(254)\n\nElse\n\n'Display empty checkbox\n\nFormula = Chr(168)\n\nEnd If\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
279,912
<p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p> <p>Which would you recommend and why?</p>
[ { "answer_id": 38231267, "author": "Szabolcs Dombi", "author_id": 6557569, "author_profile": "https://Stackoverflow.com/users/6557569", "pm_score": 4, "selected": false, "text": "pip install ModernGL\n pyglet.gl.glClearColor pip install moderngl-window prog = ctx.program(\n vertex_shader='''\n #version 330\n in vec2 in_vert;\n void main() {\n gl_Position = vec4(in_vert, 0.0, 1.0);\n }\n ''',\n fragment_shader='''\n #version 330\n out vec4 f_color;\n void main() {\n f_color = vec4(0.3, 0.5, 1.0, 1.0);\n }\n ''',\n)\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16584/" ]
279,917
<p>I'm loading data from my database, and exporting to an Excel file via a method I found on this site: <a href="http://www.appservnetwork.com/modules.php?name=News&amp;file=article&amp;sid=8" rel="noreferrer">http://www.appservnetwork.com/modules.php?name=News&amp;file=article&amp;sid=8</a></p> <p>It works, but what I want to do now is format the text before it exports - change the font and text size. Does anybody have any ideas on how to do this?</p>
[ { "answer_id": 279926, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "PEAR :: Package :: Spreadsheet_Excel_Writer" }, { "answer_id": 281902, "author": "Eric Caron", "author_id": 34340, "author_profile": "https://Stackoverflow.com/users/34340", "pm_score": 3, "selected": false, "text": "<table>\n<tr><th>Column 1</th><th>Column 2</th></tr>\n<tr><td style=\"font-size:200%\">Answer 1</td><td style=\"color:#f00\">Answer 2</td></tr>\n<tr><td colspan=\"2\" style=\"font-weight:bold\">Answer 3 with 2 columns</td></tr>\n</table>\n" }, { "answer_id": 5405337, "author": "raj", "author_id": 673023, "author_profile": "https://Stackoverflow.com/users/673023", "pm_score": 0, "selected": false, "text": "<?php\n include '../include/config.php';\n $sql = \"SELECT SQL_CALC_FOUND_ROWS\n \".DB_TBL_TUTORS_RECAPS.\".id,\n \".DB_TBL_TUTORS_RECAPS.\".date_of_tutoring_session,\n \".DB_TBL_TUTORS_RECAPS.\".created,\n \".DB_TBL_TUTORS_RECAPS.\".hours_tutored,\n \".DB_TBL_TUTORS_RECAPS.\".billable_travel,\n \".DB_TBL_TUTORS_RECAPS.\".billable_additional,\n \".DB_TBL_TUTORS_RECAPS.\".type_of_tutoring,\n \".DB_TBL_TUTORS_RECAPS.\".additional_comments,\n \".DB_TBL_TUTORS_RECAPS.\".total_billable,\n \".DB_TBL_TUTORS_RECAPS.\".materials_covered_during_session,\n \".DB_TBL_TUTORS_RECAPS.\".next_scheduled_session_location,\n \".DB_TBL_TUTORS_RECAPS.\".rate,\n \".DB_TBL_TUTORS_RECAPS.\".tutor_pay_rate,\n \".DB_TBL_APPLICANTS.\".first_name as tutor_first_name,\n \".DB_TBL_APPLICANTS.\".last_name as tutor_last_name,\n \".DB_TBL_PIPELINE.\".tutor_match_notes,\n \".DB_TBL_PIPELINE.\".date_of_submission,\n \".DB_TBL_PIPELINE.\".tutor_name,\n \".DB_TBL_PIPELINE.\".tutor_id,\n \".DB_TBL_CLIENTS.\".id as client_id,\n \".DB_TBL_CLIENTS.\".first_name,\n \".DB_TBL_CLIENTS.\".last_name,\n \".DB_TBL_CLIENTS.\".location_name,\n \".DB_TBL_CLIENTS.\".last_name,\n \".DB_TBL_CHILDREN.\".id as child_id,\n \".DB_TBL_CHILDREN.\".last_name as last,\n \".DB_TBL_CHILDREN.\".first_name as first\n FROM \n \".DB_TBL_TUTORS_RECAPS.\"\n LEFT JOIN \".DB_TBL_PIPELINE.\" ON \".DB_TBL_PIPELINE.\".id= \".DB_TBL_TUTORS_RECAPS.\".pipeline_id\n LEFT JOIN \".DB_TBL_CHILDREN.\" ON \".DB_TBL_CHILDREN.\".id= \".DB_TBL_TUTORS_RECAPS.\".child_id \n LEFT JOIN \".DB_TBL_CLIENTS.\" ON \".DB_TBL_CLIENTS.\".id= \".DB_TBL_TUTORS_RECAPS.\".client_id \n LEFT JOIN \".DB_TBL_TUTORS.\" ON \".DB_TBL_TUTORS_RECAPS.\".tutor_id= \".DB_TBL_TUTORS.\".id \n LEFT JOIN \".DB_TBL_APPLICANTS.\" ON \".DB_TBL_APPLICANTS.\".id= \".DB_TBL_TUTORS.\".applicant_id \n WHERE \n\n\n \" . DB_TBL_CLIENTS . \".status = 'Existing' AND\n\n \" . DB_TBL_APPLICANTS . \".status = 'Existing' AND\n\n \" . DB_TBL_PIPELINE . \".status = 'Existing' AND \n \" . DB_TBL_TUTORS_RECAPS . \".is_deleted = '0' \n GROUP BY \" . DB_TBL_TUTORS_RECAPS . \".id\n ORDER BY \" . DB_TBL_TUTORS_RECAPS . \".created DESC \";\n\n $totallogs = $db->query($sql);\n $filename = \"Tutoring_Log.xls\";\n $contents = \"Recap# \\t Tutor Name \\t Client Name \\t Child Name \\t Type of tutoring \\t Date of Tutoring session \\t Hours tutored \\t Billable Travel \\t Billable Additional \\t Total Billable \\t Client Rate \\t Tutor Pay Rate \\t \\n\";\n $contents .= \" \\n\";\n\n while($tutorRecords = $db->fetchNextObject($totallogs)){\n\n $contents .= \"\".$tutorRecords->id.\" \\t \".$tutorRecords->tutor_first_name.' '.$tutorRecords->tutor_last_name.\" \\t \".$tutorRecords->first_name.' '.$tutorRecords->last_name.\" \\t \".$tutorRecords->first.' '.$tutorRecords->last.\" \\t \".$globalsConstant['type_of_tutoring'][$tutorRecords->type_of_tutoring].\" \\t \".date(MDY,$tutorRecords->date_of_tutoring_session).\" \\t \".str_replace('.',':',$tutorRecords->hours_tutored).\" \\t \".str_replace('.',':',$tutorRecords->billable_travel).\" \\t \".str_replace('.',':',$tutorRecords->billable_additional).\" \\t \".str_replace('.',':',$tutorRecords->total_billable).\" \\t \".CURRENCY.$tutorRecords->rate.\" \\t \".CURRENCY.$tutorRecords->tutor_pay_rate.\" \\t \\n\";\n\n }\n\n header('Content-type: application/ms-excel');\n header('Content-Disposition: attachment; filename='.$filename);\n echo $contents;\n ?>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20826/" ]
279,919
<p>Is there a C function call that can change the last modified date of a file or directory in Windows?</p>
[ { "answer_id": 279931, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "BOOL WINAPI SetFileTime(\n __in HANDLE hFile,\n __in_opt const FILETIME *lpCreationTime,\n __in_opt const FILETIME *lpLastAccessTime,\n __in_opt const FILETIME *lpLastWriteTime\n);\n" }, { "answer_id": 279944, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "hFolder = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING,\nFILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS, NULL);\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
279,945
<p>I have a file <code>test.txt</code> that is inside a zip archive <code>test.zip</code>. The permissions on <code>test.txt</code> are out of my control when it's compressed, but now I want them to be group-writeable. I am extracting the file with Python, and don't want to escape out to the shell.</p> <p><strong>EDIT:</strong> Here's what I've got so far:</p> <pre><code>import zipfile z = zipfile.ZipFile('test.zip', 'w') zi = zipfile.ZipInfo('test.txt') zi.external_attr = 0777 &lt;&lt; 16L z.writestr(zi, 'FOO') z.close() z = zipfile.ZipFile('test.zip', 'r') for name in z.namelist(): newFile = open(name, "wb") newFile.write(z.read(name)) newFile.close() z.close() </code></pre> <p>This works perfectly on OS X using 2.5.1, but it doesn't work on my home box (Debian, Python 2.4 &amp; 2.5) or on RHEL 5 with Python 2.4. On anything but OS X it doesn't error, but doesn't change the permissions either. Any ideas why? Also, how does <code>writestr()</code> work? I know I'm using it incorrectly here.</p> <p>Is there a way to do this without <code>os.chmod</code> (the user extracting the file doesn't have permissions to use <code>os.chmod</code> after it's extracted)? I have full write access to the zip file.</p> <p>More info:</p> <pre><code>&gt; ls -l test.zip -rwxrwxrwx 1 myuser mygroup 2008-11-11 13:24 test.zip &gt; unzip test.zip Archive: test.zip inflating: test.txt &gt; ls -l test.txt -rw-r--r-- 1 myuser mygroup 2008-11-11 13:34 test.txt </code></pre> <p>The user extracting is not <code>myuser</code>, but is in <code>mygroup</code>.</p>
[ { "answer_id": 279985, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 0, "selected": false, "text": "for n in `unzip -l test.zip | awk 'NR > 3 && NF == 4 { print $4 }'`; do unzip -p test.zip $n > $n; done\n" }, { "answer_id": 596455, "author": "Petriborg", "author_id": 2815, "author_profile": "https://Stackoverflow.com/users/2815", "pm_score": 3, "selected": false, "text": "# extract all of the zip\nfor file in zf.filelist:\n name = file.filename\n perm = ((file.external_attr >> 16L) & 0777)\n if name.endswith('/'):\n outfile = os.path.join(dir, name)\n os.mkdir(outfile, perm)\n else:\n outfile = os.path.join(dir, name)\n fh = os.open(outfile, os.O_CREAT | os.O_WRONLY , perm)\n os.write(fh, zf.read(name))\n os.close(fh)\n print \"Extracting: \" + outfile\n" }, { "answer_id": 66880535, "author": "Mike T", "author_id": 327026, "author_profile": "https://Stackoverflow.com/users/327026", "pm_score": 1, "selected": false, "text": "import os\nimport zipfile\n\nzip_file = \"/path/to/archive.zip\"\nout_dir = \"/path/to/output\"\n\nos.makedirs(out_dir, exist_ok=True)\n\nwith zipfile.ZipFile(zip_file, \"r\") as zf:\n for file in zf.filelist:\n name = file.filename\n perm = ((file.external_attr >> 16) & 0o777)\n print(\"Extracting: \" + name)\n if name.endswith(\"/\"):\n os.mkdir(os.path.join(out_dir, name), perm)\n else:\n outfile = os.path.join(out_dir, name)\n fh = os.open(outfile, os.O_CREAT | os.O_WRONLY, perm)\n os.write(fh, zf.read(name))\n os.close(fh)\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1057/" ]
279,953
<p>I am using a service component through ASP.NET MVC. I would like to send the email in a asynchronous way to let the user do other stuff without having to wait for the sending.</p> <p>When I send a message without attachments it works fine. When I send a message with at least one in-memory attachment it fails.</p> <p>So, I would like to know if it is possible to use an async method with in-memory attachments.</p> <p>Here is the sending method</p> <pre><code> public static void Send() { MailMessage message = new MailMessage("from@foo.com", "too@foo.com"); using (MemoryStream stream = new MemoryStream(new byte[64000])) { Attachment attachment = new Attachment(stream, "my attachment"); message.Attachments.Add(attachment); message.Body = "This is an async test."; SmtpClient smtp = new SmtpClient("localhost"); smtp.Credentials = new NetworkCredential("foo", "bar"); smtp.SendAsync(message, null); } } </code></pre> <p>Here is my current error</p> <pre><code> System.Net.Mail.SmtpException: Failure sending mail. ---> System.NotSupportedException: Stream does not support reading. at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result) --- End of inner exception stack trace --- </code></pre> <hr> <p>Solution</p> <pre><code> public static void Send() { MailMessage message = new MailMessage("from@foo.com", "to@foo.com"); MemoryStream stream = new MemoryStream(new byte[64000]); Attachment attachment = new Attachment(stream, "my attachment"); message.Attachments.Add(attachment); message.Body = "This is an async test."; SmtpClient smtp = new SmtpClient("localhost"); //smtp.Credentials = new NetworkCredential("login", "password"); smtp.SendCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { if (e.Error != null) { System.Diagnostics.Trace.TraceError(e.Error.ToString()); } MailMessage userMessage = e.UserState as MailMessage; if (userMessage != null) { userMessage.Dispose(); } }; smtp.SendAsync(message, message); } </code></pre>
[ { "answer_id": 41071322, "author": "sweetfa", "author_id": 490614, "author_profile": "https://Stackoverflow.com/users/490614", "pm_score": 0, "selected": false, "text": " public event EventHandler EmailSendCancelled = delegate { };\n\n public event EventHandler EmailSendFailure = delegate { };\n\n public event EventHandler EmailSendSuccess = delegate { };\n ...\n\n MemoryStream mem = new MemoryStream();\n try\n {\n thisReport.ExportToPdf(mem);\n\n // Create a new attachment and put the PDF report into it.\n mem.Seek(0, System.IO.SeekOrigin.Begin);\n //Attachment att = new Attachment(mem, \"MyOutputFileName.pdf\", \"application/pdf\");\n Attachment messageAttachment = new Attachment(mem, thisReportName, \"application/pdf\");\n\n // Create a new message and attach the PDF report to it.\n MailMessage message = new MailMessage();\n message.Attachments.Add(messageAttachment);\n\n // Specify sender and recipient options for the e-mail message.\n message.From = new MailAddress(NOES.Properties.Settings.Default.FromEmailAddress, NOES.Properties.Settings.Default.FromEmailName);\n message.To.Add(new MailAddress(toEmailAddress, NOES.Properties.Settings.Default.ToEmailName));\n\n // Specify other e-mail options.\n //mail.Subject = thisReport.ExportOptions.Email.Subject;\n message.Subject = subject;\n message.Body = body;\n\n // Send the e-mail message via the specified SMTP server.\n SmtpClient smtp = new SmtpClient();\n smtp.SendCompleted += SmtpSendCompleted;\n smtp.SendAsync(message, message);\n }\n catch (Exception)\n {\n if (mem != null)\n {\n mem.Dispose();\n mem.Close();\n }\n throw;\n }\n }\n\n private void SmtpSendCompleted(object sender, AsyncCompletedEventArgs e)\n {\n var message = e.UserState as MailMessage;\n if (message != null)\n {\n foreach (var attachment in message.Attachments)\n {\n if (attachment != null)\n {\n attachment.Dispose();\n }\n }\n message.Dispose();\n }\n if (e.Cancelled)\n EmailSendCancelled?.Invoke(this, EventArgs.Empty);\n else if (e.Error != null)\n {\n EmailSendFailure?.Invoke(this, EventArgs.Empty);\n throw e.Error;\n }\n else\n EmailSendSuccess?.Invoke(this, EventArgs.Empty);\n }\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195872/" ]
279,959
<p>I have an entry in my .vimrc which makes it page down the viewport when I hit the spacebar. It looks like this:</p> <pre><code>map &lt;Space&gt; &lt;PageDown&gt; </code></pre> <p>I want to create another key mapping which pages the viewport up when holding shift and hitting the spacebar. I have tried the following entries:</p> <pre><code>map &lt;Shift&gt;&lt;Space&gt; &lt;PageUp&gt; map &lt;S-Space&gt; &lt;PageUp&gt; </code></pre> <p>Neither work. Anybody know how to achieve this functionality?</p>
[ { "answer_id": 279973, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "map <Space> ^D \" Pagedown when press Space\nmap <S-Space> ^U \" Page Up when press Shift Space\n" }, { "answer_id": 7701779, "author": "Steve McKinney", "author_id": 139683, "author_profile": "https://Stackoverflow.com/users/139683", "pm_score": 2, "selected": false, "text": "nnoremap <Space> <C-d>\nnnoremap <S-Space> <C-u>\n" }, { "answer_id": 63084982, "author": "ebk", "author_id": 4710226, "author_profile": "https://Stackoverflow.com/users/4710226", "pm_score": 1, "selected": false, "text": ":h timeout - { key: Space, mods: Shift, chars: \"\\x5c\\x08 \" } showkey -a \\^H 92 0134 0x5c \n 8 0010 0x08 \n 32 0040 0x20\n no <Bslash><C-h><Space> <C-b> vno <Bslash><C-h><Space> <C-b>" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476/" ]
279,962
<p>How can I export a GridView's data to a Microsoft Excel 2007 file?</p> <p>Also, does Microsoft Excel 2007 support html elements and tags?</p>
[ { "answer_id": 280012, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "Response.ContentType = \"application/vnd.ms-excel\";\n Response.AppendHeader(\"Content-disposition\", \"attachment; filename=my.xls\");\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36430/" ]
279,966
<p>I am building a PHP application in CodeIgniter. CodeIgniter sends all requests to the main controller: <code>index.php</code>. However, I don't like to see <code>index.php</code> in the URI. For example, <code>http://www.example.com/faq/whatever</code> will route to <code>http://www.example.com/index.php/faq/whatever</code>. I need a reliable way for a script to know what it's address is, so it will know what to do with the navigation. I've used <code>mod_rewrite</code>, as per CodeIgniter documentation.</p> <p>The rule is as follows:</p> <pre><code>RewriteEngine on RewriteCond $1 !^(images|inc|favicon\.ico|index\.php|robots\.txt) RewriteRule ^(.*)$ /index.php/$1 [L] </code></pre> <p>Normally, I would just check <code>php_self</code>, but in this case it's always <code>index.php</code>. I can get it from <code>REQUEST_URI</code>, <code>PATH_INFO</code>, etc., but I'm trying to decide which will be most reliable. Does anyone know (or know where to find) the real difference between <code>PHP_SELF</code>, <code>PATH_INFO</code>, <code>SCRIPT_NAME</code>, and <code>REQUEST_URI</code>? Thanks for your help!</p> <p><strong>Note</strong>: I've had to add spaces, as SO sees the underscore, and makes it italic for some reason. </p> <p><strong>Updated</strong>: Fixed the spaces.</p>
[ { "answer_id": 279986, "author": "Xenph Yan", "author_id": 264, "author_profile": "https://Stackoverflow.com/users/264", "pm_score": 2, "selected": false, "text": "$REQUEST_URI" }, { "answer_id": 280068, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 3, "selected": false, "text": "http://example.com/index.php/news/local/345\n /news/local/345\n" }, { "answer_id": 326331, "author": "Odin", "author_id": 41640, "author_profile": "https://Stackoverflow.com/users/41640", "pm_score": 8, "selected": false, "text": "[PHP_SELF] => /test.php/foo/bar\n[SCRIPT_NAME] => /test.php\n [SCRIPT_NAME] => /test.php\n[REQUEST_URI] => /test.php?foo=bar\n [REQUEST_URI] => /test.php\n[SCRIPT_NAME] => /test2.php\n [REQUEST_URI] => /test.php\n[SCRIPT_NAME] => /404error.php\n [SCRIPT_NAME] => /404error.php\n[REQUEST_URI] => /404error.php?404;http://example.com/test.php\n" }, { "answer_id": 395687, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "RewriteEngine on\nRewriteCond $1 !^(images|inc|favicon\\.ico|index\\.php|robots\\.txt)\nRewriteRule ^(.*)$ /index.php?url=$1 [L]\n $_GET['url'];" }, { "answer_id": 9600525, "author": "Mike", "author_id": 949747, "author_profile": "https://Stackoverflow.com/users/949747", "pm_score": 5, "selected": false, "text": "PATH_INFO RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !^(favicon\\.ico|robots\\.txt)\nRewriteRule ^(.*)$ index.php/$1 [L]\n [SCRIPT_NAME] => /index.php\n [PHP_SELF] => /index.php\n[PATH_INFO] IS NOT AVAILABLE (fallback to REQUEST_URI in your script)\n[REQUEST_URI] => /\n[QUERY_STRING] => \n [PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /test\n[QUERY_STRING] => \n [PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /test?123\n[QUERY_STRING] => 123\n RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !^(favicon\\.ico|robots\\.txt)\nRewriteRule ^(.*)$ index.php?url=$1 [L,QSA]\n [SCRIPT_NAME] => /index.php\n[PHP_SELF] => /index.php\n[PATH_INFO] IS NOT AVAILABLE (fallback to REQUEST_URI in your script)\n [REQUEST_URI] => /\n[QUERY_STRING] => \n [REQUEST_URI] => /test\n[QUERY_STRING] => url=test\n [REQUEST_URI] => /test?123\n[QUERY_STRING] => url=test&123\n RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !^(favicon\\.ico|robots\\.txt)\nRewriteRule ^(([a-z]{2})|(([a-z]{2})/)?(.*))$ index.php/$5 [NC,L,E=LANGUAGE:$2$4]\n RewriteRule ^([a-z]{2})(/(.*))?$ $3 [NC,L,E=LANGUAGE:$1]\n\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !^(favicon\\.ico|robots\\.txt)\nRewriteRule ^(.*)$ index.php/$1 [L]\n [SCRIPT_NAME] => /index.php\n [PHP_SELF] => /index.php\n[PATH_INFO] IS NOT AVAILABLE (fallback to REQUEST_URI in your script)\n[REQUEST_URI] => /\n[QUERY_STRING] => \n[REDIRECT_LANGUAGE] IS NOT AVAILABLE\n [PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /test\n[QUERY_STRING] => \n[REDIRECT_LANGUAGE] => \n [PHP_SELF] => /index.php/\n[PATH_INFO] => /\n[REQUEST_URI] => /en\n[QUERY_STRING] => \n[REDIRECT_LANGUAGE] => en\n [PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /en/test\n[REDIRECT_LANGUAGE] => en\n [PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /en/test?123\n[QUERY_STRING] => 123\n[REDIRECT_LANGUAGE] => en\n" }, { "answer_id": 29553868, "author": "Beejor", "author_id": 3672465, "author_profile": "https://Stackoverflow.com/users/3672465", "pm_score": 4, "selected": false, "text": "  $_SERVER['REQUEST_URI']      $_SERVER['PHP_SELF']      $_SERVER['SCRIPT_NAME']      $_SERVER['SCRIPT_FILENAME']     __FILE__    /var/www/index.php /index.php http://foo.com/index.php /index.php?foo=bar REQUEST_URI PHP_SELF PHP_SELF SCRIPT_FILENAME PATH_INFO SCRIPT_FILENAME __FILE__" }, { "answer_id": 34303983, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "/var/www/test/php/script.php <?php\ninclude (\"script_included.php\")\n?>\n /var/www/test/php/script_included.php <?php\necho \"REQUEST_URI: \" . $_SERVER['REQUEST_URI'] . \"<br>\"; \necho \"PHP_SELF: \" . $_SERVER['PHP_SELF'] . \"<br>\";\necho \"QUERY_STRING: \" . $_SERVER['QUERY_STRING'] . \"<br>\";\necho \"SCRIPT_NAME: \" . $_SERVER['SCRIPT_NAME'] . \"<br>\";\necho \"PATH_INFO: \" . $_SERVER['PATH_INFO'] . \"<br>\";\necho \"SCRIPT_FILENAME: \" . $_SERVER['SCRIPT_FILENAME'] . \"<br>\";\necho \"__FILE__ : \" . __FILE__ . \"<br>\"; \n?>\n /var/www/test/.htaccess RewriteEngine On\nRewriteRule before_rewrite/script.php/path/(.*) after_rewrite/script.php/path/$1 \n Alias /test/after_rewrite/ /var/www/test/php/\n www.example.com/test/before_rewrite/script.php/path/info?q=helloword\n REQUEST_URI: /test/before_rewrite/script.php/path/info?q=helloword\nPHP_SELF: /test/after_rewrite/script.php/path/info\nQUERY_STRING: q=helloword\nSCRIPT_NAME: /test/after_rewrite/script.php\nPATH_INFO: /path/info\nSCRIPT_FILENAME: /var/www/test/php/script.php\n__FILE__ : /var/www/test/php/script_included.php\n PHP_SELF = SCRIPT_NAME + PATH_INFO = full url path between domain and query string. \n REQUEST_URI = PHP_SELF + ? + QUERY_STRING \n SCRIPT_FILENAME __FILE__ PATH_INFO SCRIPT_NAME SCRIPT_FILENAME [PHP_SELF] = [SCRIPT_NAME] + [PATH_INFO] Alias \\index.php \\var\\www\\index.php" }, { "answer_id": 51481605, "author": "AbsoluteƵERØ", "author_id": 2145800, "author_profile": "https://Stackoverflow.com/users/2145800", "pm_score": 1, "selected": false, "text": "_inf0.php <?php\n $my_ip = '0.0.0.0';\n\n if($_SERVER['REMOTE_ADDR']==$my_ip){\n phpinfo();\n } else {\n //something\n }\n /_inf0.php?q=500" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
279,974
<p>I'm finding myself writing a bunch of related functions dealing with different nouns (clusters, sql servers, servers in general, files, etc.) and put each of these groups of functions in separate files (say cluster_utils.ps1, for example). I want to be able to "import" some of these libraries in my profile and others in my powershell session if I need them. I have written 2 functions that seem to solve the problem, but since I've only been using powershell for a month I thought I'd ask to see if there were any existing "best practice" type scripts I could be using instead.</p> <p>To use these functions, I dot-source them (in my profile or my session)... for example,</p> <pre><code># to load c:\powershellscripts\cluster_utils.ps1 if it isn't already loaded . require cluster_utils </code></pre> <p>Here are the functions:</p> <pre><code>$global:loaded_scripts=@{} function require([string]$filename){ if (!$loaded_scripts[$filename]){ . c:\powershellscripts\$filename.ps1 $loaded_scripts[$filename]=get-date } } function reload($filename){ . c:\powershellscripts\$filename.ps1 $loaded_scripts[$filename]=get-date } </code></pre> <p>Any feedback would be helpful.</p>
[ { "answer_id": 282098, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "$global:scriptdirectory= 'c:\\powershellscripts'\n$global:loaded_scripts=@{}\nfunction require(){\n param ([string]$filename, [string]$path=$scriptdirectory)\n if (!$loaded_scripts[$filename]){\n . (Join-Path $path $filename)\n $loaded_scripts[$filename]=get-date\n }\n}\n\nfunction reload(){\n param ([string]$filename, [string]$path=$scriptdirectory)\n . (Join-Path $path $filename)\n $loaded_scripts[$filename]=get-date\n}\n" }, { "answer_id": 293947, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 4, "selected": true, "text": "$global:scriptdirectory = 'C:\\powershellscripts'\n$global:loaded_scripts = @{}\n\nfunction require {\n param(\n [string[]]$filenames=$(throw 'Please specify scripts to load'),\n [string]$path=$scriptdirectory\n )\n\n $unloadedFilenames = $filenames | where { -not $loaded_scripts[$_] }\n reload $unloadedFilenames $path\n}\n\nfunction reload {\n param(\n [string[]]$filenames=$(throw 'Please specify scripts to reload'),\n [string]$path=$scriptdirectory\n )\n\n foreach( $filename in $filenames ) {\n . (Join-Path $path $filename)\n $loaded_scripts[$filename] = Get-Date\n }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36429/" ]
279,988
<p>If i try to paste source code in word 2007 the spacing between the lines seems to get messed up as all new lines are spaced way apart compared to a programming text editor.</p> <p>Can somebody tell me how to paste source code in word 2007 preserving the formatting and the spacing between lines?</p>
[ { "answer_id": 446085, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 0, "selected": false, "text": "2html.vim source $VIM/syntax/2html.vim\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14316/" ]
279,991
<p>Please tell me how can save a string with special characters to DB.Special characters may contatin single <code>quotes/double quotes</code> etc.. I am using ASP.NET with C#</p>
[ { "answer_id": 280025, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "Using (SqlConnection conn = new SqlConnection(connstr))\n{\n Using (SqlCommand command = new SqlCommand(\"INSERT INTO FOO (col) VALUES (@arg)\"))\n {\n command.Connection = conn;\n command.Parameters.AddWithValue(\"@arg\",SpecialCharsString);\n command.ExecuteNonQuery();\n }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/279991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
280,003
<p>Preferably in VB.Net, but C# is fine, how can I access the extra properties added to a file by my digital camera, like <code>Date Picture Taken</code>, <code>Shutter Speed</code> or <code>Camera Model</code>?</p>
[ { "answer_id": 280117, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 1, "selected": false, "text": "BitmapMetadata System.Windows.Media.Imaging BitmapMetadata" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16415/" ]
280,014
<p>I have a script which logs on to a remote server and tries to rename files, using PHP.</p> <p>The code currently looks something like this example from the php.net website:</p> <pre><code>if (ftp_rename($conn_id, $old_file, $new_file)) { echo "successfully renamed $old_file to $new_file\n"; } else { echo "There was a problem while renaming $old_file to $new_file\n"; } </code></pre> <p>but ... what was the error? Permissions, no such directory, disk full?</p> <p>How can I get PHP to return the FTP error? Something like this:</p> <pre><code>echo "There was a problem while renaming $old_file to $new_file: the server says $error_message\n"; </code></pre>
[ { "answer_id": 12910495, "author": "Peter Hopfgartner", "author_id": 1630567, "author_profile": "https://Stackoverflow.com/users/1630567", "pm_score": 4, "selected": false, "text": "$trackErrors = ini_get('track_errors');\nini_set('track_errors', 1);\nif (!@ftp_put($my_ftp_conn_id, $tmpRemoteFileName, $localFileName, FTP_BINARY)) {\n // error message is now in $php_errormsg\n $msg = $php_errormsg;\n ini_set('track_errors', $trackErrors);\n throw new Exception($msg);\n}\nini_set('track_errors', $trackErrors);\n" }, { "answer_id": 56710674, "author": "jsherk", "author_id": 570759, "author_profile": "https://Stackoverflow.com/users/570759", "pm_score": 3, "selected": false, "text": "if (ftp_rename($conn_id, $old_file, $new_file)) {\n echo \"successfully renamed $old_file to $new_file\\n\";\n} else {\n echo \"There was a problem while renaming $old_file to $new_file\\n\";\n print_r( error_get_last() ); // ADDED THIS LINE\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242241/" ]
280,033
<p>I am new to C++ and I had a few general questions about code separation. I have currently built a small application, all in one file. What I want to do now is convert this into separate files such that they contain similar code or whatnot. My real question right now is, how do I know how to separate things? What is the invisible margin that code should be separated at? </p> <p>Also, what's the point of header files? Is it to forward declare methods and classes so I can use them in my code before they are included by the linker during compilation? </p> <p>Any insight into methods or best practises would be great, thanks!</p>
[ { "answer_id": 280048, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 5, "selected": false, "text": "Menu.h: Contains the Menu declaration.\nMenu.cpp: Contains the Menu definition.\n" }, { "answer_id": 280054, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 2, "selected": false, "text": "// A.h\nclass A\n{\npublic:\n int fn();\n};\n // A.cpp\n#include \"A.h\"\nint A::fn() {/* implementation of fn */}\n\n//B.cpp\n#include \"A.h\"\nvoid OtherFunction() {\n A a;\n a.fn();\n}\n // B.cpp\n#include \"A.cpp\" //DON'T do this!\n" }, { "answer_id": 280099, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": false, "text": "foo.hpp: /* Only declaration of class foo we define below. Note that a declaration\n * is not a definition. But a definition is always also a declaration */\nclass foo;\n\n/* definition of a class foo. the same class definition can appear \n in multiple translation units provided that each definition is the same \n basicially, but only once per translation unit. This too is called the \n \"One Definition Rule\" (ODR). */\nclass foo {\n /* declaration of a member function doit */\n void doit();\n\n /* definition of an data-member age */\n int age;\n};\n /* if you have translation unit non-local (with so-called extern linkage) \n names, you declare them here, so other translation units can include \n your file \"foo.hpp\" and use them. */\nvoid getTheAnswer();\n\n/* to avoid that the following is a definition of a object, you put \"extern\" \n in front of it. */\nextern int answerCheat;\n foo.cpp: /* include the header of it */\n#include \"foo.hpp\"\n\n/* definition of the member function doit */\nvoid foo::doit() {\n /* ... */\n}\n\n/* definition of a translation unit local name. preferred way in c++. */\nnamespace {\n void help() {\n /* ... */\n }\n}\n\nvoid getTheAnswer() {\n /* let's call our helper function */\n help();\n /* ... */\n}\n\n/* define answerCheat. non-const objects are translation unit nonlocal \n by default */\nint answerCheat = 42;\n bar.hpp: /* so, this is the same as above, just with other classes/files... */\nclass bar {\npublic:\n bar(); /* constructor */\n}; \n bar.cpp: /* we need the foo.hpp file, which declares getTheAnswer() */\n#include \"foo.hpp\"\n#include \"bar.hpp\"\n\nbar::bar() {\n /* make use of getTheAnswer() */\n getTheAnswer();\n}\n static void help() { \n /* .... */\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
280,049
<p>I want to know when an image has finished loading. Is there a way to do it with a callback?</p> <p>If not, is there a way to do it at all?</p>
[ { "answer_id": 280087, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 6, "selected": false, "text": " window.onload = function () {\n\n var logo = document.getElementById('sologo');\n\n logo.onload = function () {\n alert (\"The image has loaded!\"); \n };\n\n setTimeout(function(){\n logo.src = 'https://edmullen.net/test/rc.jpg'; \n }, 5000);\n }; <html>\n <head>\n <title>Image onload()</title>\n </head>\n <body>\n\n <img src=\"#\" alt=\"This image is going to load\" id=\"sologo\"/>\n\n <script type=\"text/javascript\">\n\n </script>\n </body>\n </html>" }, { "answer_id": 280142, "author": "Jon DellOro", "author_id": 36456, "author_profile": "https://Stackoverflow.com/users/36456", "pm_score": 4, "selected": false, "text": "var gAllImages = [];\n\nfunction makeThumbDivs(thumbnailsBegin, thumbnailsEnd)\n{\n gAllImages = [];\n\n for (var i = thumbnailsBegin; i < thumbnailsEnd; i++) \n {\n var theImage = new Image();\n theImage.src = \"thumbs/\" + getFilename(globals.gAllPageGUIDs[i]);\n gAllImages.push(theImage);\n\n setTimeout('checkForAllImagesLoaded()', 5);\n window.status=\"Creating thumbnail \"+(i+1)+\" of \" + thumbnailsEnd;\n\n // make a new div containing that image\n makeASingleThumbDiv(globals.gAllPageGUIDs[i]);\n }\n}\n\nfunction checkForAllImagesLoaded()\n{\n for (var i = 0; i < gAllImages.length; i++) {\n if (!gAllImages[i].complete) {\n var percentage = i * 100.0 / (gAllImages.length);\n percentage = percentage.toFixed(0).toString() + ' %';\n\n userMessagesController.setMessage(\"loading... \" + percentage);\n setTimeout('checkForAllImagesLoaded()', 20);\n return;\n }\n }\n\n userMessagesController.setMessage(globals.defaultTitle);\n}\n" }, { "answer_id": 13053752, "author": "dave", "author_id": 1771857, "author_profile": "https://Stackoverflow.com/users/1771857", "pm_score": 0, "selected": false, "text": "DrawThumbnails ThumbnailImageArray addThumbnailImages(10); var ThumbnailImageArray = [];\n\nfunction addThumbnailImages(MaxNumberOfImages)\n{\n var imgs = [];\n\n for (var i=1; i<MaxNumberOfImages; i++)\n {\n imgs.push(i+\".jpeg\");\n }\n\n preloadimages(imgs).done(function (images){\n var c=0;\n\n for(var i=0; i<images.length; i++)\n {\n if(images[i].width >0) \n {\n if(c != i)\n images[c] = images[i];\n c++;\n }\n }\n\n images.length = c;\n\n DrawThumbnails();\n });\n}\n\n\n\nfunction preloadimages(arr)\n{\n var loadedimages=0\n var postaction=function(){}\n var arr=(typeof arr!=\"object\")? [arr] : arr\n\n function imageloadpost()\n {\n loadedimages++;\n if (loadedimages==arr.length)\n {\n postaction(ThumbnailImageArray); //call postaction and pass in newimages array as parameter\n }\n };\n\n for (var i=0; i<arr.length; i++)\n {\n ThumbnailImageArray[i]=new Image();\n ThumbnailImageArray[i].src=arr[i];\n ThumbnailImageArray[i].onload=function(){ imageloadpost();};\n ThumbnailImageArray[i].onerror=function(){ imageloadpost();};\n }\n //return blank object with done() method \n //remember user defined callback functions to be called when images load\n return { done:function(f){ postaction=f || postaction } };\n}\n" }, { "answer_id": 24201249, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 8, "selected": false, "text": ".complete var img = document.querySelector('img')\n\nfunction loaded() {\n alert('loaded')\n}\n\nif (img.complete) {\n loaded()\n} else {\n img.addEventListener('load', loaded)\n img.addEventListener('error', function() {\n alert('error')\n })\n}\n" }, { "answer_id": 42946530, "author": "Alexander Drobyshevsky", "author_id": 1693748, "author_profile": "https://Stackoverflow.com/users/1693748", "pm_score": 2, "selected": false, "text": "var $img = $('img');\n\nif ($img.length > 0 && !$img.get(0).complete) {\n $img.on('load', triggerAction);\n}\n\nfunction triggerAction() {\n alert('img has been loaded');\n}\n" }, { "answer_id": 48208414, "author": "Idan Beker", "author_id": 7932878, "author_profile": "https://Stackoverflow.com/users/7932878", "pm_score": 4, "selected": false, "text": "function waitForImageToLoad(imageElement){\n return new Promise(resolve=>{imageElement.onload = resolve})\n}\n\nvar myImage = document.getElementById('myImage');\nvar newImageSrc = \"https://pmchollywoodlife.files.wordpress.com/2011/12/justin-bieber-bio-photo1.jpg?w=620\"\n\nmyImage.src = newImageSrc;\nwaitForImageToLoad(myImage).then(()=>{\n // Image have loaded.\n console.log('Loaded lol')\n}); <img id=\"myImage\" src=\"\">" }, { "answer_id": 50569577, "author": "Mike", "author_id": 232115, "author_profile": "https://Stackoverflow.com/users/232115", "pm_score": -1, "selected": false, "text": "render() {\n <img \nonLoad={() => this.onImgLoad({ item })}\nonError={() => this.onImgLoad({ item })}\n\nsrc={item.src} key={item.key}\nref={item.key} />\n" }, { "answer_id": 60971078, "author": "Sajad", "author_id": 4205231, "author_profile": "https://Stackoverflow.com/users/4205231", "pm_score": 2, "selected": false, "text": "const img = new Image();\nimg.src = 'path/to/img.jpg';\n\nimg.decode().then(() => {\n/* set styles */\n/* add img to DOM */ \n});\n loads the compressed version of image decodes it paints paint decoded" }, { "answer_id": 62185013, "author": "Hugh", "author_id": 8930534, "author_profile": "https://Stackoverflow.com/users/8930534", "pm_score": 2, "selected": false, "text": "async function newImageSrc(src) {\n // Get a reference to the image in whatever way suits.\n let image = document.getElementById('image-id');\n\n // Update the source.\n img.src = src;\n\n // Wait for it to load.\n await new Promise((resolve) => { image.onload = resolve; });\n\n // Done!\n console.log('image loaded! do something...');\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
280,053
<p>Please help! Have been staring at this for 12 hours; and have looked online and can't find solution.</p> <p>In my application, I use 2 UIView controls in separate pages/controllers:</p> <ul> <li>UIImageView (retrieve data via NSData dataWithContentsOfUrl)</li> <li>UIWebView</li> </ul> <p>Just to isolate my code, and make it easier to explain, I created a new view based project called "MyTestApplication"</p> <p>1 - I added a simple NSData dataWithContentsOfUrl in the delegate function.</p> <pre><code>NSData *imageData = [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://www.google.com/intl/en_ALL/images/logo.gif"]]; </code></pre> <p>(Nothing to release here since it's all using convenience functions)</p> <p><a href="http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.preview.jpg" rel="nofollow noreferrer">alt text http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.preview.jpg</a></p> <p><a href="http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.jpg" rel="nofollow noreferrer">View Image</a></p> <p>2 - Run it to verify no leaks (as expected)</p> <p><a href="http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.preview.jpg" rel="nofollow noreferrer">alt text http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.preview.jpg</a></p> <p><a href="http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.jpg" rel="nofollow noreferrer">View Image</a></p> <p>3 - Open the ViewController.xib and simply add a UIWebView from the library (no need to wire it up)</p> <p><a href="http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.preview.jpg" rel="nofollow noreferrer">alt text http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.preview.jpg</a></p> <p><a href="http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.jpg" rel="nofollow noreferrer">View Image</a></p> <p>4 - Run it to verify there are leaks! (why???)</p> <p><a href="http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.preview.jpg" rel="nofollow noreferrer">alt text http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.preview.jpg</a></p> <p><a href="http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.jpg" rel="nofollow noreferrer">View Image</a></p> <p>What am I doing wrong? Please help!</p> <p>Why would NSData cause memory leak if I'm using UIWebView? I just don't get it. Thanks. </p>
[ { "answer_id": 1442691, "author": "Sam", "author_id": 101750, "author_profile": "https://Stackoverflow.com/users/101750", "pm_score": 3, "selected": false, "text": "dataWithContentsOfURL: dataWithContentsOfURL:options:error: NSURL *url = [NSURL URLWithString:urlString];\nNSError *error = nil;\nNSData *data = [NSData dataWithContentsOfURL:url\n options:0\n error:&error];\n" }, { "answer_id": 30437935, "author": "palob", "author_id": 395963, "author_profile": "https://Stackoverflow.com/users/395963", "pm_score": 0, "selected": false, "text": "[NSData dataWithContentsOfURL:url options:0 error:&error] NSURLRequest* request = [NSURLRequest requestWithURL:imageURL];\nNSData* imageData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];\n[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
280,058
<p>Basically I need to insert a bunch of data to an Excel file. Creating an OleDB connection appears to be the fastest way but I've seen to have run into memory issues. The memory used by the process seems to keep growing as I execute INSERT queries. I've narrowed them down to only happen when I output to the Excel file (the memory holds steady without the output to Excel). I close and reopen the connection in between each worksheet, but this doesn't seem to have an effect on the memory usage (as so does Dispose()). The data is written successfully as I can verify with relatively small data sets. If anyone has insight, it would be appreciated.</p> <p><em>initializeADOConn()</em> is called in the constructor</p> <p><em>initADOConnInsertComm()</em> creates the insert parameterized insert query</p> <p><em>writeRecord()</em> is called whenever a new record is written. New worksheets are created as needed.</p> <pre><code>public bool initializeADOConn() { /* Set up the connection string and connect.*/ string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + this.destination + ";Extended Properties=\"Excel 8.0;HDR=YES;\""; //DbProviderFactory factory = //DbProviderFactories.GetFactory("System.Data.OleDb"); conn = new OleDbConnection(connectionString); conn.ConnectionString = connectionString; conn.Open(); /* Intialize the insert command. */ initADOConnInsertComm(); return true; } public override bool writeRecord(FileListerFileInfo file) { /* If all available sheets are full, make a new one. */ if (numWritten % EXCEL_MAX_ROWS == 0) { conn.Close(); conn.Open(); createNextSheet(); } /* Count this record as written. */ numWritten++; /* Get all of the properties of the FileListerFileInfo record and add * them to the parameters of the insert query. */ PropertyInfo[] properties = typeof(FileListerFileInfo).GetProperties(); for (int i = 0; i &lt; insertComm.Parameters.Count; i++) insertComm.Parameters[i].Value = properties[i].GetValue(file, null); /* Add the record. */ insertComm.ExecuteNonQuery(); return true; } </code></pre> <p>EDIT:</p> <p>No, I do not use Excel at all. I'm intentionally avoiding Interop.Excel due to its poor performance (at least from my dabbles with it).</p>
[ { "answer_id": 280348, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 1, "selected": false, "text": "CREATE TABLE CREATE TABLE [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable \n(\n x FLOAT\n);\n INSERT INSERT INTO [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable (x) \n VALUES (0);\n INSERT INSERT INTO MyExcelTable (key_col, data_col)\nSELECT DT1.key_col, DT1.data_col\nFROM (\n SELECT 22 AS key_col, 'abc' AS data_col\n FROM [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable\n UNION ALL\n SELECT 55 AS key_col, 'xyz' AS data_col\n FROM [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable\n UNION ALL\n SELECT 99 AS key_col, 'efg' AS data_col\n FROM [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable\n) AS DT1;\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469014/" ]
280,069
<p>I'm writing a C++ program that doesn't work (I get a segmentation fault) when I compile it with optimizations (options -O1, -O2, -O3, etc.), but it works just fine when I compile it without optimizations.</p> <p>Is there any chance that the error is in my code? or should I assume that this is a bug in GCC?</p> <p>My GCC version is 3.4.6.</p> <p>Is there any known workaround for this kind of problem?</p> <p>There is a big difference in speed between the optimized and unoptimized version of my program, so I really need to use optimizations.</p> <hr> <p>This is my original functor. The one that works fine with no levels of optimizations and throws a segmentation fault with any level of optimization:</p> <pre><code>struct distanceToPointSort{ indexedDocument* point ; distanceToPointSort(indexedDocument* p): point(p) {} bool operator() (indexedDocument* p1,indexedDocument* p2){ return distance(point,p1) &lt; distance(point,p2) ; } } ; </code></pre> <p>And this one works flawlessly with any level of optimization:</p> <pre><code>struct distanceToPointSort{ indexedDocument* point ; distanceToPointSort(indexedDocument* p): point(p) {} bool operator() (indexedDocument* p1,indexedDocument* p2){ float d1=distance(point,p1) ; float d2=distance(point,p2) ; std::cout &lt;&lt; "" ; //without this line, I get a segmentation fault anyways return d1 &lt; d2 ; } } ; </code></pre> <p>Unfortunately, this problem is hard to reproduce because it happens with some specific values. I get the segmentation fault upon sorting just one out of more than a thousand vectors, so it really depends on the specific combination of values each vector has.</p>
[ { "answer_id": 280080, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "-Wall -Wextra -ansi -pedantic" }, { "answer_id": 280082, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": " g++ -Wall -Wextra -pedantic -ansi\n" }, { "answer_id": 280219, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\n\nint main()\n{\n int i = 0, j = 1, k = 2;\n printf(\"%d %d %d\\n\", *(&j-1), *(&j), *(&j+1));\n return 0;\n}\n" }, { "answer_id": 280895, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "std::vector<T*>" }, { "answer_id": 282455, "author": "GetFree", "author_id": 25700, "author_profile": "https://Stackoverflow.com/users/25700", "pm_score": 1, "selected": false, "text": "struct distanceToPointSort{\n indexedDocument* point ;\n distanceToPointSort(indexedDocument* p): point(p) {}\n bool operator() (indexedDocument* p1,indexedDocument* p2){\n return distance(point,p1) < distance(point,p2) ;\n }\n} ;\n struct distanceToPointSort{\n indexedDocument* point ;\n distanceToPointSort(indexedDocument* p): point(p) {}\n bool operator() (indexedDocument* p1,indexedDocument* p2){\n\n float d1=distance(point,p1) ;\n float d2=distance(point,p2) ;\n\n std::cout << \"\" ; //without this line, I get a segmentation fault anyways\n\n return d1 < d2 ;\n }\n} ;\n" }, { "answer_id": 282508, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 3, "selected": false, "text": "volatile float d1=distance(point,p1) ;\nvolatile float d2=distance(point,p2) ;\nreturn d1 < d2 ;\n" }, { "answer_id": 283937, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 4, "selected": true, "text": "-ffloat-store" }, { "answer_id": 1426017, "author": "Ringding", "author_id": 135811, "author_profile": "https://Stackoverflow.com/users/135811", "pm_score": 0, "selected": false, "text": "distanceToPointSort -mfpmath=sse sort -ffloat-store" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25700/" ]
280,075
<p>I'm trying to implement (what I think is) a pretty simple data model for a counter:</p> <pre><code>class VisitorDayTypeCounter(models.Model): visitType = models.CharField(max_length=60) visitDate = models.DateField('Visit Date') counter = models.IntegerField() </code></pre> <p>When someone comes through, it will look for a row that matches the visitType and visitDate; if this row doesn't exist, it will be created with counter=0.</p> <p>Then we increment the counter and save.</p> <p>My concern is that this process is totally a race. Two requests could simultaneously check to see if the entity is there, and both of them could create it. Between reading the counter and saving the result, another request could come through and increment it (resulting in a lost count).</p> <p>So far I haven't really found a good way around this, either in the Django documentation or in the tutorial (in fact, it looks like the tutorial has a race condition in the Vote part of it).</p> <p>How do I do this safely?</p>
[ { "answer_id": 280125, "author": "Daniel Naab", "author_id": 32638, "author_profile": "https://Stackoverflow.com/users/32638", "pm_score": 3, "selected": false, "text": "class VisitorDayTypeCounter(models.Model):\n visitType = models.CharField(max_length=60)\n visitDate = models.DateField('Visit Date')\n counter = models.IntegerField()\n class Meta:\n unique_together = (('visitType', 'visitDate'))\n" }, { "answer_id": 282868, "author": "iconoplast", "author_id": 36683, "author_profile": "https://Stackoverflow.com/users/36683", "pm_score": 2, "selected": true, "text": "class VisitorDayTypeCounterManager(models.Manager):\n def get_query_set(self):\n qs = super(VisitorDayTypeCounterManager, self).get_query_set()\n\n from django.db import connection\n cursor = connection.cursor()\n\n pk_list = qs.values_list('id', flat=True)\n cursor.execute('UPDATE table_name SET counter = counter + 1 WHERE id IN %s', [pk_list])\n\n return qs\n\nclass VisitorDayTypeCounter(models.Model):\n ...\n\n objects = VisitorDayTypeCounterManager()\n" }, { "answer_id": 370552, "author": "kmmbvnr", "author_id": 46548, "author_profile": "https://Stackoverflow.com/users/46548", "pm_score": 3, "selected": false, "text": "visitors = VisitorDayTypeCounter.objects.get(day=curday).for_update()\nvisitors.counter += 1\nvisitors.save()\n" }, { "answer_id": 1955700, "author": "bjunix", "author_id": 80254, "author_profile": "https://Stackoverflow.com/users/80254", "pm_score": 5, "selected": false, "text": "from django.db.models import F\nproduct = Product.objects.get(name='Venezuelan Beaver Cheese')\nproduct.number_sold = F('number_sold') + 1\nproduct.save()\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13868/" ]
280,101
<p>What are the best ways (or at least most common ways) in ASP (VBScript) for input handling? My main concerns are HTML/JavaScript injections &amp; SQL injections. Is there some equivalent to PHP's <code>htmlspecialchars</code> or <code>addslashes</code>, et cetera? Or do I have to do it manually with something like string replace functions?</p>
[ { "answer_id": 280259, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "Server.HTMLEncode() ÀDODB.Command ADODB.CommandParameter" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25413/" ]
280,106
<p>I am implementing a Comment box facility in my application which user can resize using mouse. This comment box contains a scrollpane which instead contains a <code>JEditorPane</code> in which user can insert comment. I have added the editor pane inside a scroll pane for the following reason:</p> <p><a href="https://stackoverflow.com/questions/271881/auto-scolling-of-jeditorpane">auto scolling of jeditorpane</a></p> <p>When the user resizes the comment box, I am setting the desired size for <code>JScrollPane</code> and the <code>JEditorPane</code>. When the user is increasing the size of the comment box, the size of these components are increasing as desired but when the size of the comment box is decreased, the size of the <code>JEditorPane</code> does not decrease even after setting the size. This leads to the scrollbars inside the scrollpane.</p> <p>I tried using <code>setPreferrredSize</code>, <code>setSize</code>, <code>setMaximumSize</code> for <code>JEditorPane</code>. Still the size of the editor pane is not reducing. I tried calling <code>revalidate()</code> or <code>updateUI()</code> after the setting of size but no use. </p> <p>I am using Java 1.4.2. </p> <p>Please provide me some insight....</p>
[ { "answer_id": 1525149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public static void main(String...args) {\n //our test frame\n JFrame frame = new JFrame(\"JEditorPane inside JScrollPane resizing\");\n frame.setLayout(new BorderLayout());\n\n //our editing pane\n final JEditorPane editor = new JEditorPane();\n\n //our simple scroll pane\n final JScrollPane scroller = new JScrollPane(editor);\n\n //NOTE: this is the magic that is kind of a workaround\n // you can also implement your own type of JScrollPane\n // using the JScrollBar and a JViewport which is the \n // preferred method of doing something like this the \n // other option is to create a JEditorPane subclass that\n // implements the Scrollable interface.\n scroller.addComponentListener(new ComponentAdapter() {\n @Override\n public void componentResized(ComponentEvent e) {\n editor.setSize(new Dimension(\n scroller.getWidth()-20, \n scroller.getHeight()-20));\n }\n });\n\n //just use up the entire frame area.\n frame.add(scroller, BorderLayout.CENTER);\n\n //quick and dirty close event handler\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(320, 240); //something not too big\n frame.setLocationRelativeTo(null); //centers window on screen\n frame.setVisible(true); // normally done in a SwingUtilities.invokeLater\n}\n" }, { "answer_id": 7889617, "author": "Mike B", "author_id": 214756, "author_profile": "https://Stackoverflow.com/users/214756", "pm_score": 3, "selected": false, "text": "getScrollableTracksViewportWidth() JEditorPane pane = new JEditorPane() {\n public boolean getScrollableTracksViewportWidth() {\n return true;\n }\n};\npanel.add(new JScrollPane(pane));\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22550/" ]
280,107
<p>I have often heard this term being used, but I have never really understood it.</p> <p>What does it mean, and can anyone give some examples/point me to some links?</p> <p>EDIT: Thanks to everyone for the replies. Can you also tell me how the canonical representation is useful in equals() performance, as stated in Effective Java?</p>
[ { "answer_id": 361827, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 6, "selected": false, "text": "myFile.txt # in current working dir\n../conf/myFile.txt # relative to the CWD\n/apps/tomcat/conf/myFile.txt # absolute path using symbolic links\n/u1/local/apps/tomcat-5.5.1/conf/myFile.txt # absolute path with no symlinks\n equals() String.intern() if (day == Days.SUNDAY) Days" }, { "answer_id": 11776328, "author": "Chris Mawata", "author_id": 1571210, "author_profile": "https://Stackoverflow.com/users/1571210", "pm_score": 3, "selected": false, "text": "a.equals(b) a == b a==b a.equals(b) a.equals(b)" }, { "answer_id": 12388260, "author": "Michael Marton", "author_id": 1507781, "author_profile": "https://Stackoverflow.com/users/1507781", "pm_score": 5, "selected": false, "text": "{true, false, 1, 0} {true, false} \"true\" \"1\" \"true\" \"false\" \"0\" \"false\"" }, { "answer_id": 52898626, "author": "The Gilbert Arenas Dagger", "author_id": 2860319, "author_profile": "https://Stackoverflow.com/users/2860319", "pm_score": 0, "selected": false, "text": "equals public final class CaseInsensitiveString {\n\n private final String s;\n\n public CaseInsensitiveString(String s) {\n this.s = Objects.requireNonNull(s);\n }\n\n @Override \n public boolean equals(Object o) {\n return o instanceof CaseInsensitiveString && ((CaseInsensitiveString) o).s.equalsIgnoreCase(s);\n }\n}\n equals String equalsIgnoreCase String CaseInsensitiveString String CaseInsensitiveString equals hashcode" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9195/" ]
280,109
<p>I'm creating a data entry app for some in-house stuff.</p> <p>My team needs to enter info about "items" which can have many "categories" and vice versa.</p> <p>I need a quick way to let them enter an arbitrary amount of categories.</p> <p>Here's my idea:</p> <p>On the item entry page, I'll have it so that initially there's one text input for "categories" and if it's tabbed out of while it's empty, the input field is deleted (unless it's the only one) and focus skips to the next field. If it's <em>not</em> empty when it's tabbed out of <strong>and</strong> if it's the last input field in the array, then an additional "category" text input will be added and focused.</p> <p>This way people can enter an arbitrary amount of categories really quickly, without taking their hands off the keyboard, just by typing and hitting tab. Then hitting tab twice to denote the end of the list.</p> <p>First of all, what do you think of this interface? Is there a better way to do it?</p> <p>Second of all, is there a jQuery (or something) plugin to do this? I've searched but can't find one. I searched scriptaculous/prototype and mootools too, with no luck.</p> <p>I would obviously rather use something tried and tested than roll my own.</p> <p>Any and all advice appreciated</p>
[ { "answer_id": 361827, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 6, "selected": false, "text": "myFile.txt # in current working dir\n../conf/myFile.txt # relative to the CWD\n/apps/tomcat/conf/myFile.txt # absolute path using symbolic links\n/u1/local/apps/tomcat-5.5.1/conf/myFile.txt # absolute path with no symlinks\n equals() String.intern() if (day == Days.SUNDAY) Days" }, { "answer_id": 11776328, "author": "Chris Mawata", "author_id": 1571210, "author_profile": "https://Stackoverflow.com/users/1571210", "pm_score": 3, "selected": false, "text": "a.equals(b) a == b a==b a.equals(b) a.equals(b)" }, { "answer_id": 12388260, "author": "Michael Marton", "author_id": 1507781, "author_profile": "https://Stackoverflow.com/users/1507781", "pm_score": 5, "selected": false, "text": "{true, false, 1, 0} {true, false} \"true\" \"1\" \"true\" \"false\" \"0\" \"false\"" }, { "answer_id": 52898626, "author": "The Gilbert Arenas Dagger", "author_id": 2860319, "author_profile": "https://Stackoverflow.com/users/2860319", "pm_score": 0, "selected": false, "text": "equals public final class CaseInsensitiveString {\n\n private final String s;\n\n public CaseInsensitiveString(String s) {\n this.s = Objects.requireNonNull(s);\n }\n\n @Override \n public boolean equals(Object o) {\n return o instanceof CaseInsensitiveString && ((CaseInsensitiveString) o).s.equalsIgnoreCase(s);\n }\n}\n equals String equalsIgnoreCase String CaseInsensitiveString String CaseInsensitiveString equals hashcode" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
280,115
<p>I am creating menus in WPF programatically using vb.net. Can someone show me how I can add separator bar to a menu in code? No xaml please.</p>
[ { "answer_id": 280194, "author": "Jeff Donnici", "author_id": 821, "author_profile": "https://Stackoverflow.com/users/821", "pm_score": 7, "selected": true, "text": "using System.Windows.Controls;\n\n//\n\nMenu myMenu = new Menu();\nmyMenu.Items.Add(new Separator());\n" }, { "answer_id": 13658089, "author": "Adrian Toman", "author_id": 651104, "author_profile": "https://Stackoverflow.com/users/651104", "pm_score": 5, "selected": false, "text": "<Menu>\n <MenuItem Header=\"Menu Item 1\" />\n <Separator />\n <MenuItem Header=\"Menu Item 1\" />\n<Menu>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3566/" ]
280,127
<p>I'm bored with surrounding code with try catch like this..</p> <pre><code>try { //some boring stuff } catch(Exception ex) { //something even more boring stuff } </code></pre> <p>I would like something like</p> <pre><code>SurroundWithTryCatch(MyMethod) </code></pre> <p>I know I can accomplish this behaviour by creating a delegate with the exact signature of the function, but creating a delegate for all the methods in my application it's just not an option.</p> <p>I can also do this by injecting IL code but this is expensive in terms of performance as it creates an wrapper assembly around mine.</p> <p>Any other valid ideeas?</p>
[ { "answer_id": 280132, "author": "stiduck", "author_id": 35398, "author_profile": "https://Stackoverflow.com/users/35398", "pm_score": 2, "selected": false, "text": "var user = db.Users.SingleOrDefault(u => u.Username == 3);\n\nif (user == null)\n throw new ArgumentNullException(\"User\", \"User cannot be null.\");\n\n// \"else\" continue your code...\n" }, { "answer_id": 280165, "author": "Roopinder", "author_id": 31068, "author_profile": "https://Stackoverflow.com/users/31068", "pm_score": 0, "selected": false, "text": "ExceptionCatcher.catchAll(new Runnable() {\n public void run() {\n //run delegate here\n MyMethod();\n }\n});\n" }, { "answer_id": 280167, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "Exception System public void SurroundWithTryCatch(Action action)\n{\n try\n {\n action();\n }\n catch(Exception ex)\n {\n //something even more boring stuff\n } \n}\n SurroundWithTryCatch(MyMethod) public void MyMethod()\n{\n SurroundWithTryCatch(() => \n {\n // Logic here\n });\n}\n public int MyMethod()\n{\n return SurroundWithTryCatch(() => \n {\n // Logic here\n return 5;\n });\n}\n SurroundWithTryCatch public T SurroundWithTryCatch<T>(Func<T> func)\n{ \n try\n {\n return func();\n }\n catch(Exception ex)\n {\n //something even more boring stuff\n } \n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34296/" ]
280,162
<p>I have some low level serialization code that is templated, and I need to know the system's endianness at compiletime obviously (because the templates specializes based on the system's endianness). </p> <p>Right now I have a header with some platform defines, but I'd rather have someway to make assertions about endianness with some templated test (like a static_assert or boost_if). Reason being my code will need to be compiled and ran on a wide range of machines, of many specialized vendor, and probably devices that don't exist in 2008, so I can't really guess what might need to go into that header years down the road. And since the code-base has an expected lifetime of about 10 years. So I can't follow the code for-ever.</p> <p>Hopefully this makes my situation clear.</p> <p>So does anyone know of a compile-time test that can determine endianness, without relying on vendor specific defines?</p>
[ { "answer_id": 280164, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "BOOST_STATIC_ASSERT(!BIG_ENDIAN); static_assert" }, { "answer_id": 280526, "author": "Hasturkun", "author_id": 20270, "author_profile": "https://Stackoverflow.com/users/20270", "pm_score": 5, "selected": true, "text": "AC_C_BIGENDIAN WORDS_BIGENDIAN int is_big_endian()\n{\n union {\n long int l;\n char c[sizeof (long int)];\n } u;\n\n u.l = 1;\n\n if (u.c[sizeof(long int)-1] == 1)\n {\n return 1;\n }\n else\n return 0;\n}\n" }, { "answer_id": 54175491, "author": "Walter Whitman", "author_id": 10904636, "author_profile": "https://Stackoverflow.com/users/10904636", "pm_score": -1, "selected": false, "text": "const uint8_t IsLittleEndian = char (0x0001);\n #define IsLittleEndian char (0x0001)\n [low order/least significant byte][high order/most significant byte] [high order/most significant byte][low order/least significant byte] 0x1234 uint16_t [34][12] 0x1234 [12][34] #define __STDC_FORMAT_MACROS // Required for the MingW toolchain\n#include <iostream>\n#include <inttypes.h>\n\nconst uint8_t IsLittleEndian = char (0x0001);\n//#define IsLittleEndian char (0x0001)\n\nstd::string CurrentEndianMsg;\nstd::string OppositeEndianMsg;\n\ntemplate <typename IntegerType>\nvoid PrintIntegerDetails(IntegerType IntegerValue)\n{\n uint16_t SizeOfIntegerValue = sizeof(IntegerValue);\n int8_t i;\n\n std::cout << \"Integer size (in bytes): \" << SizeOfIntegerValue << \"\\n\";\n std::cout << \"Integer value (Decimal): \" << IntegerValue << \"\\n\";\n std::cout << \"Integer value (Hexidecimal): \";\n\n switch (SizeOfIntegerValue)\n {\n case 2: printf(\"0x%04X\\n\", (unsigned int) IntegerValue);\n break;\n case 4: printf(\"0x%08X\\n\", (unsigned int) IntegerValue);\n break;\n case 8: printf(\"0x%016\" PRIX64 \"\\n\", (uint64_t) IntegerValue);\n break;\n }\n\n std::cout << \"Integer stored in memory in byte order:\\n\";\n std::cout << \" \" << CurrentEndianMsg << \" processor [current]: \";\n\n for(i = 0; i < SizeOfIntegerValue; i++)https://stackoverflow.com/qhttps://stackoverflow.com/questions/280162/is-there-a-way-to-do-a-c-style-compile-time-assertion-to-determine-machines-e/54175491#54175491uestions/280162/is-there-a-way-to-do-a-c-style-compile-time-assertion-to-determine-machines-e/54175491#54175491\n {\n printf(\"%02X \", (((unsigned char*) &IntegerValue)[i]));\n }\n\n std::cout << \"\\n \" << OppositeEndianMsg << \" processor [simulated]: \";\n\n for(i = SizeOfIntegerValue - 1; i >= 0; i--)\n {\n printf(\"%02X \", (((unsigned char*) &IntegerValue)[i]));\n }\n\n std::cout << \"\\n\\n\";\n}\n\n\nint main()\n{\n uint16_t ValueUInt16a = 0x0001;\n uint16_t ValueUInt16b = 0x1234;\n uint32_t ValueUInt32a = 0x00000001;\n uint32_t ValueUInt32b = 0x12345678;\n uint64_t ValueUInt64a = 0x0000000000000001;\n uint64_t ValueUInt64b = 0x123456789ABCDEF0;\n\n std::cout << \"Current processor endianness: \";\n\n switch (IsLittleEndian) {\n case 0: CurrentEndianMsg = \"Big Endian\";\n OppositeEndianMsg = \"Little Endian\";\n break;\n case 1: CurrentEndianMsg = \"Little Endian\";\n OppositeEndianMsg = \"Big Endian\";\n break;\n }\n\n std::cout << CurrentEndianMsg << \"\\n\\n\";\n\n PrintIntegerDetails(ValueUInt16a);\n PrintIntegerDetails(ValueUInt16b);\n PrintIntegerDetails(ValueUInt32a);\n PrintIntegerDetails(ValueUInt32b);\n PrintIntegerDetails(ValueUInt64a);\n PrintIntegerDetails(ValueUInt64b);\n\n return 0;\n}\n\n Current processor endianness: Little Endian\n\nInteger size (in bytes): 2\nInteger value (Decinal): 1\nInteger value (Hexidecimal): 0x0001\nInteger stored in memory in byte order:\n Little Endian processor [current]: 01 00\n Big Endian processor [simulated]: 00 01\n\nInteger size (in bytes): 2\nInteger value (Decinal): 4660\nInteger value (Hexidecimal): 0x1234\nInteger stored in memory in byte order:\n Little Endian processor [current]: 34 12\n Big Endian processor [simulated]: 12 34\n\nInteger size (in bytes): 4\nInteger value (Decinal): 1\nInteger value (Hexidecimal): 0x00000001\nInteger stored in memory in byte order:\n Little Endian processor [current]: 01 00 00 00\n Big Endian processor [simulated]: 00 00 00 01\n\nInteger size (in bytes): 4\nInteger value (Decinal): 305419896\nInteger value (Hexidecimal): 0x12345678\nInteger stored in memory in byte order:\n Little Endian processor [current]: 78 56 34 12\n Big Endian processor [simulated]: 12 34 56 78\n\nInteger size (in bytes): 8\nInteger value (Decinal): 1\nInteger value (Hexidecimal): 0x0000000000000001\nInteger stored in memory in byte order:\n Little Endian processor [current]: 01 00 00 00 00 00 00 00\n Big Endian processor [simulated]: 00 00 00 00 00 00 00 01\n\nInteger size (in bytes): 8\nInteger value (Decinal): 13117684467463790320\nInteger value (Hexidecimal): 0x123456789ABCDEF0While the process\nInteger stored in memory in byte order:\n Little Endian processor [current]: F0 DE BC 9A 78 56 34 12\n Big Endian processor [simulated]: 12 34 56 78 9A BC DE F0\n\n #define __STDC_FORMAT_MACROS 16-Bit Value (Hex): 0x1234\n\nMemory Offset: [00] [01]\n ---------\nMemory Byte Values: [34] [12] <Little Endian>\n [12] [34] <Big Endian>\n\n================================================\n\n16-Bit Value (Hex): 0x0001\n\nMemory Offset: [00] [01]\n ---------\nMemory Byte Values: [01] [00] <Little Endian>\n [00] [01] <Big Endian>\n 0x0001 char (0x0001) Original 16-Bit Value: 0x0001\n\nStored in memory as: [01][00] <-- Little Endian\n [00][01] <-- Big Endian\n\nTruncate to char: [01][xx] <-- Little Endian\n [01] Final Result\n [00][xx] <-- Big Endian\n [00] Final Result\n #define __STDC_FORMAT_MACROS // Required for the MingW toolchain\n#include <iostream>\n#include <inttypes.h>\n\nstd::string CurrentEndianMsg;\nstd::string OppositeEndianMsg;\n\ntemplate <typename IntegerType>\nvoid PrintIntegerDetails(IntegerType IntegerValue)\n{\n uint16_t SizeOfIntegerValue = sizeof(IntegerValue);\n int8_t i;\n\n std::cout << \"Integer size (in bytes): \" << SizeOfIntegerValue << \"\\n\";\n std::cout << \"Integer value (Decimal): \" << IntegerValue << \"\\n\";\n std::cout << \"Integer value (Hexidecimal): \";\n\n switch (SizeOfIntegerValue)\n {\n case 2: printf(\"0x%04X\\n\", (unsigned int) IntegerValue);\n break;\n case 4: printf(\"0x%08X\\n\", (unsigned int) IntegerValue);\n break;\n case 8: printf(\"0x%016\" PRIX64 \"\\n\", (uint64_t) IntegerValue);\n break;\n }\n\n std::cout << \"Integer stored in memory in byte order:\\n\";\n std::cout << \" \" << CurrentEndianMsg << \" processor [current]: \";\n\n for(i = 0; i < SizeOfIntegerValue; i++)\n {\n printf(\"%02X \", (((unsigned char*) &IntegerValue)[i]));\n }\n\n std::cout << \"\\n \" << OppositeEndianMsg << \" processor [simulated]: \";\n\n for(i = SizeOfIntegerValue - 1; i >= 0; i--)\n {\n printf(\"%02X \", (((unsigned char*) &IntegerValue)[i]));\n }\n\n std::cout << \"\\n\\n\";\n}\n\n\nint main()\n{\n uint16_t ValueUInt16a = 0x0001;\n uint16_t ValueUInt16b = 0x1234;\n uint32_t ValueUInt32a = 0x00000001;\n uint32_t ValueUInt32b = 0x12345678;\n uint64_t ValueUInt64a = 0x0000000000000001;\n uint64_t ValueUInt64b = 0x123456789ABCDEF0;\n\n uint16_t EndianTestValue = 0x0001;\n uint8_t IsLittleEndian = ((unsigned char*) &EndianTestValue)[0];\n\n std::cout << \"Current processor endianness: \";\n\n switch (IsLittleEndian) {\n case 0: CurrentEndianMsg = \"Big Endian\";\n OppositeEndianMsg = \"Little Endian\";\n break;\n case 1: CurrentEndianMsg = \"Little Endian\";\n OppositeEndianMsg = \"Big Endian\";\n break;\n }\n\n std::cout << CurrentEndianMsg << \"\\n\\n\";\n\n PrintIntegerDetails(ValueUInt16a);\n PrintIntegerDetails(ValueUInt16b);\n PrintIntegerDetails(ValueUInt32a);\n PrintIntegerDetails(ValueUInt32b);\n PrintIntegerDetails(ValueUInt64a);\n PrintIntegerDetails(ValueUInt64b);\n\n return 0;\n}\n\n 0x0001" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
280,199
<p>The library should;</p> <ul> <li>Be easy to use and few lines of client code should accomplish much</li> <li>Be as platform independent as possible. (In case of future ports to other platforms)</li> <li>Have C++ bindings.</li> <li>Be mature and stable</li> </ul> <p>I would also like to be notified of most HID events through callbacks.</p> <p>I have considered the following alternatives:</p> <ul> <li>libhid - (Unfortunately?) this is GPL and cannot be used in my application.</li> <li>WDK - Seems to be a bit low-level for my use. I don’t need that kind of control.</li> <li>atusbhid - This has an appropriate level of abstraction, but it is firmly tied to the Windows messaging loop</li> </ul> <p>Are there other alternatives to offer?</p>
[ { "answer_id": 508526, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 2, "selected": false, "text": "HKML\\SYSTEM\\CCS\\Control\\DeviceClasses\\{4d1e55...}\\" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36112/" ]
280,201
<p>In a html page we use the head tag to add reference to our external .js files .. we can also include script tags in the body .. But how do we include our external .js file in a web user control?</p> <p>After little googling I got this. It works but is this the only way?</p> <pre><code>ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "MyUniquekey", @"&lt;script src=""myJsFile.js"" type=""text/javascript""&gt;&lt;/script&gt;", false); </code></pre> <p>-- Zuhaib</p>
[ { "answer_id": 280338, "author": "Phil Jenkins", "author_id": 35496, "author_profile": "https://Stackoverflow.com/users/35496", "pm_score": 3, "selected": true, "text": "Page.ClientScript.RegisterClientScriptInclude(\"key\", \"path/to/script.js\");\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25138/" ]
280,207
<p>I have an object.</p> <pre><code> fp = open(self.currentEmailPath, "rb") p = email.Parser.Parser() self._currentEmailParsedInstance= p.parse(fp) fp.close() </code></pre> <p>self.currentEmailParsedInstance, from this object I want to get the body of an email, text only no HTML....</p> <p>How do I do it?</p> <hr> <p>something like this? </p> <pre><code> newmsg=self._currentEmailParsedInstance.get_payload() body=newmsg[0].get_content....? </code></pre> <p>then strip the html from body. just what is that .... method to return the actual text... maybe I mis-understand you</p> <pre><code> msg=self._currentEmailParsedInstance.get_payload() print type(msg) </code></pre> <p>output = type 'list'</p> <hr> <p>the email </p> <p>Return-Path: <br> Received: from xx.xx.net (example) by mxx3.xx.net (xxx)<br> id 485EF65F08EDX5E12 for xxx@xx.com; Thu, 23 Oct 2008 06:07:51 +0200<br> Received: from xxxxx2 (ccc) by example.net (ccc) (authenticated as xxxx.xxx@example.com) id 48798D4001146189 for example.example@example-example.com; Thu, 23 Oct 2008 06:07:51 +0200<br> From: "example" <br> To: <br> Subject: FW: example Date: Thu, 23 Oct 2008 12:07:45 +0800<br> Organization: example Message-ID: &lt;001601c934c4$xxxx30$a9ff460a@xxx><br> MIME-Version: 1.0<br> Content-Type: multipart/mixed;<br> boundary="----=_NextPart_000_0017_01C93507.F6F64E30"<br> X-Mailer: Microsoft Office Outlook 11<br> X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3138<br> Thread-Index: Ack0wLaumqgZo1oXSBuIpUCEg/wfOAABAFEA </p> <p>This is a multi-part message in MIME format. </p> <p>------=_NextPart_000_0017_01C93507.F6F64E30<br> Content-Type: multipart/alternative;<br> boundary="----=_NextPart_001_0018_01C93507.F6F64E30" </p> <p>------=_NextPart_001_0018_01C93507.F6F64E30<br> Content-Type: text/plain;<br> charset="us-ascii"<br> Content-Transfer-Encoding: 7bit </p> <p>From: example.example[mailto:example@example.com]<br> Sent: Thursday, October 23, 2008 11:37 AM<br> To: xxxx@example.com<br> Subject: S/I for example(B/L<br> No.:4357-0120-810.044) </p> <p>Please find attached the example.doc), </p> <p>Thanks. </p> <p>B.rgds, </p> <p>xxx xxx </p> <p>------=_NextPart_001_0018_01C93507.F6F64E30<br> Content-Type: text/html;<br> charset="us-ascii"<br> Content-Transfer-Encoding: quoted-printable </p> <p> xmlns:o=3D"urn:schemas-microsoft-com:office:office" =<br> xmlns:w=3D"urn:schemas-microsoft-com:office:word" =<br> xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" =<br> xmlns=3D"<a href="http://www.w3.org/TR/REC-html40" rel="nofollow noreferrer">http://www.w3.org/TR/REC-html40</a>"> </p> <p>HTML STUFF till </p> <p>------=_NextPart_001_0018_01C93507.F6F64E30-- </p> <p>------=_NextPart_000_0017_01C93507.F6F64E30<br> Content-Type: application/msword;<br> name="xxxx.doc"<br> Content-Transfer-Encoding: base64<br> Content-Disposition: attachment;<br> filename="xxxx.doc" </p> <p>0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAYAAAAAAAAAAA EAAAYgAAAAEAAAD+////AAAAAF8AAAD///////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////s pcEAI2AJBAAA+FK/AAAAAAAAEAAAAAAABgAAnEIAAA4AYmpiaqEVoRUAAAAAAAAAAAAAAAAAAAAA AAAECBYAMlAAAMN/AADDfwAAQQ4AAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAKQAAAAAAEYEAAAAAAAARgQAAEYE AAAAAAAARgQAAAAAAABGBAAAAAAAAEYEAAAAAAAARgQAABQAAAAAAAAAAAAAAFoEAAAAAAAA4hsA AAAAAADiGwAAAAAAAOIbAAA4AAAAGhwAAHwAAACWHAAARAAAAFoEAAAAAAAABzcAAEgBAADmHAAA FgAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAA AAAAMjYAAAIAAAA0NgAAAAAAADQ2AAAAAAAANDYAAAAAAAA0NgAAAAAAADQ2AAAAAAAANDYAACQA AABPOAAAaAIAALc6AACOAAAAWDYAAGkAAAAAAAAAAAAAAAAAAAAAAAAARgQAAAAAAABHLAAAAAAA AAAAAAAAAAAAAAAAAAAAAAD8HAAAAAAAAPwcAAAAAAAARywAAAAAAABHLAAAAAAAAFg2AAAAAAAA</p> <p>------=_NextPart_000_0017_01C93507.F6F64E30-- </p> <hr> <p>I just want to get : </p> <p>From: xxxx.xxxx [mailto:xxxx@example.com]<br> Sent: Thursday, October 23, 2008 11:37 AM<br> To: xxxx@example.com<br> Subject: S/I for xxxxx (B/L<br> No.:4357-0120-810.044) </p> <p>Pls find attached the xxxx.doc), </p> <p>Thanks. </p> <p>B.rgds, </p> <p>xxx xxx </p> <hr> <p>not sure if the mail is malformed! seems if you get an html page you have to do this:</p> <pre><code> parts=self._currentEmailParsedInstance.get_payload() print parts[0].get_content_type() ..._multipart/alternative_ textParts=parts[0].get_payload() print textParts[0].get_content_type() ..._text/plain_ body=textParts[0].get_payload() print body ...get the text without a problem!! </code></pre> <p>thank you so much Vinko.</p> <p>So its kinda like dealing with xml, recursive in nature.</p>
[ { "answer_id": 280238, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "self.currentEmailParsedInstance.get_payload()\n >>> parser = email.parser.Parser()\n>>> message = parser.parse(open('/home/vinko/jlm.txt','r'))\n>>> message.is_multipart()\nTrue\n>>> parts = message.get_payload()\n>>> len(parts)\n2\n>>> parts[0].get_content_type()\n'text/plain'\n>>> parts[1].get_content_type()\n'message/rfc822'\n>>> parts[0].get_payload()\n'Message Text'\n" }, { "answer_id": 280562, "author": "Setori", "author_id": 21537, "author_profile": "https://Stackoverflow.com/users/21537", "pm_score": 0, "selected": false, "text": " parser = email.parser.Parser()\n self._email = parser.parse(open('/home/vinko/jlm.txt','r'))\n parts=self._email.get_payload()\n check=parts[0].get_content_type()\n if check == \"text/plain\":\n return parts[0].get_payload()\n elif check == \"multipart/alternative\":\n part=parts[0].get_payload()\n if part[0].get_content_type() == \"text/plain\":\n return part[0].get_payload()\n else:\n return \"cannot obtain the body of the email\"\n else:\n return \"cannot obtain the body of the email\"\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21537/" ]
280,222
<p>I have input consisting of a list of nested lists like this:</p> <pre><code>l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] </code></pre> <p>I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this:</p> <pre><code>[39, 6, 13, 50] </code></pre> <p>Then I want to sort based on these. So the output should be:</p> <pre><code>[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] </code></pre> <p>What's a nice pythonic way of doing this?</p>
[ { "answer_id": 280224, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "l.sort(key=sum_nested)\n sum_nested() def sum_nested(astruct):\n try: return sum(map(sum_nested, astruct))\n except TypeError:\n return astruct\n\n\nassert sum_nested([[([8, 9], 10), 11], 12]) == 50\n" }, { "answer_id": 280226, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "def asum(a):\n if isinstance(a, list):\n return sum(asum(x) for x in a)\n else:\n return a\n\nl = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]\nl.sort(key=asum)\nprint l\n" }, { "answer_id": 280865, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 5, "selected": true, "text": ">>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]\n>>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t\n...\n>>> sorted(l, key=asum)\n[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
280,229
<p>I want to add an item to an ASP.Net combobox using Javascript. I can retrieve the ID (No Masterpage). How can I add values to the combobox from Javascript? My present code looks like this.</p> <pre><code> //Fill the years (counting 100 from the first) function fillvarYear() { var dt = $('#txtBDate').val(); dt = dt.toString().substring(6); var ye = parseInt(dt); //Loop and add the next 100 years from the birth year to the combo for (var j = 1; j &lt;= 100; j++) { ye += 1; //Add one year to the year count var opt = document.createElement("OPTION"); opt.text = ye; opt.value = ye; document.form1.ddlYear.add(opt); } } </code></pre>
[ { "answer_id": 280520, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": true, "text": "string selectedValue = Request.Params[combobox.UniqueId]\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33052/" ]
280,243
<p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
[ { "answer_id": 280284, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": false, "text": "def mklist(*args):\n result = None\n for element in reversed(args):\n result = (element, result)\n return result\n" }, { "answer_id": 280286, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 6, "selected": false, "text": "#! /usr/bin/env python\n\nclass Node(object):\n def __init__(self):\n self.data = None # contains the data\n self.next = None # contains the reference to the next node\n\n\nclass LinkedList:\n def __init__(self):\n self.cur_node = None\n\n def add_node(self, data):\n new_node = Node() # create a new node\n new_node.data = data\n new_node.next = self.cur_node # link the new node to the 'previous' node.\n self.cur_node = new_node # set the current node to the new one.\n\n def list_print(self):\n node = self.cur_node # cant point to ll!\n while node:\n print node.data\n node = node.next\n\n\n\nll = LinkedList()\nll.add_node(1)\nll.add_node(2)\nll.add_node(3)\n\nll.list_print()\n" }, { "answer_id": 280572, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 1, "selected": false, "text": "ls = (1, 2, 3, 4, 5)\n\ndef first(ls): return ls[0]\ndef rest(ls): return ls[1:]\n" }, { "answer_id": 281294, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "__slots__ = '_head','_tail' >>> l = LinkedList([1,2,3,4])\n>>> l\nLinkedList([1, 2, 3, 4])\n>>> l.head, l.tail\n(1, LinkedList([2, 3, 4]))\n\n# Prepending is O(1) and can be done with:\nLinkedList.cons(0, l)\nLinkedList([0, 1, 2, 3, 4])\n# Or prepending arbitrary sequences (Still no copy of l performed):\n[-1,0] + l\nLinkedList([-1, 0, 1, 2, 3, 4])\n\n# Normal list indexing and slice operations can be performed.\n# Again, no copy is made unless needed.\n>>> l[1], l[-1], l[2:]\n(2, 4, LinkedList([3, 4]))\n>>> assert l[2:] is l.next.next\n\n# For cases where the slice stops before the end, or uses a\n# non-contiguous range, we do need to create a copy. However\n# this should be transparent to the user.\n>>> LinkedList(range(100))[-10::2]\nLinkedList([90, 92, 94, 96, 98])\n import itertools\n\nclass LinkedList(object):\n \"\"\"Immutable linked list class.\"\"\"\n\n def __new__(cls, l=[]):\n if isinstance(l, LinkedList): return l # Immutable, so no copy needed.\n i = iter(l)\n try:\n head = i.next()\n except StopIteration:\n return cls.EmptyList # Return empty list singleton.\n\n tail = LinkedList(i)\n\n obj = super(LinkedList, cls).__new__(cls)\n obj._head = head\n obj._tail = tail\n return obj\n\n @classmethod\n def cons(cls, head, tail):\n ll = cls([head])\n if not isinstance(tail, cls):\n tail = cls(tail)\n ll._tail = tail\n return ll\n\n # head and tail are not modifiable\n @property \n def head(self): return self._head\n\n @property\n def tail(self): return self._tail\n\n def __nonzero__(self): return True\n\n def __len__(self):\n return sum(1 for _ in self)\n\n def __add__(self, other):\n other = LinkedList(other)\n\n if not self: return other # () + l = l\n start=l = LinkedList(iter(self)) # Create copy, as we'll mutate\n\n while l:\n if not l._tail: # Last element?\n l._tail = other\n break\n l = l._tail\n return start\n\n def __radd__(self, other):\n return LinkedList(other) + self\n\n def __iter__(self):\n x=self\n while x:\n yield x.head\n x=x.tail\n\n def __getitem__(self, idx):\n \"\"\"Get item at specified index\"\"\"\n if isinstance(idx, slice):\n # Special case: Avoid constructing a new list, or performing O(n) length \n # calculation for slices like l[3:]. Since we're immutable, just return\n # the appropriate node. This becomes O(start) rather than O(n).\n # We can't do this for more complicated slices however (eg [l:4]\n start = idx.start or 0\n if (start >= 0) and (idx.stop is None) and (idx.step is None or idx.step == 1):\n no_copy_needed=True\n else:\n length = len(self) # Need to calc length.\n start, stop, step = idx.indices(length)\n no_copy_needed = (stop == length) and (step == 1)\n\n if no_copy_needed:\n l = self\n for i in range(start): \n if not l: break # End of list.\n l=l.tail\n return l\n else:\n # We need to construct a new list.\n if step < 1: # Need to instantiate list to deal with -ve step\n return LinkedList(list(self)[start:stop:step])\n else:\n return LinkedList(itertools.islice(iter(self), start, stop, step))\n else: \n # Non-slice index.\n if idx < 0: idx = len(self)+idx\n if not self: raise IndexError(\"list index out of range\")\n if idx == 0: return self.head\n return self.tail[idx-1]\n\n def __mul__(self, n):\n if n <= 0: return Nil\n l=self\n for i in range(n-1): l += self\n return l\n def __rmul__(self, n): return self * n\n\n # Ideally we should compute the has ourselves rather than construct\n # a temporary tuple as below. I haven't impemented this here\n def __hash__(self): return hash(tuple(self))\n\n def __eq__(self, other): return self._cmp(other) == 0\n def __ne__(self, other): return not self == other\n def __lt__(self, other): return self._cmp(other) < 0\n def __gt__(self, other): return self._cmp(other) > 0\n def __le__(self, other): return self._cmp(other) <= 0\n def __ge__(self, other): return self._cmp(other) >= 0\n\n def _cmp(self, other):\n \"\"\"Acts as cmp(): -1 for self<other, 0 for equal, 1 for greater\"\"\"\n if not isinstance(other, LinkedList):\n return cmp(LinkedList,type(other)) # Arbitrary ordering.\n\n A, B = iter(self), iter(other)\n for a,b in itertools.izip(A,B):\n if a<b: return -1\n elif a > b: return 1\n\n try:\n A.next()\n return 1 # a has more items.\n except StopIteration: pass\n\n try:\n B.next()\n return -1 # b has more items.\n except StopIteration: pass\n\n return 0 # Lists are equal\n\n def __repr__(self):\n return \"LinkedList([%s])\" % ', '.join(map(repr,self))\n\nclass EmptyList(LinkedList):\n \"\"\"A singleton representing an empty list.\"\"\"\n def __new__(cls):\n return object.__new__(cls)\n\n def __iter__(self): return iter([])\n def __nonzero__(self): return False\n\n @property\n def head(self): raise IndexError(\"End of list\")\n\n @property\n def tail(self): raise IndexError(\"End of list\")\n\n# Create EmptyList singleton\nLinkedList.EmptyList = EmptyList()\ndel EmptyList\n" }, { "answer_id": 282238, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 7, "selected": false, "text": "from collections import deque\nd = deque([1,2,3,4])\n\nprint d\nfor x in d:\n print x\nprint d.pop(), d\n" }, { "answer_id": 283630, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 7, "selected": true, "text": "cons = lambda el, lst: (el, lst)\nmklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)\ncar = lambda lst: lst[0] if lst else lst\ncdr = lambda lst: lst[1] if lst else lst\nnth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst)\nlength = lambda lst, count=0: length(cdr(lst), count+1) if lst else count\nbegin = lambda *args: args[-1]\ndisplay = lambda lst: begin(w(\"%s \" % car(lst)), display(cdr(lst))) if lst else w(\"nil\\n\")\n w = sys.stdout.write class Node: \n def __init__(self, cargo=None, next=None): \n self.car = cargo \n self.cdr = next \n def __str__(self): \n return str(self.car)\n\ndef display(lst):\n if lst:\n w(\"%s \" % lst)\n display(lst.cdr)\n else:\n w(\"nil\\n\")\n" }, { "answer_id": 3538133, "author": "Chris Redford", "author_id": 130427, "author_profile": "https://Stackoverflow.com/users/130427", "pm_score": 5, "selected": false, "text": "L = LinkedList()\nL.insert(1)\nL.insert(1)\nL.insert(2)\nL.insert(4)\nprint L\nL.clear()\nprint L\n LinkedList class Node:\n def __init__(self, value = None, next = None):\n self.value = value\n self.next = next\n\n def __str__(self):\n return 'Node ['+str(self.value)+']'\n\nclass LinkedList:\n def __init__(self):\n self.first = None\n self.last = None\n\n def insert(self, x):\n if self.first == None:\n self.first = Node(x, None)\n self.last = self.first\n elif self.last == self.first:\n self.last = Node(x, None)\n self.first.next = self.last\n else:\n current = Node(x, None)\n self.last.next = current\n self.last = current\n\n def __str__(self):\n if self.first != None:\n current = self.first\n out = 'LinkedList [\\n' +str(current.value) +'\\n'\n while current.next != None:\n current = current.next\n out += str(current.value) + '\\n'\n return out + ']'\n return 'LinkedList []'\n\n def clear(self):\n self.__init__()\n" }, { "answer_id": 6658636, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "def add_node_at_end(self, data):\n new_node = Node()\n node = self.curr_node\n while node:\n if node.next == None:\n node.next = new_node\n new_node.next = None\n new_node.data = data\n node = node.next\n" }, { "answer_id": 8367288, "author": "Y Lan", "author_id": 1078905, "author_profile": "https://Stackoverflow.com/users/1078905", "pm_score": 0, "selected": false, "text": "'''singly linked lists, by Yingjie Lan, December 1st, 2011'''\n\nclass linkst:\n '''Singly linked list, with pythonic features.\nThe list has pointers to both the first and the last node.'''\n __slots__ = ['data', 'next'] #memory efficient\n def __init__(self, iterable=(), data=None, next=None):\n '''Provide an iterable to make a singly linked list.\nSet iterable to None to make a data node for internal use.'''\n if iterable is not None: \n self.data, self.next = self, None\n self.extend(iterable)\n else: #a common node\n self.data, self.next = data, next\n\n def empty(self):\n '''test if the list is empty'''\n return self.next is None\n\n def append(self, data):\n '''append to the end of list.'''\n last = self.data\n self.data = last.next = linkst(None, data)\n #self.data = last.next\n\n def insert(self, data, index=0):\n '''insert data before index.\nRaise IndexError if index is out of range'''\n curr, cat = self, 0\n while cat < index and curr:\n curr, cat = curr.next, cat+1\n if index<0 or not curr:\n raise IndexError(index)\n new = linkst(None, data, curr.next)\n if curr.next is None: self.data = new\n curr.next = new\n\n def reverse(self):\n '''reverse the order of list in place'''\n current, prev = self.next, None\n while current: #what if list is empty?\n next = current.next\n current.next = prev\n prev, current = current, next\n if self.next: self.data = self.next\n self.next = prev\n\n def delete(self, index=0):\n '''remvoe the item at index from the list'''\n curr, cat = self, 0\n while cat < index and curr.next:\n curr, cat = curr.next, cat+1\n if index<0 or not curr.next:\n raise IndexError(index)\n curr.next = curr.next.next\n if curr.next is None: #tail\n self.data = curr #current == self?\n\n def remove(self, data):\n '''remove first occurrence of data.\nRaises ValueError if the data is not present.'''\n current = self\n while current.next: #node to be examined\n if data == current.next.data: break\n current = current.next #move on\n else: raise ValueError(data)\n current.next = current.next.next\n if current.next is None: #tail\n self.data = current #current == self?\n\n def __contains__(self, data):\n '''membership test using keyword 'in'.'''\n current = self.next\n while current:\n if data == current.data:\n return True\n current = current.next\n return False\n\n def __iter__(self):\n '''iterate through list by for-statements.\nreturn an iterator that must define the __next__ method.'''\n itr = linkst()\n itr.next = self.next\n return itr #invariance: itr.data == itr\n\n def __next__(self):\n '''the for-statement depends on this method\nto provide items one by one in the list.\nreturn the next data, and move on.'''\n #the invariance is checked so that a linked list\n #will not be mistakenly iterated over\n if self.data is not self or self.next is None:\n raise StopIteration()\n next = self.next\n self.next = next.next\n return next.data\n\n def __repr__(self):\n '''string representation of the list'''\n return 'linkst(%r)'%list(self)\n\n def __str__(self):\n '''converting the list to a string'''\n return '->'.join(str(i) for i in self)\n\n #note: this is NOT the class lab! see file linked.py.\n def extend(self, iterable):\n '''takes an iterable, and append all items in the iterable\nto the end of the list self.'''\n last = self.data\n for i in iterable:\n last.next = linkst(None, i)\n last = last.next\n self.data = last\n\n def index(self, data):\n '''TODO: return first index of data in the list self.\n Raises ValueError if the value is not present.'''\n #must not convert self to a tuple or any other containers\n current, idx = self.next, 0\n while current:\n if current.data == data: return idx\n current, idx = current.next, idx+1\n raise ValueError(data)\n" }, { "answer_id": 15182629, "author": "Brent O'Connor", "author_id": 176611, "author_profile": "https://Stackoverflow.com/users/176611", "pm_score": 2, "selected": false, "text": "class Node:\n\n def __init__(self, data=None):\n self.data = data\n self.next = None\n\n def __str__(self):\n return str(self.data)\n\n\nclass LinkedList:\n\n def __init__(self):\n self.head = None\n self.curr = None\n self.tail = None\n\n def __iter__(self):\n return self\n\n def next(self):\n if self.head and not self.curr:\n self.curr = self.head\n return self.curr\n elif self.curr.next:\n self.curr = self.curr.next\n return self.curr\n else:\n raise StopIteration\n\n def append(self, data):\n n = Node(data)\n if not self.head:\n self.head = n\n self.tail = n\n else:\n self.tail.next = n\n self.tail = self.tail.next\n\n\n# Add 5 nodes\nll = LinkedList()\nfor i in range(1, 6):\n ll.append(i)\n\n# print out the list\nfor n in ll:\n print n\n\n\"\"\"\nExample output:\n$ python linked_list.py\n1\n2\n3\n4\n5\n\"\"\"\n" }, { "answer_id": 17850004, "author": "bouzafr", "author_id": 2617240, "author_profile": "https://Stackoverflow.com/users/2617240", "pm_score": 0, "selected": false, "text": "class LinkedList:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n def insert(self, node):\n if not self.next:\n self.next = node\n else:\n self.next.insert(node)\n\n def __str__(self):\n if self.next:\n return '%s -> %s' % (self.value, str(self.next))\n else:\n return ' %s ' % self.value\n\nif __name__ == \"__main__\":\n items = ['a', 'b', 'c', 'd', 'e'] \n ll = None\n for item in items:\n if ll:\n next_ll = LinkedList(item)\n ll.insert(next_ll)\n else:\n ll = LinkedList(item)\n print('[ %s ]' % ll)\n" }, { "answer_id": 19008675, "author": "Thomas Levine", "author_id": 407226, "author_profile": "https://Stackoverflow.com/users/407226", "pm_score": 2, "selected": false, "text": "len" }, { "answer_id": 20658095, "author": "P. Luo", "author_id": 962910, "author_profile": "https://Stackoverflow.com/users/962910", "pm_score": 0, "selected": false, "text": "collections.deque llist class Node (object):\n \"\"\" Node for a linked list. \"\"\"\n def __init__ (self, value, next=None):\n self.value = value\n self.next = next\n\nclass LinkedList (object):\n \"\"\" Linked list ADT implementation using class. \n A linked list is a wrapper of a head pointer\n that references either None, or a node that contains \n a reference to a linked list.\n \"\"\"\n def __init__ (self, iterable=()):\n self.head = None\n for x in iterable:\n self.head = Node(x, self.head)\n\n def __iter__ (self):\n p = self.head\n while p is not None:\n yield p.value\n p = p.next\n\n def prepend (self, x): # 'appendleft'\n self.head = Node(x, self.head)\n\n def reverse (self):\n \"\"\" In-place reversal. \"\"\"\n p = self.head\n self.head = None\n while p is not None:\n p0, p = p, p.next\n p0.next = self.head\n self.head = p0\n\nif __name__ == '__main__':\n ll = LinkedList([6,5,4])\n ll.prepend(3); ll.prepend(2)\n print list(ll)\n ll.reverse()\n print list(ll)\n" }, { "answer_id": 24342598, "author": "user1244663", "author_id": 1244663, "author_profile": "https://Stackoverflow.com/users/1244663", "pm_score": 1, "selected": false, "text": "class LL(object):\n def __init__(self,val):\n self.val = val\n self.next = None\n\n def pushNodeEnd(self,top,val):\n if top is None:\n top.val=val\n top.next=None\n else:\n tmp=top\n while (tmp.next != None):\n tmp=tmp.next \n newNode=LL(val)\n newNode.next=None\n tmp.next=newNode\n\n def pushNodeFront(self,top,val):\n if top is None:\n top.val=val\n top.next=None\n else:\n newNode=LL(val)\n newNode.next=top\n top=newNode\n\n def popNodeFront(self,top):\n if top is None:\n return\n else:\n sav=top\n top=top.next\n return sav\n\n def popNodeEnd(self,top):\n if top is None:\n return\n else:\n tmp=top\n while (tmp.next != None):\n prev=tmp\n tmp=tmp.next\n prev.next=None\n return tmp\n\ntop=LL(10)\ntop.pushNodeEnd(top, 20)\ntop.pushNodeEnd(top, 30)\npop=top.popNodeEnd(top)\nprint (pop.val)\n" }, { "answer_id": 26088052, "author": "Adeel", "author_id": 1827883, "author_profile": "https://Stackoverflow.com/users/1827883", "pm_score": -1, "selected": false, "text": "class Node:\n def __init__(self, value=None, next=None):\n self.value = value\n self.next = next\n\n def __str__(self):\n return str(self.value)\n\n\nclass LinkedList:\n def __init__(self):\n self.first = None\n self.last = None\n\n def add(self, x):\n current = Node(x, None)\n try:\n self.last.next = current\n except AttributeError:\n self.first = current\n self.last = current\n else:\n self.last = current\n\n def print_list(self):\n node = self.first\n while node:\n print node.value\n node = node.next\n\nll = LinkedList()\nll.add(\"1st\")\nll.add(\"2nd\")\nll.add(\"3rd\")\nll.add(\"4th\")\nll.add(\"5th\")\n\nll.print_list()\n\n# Result: \n# 1st\n# 2nd\n# 3rd\n# 4th\n# 5th\n" }, { "answer_id": 26658719, "author": "Divesh Kumar", "author_id": 4199342, "author_profile": "https://Stackoverflow.com/users/4199342", "pm_score": -1, "selected": false, "text": "enter code here\nenter code here\n\nclass node:\n def __init__(self):\n self.data = None\n self.next = None\nclass linked_list:\n def __init__(self):\n self.cur_node = None\n self.head = None\n def add_node(self,data):\n new_node = node()\n if self.head == None:\n self.head = new_node\n self.cur_node = new_node\n new_node.data = data\n new_node.next = None\n self.cur_node.next = new_node\n self.cur_node = new_node\n def list_print(self):\n node = self.head\n while node:\n print (node.data)\n node = node.next\n def delete(self):\n node = self.head\n next_node = node.next\n del(node)\n self.head = next_node\na = linked_list()\na.add_node(1)\na.add_node(2)\na.add_node(3)\na.add_node(4)\na.delete()\na.list_print()\n" }, { "answer_id": 40072598, "author": "demosthenes", "author_id": 1261030, "author_profile": "https://Stackoverflow.com/users/1261030", "pm_score": 1, "selected": false, "text": "class LinkedStack:\n'''LIFO Stack implementation using a singly linked list for storage.'''\n\n_ToList = []\n\n#---------- nested _Node class -----------------------------\nclass _Node:\n '''Lightweight, nonpublic class for storing a singly linked node.'''\n __slots__ = '_element', '_next' #streamline memory usage\n\n def __init__(self, element, next):\n self._element = element\n self._next = next\n\n#--------------- stack methods ---------------------------------\ndef __init__(self):\n '''Create an empty stack.'''\n self._head = None\n self._size = 0\n\ndef __len__(self):\n '''Return the number of elements in the stack.'''\n return self._size\n\ndef IsEmpty(self):\n '''Return True if the stack is empty'''\n return self._size == 0\n\ndef Push(self,e):\n '''Add element e to the top of the Stack.'''\n self._head = self._Node(e, self._head) #create and link a new node\n self._size +=1\n self._ToList.append(e)\n\ndef Top(self):\n '''Return (but do not remove) the element at the top of the stack.\n Raise exception if the stack is empty\n '''\n\n if self.IsEmpty():\n raise Exception('Stack is empty')\n return self._head._element #top of stack is at head of list\n\ndef Pop(self):\n '''Remove and return the element from the top of the stack (i.e. LIFO).\n Raise exception if the stack is empty\n '''\n if self.IsEmpty():\n raise Exception('Stack is empty')\n answer = self._head._element\n self._head = self._head._next #bypass the former top node\n self._size -=1\n self._ToList.remove(answer)\n return answer\n\ndef Count(self):\n '''Return how many nodes the stack has'''\n return self.__len__()\n\ndef Clear(self):\n '''Delete all nodes'''\n for i in range(self.Count()):\n self.Pop()\n\ndef ToList(self):\n return self._ToList\n" }, { "answer_id": 40889052, "author": "Mina Gabriel", "author_id": 1410185, "author_profile": "https://Stackoverflow.com/users/1410185", "pm_score": 1, "selected": false, "text": "class LinkedStack:\n# Nested Node Class\nclass Node:\n def __init__(self, element, next):\n self.__element = element\n self.__next = next\n\n def get_next(self):\n return self.__next\n\n def get_element(self):\n return self.__element\n\ndef __init__(self):\n self.head = None\n self.size = 0\n self.data = []\n\ndef __len__(self):\n return self.size\n\ndef __str__(self):\n return str(self.data)\n\ndef is_empty(self):\n return self.size == 0\n\ndef push(self, e):\n newest = self.Node(e, self.head)\n self.head = newest\n self.size += 1\n self.data.append(newest)\n\ndef top(self):\n if self.is_empty():\n raise Empty('Stack is empty')\n return self.head.__element\n\ndef pop(self):\n if self.is_empty():\n raise Empty('Stack is empty')\n answer = self.head.element\n self.head = self.head.next\n self.size -= 1\n return answer\n from LinkedStack import LinkedStack\n\nx = LinkedStack()\n\nx.push(10)\nx.push(25)\nx.push(55)\n\n\nfor i in range(x.size - 1, -1, -1):\n\n print '|', x.data[i].get_element(), '|' ,\n #next object\n\n if x.data[i].get_next() == None:\n print '--> None'\n else:\n print x.data[i].get_next().get_element(), '-|----> ',\n | 55 | 25 -|----> | 25 | 10 -|----> | 10 | --> None\n" }, { "answer_id": 41977119, "author": "Sudhanshu Dev", "author_id": 3875597, "author_profile": "https://Stackoverflow.com/users/3875597", "pm_score": 2, "selected": false, "text": "class Node(object):\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\n def setData(self, data):\n self.data = data\n return self.data\n\n def setNext(self, next):\n self.next = next\n\n def getNext(self):\n return self.next\n\n def hasNext(self):\n return self.next != None\n\n\nclass singleLinkList(object):\n\n def __init__(self):\n self.head = None\n\n def isEmpty(self):\n return self.head == None\n\n def insertAtBeginning(self, data):\n newNode = Node()\n newNode.setData(data)\n\n if self.listLength() == 0:\n self.head = newNode\n else:\n newNode.setNext(self.head)\n self.head = newNode\n\n def insertAtEnd(self, data):\n newNode = Node()\n newNode.setData(data)\n\n current = self.head\n\n while current.getNext() != None:\n current = current.getNext()\n\n current.setNext(newNode)\n\n def listLength(self):\n current = self.head\n count = 0\n\n while current != None:\n count += 1\n current = current.getNext()\n return count\n\n def print_llist(self):\n current = self.head\n print(\"List Start.\")\n while current != None:\n print(current.getData())\n current = current.getNext()\n\n print(\"List End.\")\n\n\n\nif __name__ == '__main__':\n ll = singleLinkList()\n ll.insertAtBeginning(55)\n ll.insertAtEnd(56)\n ll.print_llist()\n print(ll.listLength())\n" }, { "answer_id": 42824275, "author": "Arovit", "author_id": 587088, "author_profile": "https://Stackoverflow.com/users/587088", "pm_score": 1, "selected": false, "text": "class Node:\n def __init__(self):\n self.data = None\n self.next = None\n def __str__(self):\n return \"Data %s: Next -> %s\"%(self.data, self.next)\n\nclass LinkedList:\n def __init__(self):\n self.head = Node()\n self.curNode = self.head\n def insertNode(self, data):\n node = Node()\n node.data = data\n node.next = None\n if self.head.data == None:\n self.head = node\n self.curNode = node\n else:\n self.curNode.next = node\n self.curNode = node\n def printList(self):\n print self.head\n\nl = LinkedList()\nl.insertNode(1)\nl.insertNode(2)\nl.insertNode(34)\n Data 1: Next -> Data 2: Next -> Data 34: Next -> Data 4: Next -> None\n" }, { "answer_id": 42993060, "author": "Farhad Maleki", "author_id": 5064004, "author_profile": "https://Stackoverflow.com/users/5064004", "pm_score": 3, "selected": false, "text": "dllist sllist first dllistnode None last dllistnode append(x) x dllistnode appendleft(x) x dllistnode appendright(x) x dllistnode clear() extend(iterable) iterable extendleft(iterable) iterable extendright(iterable) iterable insert(x[, before]) x before x dllistnode before dllistnode nodeat(index) dllistnode index pop() popleft() popright() remove(node) node dllistnode llist.dllistnode([value]) value dllistnode next prev value llist.sllist([iterable]) iterable sllist sllist" }, { "answer_id": 44469829, "author": "Andre Araujo", "author_id": 2452792, "author_profile": "https://Stackoverflow.com/users/2452792", "pm_score": 0, "selected": false, "text": "class node:\n def __init__(self, before=None, cargo=None, next=None): \n self._previous = before\n self._cargo = cargo \n self._next = next \n\n def __str__(self):\n return str(self._cargo) or None \n\nclass linkedList:\n def __init__(self): \n self._head = None \n self._length = 0\n\n def add(self, cargo):\n n = node(None, cargo, self._head)\n if self._head:\n self._head._previous = n\n self._head = n\n self._length += 1\n\n def search(self,cargo):\n node = self._head\n while (node and node._cargo != cargo):\n node = node._next\n return node\n\n def delete(self,cargo):\n node = self.search(cargo)\n if node:\n prev = node._previous\n nx = node._next\n if prev:\n prev._next = node._next\n else:\n self._head = nx\n nx._previous = None\n if nx:\n nx._previous = prev \n else:\n prev._next = None\n self._length -= 1\n\n def __str__(self):\n print 'Size of linked list: ',self._length\n node = self._head\n while node:\n print node\n node = node._next\n from linkedlist import node, linkedList\n\ndef test():\n\n print 'Testing Linked List'\n\n l = linkedList()\n\n l.add(10)\n l.add(20)\n l.add(30)\n l.add(40)\n l.add(50)\n l.add(60)\n\n print 'Linked List after insert nodes:'\n l.__str__()\n\n print 'Search some value, 30:'\n node = l.search(30)\n print node\n\n print 'Delete some value, 30:'\n node = l.delete(30)\n l.__str__()\n\n print 'Delete first element, 60:'\n node = l.delete(60)\n l.__str__()\n\n print 'Delete last element, 10:'\n node = l.delete(10)\n l.__str__()\n\n\nif __name__ == \"__main__\":\n test()\n Testing Linked List\nLinked List after insert nodes:\nSize of linked list: 6\n60\n50\n40\n30\n20\n10\nSearch some value, 30:\n30\nDelete some value, 30:\nSize of linked list: 5\n60\n50\n40\n20\n10\nDelete first element, 60:\nSize of linked list: 4\n50\n40\n20\n10\nDelete last element, 10:\nSize of linked list: 3\n50\n40\n20\n" }, { "answer_id": 45598670, "author": "Abhinav Mehta", "author_id": 8441618, "author_profile": "https://Stackoverflow.com/users/8441618", "pm_score": 2, "selected": false, "text": "class Node:\n def __init__(self, initdata):\n self.data = initdata\n self.next = None\n\n def get_data(self):\n return self.data\n\n def set_data(self, data):\n self.data = data\n\n def get_next(self):\n return self.next\n\n def set_next(self, node):\n self.next = node\n\n\n# ------------------------ Link List class ------------------------------- #\nclass LinkList:\n\n def __init__(self):\n self.head = None\n\n def is_empty(self):\n return self.head == None\n\n def traversal(self, data=None):\n node = self.head\n index = 0\n found = False\n while node is not None and not found:\n if node.get_data() == data:\n found = True\n else:\n node = node.get_next()\n index += 1\n return (node, index)\n\n def size(self):\n _, count = self.traversal(None)\n return count\n\n def search(self, data):\n node, _ = self.traversal(data)\n return node\n\n def add(self, data):\n node = Node(data)\n node.set_next(self.head)\n self.head = node\n\n def remove(self, data):\n previous_node = None\n current_node = self.head\n found = False\n while current_node is not None and not found:\n if current_node.get_data() == data:\n found = True\n if previous_node:\n previous_node.set_next(current_node.get_next())\n else:\n self.head = current_node\n else:\n previous_node = current_node\n current_node = current_node.get_next()\n return found\n link_list = LinkList()\nlink_list.add(10)\nlink_list.add(20)\nlink_list.add(30)\nlink_list.add(40)\nlink_list.add(50)\nlink_list.size()\nlink_list.search(30)\nlink_list.remove(20)\n" }, { "answer_id": 46755929, "author": "Cold Tison", "author_id": 8779792, "author_profile": "https://Stackoverflow.com/users/8779792", "pm_score": -1, "selected": false, "text": "# LinkedList..\n\nclass node:\n def __init__(self): ##Cluster of Nodes' properties \n self.data=None\n self.next=None\n self.prev=None\n\nclass linkedList():\n def __init__(self):\n self.t = node() // for future use\n self.cur_node = node() // current node\n self.start=node()\n\n def add(self,data): // appending the LL\n\n self.new_node = node()\n self.new_node.data=data\n if self.cur_node.data is None: \n self.start=self.new_node //For the 1st node only\n\n self.cur_node.next=self.new_node\n self.new_node.prev=self.cur_node\n self.cur_node=self.new_node\n\n\n def backward_display(self): //Displays LL backwards\n self.t=self.cur_node\n while self.t.data is not None:\n print(self.t.data)\n self.t=self.t.prev\n\n def forward_display(self): //Displays LL Forward\n self.t=self.start\n while self.t.data is not None:\n print(self.t.data)\n self.t=self.t.next\n if self.t.next is None:\n print(self.t.data)\n break\n\n def main(self): //This is kind of the main \n function in C\n ch=0\n while ch is not 4: //Switch-case in C \n ch=int(input(\"Enter your choice:\"))\n if ch is 1:\n data=int(input(\"Enter data to be added:\"))\n ll.add(data)\n ll.main()\n elif ch is 2:\n ll.forward_display()\n ll.main()\n elif ch is 3:\n ll.backward_display()\n ll.main()\n else:\n print(\"Program ends!!\")\n return\n\n\nll=linkedList()\nll.main()\n" }, { "answer_id": 57751171, "author": "Emma", "author_id": 6553328, "author_profile": "https://Stackoverflow.com/users/6553328", "pm_score": 0, "selected": false, "text": "\"\"\"\n\n\nSingle Linked List (SLL):\nA simple object-oriented implementation of Single Linked List (SLL) \nwith some associated methods, such as create list, count nodes, delete nodes, and such. \n\n\n\"\"\"\n\nclass Node:\n \"\"\"\n Instantiates a node\n \"\"\"\n def __init__(self, value):\n \"\"\"\n Node class constructor which sets the value and link of the node\n\n \"\"\"\n self.info = value\n self.link = None\n\nclass SingleLinkedList:\n \"\"\"\n Instantiates the SLL class\n \"\"\"\n def __init__(self):\n \"\"\"\n SLL class constructor which sets the value and link of the node\n\n \"\"\"\n self.start = None\n\n def create_single_linked_list(self):\n \"\"\"\n Reads values from stdin and appends them to this list and creates a SLL with integer nodes\n\n \"\"\"\n try:\n number_of_nodes = int(input(\" Enter a positive integer between 1-50 for the number of nodes you wish to have in the list: \"))\n if number_of_nodes <= 0 or number_of_nodes > 51:\n print(\" The number of nodes though must be an integer between 1 to 50!\")\n self.create_single_linked_list()\n\n except Exception as e:\n print(\" Error: \", e)\n self.create_single_linked_list()\n\n\n try:\n for _ in range(number_of_nodes):\n try:\n data = int(input(\" Enter an integer for the node to be inserted: \"))\n self.insert_node_at_end(data)\n except Exception as e:\n print(\" Error: \", e)\n except Exception as e:\n print(\" Error: \", e)\n\n def count_sll_nodes(self):\n \"\"\"\n Counts the nodes of the linked list\n\n \"\"\"\n try:\n p = self.start\n n = 0\n while p is not None:\n n += 1\n p = p.link\n\n if n >= 1:\n print(f\" The number of nodes in the linked list is {n}\")\n else:\n print(f\" The SLL does not have a node!\")\n except Exception as e: \n print(\" Error: \", e)\n\n def search_sll_nodes(self, x):\n \"\"\"\n Searches the x integer in the linked list\n \"\"\"\n try:\n position = 1\n p = self.start\n while p is not None:\n if p.info == x:\n print(f\" YAAAY! We found {x} at position {position}\")\n return True\n\n #Increment the position\n position += 1 \n #Assign the next node to the current node\n p = p.link\n else:\n print(f\" Sorry! We couldn't find {x} at any position. Maybe, you might want to use option 9 and try again later!\")\n return False\n except Exception as e:\n print(\" Error: \", e)\n\n def display_sll(self):\n \"\"\"\n Displays the list\n \"\"\"\n try:\n if self.start is None:\n print(\" Single linked list is empty!\")\n return\n\n display_sll = \" Single linked list nodes are: \"\n p = self.start\n while p is not None:\n display_sll += str(p.info) + \"\\t\"\n p = p.link\n\n print(display_sll)\n\n except Exception as e:\n print(\" Error: \", e) \n\n def insert_node_in_beginning(self, data):\n \"\"\"\n Inserts an integer in the beginning of the linked list\n\n \"\"\"\n try:\n temp = Node(data)\n temp.link = self.start\n self.start = temp\n except Exception as e:\n print(\" Error: \", e)\n\n def insert_node_at_end(self, data):\n \"\"\"\n Inserts an integer at the end of the linked list\n\n \"\"\"\n try: \n temp = Node(data)\n if self.start is None:\n self.start = temp\n return\n\n p = self.start \n while p.link is not None:\n p = p.link\n p.link = temp\n except Exception as e:\n print(\" Error: \", e)\n\n\n def insert_node_after_another(self, data, x):\n \"\"\"\n Inserts an integer after the x node\n\n \"\"\"\n try:\n p = self.start\n\n while p is not None:\n if p.info == x:\n break\n p = p.link\n\n if p is None:\n print(f\" Sorry! {x} is not in the list.\")\n else:\n temp = Node(data)\n temp.link = p.link\n p.link = temp\n except Exception as e: \n print(\" Error: \", e)\n\n\n def insert_node_before_another(self, data, x):\n \"\"\"\n Inserts an integer before the x node\n\n \"\"\"\n\n try:\n\n # If list is empty\n if self.start is None:\n print(\" Sorry! The list is empty.\")\n return \n # If x is the first node, and new node should be inserted before the first node\n if x == self.start.info:\n temp = Node(data)\n temp.link = p.link\n p.link = temp\n\n # Finding the reference to the prior node containing x\n p = self.start\n while p.link is not None:\n if p.link.info == x:\n break\n p = p.link\n\n if p.link is not None:\n print(f\" Sorry! {x} is not in the list.\")\n else:\n temp = Node(data)\n temp.link = p.link\n p.link = temp \n\n except Exception as e:\n print(\" Error: \", e)\n\n def insert_node_at_position(self, data, k):\n \"\"\"\n Inserts an integer in k position of the linked list\n\n \"\"\"\n try:\n # if we wish to insert at the first node\n if k == 1:\n temp = Node(data)\n temp.link = self.start\n self.start = temp\n return\n\n p = self.start\n i = 1\n\n while i < k-1 and p is not None:\n p = p.link\n i += 1\n\n if p is None:\n print(f\" The max position is {i}\") \n else: \n temp = Node(data)\n temp.link = self.start\n self.start = temp\n\n except Exception as e:\n print(\" Error: \", e)\n\n def delete_a_node(self, x):\n \"\"\"\n Deletes a node of a linked list\n\n \"\"\"\n try:\n # If list is empty\n if self.start is None:\n print(\" Sorry! The list is empty.\")\n return\n\n # If there is only one node\n if self.start.info == x:\n self.start = self.start.link\n\n # If more than one node exists\n p = self.start\n while p.link is not None:\n if p.link.info == x:\n break \n p = p.link\n\n if p.link is None:\n print(f\" Sorry! {x} is not in the list.\")\n else:\n p.link = p.link.link\n\n except Exception as e:\n print(\" Error: \", e)\n\n def delete_sll_first_node(self):\n \"\"\"\n Deletes the first node of a linked list\n\n \"\"\"\n try:\n if self.start is None:\n return\n self.start = self.start.link\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def delete_sll_last_node(self):\n \"\"\"\n Deletes the last node of a linked list\n\n \"\"\"\n try:\n\n # If the list is empty\n if self.start is None:\n return\n\n # If there is only one node\n if self.start.link is None:\n self.start = None\n return\n\n # If there is more than one node \n p = self.start\n\n # Increment until we find the node prior to the last node \n while p.link.link is not None:\n p = p.link\n\n p.link = None \n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def reverse_sll(self):\n \"\"\"\n Reverses the linked list\n\n \"\"\"\n\n try:\n\n prev = None\n p = self.start\n while p is not None:\n next = p.link\n p.link = prev\n prev = p\n p = next\n self.start = prev\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def bubble_sort_sll_nodes_data(self):\n \"\"\"\n Bubble sorts the linked list on integer values\n\n \"\"\"\n\n try:\n\n # If the list is empty or there is only one node\n if self.start is None or self.start.link is None:\n print(\" The list has no or only one node and sorting is not required.\")\n end = None\n\n while end != self.start.link:\n p = self.start\n while p.link != end:\n q = p.link\n if p.info > q.info:\n p.info, q.info = q.info, p.info\n p = p.link\n end = p\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def bubble_sort_sll(self):\n \"\"\"\n Bubble sorts the linked list\n\n \"\"\"\n\n try:\n\n # If the list is empty or there is only one node\n if self.start is None or self.start.link is None:\n print(\" The list has no or only one node and sorting is not required.\")\n end = None\n\n while end != self.start.link:\n r = p = self.start\n while p.link != end:\n q = p.link\n if p.info > q.info:\n p.link = q.link\n q.link = p\n if p != self.start:\n r.link = q.link\n else:\n self.start = q\n p, q = q, p\n r = p\n p = p.link\n end = p\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def sll_has_cycle(self):\n \"\"\"\n Tests the list for cycles using Tortoise and Hare Algorithm (Floyd's cycle detection algorithm)\n \"\"\"\n\n try:\n\n if self.find_sll_cycle() is None:\n return False\n else:\n return True\n\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def find_sll_cycle(self):\n \"\"\"\n Finds cycles in the list, if any\n \"\"\"\n\n try:\n\n # If there is one node or none, there is no cycle\n if self.start is None or self.start.link is None:\n return None\n\n # Otherwise, \n slowR = self.start\n fastR = self.start\n\n while slowR is not None and fastR is not None:\n slowR = slowR.link\n fastR = fastR.link.link\n if slowR == fastR: \n return slowR\n\n return None\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def remove_cycle_from_sll(self):\n \"\"\"\n Removes the cycles\n \"\"\"\n\n try:\n\n c = self.find_sll_cycle()\n\n # If there is no cycle\n if c is None:\n return\n\n print(f\" There is a cycle at node: \", c.info)\n\n p = c\n q = c\n len_cycles = 0\n while True:\n len_cycles += 1\n q = q.link\n\n if p == q:\n break\n\n print(f\" The cycle length is {len_cycles}\")\n\n len_rem_list = 0\n p = self.start\n\n while p != q:\n len_rem_list += 1\n p = p.link\n q = q.link\n\n print(f\" The number of nodes not included in the cycle is {len_rem_list}\")\n\n length_list = len_rem_list + len_cycles\n\n print(f\" The SLL length is {length_list}\")\n\n # This for loop goes to the end of the SLL, and set the last node to None and the cycle is removed. \n p = self.start\n for _ in range(length_list-1):\n p = p.link\n p.link = None\n\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def insert_cycle_in_sll(self, x):\n \"\"\"\n Inserts a cycle at a node that contains x\n\n \"\"\"\n\n try:\n\n if self.start is None:\n return False\n\n p = self.start\n px = None\n prev = None\n\n\n while p is not None:\n if p.info == x:\n px = p\n prev = p\n p = p.link\n\n if px is not None:\n prev.link = px\n else:\n print(f\" Sorry! {x} is not in the list.\")\n\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def merge_using_new_list(self, list2):\n \"\"\"\n Merges two already sorted SLLs by creating new lists\n \"\"\"\n merge_list = SingleLinkedList()\n merge_list.start = self._merge_using_new_list(self.start, list2.start)\n return merge_list\n\n def _merge_using_new_list(self, p1, p2):\n \"\"\"\n Private method of merge_using_new_list\n \"\"\"\n if p1.info <= p2.info:\n Start_merge = Node(p1.info)\n p1 = p1.link\n else:\n Start_merge = Node(p2.info)\n p2 = p2.link \n pM = Start_merge\n\n while p1 is not None and p2 is not None:\n if p1.info <= p2.info:\n pM.link = Node(p1.info)\n p1 = p1.link\n else:\n pM.link = Node(p2.info)\n p2 = p2.link\n pM = pM.link\n\n #If the second list is finished, yet the first list has some nodes\n while p1 is not None:\n pM.link = Node(p1.info)\n p1 = p1.link\n pM = pM.link\n\n #If the second list is finished, yet the first list has some nodes\n while p2 is not None:\n pM.link = Node(p2.info)\n p2 = p2.link\n pM = pM.link\n\n return Start_merge\n\n def merge_inplace(self, list2):\n \"\"\"\n Merges two already sorted SLLs in place in O(1) of space\n \"\"\"\n merge_list = SingleLinkedList()\n merge_list.start = self._merge_inplace(self.start, list2.start)\n return merge_list\n\n def _merge_inplace(self, p1, p2):\n \"\"\"\n Merges two already sorted SLLs in place in O(1) of space\n \"\"\"\n if p1.info <= p2.info:\n Start_merge = p1\n p1 = p1.link\n else:\n Start_merge = p2\n p2 = p2.link\n pM = Start_merge\n\n while p1 is not None and p2 is not None:\n if p1.info <= p2.info:\n pM.link = p1\n pM = pM.link\n p1 = p1.link\n else:\n pM.link = p2\n pM = pM.link\n p2 = p2.link\n\n if p1 is None:\n pM.link = p2\n else:\n pM.link = p1\n\n return Start_merge\n\n def merge_sort_sll(self):\n \"\"\"\n Sorts the linked list using merge sort algorithm\n \"\"\"\n self.start = self._merge_sort_recursive(self.start)\n\n\n def _merge_sort_recursive(self, list_start):\n \"\"\"\n Recursively calls the merge sort algorithm for two divided lists\n \"\"\"\n\n # If the list is empty or has only one node\n if list_start is None or list_start.link is None:\n return list_start\n\n # If the list has two nodes or more\n start_one = list_start\n start_two = self._divide_list(self_start)\n start_one = self._merge_sort_recursive(start_one)\n start_two = self._merge_sort_recursive(start_two)\n start_merge = self._merge_inplace(start_one, start_two)\n\n return start_merge\n\n def _divide_list(self, p):\n \"\"\"\n Divides the linked list into two almost equally sized lists\n \"\"\"\n\n # Refers to the third nodes of the list\n q = p.link.link\n\n while q is not None and p is not None:\n # Increments p one node at the time\n p = p.link\n # Increments q two nodes at the time\n q = q.link.link\n\n start_two = p.link\n p.link = None\n\n return start_two\n\n def concat_second_list_to_sll(self, list2):\n \"\"\"\n Concatenates another SLL to an existing SLL\n \"\"\"\n\n # If the second SLL has no node\n if list2.start is None:\n return\n\n # If the original SLL has no node\n if self.start is None:\n self.start = list2.start\n return\n\n # Otherwise traverse the original SLL\n p = self.start\n while p.link is not None:\n p = p.link\n\n # Link the last node to the first node of the second SLL\n p.link = list2.start\n\n\n\n def test_merge_using_new_list_and_inplace(self):\n \"\"\"\n\n \"\"\"\n\n LIST_ONE = SingleLinkedList()\n LIST_TWO = SingleLinkedList()\n\n LIST_ONE.create_single_linked_list()\n LIST_TWO.create_single_linked_list()\n\n print(\"1️⃣ The unsorted first list is: \")\n LIST_ONE.display_sll()\n\n print(\"2️⃣ The unsorted second list is: \")\n LIST_TWO.display_sll()\n\n\n LIST_ONE.bubble_sort_sll_nodes_data()\n LIST_TWO.bubble_sort_sll_nodes_data()\n\n print(\"1️⃣ The sorted first list is: \")\n LIST_ONE.display_sll()\n\n print(\"2️⃣ The sorted second list is: \")\n LIST_TWO.display_sll()\n\n LIST_THREE = LIST_ONE.merge_using_new_list(LIST_TWO)\n\n print(\"The merged list by creating a new list is: \")\n LIST_THREE.display_sll()\n\n\n LIST_FOUR = LIST_ONE.merge_inplace(LIST_TWO)\n\n print(\"The in-place merged list is: \")\n LIST_FOUR.display_sll() \n\n\n def test_all_methods(self):\n \"\"\"\n Tests all methods of the SLL class\n \"\"\"\n\n OPTIONS_HELP = \"\"\"\n\n Select a method from 1-19: \n\n ℹ️ (1) Create a single liked list (SLL).\n ℹ️ (2) Display the SLL. \n ℹ️ (3) Count the nodes of SLL. \n ℹ️ (4) Search the SLL.\n ℹ️ (5) Insert a node at the beginning of the SLL.\n ℹ️ (6) Insert a node at the end of the SLL.\n ℹ️ (7) Insert a node after a specified node of the SLL.\n ℹ️ (8) Insert a node before a specified node of the SLL.\n ℹ️ (9) Delete the first node of SLL.\n ℹ️ (10) Delete the last node of the SLL.\n ℹ️ (11) Delete a node you wish to remove. \n ℹ️ (12) Reverse the SLL.\n ℹ️ (13) Bubble sort the SLL by only exchanging the integer values. \n ℹ️ (14) Bubble sort the SLL by exchanging links. \n ℹ️ (15) Merge sort the SLL.\n ℹ️ (16) Insert a cycle in the SLL.\n ℹ️ (17) Detect if the SLL has a cycle.\n ℹ️ (18) Remove cycle in the SLL.\n ℹ️ (19) Test merging two bubble-sorted SLLs.\n ℹ️ (20) Concatenate a second list to the SLL. \n ℹ️ (21) Exit.\n\n \"\"\"\n\n\n self.create_single_linked_list()\n\n while True:\n\n print(OPTIONS_HELP)\n\n UI_OPTION = int(input(\" Enter an integer for the method you wish to run using the above help: \"))\n\n if UI_OPTION == 1:\n data = int(input(\" Enter an integer to be inserted at the end of the list: \"))\n x = int(input(\" Enter an integer to be inserted after that: \"))\n self.insert_node_after_another(data, x)\n elif UI_OPTION == 2:\n self.display_sll()\n elif UI_OPTION == 3:\n self.count_sll_nodes()\n elif UI_OPTION == 4:\n data = int(input(\" Enter an integer to be searched: \"))\n self.search_sll_nodes(data)\n elif UI_OPTION == 5:\n data = int(input(\" Enter an integer to be inserted at the beginning: \"))\n self.insert_node_in_beginning(data)\n elif UI_OPTION == 6:\n data = int(input(\" Enter an integer to be inserted at the end: \"))\n self.insert_node_at_end(data)\n elif UI_OPTION == 7:\n data = int(input(\" Enter an integer to be inserted: \"))\n x = int(input(\" Enter an integer to be inserted before that: \"))\n self.insert_node_before_another(data, x)\n elif UI_OPTION == 8:\n data = int(input(\" Enter an integer for the node to be inserted: \"))\n k = int(input(\" Enter an integer for the position at which you wish to insert the node: \"))\n self.insert_node_before_another(data, k)\n elif UI_OPTION == 9:\n self.delete_sll_first_node()\n elif UI_OPTION == 10:\n self.delete_sll_last_node()\n elif UI_OPTION == 11:\n data = int(input(\" Enter an integer for the node you wish to remove: \"))\n self.delete_a_node(data)\n elif UI_OPTION == 12:\n self.reverse_sll()\n elif UI_OPTION == 13:\n self.bubble_sort_sll_nodes_data()\n elif UI_OPTION == 14:\n self.bubble_sort_sll()\n elif UI_OPTION == 15:\n self.merge_sort_sll()\n elif UI_OPTION == 16:\n data = int(input(\" Enter an integer at which a cycle has to be formed: \"))\n self.insert_cycle_in_sll(data)\n elif UI_OPTION == 17:\n if self.sll_has_cycle():\n print(\" The linked list has a cycle. \")\n else:\n print(\" YAAAY! The linked list does not have a cycle. \")\n elif UI_OPTION == 18:\n self.remove_cycle_from_sll()\n elif UI_OPTION == 19:\n self.test_merge_using_new_list_and_inplace()\n elif UI_OPTION == 20:\n list2 = self.create_single_linked_list()\n self.concat_second_list_to_sll(list2)\n elif UI_OPTION == 21:\n break\n else:\n print(\" Option must be an integer, between 1 to 21.\")\n\n print() \n\n\n\nif __name__ == '__main__':\n # Instantiates a new SLL object\n SLL_OBJECT = SingleLinkedList()\n SLL_OBJECT.test_all_methods()\n" }, { "answer_id": 58677862, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "class Node(object):\n def __init__(self):\n self.data = None\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def prepend_node(self, data):\n new_node = Node()\n new_node.data = data\n new_node.next = self.head\n self.head = new_node\n\n def append_node(self, data):\n new_node = Node()\n new_node.data = data\n current = self.head\n while current.next:\n current = current.next\n current.next = new_node\n\n def reverse(self):\n \"\"\" In-place reversal, modifies exiting list\"\"\"\n previous = None\n current_node = self.head\n\n while current_node:\n temp = current_node.next\n current_node.next = previous\n previous = current_node\n current_node = temp\n self.head = previous\n\n def search(self, data):\n current_node = self.head\n try:\n while current_node.data != data:\n current_node = current_node.next\n return True\n except:\n return False\n\n def display(self):\n if self.head is None:\n print(\"Linked list is empty\")\n else:\n current_node = self.head\n while current_node:\n print(current_node.data)\n current_node = current_node.next\n\n def list_length(self):\n list_length = 0\n current_node = self.head\n while current_node:\n list_length += 1\n current_node = current_node.next\n return list_length\n\n\ndef main():\n linked_list = LinkedList()\n\n linked_list.prepend_node(1)\n linked_list.prepend_node(2)\n linked_list.prepend_node(3)\n linked_list.append_node(24)\n linked_list.append_node(25)\n linked_list.display()\n linked_list.reverse()\n linked_list.display()\n print(linked_list.search(1))\n linked_list.reverse()\n linked_list.display()\n print(\"Lenght of singly linked list is: \" + str(linked_list.list_length()))\n\n\nif __name__ == \"__main__\":\n main()\n\n" }, { "answer_id": 68262495, "author": "Farzad Hosseinali", "author_id": 9477463, "author_profile": "https://Stackoverflow.com/users/9477463", "pm_score": -1, "selected": false, "text": "class Linkedlist:\n def __init__(self):\n self.outer = None\n\n def add_outermost(self, dt):\n self.outer = [dt, self.outer]\n\n def add_innermost(self, dt):\n p = self.outer\n if not p:\n self.outer = [dt, None]\n return\n while p[1]:\n p = p[1]\n p[1] = [dt, None]\n\n def visualize(self):\n p = self.outer\n l = 'Linkedlist: '\n while p:\n l += (str(p[0])+'->')\n p = p[1]\n print(l + 'None')\n\n ll = Linkedlist()\n ll.add_innermost(8)\n ll.add_outermost(3)\n ll.add_outermost(5)\n ll.add_outermost(2)\n ll.add_innermost(7)\n print(ll.outer)\n ll.visualize()\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
280,247
<p>I've tried my best and cannot figure out what happened here. It worked fine in Delphi 4. After upgrading to Delphi 2009, I don't know if this is the way it is supposed to work, or if it's a problem:</p> <p>This is what my program's menu looks like in Design Mode under Delphi 2009:</p> <p><a href="https://i.stack.imgur.com/lg57M.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lg57M.gif" alt="enter image description here"></a></p> <p>Notice that every word in the Main Menu and the File submenu have one letter underlined. It is supposed to be like this. This underlined letter is called the Accelerator Key and is standard in Windows applications so that you can use the Alt-key and that letter to quickly select the menu item and then submenu item with the keyboard rather than with your mouse.</p> <p>You get them this way by using the "&amp;" character as part of the caption of the item, for example: Save &amp;As...</p> <p>When I run my application, and use the mouse to open the File menu, it looks like this:</p> <p><a href="https://i.stack.imgur.com/zpw14.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zpw14.gif" alt="enter image description here"></a></p> <p>The characters are underlined in the main menu, but are not underlined in the File menu.</p> <p>If instead, I use the Alt-F key to open up the File submenu, then it looks correct like this:</p> <p><a href="https://i.stack.imgur.com/Hxwn0.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hxwn0.gif" alt="enter image description here"></a></p> <p>and all the Accelerator Key letters are properly underlined.</p> <p>I've played with the AutoHotKeys option but that's not the problem.</p> <p>Has someone encountered this problem before? Is the example in the 2nd image correct behavior that I don't know of? Or is there some option or coding mistake that I might have missed?</p> <hr> <p>Nov 2009 (one year later): mghie seems to have got to the root of this and figured out the problem. See his accepted answer below.</p>
[ { "answer_id": 280289, "author": "mghie", "author_id": 30568, "author_profile": "https://Stackoverflow.com/users/30568", "pm_score": 4, "selected": true, "text": "WM_DRAWITEM ODS_NOACCEL protected\n procedure WndProc(var Message: TMessage); override;\n procedure TYourForm.WndProc(var Message: TMessage);\nconst\n ODS_NOACCEL = $100;\nvar\n pDIS: PDrawItemStruct;\n ShowAccel: BOOL;\nbegin\n if (Message.Msg = WM_DRAWITEM) then begin\n pDIS := PDrawItemStruct(Message.LParam);\n if (pDIS^.CtlType = ODT_MENU)\n and SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, @ShowAccel, 0)\n then begin\n if ShowAccel then\n pDIS^.itemState := pDIS^.itemState and not ODS_NOACCEL;\n end;\n end;\n inherited;\nend;\n SystemParametersInfo() WM_DRAWITEM WM_SETTINGCHANGE" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30176/" ]
280,249
<p>I have created a site, which parses XML files and display its content on the appropriate page. Is my site a dynamic web page or static web page?</p> <p>How do dynamic and static web pages differ?</p> <p>I feel it's dynamic, because I parse the content from xml files; initially i don't have any content in my main page..</p> <p>What do you think about this, please explain it..</p>
[ { "answer_id": 280330, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "/view.php?page=index" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
280,260
<p>EDIT: <strong>I would really like to see some general discussion about the formats, their pros and cons!</strong></p> <p>EDIT2: The 'bounty didn't really help to create the needed discussion, there are a few interesting answers but the comprehensive coverage of the topic is still missing. Six persons marked the question as favourites, which shows me that there is an interest in this discussion.</p> <p>When deciding about <strong>internationalization</strong> the toughest part IMO is the choice of storage format.</p> <p>For example the Zend PHP Framework offers the following adapters which cover pretty much all my options:</p> <ul> <li>Array : no, hard to maintain</li> <li><strong>CSV : don't know, possible problems with encoding</strong></li> <li><strong>Gettext : frequently used, poEdit for all platforms available BUT complicated</strong></li> <li><strong>INI : don't know, possible problems with encoding</strong></li> <li>TBX : no clue</li> <li>TMX : too much of a big thing? no editors freely available.</li> <li>QT : not very widespread, no free tools</li> <li><strong>XLIFF : the comming standard? BUT no free tools available.</strong></li> <li>XMLTM : no, not what I need</li> </ul> <p>basically I'm stuck with the 4 'bold' choices. I would like to use INI files but I'm reading about the encoding problems... is it really a problem, if I use strict UTF-8 (files, connections, db, etc.)?</p> <p>I'm on Windows and I tried to figure out how poEdit functions but just didn't manage. No tutorials on the web either, is <strong>gettext</strong> still a choice or an endangered species anyways?</p> <p>What about <strong>XLIFF</strong>, has anybody worked with it? Any tips on what tools to use?</p> <p>Any ideas for <strong>Eclipse</strong> integration of any of these technologies?</p>
[ { "answer_id": 280291, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 4, "selected": false, "text": "_(\"Text\"), gettext(\"Text\") bindtextdomain() gettext" }, { "answer_id": 501722, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 0, "selected": false, "text": "£(\"btn_save\")\n£(Order.class,\"amt\")\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11995/" ]
280,270
<p>Using LINQ to Entities sounds like a great way to query against a database and get actual CLR objects that I can modify, data bind against and so forth. But if I perform the same query a second time do I get back references to the same CLR objects or an entirely new set? </p> <p>I do not want multiple queries to generate an ever growing number of copies of the same actual data. The problem here is that I could alter the contents of one entity and save it back to the database but another instance of the entity is still in existence elsewhere and holding the old data.</p>
[ { "answer_id": 280335, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "// uses object identity cache (IIRC)\nvar obj = ctx.Single(x=>x.Id == id);\n // causes round-trip (IIRC)\nvar obj = ctx.Where(x=>x.Id == id).Single();\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ]
280,298
<p>A complicated-sounding term with no good explanations from a simple google search... are there any more academically-oriented folk who could explain this one?</p>
[ { "answer_id": 286474, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 3, "selected": true, "text": "public class Hey<T>\n{\n public T idOrInc(T var)\n {\n if (var instanceof Integer)\n return (T)(new Integer(((Integer)var).intValue()+1));\n return var;\n }\n public static void main(String[] args) {\n Hey<Integer> h = new Hey<Integer>();\n System.out.println(h.idOrInc(new Integer(10)));\n Hey<Double> h2 = new Hey<Double>();\n System.out.println(h2.idOrInc(new Double(10)));\n }\n}\n $ java Hey\n11\n10.0\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
280,313
<p>I am trying to merge several XML files in a single XDocument object.</p> <p>Merge does not exist in XDocument object. I miss this.</p> <p>Has anyone already implemented a Merge extension method for XDocument, or something similar ?</p>
[ { "answer_id": 280379, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "XDocument XmLDocument XmlDoucument XDocument XmlDocument ImportNode XDocument XNode.ReadFrom .Add XmlReader/XmlWriter XmlWriter WriteNode XmlReader XmlReader static void AppendChildren(this XmlWriter writer, string path)\n {\n using (XmlReader reader = XmlReader.Create(path))\n {\n reader.MoveToContent();\n int targetDepth = reader.Depth + 1;\n if(reader.Read()) {\n while (reader.Depth == targetDepth)\n {\n writer.WriteNode(reader, true);\n } \n }\n }\n }\n" }, { "answer_id": 280512, "author": "Larry", "author_id": 24472, "author_profile": "https://Stackoverflow.com/users/24472", "pm_score": 6, "selected": true, "text": "var MyDoc = XDocument.Load(\"File1.xml\");\nMyDoc.Root.Add(XDocument.Load(\"File2.xml\").Root.Elements());\n" }, { "answer_id": 27907730, "author": "SV0505", "author_id": 2227230, "author_profile": "https://Stackoverflow.com/users/2227230", "pm_score": 2, "selected": false, "text": "public static XDocument MergeDir(string xmlDir)\n{\n XDocument xdoc = XDocument.Parse(\"<root></root>\");\n System.IO.DirectoryInfo directory = new DirectoryInfo(xmlDir);\n if (directory.Exists)\n {\n foreach (System.IO.FileInfo file in directory.GetFiles())\n {\n if (file.Extension == \".xml\")\n {\n xdoc.Root.Add(XDocument.Load(file.FullName).Root.Elements());\n }\n }\n }\n\n return xdoc;\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24472/" ]
280,324
<p>I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.</p> <p>However, I'm looking through the <em>wxPython in Action</em> book and notice that "self" isn't used all the time. For example:</p> <pre><code> import wx class TextFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Text Entry Example', size=(300, 100)) panel = wx.Panel(self, -1) basicLabel = wx.StaticText(panel, -1, "Basic Control:") basicText = wx.TextCtrl(panel, -1, "I've entered some text!", size=(175, -1)) basicText.SetInsertionPoint(0) pwdLabel = wx.StaticText(panel, -1, "Password:") pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1), style=wx.TE_PASSWORD) sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6) sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText]) panel.SetSizer(sizer) </code></pre> <p>The one below does use "self".</p> <pre><code>import wx class ButtonFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Button Example', size=(300, 100)) panel = wx.Panel(self, -1) self.button = wx.Button(panel, -1, "Hello", pos=(50, 20)) self.Bind(wx.EVT_BUTTON, self.OnClick, self.button) self.button.SetDefault() def OnClick(self, event): self.button.SetLabel("Clicked") </code></pre> <p>If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?</p>
[ { "answer_id": 280332, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "self panel self" }, { "answer_id": 280561, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "self.attribute wx.Frame.__init__() self wx.Panel" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
280,331
<p>This seems like it should be easy but I'm stumped. In WPF, I'd like a TextBox that stretches to the width of it's parent, but only to a maximum width. The problem is that I want it to be left justified within its parent. To get it to stretch you have to use HorizontalAlignment="Stretch", but then the result is centered. I've experimented with HorizontalContentAlignment, but it doesn't seem to do anything.</p> <p>How do I get this blue text box to grow with the size of the window, have a maximum width of 200 pixels, and be left justified?</p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;StackPanel&gt; &lt;TextBox Background="Azure" Text="Hello" HorizontalAlignment="Stretch" MaxWidth="200" /&gt; &lt;/StackPanel&gt; &lt;/Page&gt; </code></pre> <p>What's the trick?</p>
[ { "answer_id": 280402, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 6, "selected": false, "text": "<Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\" MaxWidth=\"200\"/>\n </Grid.ColumnDefinitions>\n\n <TextBox Background=\"Azure\" Text=\"Hello\" />\n</Grid>\n" }, { "answer_id": 280417, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 8, "selected": true, "text": "HorizontalAlignment MaxWidth Width ActualWidth <Page\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <StackPanel Name=\"Container\"> \n <TextBox Background=\"Azure\" \n Width=\"{Binding ElementName=Container,Path=ActualWidth}\"\n Text=\"Hello\" HorizontalAlignment=\"Left\" MaxWidth=\"200\" />\n </StackPanel>\n</Page>\n" }, { "answer_id": 3573316, "author": "Filip Skakun", "author_id": 41942, "author_profile": "https://Stackoverflow.com/users/41942", "pm_score": 3, "selected": false, "text": "Width=\"{Binding ActualWidth,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}\"\n" }, { "answer_id": 46027269, "author": "Patrick Cairns", "author_id": 4204476, "author_profile": "https://Stackoverflow.com/users/4204476", "pm_score": 0, "selected": false, "text": "SharedSizeGroup <Grid>\n <Grid.ColumnDefinition>\n <ColumnDefinition SharedSizeGroup=\"col1\"></ColumnDefinition> \n <ColumnDefinition SharedSizeGroup=\"col2\"></ColumnDefinition>\n </Grid.ColumnDefinition>\n <TextBox Background=\"Azure\" Text=\"Hello\" Grid.Column=\"1\" MaxWidth=\"200\" />\n</Grid>\n" }, { "answer_id": 50928803, "author": "Y C", "author_id": 1257577, "author_profile": "https://Stackoverflow.com/users/1257577", "pm_score": 2, "selected": false, "text": "public class StretchMaxWidthBehavior : Behavior<FrameworkElement>\n{ \n protected override void OnAttached()\n {\n base.OnAttached();\n ((FrameworkElement)this.AssociatedObject.Parent).SizeChanged += this.OnSizeChanged;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n ((FrameworkElement)this.AssociatedObject.Parent).SizeChanged -= this.OnSizeChanged;\n }\n\n private void OnSizeChanged(object sender, SizeChangedEventArgs e)\n {\n this.SetAlignments();\n }\n\n private void SetAlignments()\n {\n var slot = LayoutInformation.GetLayoutSlot(this.AssociatedObject);\n var newWidth = slot.Width;\n var newHeight = slot.Height;\n\n if (!double.IsInfinity(this.AssociatedObject.MaxWidth))\n {\n if (this.AssociatedObject.MaxWidth < newWidth)\n {\n this.AssociatedObject.HorizontalAlignment = HorizontalAlignment.Left;\n this.AssociatedObject.Width = this.AssociatedObject.MaxWidth;\n }\n else\n {\n this.AssociatedObject.HorizontalAlignment = HorizontalAlignment.Stretch;\n this.AssociatedObject.Width = double.NaN;\n }\n }\n\n if (!double.IsInfinity(this.AssociatedObject.MaxHeight))\n {\n if (this.AssociatedObject.MaxHeight < newHeight)\n {\n this.AssociatedObject.VerticalAlignment = VerticalAlignment.Top;\n this.AssociatedObject.Height = this.AssociatedObject.MaxHeight;\n }\n else\n {\n this.AssociatedObject.VerticalAlignment = VerticalAlignment.Stretch;\n this.AssociatedObject.Height = double.NaN;\n }\n }\n }\n}\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition />\n </Grid.ColumnDefinitions>\n\n <TextBlock Grid.Column=\"0\" Text=\"Label\" />\n <TextBox Grid.Column=\"1\" MaxWidth=\"600\">\n <i:Interaction.Behaviors> \n <cbh:StretchMaxWidthBehavior/>\n </i:Interaction.Behaviors>\n </TextBox>\n</Grid>\n System.Windows.Interactivity" }, { "answer_id": 58641460, "author": "maxp", "author_id": 35026, "author_profile": "https://Stackoverflow.com/users/35026", "pm_score": 2, "selected": false, "text": "<TextBox\n Width=\"{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}}\"\n MaxWidth=\"500\"\n HorizontalAlignment=\"Left\" />\n" }, { "answer_id": 62392131, "author": "sparedev", "author_id": 11141718, "author_profile": "https://Stackoverflow.com/users/11141718", "pm_score": 0, "selected": false, "text": "<StackPanel Name=\"JustContainer\" VerticalAlignment=\"Center\" HorizontalAlignment=\"Stretch\" Background=\"BlueViolet\" >\n <TextBox \n Name=\"Input\" Text=\"Hello World\" \n MaxWidth=\"300\"\n HorizontalAlignment=\"Right\"\n Width=\"{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}}\">\n </TextBox>\n</StackPanel>\n" }, { "answer_id": 74678187, "author": "mike", "author_id": 4247806, "author_profile": "https://Stackoverflow.com/users/4247806", "pm_score": 0, "selected": false, "text": "TextBox MaxWidth System.Windows.Interactivity public class StretchAlignmentPanel : ContentControl\n{\n public StretchAlignmentPanel()\n {\n this.SizeChanged += StretchAlignmentPanel_SizeChanged;\n }\n\n public static readonly DependencyProperty HorizontalFallbackAlignmentProperty = DependencyProperty.Register(\n nameof(HorizontalFallbackAlignment), typeof(HorizontalAlignment), typeof(StretchAlignmentPanel), new PropertyMetadata(HorizontalAlignment.Stretch));\n\n public HorizontalAlignment HorizontalFallbackAlignment\n {\n get { return (HorizontalAlignment)GetValue(HorizontalFallbackAlignmentProperty); }\n set { SetValue(HorizontalFallbackAlignmentProperty, value); }\n }\n\n public static readonly DependencyProperty VerticalFallbackAlignmentProperty = DependencyProperty.Register(\n nameof(VerticalFallbackAlignment), typeof(VerticalAlignment), typeof(StretchAlignmentPanel), new PropertyMetadata(VerticalAlignment.Stretch));\n\n public VerticalAlignment VerticalFallbackAlignment\n {\n get { return (VerticalAlignment)GetValue(VerticalFallbackAlignmentProperty); }\n set { SetValue(VerticalFallbackAlignmentProperty, value); }\n }\n\n private void StretchAlignmentPanel_SizeChanged(object sender, System.Windows.SizeChangedEventArgs e)\n {\n var fe = this.Content as FrameworkElement;\n if (fe == null) return;\n \n if(e.WidthChanged) applyHorizontalAlignment(fe);\n if(e.HeightChanged) applyVerticalAlignment(fe);\n }\n\n private void applyHorizontalAlignment(FrameworkElement fe)\n {\n if (HorizontalFallbackAlignment == HorizontalAlignment.Stretch) return;\n\n if (this.ActualWidth > fe.MaxWidth)\n {\n fe.HorizontalAlignment = HorizontalFallbackAlignment;\n fe.Width = fe.MaxWidth;\n }\n else\n {\n fe.HorizontalAlignment = HorizontalAlignment.Stretch;\n fe.Width = double.NaN;\n }\n }\n\n private void applyVerticalAlignment(FrameworkElement fe)\n {\n if (VerticalFallbackAlignment == VerticalAlignment.Stretch) return;\n\n if (this.ActualHeight > fe.MaxHeight)\n {\n fe.VerticalAlignment = VerticalFallbackAlignment;\n fe.Height= fe.MaxHeight;\n }\n else\n {\n fe.VerticalAlignment = VerticalAlignment.Stretch;\n fe.Height= double.NaN;\n }\n }\n}\n <controls:StretchAlignmentPanel HorizontalFallbackAlignment=\"Right\">\n <TextBox MaxWidth=\"200\" MinWidth=\"100\" Text=\"Example\"/>\n</controls:StretchAlignmentPanel>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9045/" ]
280,345
<p>I'm trying to start <code>iexplore.exe</code> let it run for 5 seconds and then close it again.</p> <p><code>iexplore</code> opens just fine however it doesn't close when I call the PostThreadMessage. Can anyone see what I'm doing wrong? Here is my code:</p> <pre><code>CString IEPath = "C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE";//GetIEPath(); //IEPath += ' ' + url; std::string strCommand((LPCTSTR)IEPath); PROCESS_INFORMATION procinfo; STARTUPINFO startupinfo; GetStartupInfo(&amp;startupinfo); CreateProcess( NULL, (char *)strCommand.c_str(),// name of executable module NULL, // lpProcessAttributes NULL, // lpThreadAttributes false, // handle inheritance option CREATE_SHARED_WOW_VDM, // creation flags NULL, // new environment block NULL, // current directory name &amp;startupinfo, // startup information &amp;procinfo // process information ); Sleep(5000); ::PostThreadMessage(procinfo.dwThreadId, WM_QUIT, 0, 0); //&lt;---Dosent Close internet explorer! </code></pre> <p>Anyone have an idea of what I'm doing wrong? Or is there better way what to do the trick?</p>
[ { "answer_id": 280377, "author": "schnaader", "author_id": 34065, "author_profile": "https://Stackoverflow.com/users/34065", "pm_score": 1, "selected": false, "text": "TerminateProcess(procinfo.hProcess, 0);\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36476/" ]
280,347
<p>How to convert Unicode string into a utf-8 or utf-16 string? My VS2005 project is using Unicode char set, while sqlite in cpp provide </p> <pre><code>int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); int sqlite3_open16( const void *filename, /* Database filename (UTF-16) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); </code></pre> <p>for opening a folder. How can I convert string, CString, or wstring into UTF-8 or UTF-16 charset?</p> <p>Thanks very much!</p>
[ { "answer_id": 280358, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": false, "text": "CP_UTF8 CodePage CHAR buf[256]; // or whatever\nWideCharToMultiByte(\n CP_UTF8, \n 0, \n StringToConvert, // the string you have\n -1, // length of the string - set -1 to indicate it is null terminated\n buf, // output\n __countof(buf), // size of the buffer in bytes - if you leave it zero the return value is the length required for the output buffer\n NULL, \n NULL\n);\n sqlite3_open16" }, { "answer_id": 280360, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 0, "selected": false, "text": "\"Convert utf-32 into utf-8 or utf-16\"" }, { "answer_id": 280443, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 4, "selected": true, "text": "void * void * (void*)(LPCWSTR)strFilename char wchar_t wchar_t char" }, { "answer_id": 25456096, "author": "Helstrom", "author_id": 3739445, "author_profile": "https://Stackoverflow.com/users/3739445", "pm_score": 0, "selected": false, "text": "sqlite3_open(CStringA(L\"MyWideCharFileName\"), ...);\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25749/" ]
280,356
<p>In my webpage, I want the website to greet the user, but the username is surrounded by 'single quotations'. Since this isn't to prevent MySQL injection, i just want to remove quotes around my name on the display page.</p> <p>Ex: Welcome 'user'! I'm trying to find the way where i can strip the quotations around the user and have it display on the example below.</p> <p>Ex: Welcome user!</p> <p>The only line of code that I can think relating is this:</p> <p>$login = $_SESSION['login'];</p> <p>Does anyone know how to strip single lines quotes?</p>
[ { "answer_id": 280366, "author": "davil", "author_id": 22592, "author_profile": "https://Stackoverflow.com/users/22592", "pm_score": 1, "selected": false, "text": "echo 'Welcome ' . trim($login, \"'\");\n" }, { "answer_id": 280368, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 5, "selected": true, "text": "$login ' substr() $login = substr($_SESSION['login'], 1, -1); // example 1\n ' str_replace() $login = str_replace(\"'\", '', $_SESSION['login']); // example 2\n trim() $login = trim($_SESSION['login'], \"'\"); // example 3\n $login = trim($_SESSION['login'], \"'\\\"\"); // example 4\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
280,363
<p>Spring IoC container gives you <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-arbitrary-method-replacement" rel="nofollow noreferrer">an option</a> of replacing a method of a bean. Can someone provide a real life example of using this feature to solve real life problem?</p> <p>I can see this used for adapting an old legacy code (w/o sources) to work with your app. But I think I would consider writing an adapter class using the legacy code directly instead of Spring method replacement approach.</p>
[ { "answer_id": 280433, "author": "MrM", "author_id": 319803, "author_profile": "https://Stackoverflow.com/users/319803", "pm_score": 0, "selected": false, "text": "<bean id=\"propertyConfigurer\" class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\">\n <property name=\"locations\">\n <list>\n <value>file.properties</value>\n </list>\n </property>\n</bean> \n\n\n<bean id=\"DocumentAnalyzer\" class=\"${lucene.document_analyzer}\">\n</bean>\n\n<bean id=\"QueryAnalyzer\" class=\"${lucene.query_analyzer}\">\n</bean> \n\n<bean id=\"IndexSearcher\" class=\"org.apache.lucene.search.IndexSearcher\" scope=\"prototype\">\n <constructor-arg>\n <value>${lucene.repository_path}</value> \n </constructor-arg>\n\n</bean> \n Analyzer analyzer = (Analyzer) BeanLoader.getFactory().getBean(\"DocumentAnalyzer\");\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4052/" ]
280,378
<p>I read a little of the help for my advanced installer 6.5.1 and couldn't find a way to change the version string except by hand.</p>
[ { "answer_id": 2076057, "author": "Fred", "author_id": 251983, "author_profile": "https://Stackoverflow.com/users/251983", "pm_score": 3, "selected": false, "text": ":COMPILE_AIP\n\nSET AIP_DIR=\"C:\\Program Files\\Caphyon\\Advanced Installer 7.1.3\"\n\nECHO Advanced Installer Directiry: %AIP_DIR%\n\nECHO.\nECHO //////////////////////////\nECHO //Compiling AIP Files...//\nECHO //////////////////////////\nECHO.\n\nECHO Setting version on all installers...\nECHO Setting version on all installers... >> %DESTINATION_APP_DIR%_push_script_output.txt\n%AIP_DIR%\\advancedinstaller /edit \"<pathtoaipfile>\\installproject.aip\" /SetVersion -fromfile <path to exe defining app version>\n IF NOT ERRORLEVEL 0 GOTO ERROR_HANDLER\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30324/" ]
280,385
<p>Let's say we have a method signature like </p> <pre><code>public static function explodeDn($dn, array &amp;$keys = null, array &amp;$vals = null, $caseFold = self::ATTR_CASEFOLD_NONE) </code></pre> <p>we can easily call the method by omitting all parameters after <code>$dn</code>:</p> <pre><code>$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com'); </code></pre> <p>We can also call the method with 3 parameters:</p> <pre><code>$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v); </code></pre> <p>and with 4 parameters:</p> <pre><code>$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v, Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER); </code></pre> <p>But why is it impossible to call the method with the following parameter combination for example:</p> <pre><code>$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, null, Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER); $dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', null, $v); </code></pre> <p>What's the difference between passing <code>null</code> to the method and relying on the default value? Is this constraint written in the manual? Can it be circumvented?</p>
[ { "answer_id": 280404, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 1, "selected": false, "text": "$k=array();\n$v=null;\n$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v, \n Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER);\n" }, { "answer_id": 3632620, "author": "josh", "author_id": 438552, "author_profile": "https://Stackoverflow.com/users/438552", "pm_score": 2, "selected": false, "text": "function foo (&$ref = NULL) {\n $args = func_get_args();\n echo var_export($ref, TRUE).' - '.var_export($args, TRUE);\n}\n$bar = NULL;\nfoo(); // NULL - array()\nfoo($bar); // NULL - array(0 => NULL)\n foo($p1, , , $p4);" }, { "answer_id": 4233438, "author": "Rafa", "author_id": 279564, "author_profile": "https://Stackoverflow.com/users/279564", "pm_score": 3, "selected": false, "text": "function makecoffee($type = \"cappuccino\")\n{\n return \"Making a cup of $type.\\n\";\n}\necho makecoffee(); // returns \"Making a cup of cappuccino.\"\necho makecoffee(null); // returns \"Making a cup of .\"\necho makecoffee(\"espresso\"); // returns \"Making a cup of espresso.\"\n makecoffee(null) function makecoffee($type = null)\n{\n if (is_null($type)){ \n $type = \"capuccino\";\n }\n return \"Making a cup of $type.\\n\";\n}\n makecoffee(null)" }, { "answer_id": 9716982, "author": "Szczepan Hołyszewski", "author_id": 1271158, "author_profile": "https://Stackoverflow.com/users/1271158", "pm_score": 4, "selected": false, "text": "function foo (&$ref = NULL) {\n\n if (is_null($ref)) $ref=\"bar\";\n echo \"$ref\\n\"; \n}\n\nfoo($dummy = NULL); //this works!\n" }, { "answer_id": 28179870, "author": "Chris Middleton", "author_id": 2407870, "author_profile": "https://Stackoverflow.com/users/2407870", "pm_score": 1, "selected": false, "text": "func($var = null) <?php\nerror_reporting(E_ALL | E_STRICT);\n\nfunction doIt(&$x = null) {\n if($x !== null) echo \"x not null: $x\\n\";\n $x = 2;\n}\n\nfunction &dummyRef() {\n $dummyRef = null;\n return $dummyRef;\n}\n\ndoIt(dummyRef());\n\ndoIt(dummyRef());\n doIt(dummy()) $dummy $dummyRef = null;\ndoIt($dummyRef);\ndoIt($dummyRef); // second call would print 'x not null: 2'\n $dn = Zend_Ldap_Dn::explodeDn(\n 'CN=Alice Baker,CN=Users,DC=example,DC=com',\n $k,\n dummyRef(),\n Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER\n);\n <?php\nfunction doItObj(&$x = null) {\n if(gettype($x) !== \"object\") echo \"x not null: $x\\n\";\n $x = 2;\n}\n\nfunction &dummyObjRef() {\n $dummyObjRef = new StdClass();\n return $dummyObjRef;\n}\n\necho \"memory before: \" . memory_get_usage(true) . \"\\n\";\n\nfor($i = 0; $i < 1000000; $i++) {\n doItObj(dummyObjRef());\n}\n\necho \"memory after: \" . memory_get_usage(true) . \"\\n\";\n\necho \"\\n$i\\n\";\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11354/" ]
280,389
<pre><code>function main() { Hello(); } function Hello() { // How do you find out the caller function is 'main'? } </code></pre> <p>Is there a way to find out the call stack?</p>
[ { "answer_id": 280396, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 11, "selected": true, "text": "function Hello()\n{\n alert(\"caller is \" + Hello.caller);\n}\n Function.caller function Hello()\n{\n alert(\"caller is \" + arguments.callee.caller.toString());\n}\n" }, { "answer_id": 280466, "author": "Pablo Cabrera", "author_id": 12540, "author_profile": "https://Stackoverflow.com/users/12540", "pm_score": 4, "selected": false, "text": "*arguments.callee.caller arguments.caller" }, { "answer_id": 280510, "author": "user15566", "author_id": 15566, "author_profile": "https://Stackoverflow.com/users/15566", "pm_score": 4, "selected": false, "text": "arguments.callee.caller.name\n" }, { "answer_id": 280598, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 4, "selected": false, "text": "function Hello() {\n alert(Hello.caller);\n}\n" }, { "answer_id": 721516, "author": "nourdine", "author_id": 87624, "author_profile": "https://Stackoverflow.com/users/87624", "pm_score": 6, "selected": false, "text": "function Hello() {\n alert(\"caller is \" + arguments.callee.caller.toString());\n}\n function Hello() {\n alert(\"caller is \" + Hello.caller.toString());\n}\n" }, { "answer_id": 3789144, "author": "Mariano Desanze", "author_id": 146513, "author_profile": "https://Stackoverflow.com/users/146513", "pm_score": 7, "selected": false, "text": "var Klass = function kls() {\n this.Hello = function() { alert(printStackTrace().join('\\n\\n')); };\n}\nnew Klass().Hello();\n ... kls.Hello ( ... function Klass kls {guess: true} arguments.callee.caller.name\n function arguments.callee.caller.toString();\n" }, { "answer_id": 4047670, "author": "ale5000", "author_id": 490687, "author_profile": "https://Stackoverflow.com/users/490687", "pm_score": 6, "selected": false, "text": "arguments.callee.caller\narguments.callee.caller.caller\narguments.callee.caller.caller.caller\n null" }, { "answer_id": 9713707, "author": "JoolzCheat", "author_id": 1270636, "author_profile": "https://Stackoverflow.com/users/1270636", "pm_score": 3, "selected": false, "text": "var callerFunction = arguments.callee.caller.toString().match(/function ([^\\(]+)/)[1];\n var callerFunction = (arguments.callee.caller.toString().match(/function ([^\\(]+)/) === null) ? 'Document Object Model': arguments.callee.caller.toString().match(/function ([^\\(]+)/)[1], arguments.callee.toString().match(/function ([^\\(]+)/)[1]);\n" }, { "answer_id": 12384187, "author": "BrazFlat", "author_id": 1665043, "author_profile": "https://Stackoverflow.com/users/1665043", "pm_score": 3, "selected": false, "text": "functionname caller.toString() <!DOCTYPE html>\n<meta charset=\"UTF-8\">\n<title>Show the callers name</title><!-- This validates as html5! -->\n<script>\nmain();\nfunction main() { Hello(); }\nfunction Hello(){\n var name = Hello.caller.toString().replace(/\\s\\([^#]+$|^[^\\s]+\\s/g,'');\n name = name.replace(/\\s/g,'');\n if ( typeof window[name] !== 'function' )\n alert (\"sorry, the type of \"+name+\" is \"+ typeof window[name]);\n else\n alert (\"The name of the \"+typeof window[name]+\" that called is \"+name);\n}\n</script>\n" }, { "answer_id": 17255041, "author": "Diego Augusto Molina", "author_id": 2512368, "author_profile": "https://Stackoverflow.com/users/2512368", "pm_score": 2, "selected": false, "text": "function getStackTrace(){\n var f = arguments.callee;\n var ret = [];\n var item = {};\n var iter = 0;\n\n while ( f = f.caller ){\n // Initialize\n item = {\n name: f.name || null,\n args: [], // Empty array = no arguments passed\n callback: f\n };\n\n // Function arguments\n if ( f.arguments ){\n for ( iter = 0; iter<f.arguments.length; iter++ ){\n item.args[iter] = f.arguments[iter];\n }\n } else {\n item.args = null; // null = argument listing not supported\n }\n\n ret.push( item );\n }\n return ret;\n}\n" }, { "answer_id": 22165274, "author": "QueueHammer", "author_id": 46810, "author_profile": "https://Stackoverflow.com/users/46810", "pm_score": 5, "selected": false, "text": "function ScriptPath() {\n var scriptPath = '';\n try {\n //Throw an error to generate a stack trace\n throw new Error();\n }\n catch(e) {\n //Split the stack trace into each line\n var stackLines = e.stack.split('\\n');\n var callerIndex = 0;\n //Now walk though each line until we find a path reference\n for(var i in stackLines){\n if(!stackLines[i].match(/http[s]?:\\/\\//)) continue;\n //We skipped all the lines with out an http so we now have a script reference\n //This one is the class constructor, the next is the getScriptPath() call\n //The one after that is the user code requesting the path info (so offset by 2)\n callerIndex = Number(i) + 2;\n break;\n }\n //Now parse the string for each section we want to return\n pathParts = stackLines[callerIndex].match(/((http[s]?:\\/\\/.+\\/)([^\\/]+\\.js)):/);\n }\n\n this.fullPath = function() {\n return pathParts[1];\n };\n\n this.path = function() {\n return pathParts[2];\n };\n\n this.file = function() {\n return pathParts[3];\n };\n\n this.fileNoExt = function() {\n var parts = this.file().split('.');\n parts.length = parts.length != 1 ? parts.length - 1 : 1;\n return parts.join('.');\n };\n}\n" }, { "answer_id": 22944747, "author": "Pablo Armentano", "author_id": 970375, "author_profile": "https://Stackoverflow.com/users/970375", "pm_score": 3, "selected": false, "text": "name arguments.callee.caller.toString()" }, { "answer_id": 30103737, "author": "heystewart", "author_id": 4875359, "author_profile": "https://Stackoverflow.com/users/4875359", "pm_score": 6, "selected": false, "text": "(new Error()).stack" }, { "answer_id": 30687518, "author": "Greg", "author_id": 410333, "author_profile": "https://Stackoverflow.com/users/410333", "pm_score": 5, "selected": false, "text": "function Hello() { return Hello.caller;}\n\nHello2 = function NamedFunc() { return NamedFunc.caller; };\n\nfunction main()\n{\n Hello(); //both return main()\n Hello2();\n}\n" }, { "answer_id": 33489922, "author": "Mario PG", "author_id": 5518040, "author_profile": "https://Stackoverflow.com/users/5518040", "pm_score": 0, "selected": false, "text": "function main()\n{\n Hello(this);\n}\n\nfunction Hello(caller)\n{\n // caller will be the object that called Hello. boom like that... \n // you can add an undefined check code if the function Hello \n // will be called without parameters from somewhere else\n}\n" }, { "answer_id": 34853024, "author": "humkins", "author_id": 1902296, "author_profile": "https://Stackoverflow.com/users/1902296", "pm_score": 6, "selected": false, "text": "function main() {\n Hello();\n}\n\nfunction Hello() {\n console.trace()\n}\n\nmain()\n// Hello @ VM261:9\n// main @ VM261:4\n" }, { "answer_id": 35799799, "author": "GrayedFox", "author_id": 3249501, "author_profile": "https://Stackoverflow.com/users/3249501", "pm_score": 1, "selected": false, "text": "function reformatString(string, callerName) {\n\n if (callerName === \"uid\") {\n string = string.toUpperCase();\n }\n\n return string;\n}\n function uid(){\n var myString = \"apples\";\n\n reformatString(myString, function.name);\n}\n" }, { "answer_id": 36256573, "author": "Abrar Jahin", "author_id": 2193439, "author_profile": "https://Stackoverflow.com/users/2193439", "pm_score": 1, "selected": false, "text": "function whoCalled()\n{\n if (arguments.caller == null)\n console.log('I was called from the global scope.');\n else\n console.log(arguments.caller + ' called me!');\n}\n function myFunc()\n{\n if (myFunc.caller == null) {\n return 'The function was called from the top!';\n }\n else\n {\n return 'This function\\'s caller was ' + myFunc.caller;\n }\n}\n" }, { "answer_id": 36277165, "author": "autistic", "author_id": 1989425, "author_profile": "https://Stackoverflow.com/users/1989425", "pm_score": 1, "selected": false, "text": "function caller()\n{\n return caller.caller.caller;\n}\n\n'use strict';\nfunction main()\n{\n // Original question:\n Hello();\n // Bounty question:\n (function() { console.log('Anonymous function called by ' + caller().name); })();\n}\n\nfunction Hello()\n{\n // How do you find out the caller function is 'main'?\n console.log('Hello called by ' + caller().name);\n}\n\nmain();" }, { "answer_id": 36596619, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "function stacktrace() {\nvar f = stacktrace;\nvar stack = 'Stack trace:';\nwhile (f) {\n stack += '\\n' + f.name;\n f = f.caller;\n}\nreturn stack;\n}\n" }, { "answer_id": 42096635, "author": "Anonymous", "author_id": 437393, "author_profile": "https://Stackoverflow.com/users/437393", "pm_score": 1, "selected": false, "text": "var stackTrace = function() {\n\n var calls = [];\n var caller = arguments.callee.caller;\n\n for (var k = 0; k < 10; k++) {\n if (caller) {\n calls.push(caller);\n caller = caller.caller;\n }\n }\n\n return calls;\n};\n\n// when I call this inside specific method I see list of references to source method, obviously, I can add toString() to each call to see only function's content\n// [function(), function(data), function(res), function(l), function(a, c), x(a, b, c, d), function(c, e)]\n" }, { "answer_id": 43674446, "author": "吴家荣", "author_id": 7387209, "author_profile": "https://Stackoverflow.com/users/7387209", "pm_score": 1, "selected": false, "text": "window.fnPureLog = function(sStatement, anyVariable) {\n if (arguments.length < 1) { \n throw new Error('Arguments sStatement and anyVariable are expected'); \n }\n if (typeof sStatement !== 'string') { \n throw new Error('The type of sStatement is not match, please use string');\n }\n var oCallStackTrack = new Error();\n console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\\n' + sStatement + ':', anyVariable);\n}\n window.fnPureLog = function(sStatement, anyVariable) {\n if (arguments.length < 1) { \n throw new Error('Arguments sStatement and anyVariable are expected'); \n }\n if (typeof sStatement !== 'string') { \n throw new Error('The type of sStatement is not match, please use string');\n }\n var oCallStackTrack = new Error();\n console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\\n' + sStatement + ':', anyVariable);\n}\n\nfunction fnBsnCallStack1() {\n fnPureLog('Stock Count', 100)\n}\n\nfunction fnBsnCallStack2() {\n fnBsnCallStack1()\n}\n\nfnBsnCallStack2();\n Call Stack:\n at window.fnPureLog (<anonymous>:8:27)\n at fnBsnCallStack1 (<anonymous>:13:5)\n at fnBsnCallStack2 (<anonymous>:17:5)\n at <anonymous>:20:1 \nStock Count: 100\n" }, { "answer_id": 45072174, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 5, "selected": false, "text": "Error stack function main() {\n Hello();\n}\n\nfunction Hello() {\n try {\n throw new Error();\n } catch (err) {\n let stack = err.stack;\n // N.B. stack === \"Error\\n at Hello ...\\n at main ... \\n....\"\n let m = stack.match(/.*?Hello.*?\\n(.*?)\\n/);\n if (m) {\n let caller_name = m[1];\n console.log(\"Caller is:\", caller_name);\n }\n }\n}\n\nmain(); Safari : Caller is: main@https://stacksnippets.net/js:14:8\nFirefox : Caller is: main@https://stacksnippets.net/js:14:3\nChrome : Caller is: at main (https://stacksnippets.net/js:14:3)\nIE Edge : Caller is: at main (https://stacksnippets.net/js:14:3)\nIE : Caller is: at main (https://stacksnippets.net/js:14:3)\n var stack = (new Error()).stack stack Error callee caller" }, { "answer_id": 47340333, "author": "inorganik", "author_id": 591487, "author_profile": "https://Stackoverflow.com/users/591487", "pm_score": 5, "selected": false, "text": "function Hello() {\n console.trace();\n}\n" }, { "answer_id": 48985787, "author": "Rovanion", "author_id": 501017, "author_profile": "https://Stackoverflow.com/users/501017", "pm_score": 4, "selected": false, "text": "caller Error 'use strict';\nconst fnNameMatcher = /([^(]+)@|at ([^(]+) \\(/;\n\nfunction fnName(str) {\n const regexResult = fnNameMatcher.exec(str);\n return regexResult[1] || regexResult[2];\n}\n\nfunction log(...messages) {\n const logLines = (new Error().stack).split('\\n');\n const callerName = fnName(logLines[1]);\n\n if (callerName !== null) {\n if (callerName !== 'log') {\n console.log(callerName, 'called log with:', ...messages);\n } else {\n console.log(fnName(logLines[2]), 'called log with:', ...messages);\n }\n } else {\n console.log(...messages);\n }\n}\n\nfunction foo() {\n log('hi', 'there');\n}\n\n(function main() {\n foo();\n}());" }, { "answer_id": 49274444, "author": "Prasanna", "author_id": 4272651, "author_profile": "https://Stackoverflow.com/users/4272651", "pm_score": 4, "selected": false, "text": "const hello = () => {\n console.log(new Error('I was called').stack)\n}\n\nconst sello = () => {\n hello()\n}\n\nsello()" }, { "answer_id": 52925988, "author": "pouyan", "author_id": 2398444, "author_profile": "https://Stackoverflow.com/users/2398444", "pm_score": 1, "selected": false, "text": "function getCallerName(func)\n{\n if (!func) return \"anonymous\";\n let caller = func.caller;\n if (!caller) return \"anonymous\";\n caller = caller.toString();\n if (!caller.trim().startsWith(\"function\")) return \"anonymous\";\n return caller.substring(0, caller.indexOf(\"(\")).replace(\"function\",\"\");\n}\n\n\n// Example of how to use \"getCallerName\" function\n\nfunction Hello(){\nconsole.log(\"ex1 => \" + getCallerName(Hello));\n}\n\nfunction Main(){\nHello();\n\n// another example\nconsole.log(\"ex3 => \" + getCallerName(Main));\n}\n\nMain();" }, { "answer_id": 57023880, "author": "VanagaS", "author_id": 2546381, "author_profile": "https://Stackoverflow.com/users/2546381", "pm_score": 6, "selected": false, "text": "console.log((new Error()).stack.split(\"\\n\")[2].trim().split(\" \")[1])\n console.log((new Error()).stack.split(\"\\n\")[1].trim().split(\" \")[1]) \n" }, { "answer_id": 60370866, "author": "ns16", "author_id": 7755085, "author_profile": "https://Stackoverflow.com/users/7755085", "pm_score": 2, "selected": false, "text": "var callerId = require('caller-id');\n\nfunction foo() {\n bar();\n}\nfunction bar() {\n var caller = callerId.getData();\n /*\n caller = {\n typeName: 'Object',\n functionName: 'foo',\n filePath: '/path/of/this/file.js',\n lineNumber: 5,\n topLevelFlag: true,\n nativeFlag: false,\n evalFlag: false\n }\n */\n}\n" }, { "answer_id": 65168658, "author": "Israel", "author_id": 8244338, "author_profile": "https://Stackoverflow.com/users/8244338", "pm_score": 2, "selected": false, "text": "function getCaller(functionBack= 0) {\n const back = functionBack * 2;\n const stack = new Error().stack.split('at ');\n const stackIndex = stack[3 + back].includes('C:') ? (3 + back) : (4 + back);\n const isAsync = stack[stackIndex].includes('async');\n let result;\n if (isAsync)\n result = stack[stackIndex].split(' ')[1].split(' ')[0];\n else\n result = stack[stackIndex].split(' ')[0];\n return result;\n}\n" }, { "answer_id": 69769143, "author": "bbonch", "author_id": 1513020, "author_profile": "https://Stackoverflow.com/users/1513020", "pm_score": 0, "selected": false, "text": "function main()\n{\n Hello();\n}\n\nfunction Hello()\n{\n new Error().stack\n}\n" }, { "answer_id": 69837438, "author": "Anna Do", "author_id": 9957129, "author_profile": "https://Stackoverflow.com/users/9957129", "pm_score": 2, "selected": false, "text": "1. console.trace();\n2. console.log((new Error).stack)\n\n// do the same as #2 just with better view\n3. console.log((new Error).stack.split(\"\\n\")) \n" }, { "answer_id": 70904900, "author": "Mohamad amin Moslemi", "author_id": 11738858, "author_profile": "https://Stackoverflow.com/users/11738858", "pm_score": 0, "selected": false, "text": "debugger;" }, { "answer_id": 72656754, "author": "Putin - The Hero", "author_id": 961631, "author_profile": "https://Stackoverflow.com/users/961631", "pm_score": 1, "selected": false, "text": "Strict Mode On/Off console.log(`caller:${(new Error()).stack?.split('\\n')[2].trim().split(' ')[1]}`)\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11413/" ]
280,406
<p>I have problems with bringing a windows mobile 6 form to the front. I tried things like this already</p> <pre><code>Form1 testForm = new Form1(); testForm.Show(); testForm.BringToFront(); testForm.Focus(); </code></pre> <p>But it's always behind the form that includes that code. The only things that have worked for me are</p> <pre><code>testForm.TopMost = true; </code></pre> <p>or Hide(); the old form and then show the new one, but i want to avoid hiding the other form. TopMost isn't very clean anyway with using multiple other forms.</p> <p>The other thing that works is</p> <pre><code>testForm.ShowDialog(); </code></pre> <p>but I don't want to show the form modal.</p> <p>To cut it short. I just want to show the new form in front of another form, and if I close it, I want to see the old form again.</p> <p>Maybe someone can help me with this problem. Thank you.</p>
[ { "answer_id": 280478, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 3, "selected": true, "text": "[DllImport(\"coredll.dll\")]\nprivate static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n[DllImport(\"coredll.dll\", EntryPoint=\"SetForegroundWindow\")]\nprivate static extern int SetForegroundWindow(IntPtr hWnd);\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36481/" ]
280,413
<p><strong>Closed as exact duplicate of <a href="https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method">"How can I find the method that called the current method?"</a></strong></p> <p>Is <a href="https://stackoverflow.com/questions/280389/javascript-how-do-you-find-the-caller-function">this</a> possible with c#?</p> <pre><code>void main() { Hello(); } void Hello() { // how do you find out the caller is function 'main'? } </code></pre>
[ { "answer_id": 280425, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "Console.WriteLine(new StackFrame(1).GetMethod().Name);\n" }, { "answer_id": 280432, "author": "schnaader", "author_id": 34065, "author_profile": "https://Stackoverflow.com/users/34065", "pm_score": 2, "selected": false, "text": "System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1);\nSystem.Diagnostics.StackFrame sf = st.GetFrame(0);\nstring msg = sf.GetMethod().DeclaringType.FullName + \".\" +\nsf.GetMethod().Name;\nMessageBox.Show( msg );\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
280,421
<p>It seems that when I have one mysql_real_query() function in a continuous while loop, the query will get executed OK.</p> <p>However, if multiple mysql_real_query() are inside the while loop, one right after the other. Depending on the query, sometimes neither the first query nor second query will execute properly.</p> <p>This seems like a threading issue to me. I'm wondering if the mysql c api has a way of dealing with this? Does anyone know how to deal with this? mysql_free_result() doesn't work since I am not even storing the results.</p> <pre><code>//keep polling as long as stop character '-' is not read while(szRxChar != '-') { // Check if a read is outstanding if (HasOverlappedIoCompleted(&amp;ovRead)) { // Issue a serial port read if (!ReadFile(hSerial,&amp;szRxChar,1, &amp;dwBytesRead,&amp;ovRead)) { DWORD dwErr = GetLastError(); if (dwErr!=ERROR_IO_PENDING) return dwErr; } } // Wait 5 seconds for serial input if (!(HasOverlappedIoCompleted(&amp;ovRead))) { WaitForSingleObject(hReadEvent,RESET_TIME); } // Check if serial input has arrived if (GetOverlappedResult(hSerial,&amp;ovRead, &amp;dwBytesRead,FALSE)) { // Wait for the write GetOverlappedResult(hSerial,&amp;ovWrite, &amp;dwBytesWritten,TRUE); //load tagBuffer with byte stream tagBuffer[i] = szRxChar; i++; tagBuffer[i] = 0; //char arrays are \0 terminated //run query with tagBuffer if( strlen(tagBuffer)==PACKET_LENGTH ) { sprintf(query,"insert into scan (rfidnum) values ('"); strcat(query, tagBuffer); strcat(query, "')"); mysql_real_query(&amp;mysql,query,(unsigned int)strlen(query)); i=0; } mysql_real_query(&amp;mysql,"insert into scan (rfidnum) values ('2nd query')",(unsigned int)strlen("insert into scan (rfid) values ('2nd query')")); mysql_free_result(res); } } </code></pre>
[ { "answer_id": 280456, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "tagBuffer mysql_real_query tagBuffer" }, { "answer_id": 282302, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "mysql_real_query() if ((err = mysql_real_query(&mysql,\"insert into scan (rfidnum) values ('2nd query')\",\n (unsigned int)strlen(\"insert into scan (rfid) values ('2nd query')\"))) != 0)\n{\n // report err here, get additional information from these two API calls:\n errno = mysql_errno(&mysql);\n errmsg = mysql_error(&mysql);\n}\n mysql_error() SELECT CR_COMMANDS_OUT_OF_SYNC SELECT mysql_free_result() mysql_use_result() mysql_use_result()" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
280,426
<p>We've got a fairly complex httphandler for handling images. Basically it streams any part of the image at any size that is requested. Some clients use this handler without any problems. But we've got one location that gives us problems, and now it also gives problems on my development environment.</p> <p>What happens is that the client never receives anything on some requests. So request 1 and 2 are fine, but request 3 and 4 never end. </p> <ul> <li>While debugging I can see that the server is ready and has completed the request.</li> <li>The client however is still waiting on a result (debugging with fiddler2 shows that there is no response received)</li> </ul> <p>The code that we use to stream an image is</p> <pre><code> if (!context.Response.IsClientConnected) { imageStream.Close(); imageStream.Dispose(); return; } context.Response.BufferOutput = true; context.Response.ContentType = "image/" + imageformat; context.Response.AppendHeader("Content-Length", imageStream.Length.ToString()); if (imageStream != null &amp;&amp; imageStream.Length &gt; 0 &amp;&amp; context.Response.IsClientConnected) context.Response.BinaryWrite(imageStream.ToArray()); if (context.Response.IsClientConnected) context.Response.Flush(); imageStream.Close(); imageStream.Dispose(); </code></pre> <p>The imageStream is a MemoryStream with the contents of an image.</p> <p>After the call to response.Flush() we do some more clean-up and writing summaries to the eventlog. </p> <p>We also call GC.Collect() after every request, because the objects that we use in-memory become very large. I know that that is not a good practice, but could it give us trouble?</p> <p>The problems with not returning requests happen at both IIS 5 (Win XP) and IIS 6 (Win 2003), we use .NET framework v2.</p>
[ { "answer_id": 280436, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "MemoryStream const int BUFFER_SIZE = 4096; // pick your poison\nbute[] buffer = new byte[BUFFER_SIZE];\nint bytesRead;\n\nwhile((bytesRead = inStream.Read(buffer, 0, BUFFER_SIZE)) > 0)\n{\n outStream.Write(buffer, 0, bytesRead);\n}\n .Response.BufferOutput = false .Response.Close()" }, { "answer_id": 280438, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "BufferOutput" }, { "answer_id": 280696, "author": "Michiel Overeem", "author_id": 5043, "author_profile": "https://Stackoverflow.com/users/5043", "pm_score": 0, "selected": false, "text": "using (HttpWebResponse test_resp = (HttpWebResponse)test_req.GetResponse())\n{\n}\n" }, { "answer_id": 281259, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 3, "selected": true, "text": "HttpWebResponse GetResponseStream" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5043/" ]
280,428
<p>I have one autocomplete search, in which by typing few characters it will show all the names, which matches the entered character. I am populating this data in the jsp using DIV tag, by using mouse I'm able to select the names. But I want to select the names in the DIV tag to be selected using the keyboard up and down arrow. Can anyone please help me out from this.</p>
[ { "answer_id": 280455, "author": "Shivasubramanian A", "author_id": 9195, "author_profile": "https://Stackoverflow.com/users/9195", "pm_score": 0, "selected": false, "text": "event.keyCode" }, { "answer_id": 375426, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 4, "selected": false, "text": "onkeydown onkeyup var UP = 38;\nvar DOWN = 40;\nvar ENTER = 13;\n\nvar getKey = function(e) {\n if(window.event) { return e.keyCode; } // IE\n else if(e.which) { return e.which; } // Netscape/Firefox/Opera\n};\n\n\nvar keynum = getKey(e);\n\nif(keynum === UP) {\n //Move selection up\n}\n\nif(keynum === DOWN) {\n //Move selection down\n}\n\nif(keynum === ENTER) {\n //Act on current selection\n}\n" }, { "answer_id": 477740, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<style>\ndiv.active{ \n background: lightblue\n}\n</style>\n<center>\n<input type=\"text\" id=\"tb\">\n<div id=\"Parent\" style=\"position:absolute;display:block;left:428px; width:146px;top:38px; height:100px; border: 2px solid lightblue; overflow:auto;\"> \n<div id=\"childOne\">1 </div> \n<div id=\"childOne\">2 </div> \n<div id=\"childOne\">3 </div> \n<div id=\"childOne\">4 </div>\n<div id=\"childOne\">5 </div>\n<div id=\"childOne\">6 </div>\n<div id=\"childOne\">7 </div>\n<div id=\"childOne\">8 </div>\n<div id=\"childOne\">9 </div>\n<div id=\"childOne\">10 </div>\n</div>\n</center>\n<script type=\"text/javascript\">\n var scrolLength = 19;\n function autocomplete( textBoxId, containerDivId ) { \n var ac = this; \n this.textbox = document.getElementById(textBoxId); \n this.div = document.getElementById(containerDivId); \n this.list = this.div.getElementsByTagName('div'); \n this.pointer = null; \n this.textbox.onkeydown = function( e ) {\n e = e || window.event; \n switch( e.keyCode ) { \n case 38: //up \n ac.selectDiv(-1); \n break; \n case 40: //down \n ac.selectDiv(1); \n break; } \n } \n\n this.selectDiv = function( inc ) { \n if(this.pointer > 1){\n scrollDiv();\n }\n if(this.pointer == 0)\n document.getElementById(\"Parent\").scrollTop = 0; \n if( this.pointer !== null && this.pointer+inc >= 0 && this.pointer+inc < this.list.length ) { \n this.list[this.pointer].className = ''; \n this.pointer += inc; \n this.list[this.pointer].className = 'active'; \n this.textbox.value = this.list[this.pointer].innerHTML; \n }\n if( this.pointer === null ) { \n\n this.pointer = 0; \n scrolLength = 20;\n this.list[this.pointer].className = 'active'; \n this.textbox.value = this.list[this.pointer].innerHTML; \n } \n }\n function scrollDiv(){\n if(window.event.keyCode == 40){\n document.getElementById(\"Parent\").scrollTop = scrolLength;\n scrolLength = scrolLength + 19; \n } \n else if(window.event.keyCode == 38){\n\n scrolLength = scrolLength - 19; \n document.getElementById(\"Parent\").scrollTop = scrolLength;\n\n }\n }\n } \n new autocomplete( 'tb', 'Parent' );\n</script>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
280,435
<p>I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex?</p> <p>For example, the user wants to search for Word <code>(s)</code>: regex engine will take the <code>(s)</code> as a group. I want it to treat it like a string <code>&quot;(s)&quot; </code>. I can run <code>replace</code> on user input and replace the <code>(</code> with <code>\(</code> and the <code>)</code> with <code>\)</code> but the problem is I will need to do replace for every possible regex symbol.</p> <p>Do you know some better way ?</p>
[ { "answer_id": 280441, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 10, "selected": true, "text": "re.escape() re def simplistic_plural(word, text):\n word_or_plural = re.escape(word) + 's?'\n return re.match(word_or_plural, text)\n" }, { "answer_id": 280463, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 6, "selected": false, "text": "re.escape() >>> import re\n>>> re.escape('^a.*$')\n'\\\\^a\\\\.\\\\*\\\\$'\n _" }, { "answer_id": 42423081, "author": "Owen", "author_id": 371739, "author_profile": "https://Stackoverflow.com/users/371739", "pm_score": 3, "selected": false, "text": "re.escape() >>> re.sub('a', re.escape('_'), 'aa')\n'\\\\_\\\\_'\n >>> re.sub('a', lambda _: '_', 'aa')\n'__'\n re.sub()" }, { "answer_id": 73068412, "author": "Charlie Parker", "author_id": 1601580, "author_profile": "https://Stackoverflow.com/users/1601580", "pm_score": -1, "selected": false, "text": "\\n print \\r\"\\n\" r\"(\\n+) r\"(\\fun \\( x : nat \\) :)\" re.escape(regex) # escapes non-alphanumeric to help match arbitrary literal string, I think the reason this is here is to help differentiate the things escaped from the regex we are inserting in the next line and the literal things we wanted escaped.\n __ppt = re.escape(_ppt) # used for e.g. parenthesis ( are not interpreted as was to group this but literally\n _ppt\nOut[4]: '(let H : forall x : bool, negb (negb x) = x := fun x : bool =>HEREinHERE)'\n__ppt\nOut[5]: '\\\\(let\\\\ H\\\\ :\\\\ forall\\\\ x\\\\ :\\\\ bool,\\\\ negb\\\\ \\\\(negb\\\\ x\\\\)\\\\ =\\\\ x\\\\ :=\\\\ fun\\\\ x\\\\ :\\\\ bool\\\\ =>HEREinHERE\\\\)'\nprint(rf'{_ppt=}')\n_ppt='(let H : forall x : bool, negb (negb x) = x := fun x : bool =>HEREinHERE)'\nprint(rf'{__ppt=}')\n__ppt='\\\\(let\\\\ H\\\\ :\\\\ forall\\\\ x\\\\ :\\\\ bool,\\\\ negb\\\\ \\\\(negb\\\\ x\\\\)\\\\ =\\\\ x\\\\ :=\\\\ fun\\\\ x\\\\ :\\\\ bool\\\\ =>HEREinHERE\\\\)'\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/280435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288629/" ]