qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
236,744
<p>What single aspect of agile development should we implement first to improve our development process, and why? </p> <p>I'm in a situation that's requiring me to "tweak" my process, rather than re-engineer it, and "agile" seems to be the mantra of the day. If we can make only one change that will improve something--quality, time to market, documentation, transparency, <em>etc</em>., what will have the most visible, positive impact?</p> <p>If we choose correctly, we'll be able to make a second choice. :-)</p> <p><strong>Update:</strong> <em>What is your current SDLC?</em><br> Environment: essentially "restartup." A <em>small</em> handful of developers; legacy products with 10^5-10^6 LOC and tens of thousands deployed worldwide; products are strongly interdependent; significant features added over the years, including many one-offs, w/o refactoring; tight schedules; superficial QA; no <em>post-mortems</em> or "process guru."</p> <p>Typical process:</p> <ol> <li>Create design/spec. Review by all stakeholders.</li> <li>Code one or more features/fixes.</li> <li>Revise design/spec to account for surprises.</li> <li>Test features, record defects.</li> <li>Prioritize new and remaining tasks.</li> <li>Revise design/spec/schedule.</li> <li>Return to Step 2 as necessary.</li> <li>Release for beta, record feedback.</li> <li>Return to Step 2 as necessary. </li> <li>Official release.</li> </ol> <p>Thanks for so many helpful suggestions and insights!</p>
[ { "answer_id": 237062, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 1, "selected": false, "text": "-----> [Stress] <--o-- / --o--> [RunTests]\n [TestFirst] <--o-- / --o--> [Stress]\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29157/" ]
236,749
<p>I have a bunch of ASP.NET web pages (that have a standard layout) that are product documentation. I want to create some sort of combination page that will pull all of the other page content in and concatenate them into one long page.</p> <p>IFrames won't work because I don't know the size of each page. I could have the combination page do a ton of #includes, and that would work, but I don't want to have to keep the master update to date (we have a database of page names that can change over time).</p> <p>Ultimately I'm after something that can get a list of pages, and for each one do the equivalent of a #include for that page into the current page.</p> <p>I hope that makes sense. Any thoughts?</p>
[ { "answer_id": 236767, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "Server.MapPath var actualDiskFilename = Server.MapPath(\"~/somewhere/somepage.html\");\n System.IO var virtualDir = \"~/somefolder/\";\nvar actualDir = Server.MapPath(virtualDir);\n\nvar files = Directory.GetFiles(actualDir);\n" }, { "answer_id": 236776, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": true, "text": "//assume that the array of page names has come from the DB.\nprotected void Page_Load(object sender, EventArgs e)\n{\n string[] pages = new string [] { \"~/Default.html\", \n \"~/Default2.html\", \"~/Default3.html\", \"~/Default4.html\" };\n\n foreach (string p in pages)\n {\n Response.WriteFile(p);\n }\n}\n" }, { "answer_id": 236823, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 0, "selected": false, "text": "Server.Execute" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7442/" ]
236,778
<p>I have a table named Info of this schema:</p> <pre><code>int objectId; int time; int x, y; </code></pre> <p>There is a lot of redundant data in the system - that is, <code>objectId</code> is not UNIQUE. For each <code>objectId</code> there can be multiple entries of <code>time, x, y</code>.</p> <p>I want to retrieve a list of the latest position of each object. I started out with this query:</p> <pre><code>SELECT * FROM Info GROUP BY objectId </code></pre> <p>That got me just the kind of list I was looking for. However I want also to get just the latest times for each Object, so I tried:</p> <pre><code>SELECT * FROM Info GROUP BY objectId ORDER BY time DESC </code></pre> <p>This gave me a <code>time</code> descended list of Infos. However, <strong>I don't think it did what I want - that is return me the latest <code>time, x, y</code> for each object</strong>.</p> <p>Can anyone imagine a query to do what I want?</p> <p><strong>Update</strong> I have tried the top three solutions to see how they perform against each other on a dataset of about 50,000 Infos. Here are the results:</p> <pre><code>-- NO INDEX: forever -- INDEX: 7.67 s SELECT a.* FROM Info AS a LEFT OUTER JOIN Info AS b ON (a.objectId = b.objectId AND a.time &lt; b.time) WHERE b.objectId IS NULL; -- NO INDEX: 8.05 s -- INDEX: 0.17 s select a.objectId, a.time, a.x, a.y from Info a, (select objectId, max(time) time from Info group by objectId) b where a.objectId = b.objectId and a.time = b.time; -- NO INDEX: 8.30 s -- INDEX: 0.18 s SELECT A.time, A.objectId, B.x, B.y FROM ( SELECT max(time) as time, objectId FROM Info GROUP by objectId ) as A INNER JOIN Info B ON A.objectId = b.objectId AND A.time = b.time; </code></pre> <p>By a margin, it would seem <code>where</code> outperforms <code>inner join</code>.</p>
[ { "answer_id": 236786, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": false, "text": "SELECT A.time, A.objectID, B.X, B.Y\nFROM\n(\n SELECT max(time) as time, objectID \n FROM table\n GROUP by objectID\n) as A \nINNER JOIN table B\n ON A.objectID = b.objectID AND A.Time = b.Time\n" }, { "answer_id": 236790, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 4, "selected": true, "text": "select distinct a.objectID, a.time, a.x, a.y\n from Info a,\n (select objectID, max(time) time from Info group by objectID) b\n where a.objectID = b.objectID and a.time = b.time\n" }, { "answer_id": 236828, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "SELECT a.*\nFROM Info AS a\n LEFT OUTER JOIN Info AS b ON (a.objectID = b.objectID AND a.time < b.time)\nWHERE b.objectID IS NULL;\n" }, { "answer_id": 236919, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 1, "selected": false, "text": "Select Info.*\nfrom Info\ninner join\n (select ObjectId, max(time) as Latest\n from Info\n group by ObjectId) I\non Info.ObjectId = I.ObjectID and Info.time = I.Latest\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
236,792
<p>I take care of critical app in my project. It does stuff related to parsing business msgs (legacy standard), processing them and then storing some results in a DB (another apps picks that up). After more then a year of my work (I've other apps to look after as well) the app is finally stable. I've introduced strict TDD policy and I have 20% unit test coverage (thank you Michael Feathers for your book!), most of it in critical parts. I have some white-box Fitness tests as well (whole business scenarios are covered there). I feel that I cannot further refactor this app and I'm safe to play hard with it. It's designed so badly, I want to rewrite it. App itself is around 20k of challenging legacy C/C++ code. There were other dependencies but I manged to decouple most of them.</p> <hr> <p>All I have is Sun C++ compiler, cppunitlite, STLPort and Boost. Please do not suggest other technologies (no XML, Java etc) as this is not the option in my organization. I'd like to do it with modern C++ (perhaps play with metaprogramming...), TDD from start to the end.</p> <p>There are about 30 types of msgs I need to parse. Each of them is composed of 3-10 lines, most of them are pretty similar. This is root of all evil -> lots of code duplication. Each msgs has a class describing how it should be parsed. Take a look at the main inheritance tree:</p> <pre><code> MSG_A MSG_B / \ / \ MSG_A_NEW MSG_A_CNL MSG_B_NEW MSG_B_CNL </code></pre> <p>Both trees goes much deeper. There are very small differences between MSG_A_NEW and MSG_B_NEW. It should be handled by single class that could be injected with some small customization.</p> <p>My initial plan it to have one generic msg class that will be customized. Some entity (builder... ?) will take a look at the msgs and initialize proper object that will be able to parse the msg. Another entity will be able to discover what line is it and this info will be used by builder. I'm planning to write several parsers that are responsible for parsing just one specific line. This will allow me to reuse it in parsing different msgs.</p> <p>There are several challenges that I struggle to solve in an elegant and extensible way. Each type of msg:</p> <p>has min and max number if lines - has some must-have lines - has some optional lines - certain lines must be at certain places (i.e. date cannot be before msg type), order matters</p> <p>I need to be able to validate format of the msgs.</p> <hr> <p>I'm not sure if I explained the design challenge here good enough. My design experience is very limited. I've been bug-fixing for a while now and finally I will have a change to do some fun codding :)</p> <p>What high-level advice do you have for that? Which design patterns can you identify in this description? Main design constraint is maintainability and extensibility with performance at the bottom (we have other bottlenecks anyway...).</p>
[ { "answer_id": 237077, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 0, "selected": false, "text": "CheckForRequiredLines VerifyLineOrder" }, { "answer_id": 239693, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 0, "selected": false, "text": "Tuple mpl::vector Seq1 -> MSG_A_NEW, MSG_A_CNL\nSeq2 -> MSG_B_NEW, MSG_B_CNL\n" }, { "answer_id": 242676, "author": "eli", "author_id": 12893, "author_profile": "https://Stackoverflow.com/users/12893", "pm_score": 2, "selected": true, "text": "\n CommonHandler\n ^ ^\n | | = inheritance\n MsgAHandler\n ^ ^\n | |\nANewHandler ACnlHandler\n \n\nBasicHandler <>--- IMsgHandler ------------\\\n 1 1 ^ ^ ^ ^ * | ^\n | | | | | | = inheritance\n MsgAHandler | | ANewHandler 1 |\n ACnlHandler HandlerContainer <>-/ <>- = containment\n\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3579/" ]
236,793
<p>With DWR it is possible to group together several service calls into one single HTTP request :<br> <a href="http://directwebremoting.org/dwr/browser/engine/batch" rel="noreferrer">dwr batch feature</a><br><br> This feature is very useful to reduce the latency of an ajax application. Is there a way to do something similar with GWT / GWT-RPC ?<br> Thanks for your help</p>
[ { "answer_id": 236864, "author": "dmazzoni", "author_id": 7193, "author_profile": "https://Stackoverflow.com/users/7193", "pm_score": 1, "selected": false, "text": "FooResponse callFoo(FooRequest request);\n ArrayList<FooResponse> batchCallFoo(ArrayList<FooRequest> requests) {\n ArrayList<FooResponse> responses = new ArrayList<FooResponse>();\n for (FooRequest request : requests) {\n responses.add(callFoo(request));\n }\n}\n" }, { "answer_id": 400093, "author": "stian", "author_id": 17542, "author_profile": "https://Stackoverflow.com/users/17542", "pm_score": 1, "selected": false, "text": "public int add(int x, int y);\npublic int sub(int i, int j);\n public Map<String, Integer> addAndSub(Map methodsAndArguments) {\n // Call add and sub methods with it's arguments\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11897/" ]
236,795
<p>I have a PHP class that creates a PNG image on the fly and sends it to browser. PHP manual says that I need to make sure that <em>imagedestroy</em> function is called at end to release the memory. Now, if I weren't using a class, I would have some code like this:</p> <pre><code>function shutdown_func() { global $img; if ($img) imagedestroy($img); } register_shutdown_function("shutdown_func"); </code></pre> <p>However, I believe that appropriate place for my class would be to place a call to <em>imagedestroy</em> in class' destructor.</p> <p>I failed to find out if destructors get called the same way shutdown functions does? For example, if execution stops when user presses the STOP button in browser.</p> <p>Note: whatever you write in your answer, please point to some article or manual page (URL) that supports it.</p>
[ { "answer_id": 236811, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 0, "selected": false, "text": "unset()" }, { "answer_id": 236830, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 5, "selected": true, "text": "<?php\nclass X\n{\n function __destruct()\n {\n $fp = fopen(\"/var/www/htdocs/dtor.txt\", \"w+\");\n fputs($fp, \"Destroyed\\n\");\n fclose($fp);\n }\n};\n\n$obj = new X();\nwhile (true) {\n // do nothing\n}\n?>\n <?php\nfunction shutdown_func() {\n $fp = fopen(\"/var/www/htdocs/dtor.txt\", \"w+\");\n fputs($fp, \"Destroyed2\\n\");\n fclose($fp);\n}\nregister_shutdown_function(\"shutdown_func\");\n\nwhile (true) {\n // do nothing\n}\n?>\n" }, { "answer_id": 31690231, "author": "therightstuff", "author_id": 2860309, "author_profile": "https://Stackoverflow.com/users/2860309", "pm_score": 1, "selected": false, "text": "class MyClass\n{\n protected $myVar;\n\n /**\n * constructor, registers shutdown handling\n */\n public function __construct()\n {\n $this->myVar = array();\n\n // workaround: set $self because $this fails\n $self = $this;\n // register for error logging in case of timeout\n $shutdown = function () use (&$self) {\n $self->shutdown();\n };\n register_shutdown_function($shutdown);\n }\n\n /**\n * handle shutdown events\n */\n public function shutdown()\n {\n $error = error_get_last();\n // if shutdown in error\n if ($error['type'] === E_ERROR) {\n // write contents to error log\n error_log('MyClass->myVar on shutdown' . json_encode($this->myVar), 0);\n }\n }\n\n ...\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
236,801
<p>That's basically the question, is there a "right" way to implement <code>operator&lt;&lt;</code> ? Reading <a href="http://bytes.com/forum/thread170304.html" rel="noreferrer">this</a> I can see that something like:</p> <pre><code>friend bool operator&lt;&lt;(obj const&amp; lhs, obj const&amp; rhs); </code></pre> <p>is preferred to something like </p> <pre><code>ostream&amp; operator&lt;&lt;(obj const&amp; rhs); </code></pre> <p>But I can't quite see why should I use one or the other.</p> <p>My personal case is:</p> <pre><code>friend ostream &amp; operator&lt;&lt;(ostream &amp;os, const Paragraph&amp; p) { return os &lt;&lt; p.to_str(); } </code></pre> <p>But I could probably do:</p> <pre><code>ostream &amp; operator&lt;&lt;(ostream &amp;os) { return os &lt;&lt; paragraph; } </code></pre> <p>What rationale should I base this decision on?</p> <p><em>Note</em>:</p> <pre><code> Paragraph::to_str = (return paragraph) </code></pre> <p>where paragraph's a string.</p>
[ { "answer_id": 236806, "author": "Magnus Hoff", "author_id": 2971, "author_profile": "https://Stackoverflow.com/users/2971", "pm_score": 6, "selected": false, "text": "this << ostream friend ostream" }, { "answer_id": 236813, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 3, "selected": false, "text": "bool operator<<(const obj&, const obj&);\n stream operator < bool operator << ostream& operator<<(ostream&, const obj&); \n ostream friend" }, { "answer_id": 237074, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 8, "selected": true, "text": "#include <iostream>\n\nclass Paragraph\n{\n public:\n explicit Paragraph(std::string const& init)\n :m_para(init)\n {}\n\n std::string const& to_str() const\n {\n return m_para;\n }\n\n bool operator==(Paragraph const& rhs) const\n {\n return m_para == rhs.m_para;\n }\n bool operator!=(Paragraph const& rhs) const\n {\n // Define != operator in terms of the == operator\n return !(this->operator==(rhs));\n }\n bool operator<(Paragraph const& rhs) const\n {\n return m_para < rhs.m_para;\n }\n private:\n friend std::ostream & operator<<(std::ostream &os, const Paragraph& p);\n std::string m_para;\n};\n\nstd::ostream & operator<<(std::ostream &os, const Paragraph& p)\n{\n return os << p.to_str();\n}\n\n\nint main()\n{\n Paragraph p(\"Plop\");\n Paragraph q(p);\n\n std::cout << p << std::endl << (p == q) << std::endl;\n}\n" }, { "answer_id": 237111, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": false, "text": "ostream & operator<<(ostream &os) {\n return os << paragraph;\n}\n // T << Paragraph\nT & operator << (T & p_oOutputStream, const Paragraph & p_oParagraph)\n{\n // do the insertion of p_oParagraph\n return p_oOutputStream ;\n}\n\n// T >> Paragraph\nT & operator >> (T & p_oInputStream, const Paragraph & p_oParagraph)\n{\n // do the extraction of p_oParagraph\n return p_oInputStream ;\n}\n // T << Paragraph\nT & T::operator << (const Paragraph & p_oParagraph)\n{\n // do the insertion of p_oParagraph\n return *this ;\n}\n\n// T >> Paragraph\nT & T::operator >> (const Paragraph & p_oParagraph)\n{\n // do the extraction of p_oParagraph\n return *this ;\n}\n // OUTPUT << Paragraph\ntemplate <typename charT, typename traits>\nstd::basic_ostream<charT,traits> & operator << (std::basic_ostream<charT,traits> & p_oOutputStream, const Paragraph & p_oParagraph)\n{\n // do the insertion of p_oParagraph\n return p_oOutputStream ;\n}\n\n// INPUT >> Paragraph\ntemplate <typename charT, typename traits>\nstd::basic_istream<charT,traits> & operator >> (std::basic_istream<charT,traits> & p_oInputStream, const CMyObject & p_oParagraph)\n{\n // do the extract of p_oParagraph\n return p_oInputStream ;\n}\n // OUTPUT << A\nstd::ostream & operator << (std::ostream & p_oOutputStream, const Paragraph & p_oParagraph)\n{\n // do the insertion of p_oParagraph\n return p_oOutputStream ;\n}\n\n// INPUT >> A\nstd::istream & operator >> (std::istream & p_oInputStream, const Paragraph & p_oParagraph)\n{\n // do the extract of p_oParagraph\n return p_oInputStream ;\n}\n" }, { "answer_id": 8940570, "author": "Rohit Vipin Mathews", "author_id": 1155650, "author_profile": "https://Stackoverflow.com/users/1155650", "pm_score": 0, "selected": false, "text": "operator<< #include <iostream>\n#include <string>\nusing namespace std;\n\nclass Samp\n{\npublic:\n int ID;\n string strName; \n friend std::ostream& operator<<(std::ostream &os, const Samp& obj);\n};\n std::ostream& operator<<(std::ostream &os, const Samp& obj)\n {\n os << obj.ID<< “ ” << obj.strName;\n return os;\n }\n\nint main()\n{\n Samp obj, obj1;\n obj.ID = 100;\n obj.strName = \"Hello\";\n obj1=obj;\n cout << obj <<endl<< obj1;\n\n} \n operator<< cout" }, { "answer_id": 35130062, "author": "Nehigienix", "author_id": 5785958, "author_profile": "https://Stackoverflow.com/users/5785958", "pm_score": 0, "selected": false, "text": "friend std::ostream& operator<<(std::ostream& os, const Object& object) {\n os << object._atribute1 << \" \" << object._atribute2 << \" \" << atribute._atribute3 << std::endl;\n return os;\n}\n" }, { "answer_id": 44325720, "author": "ashrasmun", "author_id": 2059351, "author_profile": "https://Stackoverflow.com/users/2059351", "pm_score": 2, "selected": false, "text": "ostream& operator << (ostream& os) #include <iostream>\n#include <string>\n\nusing namespace std;\n\nstruct Widget\n{\n string name;\n\n Widget(string _name) : name(_name) {}\n\n ostream& operator << (ostream& os)\n {\n return os << name;\n }\n};\n\nint main()\n{\n Widget w1(\"w1\");\n Widget w2(\"w2\");\n\n // These two won't work\n {\n // Error: operand types are std::ostream << std::ostream\n // cout << w1.operator<<(cout) << '\\n';\n\n // Error: operand types are std::ostream << Widget\n // cout << w1 << '\\n';\n }\n\n // However these two work\n {\n w1 << cout << '\\n';\n\n // Call to w1.operator<<(cout) returns a reference to ostream&\n w2 << w1.operator<<(cout) << '\\n';\n }\n\n return 0;\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161/" ]
236,810
<p>I'm trying to extract an uploaded zip file and store its contents in the database, one entry per file. The rubyzip library has nearly no useful documentation.</p> <p>There is an assets table that has key :string (file name) and data :binary (file contents).</p> <p>I'm using the rubyzip library, and have made it as far as this:</p> <pre><code>Zip::ZipFile.open(@file_data.local_path) do |zipfile| zipfile.each do |entry| next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file? asset = self.assets.build asset.key = entry.name asset.data = ?? # what goes here? end end </code></pre> <p>How can I set the data from a ZipEntry? Do I have to use a temp file?</p>
[ { "answer_id": 236827, "author": "Ivan", "author_id": 16957, "author_profile": "https://Stackoverflow.com/users/16957", "pm_score": 3, "selected": false, "text": "asset.data = entry.read_local_entry {|z| z.read }\n data = entry.extract \"#{RAILS_ROOT}/#{entry.name}\"\nasset.data = File.read(\"#{RAILS_ROOT}/#{entry.name}\")\n asset.data = zipfile.file.read(entry.name)\n" }, { "answer_id": 236836, "author": "jcoby", "author_id": 2884, "author_profile": "https://Stackoverflow.com/users/2884", "pm_score": 4, "selected": false, "text": "asset.data = entry.get_input_stream.read\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884/" ]
236,838
<p>Are there any good books for a relatively new but not totally new *nix user to get a bit more in depth knowledge (so no "Linux for dummies")? For the most part, I'm not looking for something to read through from start to finish. Rather, I'd rather have something that I can pick up and read in chunks when I need to know how to do something or whenever I have one of those "how do I do that again?" moments. Some areas that I'd like to see are:</p> <ul> <li>command line administration</li> <li>bash scripting</li> <li>programming (although I'd like something that isn't just relevant for C programmers)</li> </ul> <p>I'd like this to be as platform-independent as possible (meaning it has info that's relevant for any linux distro as well as BSD, Solaris, OS X, etc), but the unix systems that I use the most are OS X and Debian/Ubuntu. So if I would benefit the most from having a more platform-dependent book, those are the platforms to target.</p> <p>If I can get all this in one book, great, but I'd rather have a bit more in-depth material than coverage of <strong>everything</strong>. So if there are any books that cover just one of these areas, post it. Hell, post it even if it's not relevant to any of those areas and you think it's something that a person in my position should know about.</p>
[ { "answer_id": 565605, "author": "x-way", "author_id": 68288, "author_profile": "https://Stackoverflow.com/users/68288", "pm_score": 2, "selected": false, "text": "awk awk" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
236,851
<p>I currently work at a company that has a lot of custom applications that are made internally. There are not currently standards for a lot of things. I would like to implement a way to record/track errors that happen in this programs (most are asp.net).</p> <p>I am currently thinking of handling this in the Global.asax in the Application Error method. First trying to save the information to an Error Log/Tracking database, and if that fails, try sending an e-mail.</p> <p>What type of information is the most useful to get from the error message and other application variables (page, username etc).</p> <p>I am currently thinking of using two tables, one to get the general error and application information, and a second that holds the exception information. This will be a one to many relationship to hand the inner Exceptions that can come from one Application level exception.</p> <p>I am sure that I am missing a lot of details and would like to hear your strategy for handling this issue.</p>
[ { "answer_id": 236910, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 1, "selected": false, "text": "try \n{\n // production code\n}\ncatch(Exception ex)\n{\n Utilities.Mail.SendError(ex);\n}\n <%@ Application Language=\"C#\" %>\n<%@ Import Namespace=\"System.Diagnostics\" %>\n<script language=\"C#\" runat=\"server\">\nvoid Application_Error(object sender, EventArgs e)\n{\n //get reference to the source of the exception chain\n Exception ex = Server.GetLastError().GetBaseException();\n\n //log the details of the exception and page state to the\n //Windows Event Log\n EventLog.WriteEntry(\"myWebApplication name\",\n \"MESSAGE: \" + ex.Message + \n \"\\nSOURCE: \" + ex.Source +\n \"\\nFORM: \" + Request.Form.ToString() + \n \"\\nQUERYSTRING: \" + Request.QueryString.ToString() +\n \"\\nTARGETSITE: \" + ex.TargetSite +\n \"\\nSTACKTRACE: \" + ex.StackTrace, \n EventLogEntryType.Error);\n\n Utilities.Mail.SendError(ex);\n}\n</script>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31474/" ]
236,859
<p>Any python libs for parsing Bind zone files? Basically something that will aid in adding/removing zones and records. This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution. </p>
[ { "answer_id": 237236, "author": "Michael Gundlach", "author_id": 4105, "author_profile": "https://Stackoverflow.com/users/4105", "pm_score": 0, "selected": false, "text": "# define zone_you_care_about and line_you_wish_to_insert first, then:\nfor line in bindfile.read():\n out.write(line + '\\n')\n if ('zone \"%s\" in' % zone_you_care_about) in line:\n out.write(line_you_wish_to_insert)\n # define zone_you_care_about and relevant_text_to_remove, then:\nfor line in bindfile.read():\n if not relevant_text_to_remove in line:\n out.write(line + '\\n')\n" }, { "answer_id": 2145812, "author": "NorbertK", "author_id": 153578, "author_profile": "https://Stackoverflow.com/users/153578", "pm_score": 4, "selected": true, "text": " $TTL 86400\n@ IN SOA ns1.first-ns.de. postmaster.robot.first-ns.de. (\n 2006040800 ; serial\n 14400 ; refresh\n 1800 ; retry\n 604800 ; expire\n 86400 ) ; minimum\n\n@\n\n IN NS ns1.first-ns.de.\n" }, { "answer_id": 6710660, "author": "jccnu619", "author_id": 846874, "author_profile": "https://Stackoverflow.com/users/846874", "pm_score": 0, "selected": false, "text": "easy_install iscpy\n import iscpy\niscpy.ParseISCString(open('somefile.conf', 'r').read())\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9789/" ]
236,878
<p>this is a question that when programming I always wonder: What to use when we are writing code: </p> <pre><code>var myFiles = Directory.GetFiles(fullPath); </code></pre> <p>or</p> <pre><code>string[] myFiles = Directory.GetFiles(fullPath); </code></pre> <p><strong><em>var</em></strong> is new and is a <em>Implicitly Typed Local Variables</em>, so we can only use locally and it has rules like can't be null, etc., but I wonder if we get any advantage of using it "normally". </p> <p>The "normally" part says, not in <strong>Anonymous Types</strong>, <strong>Object and Collection Initializers</strong> and <strong>Query Expressions</strong> where that was the intent to use the var anonymous object, so what I mean is... just like the example above.</p> <p>what are your thoughts?</p>
[ { "answer_id": 236886, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "Directory.GetFiles string[] FileInfo[] var Dictionary<string,List<int>>" }, { "answer_id": 236902, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": false, "text": "var names = new List<String>();\n var connection = DatabaseConnection.CreateFromConnectionString(\"...\");\n" }, { "answer_id": 236998, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 7, "selected": true, "text": "var var d = new Dictionary<string, Dictionary<string, Queue<SomeClass>>>();\n List<string> List<string> list = MyMethod();\n var IEnumerable<string> list = MyMethod();\n var var var rows = from DataRow r in parentRow.GetChildRows(myRelation)\n where r.Field<bool>(\"Flag\")\n orderby r.Field<int>(\"SortKey\")\n select r;\n rows IEnumerable<DataRow> IEnumerable<T> foreach (DataRow r in rows)\n rows IEnumerable<DataRow> rows" }, { "answer_id": 237065, "author": "mithrandi", "author_id": 31490, "author_profile": "https://Stackoverflow.com/users/31490", "pm_score": 1, "selected": false, "text": "var var int var" }, { "answer_id": 237551, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "var" }, { "answer_id": 365409, "author": "Aleš Roubíček", "author_id": 19892, "author_profile": "https://Stackoverflow.com/users/19892", "pm_score": 2, "selected": false, "text": "var var" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28004/" ]
236,879
<p>I'm looking for a PHP library/function/class which can create <a href="http://en.wikipedia.org/wiki/Identicon" rel="nofollow noreferrer">Identicon</a>s.</p>
[ { "answer_id": 237139, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 4, "selected": false, "text": "class Gravatar\n{\n static public function GetGravatarUrl( $email, $size = 128, $type = 'identicon', $rating = 'pg' )\n {\n $gravatar = sprintf( 'http://www.gravatar.com/avatar/%s?d=%s&s=%d&r=%s',\n md5( $email ), $type, $size, $rating );\n return $gravatar;\n }\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31476/" ]
236,926
<p>I have a request for some contract work from an organization that uses <a href="http://www.neopoleon.com/home/blogs/neo/archive/2003/09/29/5458.aspx" rel="nofollow noreferrer">Excel as a database</a> and wants to do some work on the Excel data via a real database. (Yeah, I know, never mind...)</p> <p>The client has an Excel sheet that they use internally to keep track of some government programmes. The data from this Excel sheet used to be manually imported into a SQL database via CSV as intermediate format and made available via a tiny web app. Changes in either the spreadsheet or the db were done manually (by different people) and had to be kept in sync manually.</p> <p>The spec for new functionality includes:</p> <ul> <li>upload the Excel file into the web app</li> <li>make minor changes via the web app (this bit is, of course, a no-brainer)</li> <li>occasionally export the data back into Excel</li> </ul> <p>The spreadsheet (actually, it's a couple of them in a workbook) implements some guidelines necessary to interact with other institutions and therefore has to remain the same structurally before and after import. It contains a lot of formatting, hidden columns and sort buttons as well as a lot of data links between the cells in the different sheets.</p> <p>I don't want to have to reproduce the spreadsheet from scratch to deliver the export, nor do I want to manually extract the proper columns into CSV before making the import. I'm rather looking for a way to load the Excel, "query" certain fields, write them to the DB and later load the data back from the DB and manipulate only the contents of the proper cells.</p> <p>Is there a way to programatically interface with an existing spreadsheet and only read or change the bits that you need?</p>
[ { "answer_id": 248225, "author": "CestLaGalere", "author_id": 6684, "author_profile": "https://Stackoverflow.com/users/6684", "pm_score": 2, "selected": false, "text": " Dim ConnectionString As String = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" + DataFolder + \"\\;Extended Properties='text;HDR=Yes'\"\n\n Dim conn As New System.Data.OleDb.OleDbConnection(ConnectionString)\n conn.Open()\n\n Dim CommandText As String = CommandText = \"select * from [\" + CSVFileName + \"]\"\n If Filter.Length > 0 Then\n CommandText += \" WHERE \" + Filter\n End If\n\n Dim daAsset As New OleDbDataAdapter(CommandText, conn)\n Dim dsAsset As New DataSet\n daAsset.Fill(dsAsset, \"Asset\")\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
236,936
<p>I have some code that generates image of a pie chart. It's a general purpose class, so any number of slices can be given as input. Now I have problem picking good colors for the slices. Is there some algorithm that is good at that?</p> <p>Colors need to follow some rules:</p> <ul> <li>they need to look nice</li> <li>adjacent colors should not be similar (blue next to green is a no-go)</li> <li>pie background color is white, so white is out of option</li> </ul> <p>Some algorithm manipulating with RGB values would be a preferred solution.</p>
[ { "answer_id": 5651670, "author": "Niels Bosma", "author_id": 40939, "author_profile": "https://Stackoverflow.com/users/40939", "pm_score": 6, "selected": false, "text": "baseHue int n = 12;\n\nColor baseColor = System.Drawing.ColorTranslator.FromHtml(\"#8A56E2\");\ndouble baseHue = (new HSLColor(baseColor)).Hue;\n\nList<Color> colors = new List<Color>();\ncolors.Add(baseColor);\n\ndouble step = (240.0 / (double)n);\n\nfor (int i = 1; i < n; ++i)\n{\n HSLColor nextColor = new HSLColor(baseColor);\n nextColor.Hue = (baseHue + step * ((double)i)) % 240.0;\n colors.Add((Color)nextColor);\n}\n\nstring colors = string.Join(\",\", colors.Select(e => e.Name.Substring(2)).ToArray());\n" }, { "answer_id": 19389478, "author": "Pic Mickael", "author_id": 2635114, "author_profile": "https://Stackoverflow.com/users/2635114", "pm_score": 3, "selected": false, "text": "public static function ColorArrayGenerator(\n pNbColors:int,\n pNonAdjacentSimilarColor:Boolean = false):Array\n{ \n var colors:Array = new Array();\n var baseRGB:ColorRGB = new ColorRGB();\n baseRGB.setRGBFromUint(0x8A56E2);\n\n var baseHSL:ColorHSL = new ColorHSL();\n rgbToHsl(baseHSL, baseRGB);\n\n var currentHue:Number = baseHSL.Hue;\n\n colors.push(baseRGB.getUintFromRGB());\n\n var step:Number = (360.0 / pNbColors);\n var nextHSL:ColorHSL;\n var nextRGB:ColorRGB;\n var i:int;\n\n for (i = 1; i < pNbColors; i++)\n {\n currentHue += step;\n if (currentHue > 360)\n {\n currentHue -= 360;\n }\n\n nextHSL = new ColorHSL(currentHue, baseHSL.Saturation, aseHSL.Luminance);\n nextRGB = new ColorRGB();\n hslToRgb(nextRGB, nextHSL);\n\n colors.push(nextRGB.getUintFromRGB());\n }\n\n if (pNonAdjacentSimilarColor == true &&\n pNbColors > 2)\n {\n var holder:uint = 0;\n var j:int;\n\n for (i = 0, j = pNbColors / 2; i < pNbColors / 2; i += 2, j += 2)\n {\n holder = colors[i];\n colors[i] = colors[j];\n colors[j] = holder;\n }\n }\n\n return colors;\n}\n final public class ColorHSL\n{\n private var _hue:Number; // 0.0 .. 359.99999\n\n private var _sat:Number; // 0.0 .. 100.0\n\n private var _lum:Number; // 0.0 .. 100.0\n\n public function ColorHSL(\n hue:Number = 0,\n sat:Number = 0,\n lum:Number = 0)\n {\n _hue = hue;\n _sat = sat;\n _lum = lum;\n }\n\n [Bindable]public function get Hue():Number\n {\n return _hue;\n }\n\n public function set Hue(value:Number):void\n {\n if (value > 360) \n {\n _hue = value % 360;\n } // remember, hue is modulo 360\n else if (value < 0)\n {\n _hue = 0;\n }\n else\n {\n _hue = value;\n }\n }\n\n [Bindable]public function get Saturation():Number\n {\n return _sat;\n }\n\n public function set Saturation(value:Number):void\n {\n if (value > 100.0)\n {\n _sat = 100.0;\n }\n else if (value < 0)\n {\n _sat = 0;\n }\n else\n {\n _sat = value;\n }\n }\n\n [Bindable]public function get Luminance():Number\n {\n return _lum;\n }\n\n public function set Luminance(value:Number):void\n {\n if (value > 100.0)\n {\n _lum = 100.0;\n }\n else if (value < 0)\n {\n _lum = 0;\n }\n else\n {\n _lum = value;\n }\n }\n}\n final public class ColorRGB\n{\n private var _red:uint;\n private var _grn:uint;\n private var _blu:uint;\n private var _rgb:uint; // composite form: 0xRRGGBB or #RRGGBB\n\n public function ColorRGB(red:uint = 0, grn:uint = 0, blu:uint = 0)\n {\n setRGB(red, grn, blu);\n }\n\n [Bindable]public function get red():uint\n {\n return _red;\n }\n\n public function set red(value:uint):void\n {\n _red = (value & 0xFF);\n updateRGB();\n }\n\n [Bindable]public function get grn():uint\n {\n return _grn;\n }\n\n public function set grn(value:uint):void\n {\n _grn = (value & 0xFF);\n updateRGB();\n }\n\n [Bindable]public function get blu():uint\n {\n return _blu;\n }\n\n public function set blu(value:uint):void\n {\n _blu = (value & 0xFF);\n updateRGB();\n }\n\n [Bindable]public function get rgb():uint\n {\n return _rgb;\n }\n\n public function set rgb(value:uint):void\n {\n _rgb = value;\n _red = (value >> 16) & 0xFF;\n _grn = (value >> 8) & 0xFF;\n _blu = value & 0xFF;\n }\n\n public function setRGB(red:uint, grn:uint, blu:uint):void\n {\n this.red = red;\n this.grn = grn;\n this.blu = blu;\n }\n\n public function setRGBFromUint(pValue:uint):void\n {\n setRGB((( pValue >> 16 ) & 0xFF ), ( (pValue >> 8) & 0xFF ), ( pValue & 0xFF ));\n }\n\n public function getUintFromRGB():uint\n {\n return ( ( red << 16 ) | ( grn << 8 ) | blu );\n }\n\n private function updateRGB():void\n {\n _rgb = (_red << 16) + (_grn << 8) + blu;\n }\n}\n final public class ColorUtils\n{\n public static function HSV2RGB(hue:Number, sat:Number, val:Number):uint\n {\n var red:Number = 0;\n var grn:Number = 0;\n var blu:Number = 0;\n var i:Number;\n var f:Number;\n var p:Number;\n var q:Number;\n var t:Number;\n hue%=360;\n sat/=100;\n val/=100;\n hue/=60;\n i = Math.floor(hue);\n f = hue-i;\n p = val*(1-sat);\n q = val*(1-(sat*f));\n t = val*(1-(sat*(1-f)));\n if (i==0)\n {\n red=val;\n grn=t;\n blu=p;\n }\n else if (i==1)\n {\n red=q;\n grn=val;\n blu=p;\n }\n else if (i==2)\n {\n red=p;\n grn=val;\n blu=t;\n }\n else if (i==3)\n {\n red=p;\n grn=q;\n blu=val;\n }\n else if (i==4)\n {\n red=t;\n grn=p;\n blu=val;\n }\n else if (i==5)\n {\n red=val;\n grn=p;\n blu=q;\n }\n red = Math.floor(red*255);\n grn = Math.floor(grn*255);\n blu = Math.floor(blu*255);\n\n return (red<<16) | (grn << 8) | (blu);\n }\n\n //\n public static function RGB2HSV(pColor:uint):Object\n {\n var red:uint = (pColor >> 16) & 0xff;\n var grn:uint = (pColor >> 8) & 0xff;\n var blu:uint = pColor & 0xff;\n\n var x:Number;\n var val:Number;\n var f:Number;\n var i:Number;\n var hue:Number;\n var sat:Number;\n red/=255;\n grn/=255;\n blu/=255;\n x = Math.min(Math.min(red, grn), blu);\n val = Math.max(Math.max(red, grn), blu);\n if (x==val){\n return({h:undefined, s:0, v:val*100});\n }\n f = (red == x) ? grn-blu : ((grn == x) ? blu-red : red-grn);\n i = (red == x) ? 3 : ((grn == x) ? 5 : 1);\n hue = Math.floor((i-f/(val-x))*60)%360;\n sat = Math.floor(((val-x)/val)*100);\n val = Math.floor(val*100);\n return({h:hue, s:sat, v:val});\n }\n\n /**\n * Generates an array of pNbColors colors (uint) \n * The colors are generated to fill a pie chart (meaning that they circle back to the starting color)\n * @param pNbColors The number of colors to generate (ex: Number of slices in the pie chart)\n * @param pNonAdjacentSimilarColor Should the colors stay Adjacent or not ?\n */\n public static function ColorArrayGenerator(\n pNbColors:int,\n pNonAdjacentSimilarColor:Boolean = false):Array\n {\n // Based on http://www.flexspectrum.com/?p=10\n\n var colors:Array = [];\n var baseRGB:ColorRGB = new ColorRGB();\n baseRGB.setRGBFromUint(0x8A56E2);\n\n var baseHSL:ColorHSL = new ColorHSL();\n rgbToHsl(baseHSL, baseRGB);\n\n var currentHue:Number = baseHSL.Hue;\n\n colors.push(baseRGB.getUintFromRGB());\n\n var step:Number = (360.0 / pNbColors);\n var nextHSL:ColorHSL;\n var nextRGB:ColorRGB;\n var i:int;\n\n for (i = 1; i < pNbColors; i++)\n {\n currentHue += step;\n\n if (currentHue > 360)\n {\n currentHue -= 360;\n }\n\n nextHSL = new ColorHSL(currentHue, baseHSL.Saturation, baseHSL.Luminance);\n nextRGB = new ColorRGB();\n hslToRgb(nextRGB, nextHSL);\n\n colors.push(nextRGB.getUintFromRGB());\n }\n\n if (pNonAdjacentSimilarColor == true &&\n pNbColors > 2)\n {\n var holder:uint = 0;\n var j:int;\n\n for (i = 0, j = pNbColors / 2; i < pNbColors / 2; i += 2, j += 2)\n {\n holder = colors[i];\n colors[i] = colors[j];\n colors[j] = holder;\n }\n }\n\n return colors;\n }\n\n static public function rgbToHsl(hsl:ColorHSL, rgb:ColorRGB):void\n {\n var h:Number = 0;\n var s:Number = 0;\n var l:Number = 0;\n\n // Normalizes incoming RGB values.\n //\n var dRed:Number = (Number)(rgb.red / 255.0);\n var dGrn:Number = (Number)(rgb.grn / 255.0);\n var dBlu:Number = (Number)(rgb.blu / 255.0);\n\n var dMax:Number = Math.max(dRed, Math.max(dGrn, dBlu));\n var dMin:Number = Math.min(dRed, Math.min(dGrn, dBlu));\n\n //-------------------------\n // hue\n //\n if (dMax == dMin)\n {\n h = 0; // undefined\n }\n else if (dMax == dRed && dGrn >= dBlu)\n {\n h = 60.0 * (dGrn - dBlu) / (dMax - dMin);\n }\n else if (dMax == dRed && dGrn < dBlu)\n {\n h = 60.0 * (dGrn - dBlu) / (dMax - dMin) + 360.0;\n }\n else if (dMax == dGrn)\n {\n h = 60.0 * (dBlu - dRed) / (dMax-dMin) + 120.0;\n }\n else if (dMax == dBlu)\n {\n h = 60.0 * (dRed - dGrn) / (dMax - dMin) + 240.0;\n }\n\n //-------------------------\n // luminance\n //\n l = (dMax + dMin) / 2.0;\n\n //-------------------------\n // saturation\n //\n if (l == 0 || dMax == dMin)\n {\n s = 0;\n }\n else if (0 < l && l <= 0.5)\n {\n s = (dMax - dMin) / (dMax + dMin);\n }\n else if (l>0.5)\n {\n s = (dMax - dMin) / (2 - (dMax + dMin)); //(dMax-dMin > 0)?\n }\n\n hsl.Hue = h;\n hsl.Luminance = l;\n hsl.Saturation = s;\n\n } // rgbToHsl\n\n //---------------------------------------\n // Convert the input RGB values to the corresponding HSL values.\n //\n static public function hslToRgb(rgb:ColorRGB, hsl:ColorHSL):void\n {\n if (hsl.Saturation == 0)\n {\n // Achromatic color case, luminance only.\n //\n var lumScaled:int = (int)(hsl.Luminance * 255.0); \n rgb.setRGB(lumScaled, lumScaled, lumScaled);\n return;\n }\n\n // Chromatic case...\n //\n var dQ:Number = (hsl.Luminance < 0.5) ? (hsl.Luminance * (1.0 + hsl.Saturation)): ((hsl.Luminance + hsl.Saturation) - (hsl.Luminance * hsl.Saturation));\n var dP:Number = (2.0 * hsl.Luminance) - dQ;\n\n var dHueAng:Number = hsl.Hue / 360.0;\n\n var dFactor:Number = 1.0 / 3.0;\n\n var adT:Array = [];\n\n adT[0] = dHueAng + dFactor; // Tr\n adT[1] = dHueAng; // Tg\n adT[2] = dHueAng - dFactor; // Tb\n\n for (var i:int = 0; i < 3; i++)\n {\n if (adT[i] < 0)\n {\n adT[i] += 1.0;\n }\n\n if (adT[i] > 1)\n {\n adT[i] -= 1.0;\n }\n\n if ((adT[i] * 6) < 1)\n {\n adT[i] = dP + ((dQ - dP) * 6.0 * adT[i]);\n }\n else if ((adT[i] * 2.0) < 1) // (1.0 / 6.0) <= adT[i] && adT[i] < 0.5\n {\n adT[i] = dQ;\n }\n else if ((adT[i] * 3.0) < 2) // 0.5 <= adT[i] && adT[i] < (2.0 / 3.0)\n {\n adT[i] = dP + (dQ-dP) * ((2.0/3.0) - adT[i]) * 6.0;\n }\n else\n {\n adT[i] = dP;\n }\n }\n\n rgb.setRGB(adT[0] * 255.0, adT[1] * 255.0, adT[2] * 255.0);\n\n } // hslToRgb\n\n //---------------------------------------\n // Adjust the luminance value by the specified factor.\n //\n static public function adjustRgbLuminance(rgb:ColorRGB, factor:Number):void\n {\n var hsl:ColorHSL = new ColorHSL();\n\n rgbToHsl(hsl, rgb);\n\n hsl.Luminance *= factor;\n\n if (hsl.Luminance < 0.0)\n {\n hsl.Luminance = 0.0;\n }\n\n if (hsl.Luminance > 1.0)\n {\n hsl.Luminance = 1.0;\n }\n\n hslToRgb(rgb, hsl);\n }\n\n //---------------------------------------\n //\n static public function uintTo2DigitHex(value:uint):String\n {\n var str:String = value.toString(16).toUpperCase();\n\n if (1 == str.length)\n {\n str = \"0\" + str;\n }\n\n return str;\n }\n\n //---------------------------------------\n //\n static public function uintTo6DigitHex(value:uint):String\n {\n var str:String = value.toString(16).toUpperCase();\n\n if (1 == str.length) {return \"00000\" + str;}\n if (2 == str.length) {return \"0000\" + str;}\n if (3 == str.length) {return \"000\" + str;}\n if (4 == str.length) {return \"00\" + str;}\n if (5 == str.length) {return \"0\" + str;}\n\n return str;\n }\n}\n" }, { "answer_id": 25481023, "author": "Dave Jarvis", "author_id": 59087, "author_profile": "https://Stackoverflow.com/users/59087", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\"?>\n<!--\n | The MIT License\n |\n | Copyright 2014 White Magic Software, Inc.\n | \n | Permission is hereby granted, free of charge, to any person\n | obtaining a copy of this software and associated documentation\n | files (the \"Software\"), to deal in the Software without\n | restriction, including without limitation the rights to use,\n | copy, modify, merge, publish, distribute, sublicense, and/or\n | sell copies of the Software, and to permit persons to whom the\n | Software is furnished to do so, subject to the following\n | conditions:\n | \n | The above copyright notice and this permission notice shall be\n | included in all copies or substantial portions of the Software.\n | \n | THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n | OTHER DEALINGS IN THE SOFTWARE.\n +-->\n<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n<!-- Reference white (X, Y, and Z components) -->\n<xsl:variable name=\"X_r\" select=\"0.950456\"/>\n<xsl:variable name=\"Y_r\" select=\"1.000000\"/>\n<xsl:variable name=\"Z_r\" select=\"1.088754\"/>\n<xsl:variable name=\"LAB_EPSILON\" select=\"216.0 div 24389.0\"/>\n<xsl:variable name=\"LAB_K\" select=\"24389.0 div 27.0\"/>\n\n<!-- Pie wedge colours based on this hue. -->\n<xsl:variable name=\"base_colour\" select=\"'46A5E5'\"/>\n\n<!-- Pie wedge stroke colour. -->\n<xsl:variable name=\"stroke_colour\" select=\"'white'\"/>\n\n<!--\n | Creates a colour for a particular pie wedge.\n |\n | http://en.wikipedia.org/wiki/HSL_and_HSV \n +-->\n<xsl:template name=\"fill\">\n <!-- Current wedge number for generating a colour. -->\n <xsl:param name=\"wedge\"/>\n <!-- Total number of wedges in the pie. -->\n <xsl:param name=\"wedges\"/>\n <!-- RGB colour in hexadecimal. -->\n <xsl:param name=\"colour\"/>\n\n <!-- Derive the colour decimal values from $colour's HEX code. -->\n <xsl:variable name=\"r\">\n <xsl:call-template name=\"hex2dec\">\n <xsl:with-param name=\"hex\"\n select=\"substring( $colour, 1, 2 )\"/>\n </xsl:call-template>\n </xsl:variable>\n <xsl:variable name=\"g\">\n <xsl:call-template name=\"hex2dec\">\n <xsl:with-param name=\"hex\"\n select=\"substring( $colour, 3, 2 )\"/>\n </xsl:call-template>\n </xsl:variable>\n <xsl:variable name=\"b\">\n <xsl:call-template name=\"hex2dec\">\n <xsl:with-param name=\"hex\"\n select=\"substring( $colour, 5, 2 )\"/>\n </xsl:call-template>\n </xsl:variable>\n\n <!--\n | Convert RGB to XYZ, using nominal range for RGB.\n | http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html\n +-->\n <xsl:variable name=\"r_n\" select=\"$r div 255\" />\n <xsl:variable name=\"g_n\" select=\"$g div 255\" />\n <xsl:variable name=\"b_n\" select=\"$b div 255\" />\n\n <!--\n | Assume colours are in sRGB.\n | http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html\n -->\n <xsl:variable name=\"x\"\n select=\".4124564 * $r_n + .3575761 * $g_n + .1804375 * $b_n\"/>\n <xsl:variable name=\"y\"\n select=\".2126729 * $r_n + .7151522 * $g_n + .0721750 * $b_n\"/>\n <xsl:variable name=\"z\"\n select=\".0193339 * $r_n + .1191920 * $g_n + .9503041 * $b_n\"/>\n\n <!--\n | Convert XYZ to L*a*b.\n | http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_Lab.html\n +-->\n <xsl:variable name=\"if_x\">\n <xsl:call-template name=\"lab_f\">\n <xsl:with-param name=\"xyz_n\" select=\"$x div $X_r\"/>\n </xsl:call-template>\n </xsl:variable>\n <xsl:variable name=\"if_y\">\n <xsl:call-template name=\"lab_f\">\n <xsl:with-param name=\"xyz_n\" select=\"$y div $Y_r\"/>\n </xsl:call-template>\n </xsl:variable>\n <xsl:variable name=\"if_z\">\n <xsl:call-template name=\"lab_f\">\n <xsl:with-param name=\"xyz_n\" select=\"$z div $Z_r\"/>\n </xsl:call-template>\n </xsl:variable>\n\n <xsl:variable name=\"lab_l\" select=\"(116.0 * $if_y) - 16.0\"/>\n <xsl:variable name=\"lab_a\" select=\"500.0 * ($if_x - $if_y)\"/>\n <xsl:variable name=\"lab_b\" select=\"200.0 * ($if_y - $if_z)\"/>\n\n <!--\n | Convert L*a*b to LCH.\n | http://www.brucelindbloom.com/index.html?Eqn_Lab_to_LCH.html\n +-->\n <xsl:variable name=\"lch_l\" select=\"$lab_l\"/>\n\n <xsl:variable name=\"lch_c\">\n <xsl:call-template name=\"sqrt\">\n <xsl:with-param name=\"n\" select=\"($lab_a * $lab_a) + ($lab_b * $lab_b)\"/>\n </xsl:call-template>\n </xsl:variable>\n\n <xsl:variable name=\"lch_h\">\n <xsl:call-template name=\"atan2\">\n <xsl:with-param name=\"x\" select=\"$lab_b\"/>\n <xsl:with-param name=\"y\" select=\"$lab_a\"/>\n </xsl:call-template>\n </xsl:variable>\n\n <!--\n | Prevent similar adjacent colours.\n | http://math.stackexchange.com/a/936767/7932\n +-->\n <xsl:variable name=\"wi\" select=\"$wedge\"/>\n <xsl:variable name=\"wt\" select=\"$wedges\"/>\n <xsl:variable name=\"w\">\n <xsl:choose>\n <xsl:when test=\"$wt &gt; 5\">\n <xsl:variable name=\"weven\" select=\"(($wi+4) mod ($wt + $wt mod 2))\"/>\n <xsl:value-of\n select=\"$weven * (1-($wi mod 2)) + ($wi mod 2 * $wi)\"/>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$wedge\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:variable>\n <!-- lch_l, lch_c, and lch_h are now set; rotate the hue. -->\n <xsl:variable name=\"lch_wedge_h\" select=\"(360.0 div $wedges) * $wedge\"/>\n\n <!--\n | Convert wedge's hue-adjusted LCH to L*a*b.\n | http://www.brucelindbloom.com/index.html?Eqn_LCH_to_Lab.html\n +-->\n <xsl:variable name=\"lab_sin_h\">\n <xsl:call-template name=\"sine\">\n <xsl:with-param name=\"degrees\" select=\"$lch_wedge_h\"/>\n </xsl:call-template>\n </xsl:variable>\n <xsl:variable name=\"lab_cos_h\">\n <xsl:call-template name=\"cosine\">\n <xsl:with-param name=\"degrees\" select=\"$lch_wedge_h\"/>\n </xsl:call-template>\n </xsl:variable>\n\n <xsl:variable name=\"final_lab_l\" select=\"$lch_l\"/>\n <xsl:variable name=\"final_lab_a\" select=\"$lch_c * $lab_cos_h\"/>\n <xsl:variable name=\"final_lab_b\" select=\"$lch_c * $lab_sin_h\"/>\n\n <!--\n | Convert L*a*b to XYZ.\n | http://www.brucelindbloom.com/index.html?Eqn_Lab_to_XYZ.html\n +-->\n <xsl:variable name=\"of_y\" select=\"($final_lab_l + 16.0) div 116.0\"/>\n <xsl:variable name=\"of_x\" select=\"($final_lab_a div 500.0) + $of_y\"/>\n <xsl:variable name=\"of_z\" select=\"$of_y - ($final_lab_b div 200.0)\"/>\n\n <xsl:variable name=\"of_x_pow\">\n <xsl:call-template name=\"power\">\n <xsl:with-param name=\"base\" select=\"$of_x\"/>\n <xsl:with-param name=\"exponent\" select=\"3\"/>\n </xsl:call-template>\n </xsl:variable>\n <xsl:variable name=\"of_z_pow\">\n <xsl:call-template name=\"power\">\n <xsl:with-param name=\"base\" select=\"$of_z\"/>\n <xsl:with-param name=\"exponent\" select=\"3\"/>\n </xsl:call-template>\n </xsl:variable>\n\n <xsl:variable name=\"ox_r\">\n <xsl:choose>\n <xsl:when test=\"$of_x_pow &gt; $LAB_EPSILON\">\n <xsl:value-of select=\"$of_x_pow\"/>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"((116.0 * $of_x) - 16.0) div $LAB_K\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:variable>\n <xsl:variable name=\"oy_r\">\n <xsl:choose>\n <xsl:when test=\"$final_lab_l &gt; ($LAB_K * $LAB_EPSILON)\">\n <xsl:call-template name=\"power\">\n <xsl:with-param name=\"base\"\n select=\"($final_lab_l + 16.0) div 116.0\"/>\n <xsl:with-param name=\"exponent\"\n select=\"3\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$final_lab_l div $LAB_K\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:variable>\n <xsl:variable name=\"oz_r\">\n <xsl:choose>\n <xsl:when test=\"$of_z_pow &gt; $LAB_EPSILON\">\n <xsl:value-of select=\"$of_z_pow\"/>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"((116.0 * $of_z) - 16.0) div $LAB_K\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:variable>\n\n <xsl:variable name=\"X\" select=\"$ox_r * $X_r\"/>\n <xsl:variable name=\"Y\" select=\"$oy_r * $Y_r\"/>\n <xsl:variable name=\"Z\" select=\"$oz_r * $Z_r\"/>\n\n <!--\n | Convert XYZ to sRGB.\n | http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html\n +-->\n <xsl:variable name=\"R\"\n select=\"3.2404542 * $X + -1.5371385 * $Y + -0.4985314 * $Z\"/>\n <xsl:variable name=\"G\"\n select=\"-0.9692660 * $X + 1.8760108 * $Y + 0.0415560 * $Z\"/>\n <xsl:variable name=\"B\"\n select=\"0.0556434 * $X + -0.2040259 * $Y + 1.0572252 * $Z\"/>\n\n <!-- Round the result. -->\n <xsl:variable name=\"R_r\" select=\"round( $R * 255 )\"/>\n <xsl:variable name=\"G_r\" select=\"round( $G * 255 )\"/>\n <xsl:variable name=\"B_r\" select=\"round( $B * 255 )\"/>\n\n <xsl:text>rgb(</xsl:text>\n <xsl:value-of select=\"concat( $R_r, ',', $G_r, ',', $B_r )\"/>\n <xsl:text>)</xsl:text>\n</xsl:template>\n\n<xsl:template name=\"lab_f\">\n <xsl:param name=\"xyz_n\"/>\n\n <xsl:choose>\n <xsl:when test=\"$xyz_n &gt; $LAB_EPSILON\">\n <xsl:call-template name=\"nthroot\">\n <xsl:with-param name=\"index\" select=\"3\"/>\n <xsl:with-param name=\"radicand\" select=\"$xyz_n\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"($LAB_K * $xyz_n + 16.0) div 116.0\" />\n </xsl:otherwise>\n </xsl:choose>\n</xsl:template>\n\n<!-- Converts a two-digit hexadecimal number to decimal. -->\n<xsl:template name=\"hex2dec\">\n <xsl:param name=\"hex\"/>\n\n <xsl:variable name=\"digits\" select=\"'0123456789ABCDEF'\"/>\n <xsl:variable name=\"X\" select=\"substring( $hex, 1, 1 )\"/>\n <xsl:variable name=\"Y\" select=\"substring( $hex, 2, 1 )\"/>\n <xsl:variable name=\"Xval\"\n select=\"string-length(substring-before($digits,$X))\"/>\n <xsl:variable name=\"Yval\"\n select=\"string-length(substring-before($digits,$Y))\"/>\n <xsl:value-of select=\"16 * $Xval + $Yval\"/>\n</xsl:template>\n\n</xsl:stylesheet>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31476/" ]
236,972
<p>Based on this question <a href="https://stackoverflow.com/questions/19746/views-in-seperate-assemblies-in-aspnet-mvc">here</a> and using code found <a href="http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx" rel="nofollow noreferrer">here</a> I'm trying to load views that are embedded resources in a separate DLL project, and the original question's author says he has had success doing this - but I can't get it to work as it seems the MVC view engine is intercepting the request and still looking at the file system for the view. Exception:</p> <pre><code>Server Error in '/' Application. The view 'Index' or its master could not be found. The following locations were searched: ~/Views/admin/Index.aspx ~/Views/admin/Index.ascx ~/Views/Shared/Index.aspx ~/Views/Shared/Index.ascx ~/App/Views/admin/Index.aspx ~/App/Views/admin/Index.ascx ~/App/Views/Shared/Index.aspx ~/App/Views/Shared/Index.ascx </code></pre> <p>I am using a <code>CustomViewEngine</code>, like Rob Connery's /App structure one as follows:</p> <pre><code>public class CustomViewEngine : WebFormViewEngine { public CustomViewEngine() { MasterLocationFormats = new[] { "~/App/Views/{1}/{0}.master", "~/App/Views/Shared/{0}.master" }; ViewLocationFormats = new[] { "~/App/Views/{1}/{0}.aspx", "~/App/Views/{1}/{0}.ascx", "~/App/Views/Shared/{0}.aspx", "~/App/Views/Shared/{0}.ascx" }; PartialViewLocationFormats = ViewLocationFormats; } } </code></pre> <p>Here are my routes:</p> <pre><code> routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Home", "", new {controller = "Page", action = "Index", id = "Default"}); routes.MapRoute("Default", "Page/{id}", new { controller = "Page", action = "Index", id = "" }); routes.MapRoute("Plugins", "plugin/{controller}/{action}", new { controller = "", action = "Index", id = "" }); routes.MapRoute("Error", "{*url}", new { controller = "Error", action = "ResourceNotFound404" }); </code></pre> <p>In my <a href="http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx" rel="nofollow noreferrer"><code>AssemblyResourceProvider</code></a> I'm checking to see if the path starts <code>~/plugin/</code> and then using the dll filename convention <code>plugin.{controller}.dll</code></p> <p>Any suggestions?</p> <p><strong>UPDATE:</strong> By the time the routed request for say <code>http://localhost/plugin/admin</code> is getting to the VirtualFileProvider it doesn't have any View attached at the end. So in the <code>VirtualFileProvider</code>'s Open method the virtual path of <code>~/plugin/admin</code> is being passed in when it should be <code>~/plugin/admin/Index.aspx</code> as defined in my route above. Have I messed up my routes or am I right to be expecting this to happen?</p>
[ { "answer_id": 238363, "author": "jmcd", "author_id": 2285, "author_profile": "https://Stackoverflow.com/users/2285", "pm_score": 6, "selected": true, "text": "VirtualPathProvider Global.asax Application_Start return View(\"~/Plugin/YOURDLL.dll/FULLNAME_YOUR_VIEW.aspx\");" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2285/" ]
236,979
<p>I'm creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can't get it to work for all properties. I'm using preg/perl syntax in PHP.</p> <h3>Regex</h3> <pre><code>(?&lt;selector&gt;[A-Za-z]+[\s]*)[\s]*{[\s]*((?&lt;properties&gt;[A-Za-z0-9-_]+)[\s]*:[\s]*(?&lt;values&gt;[A-Za-z0-9#, ]+);[\s]*)*[\s]*} </code></pre> <h3>Test case</h3> <pre><code>body { background: #f00; font: 12px Arial; } </code></pre> <h3>Expected Outcome</h3> <pre><code>Array( [0] =&gt; Array( [0] =&gt; body { background: #f00; font: 12px Arial; } [selector] =&gt; Array( [0] =&gt; body ) [1] =&gt; Array( [0] =&gt; body ) [2] =&gt; font: 12px Arial; [properties] =&gt; Array( [0] =&gt; font ) [3] =&gt; Array( [0] =&gt; font ) [values] =&gt; Array( [0] =&gt; 12px Arial [1] =&gt; background: #f00 ) [4] =&gt; Array( [0] =&gt; 12px Arial [1] =&gt; background: #f00 ) ) ) </code></pre> <h3>Real Outcome</h3> <pre><code>Array( [0] =&gt; Array ( [0] =&gt; body { background: #f00; font: 12px Arial; } [selector] =&gt; body [1] =&gt; body [2] =&gt; font: 12px Arial; [properties] =&gt; font [3] =&gt; font [values] =&gt; 12px Arial [4] =&gt; 12px Arial ) ) </code></pre> <p>Thanks in advance for any help - this has been confusing me all afternoon!</p>
[ { "answer_id": 236984, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 5, "selected": true, "text": "/([^{])\\s*\\{\\s*([^}]*?)\\s*}/\n" }, { "answer_id": 237381, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 3, "selected": false, "text": "body{..} color:rgb(1,2,3); $cssp = new cssparser;\n$cssp -> ParseStr(\"body { background: #f00;font: 12px Arial; }\");\nprint_r($cssp->css);\n Array\n(\n [body] => Array\n (\n [background] => #f00\n [font] => 12px arial\n )\n)\n if($this->html) {$this->Add(\"VAR\", \"\");}" }, { "answer_id": 2694121, "author": "Nick Franceschina", "author_id": 130221, "author_profile": "https://Stackoverflow.com/users/130221", "pm_score": 3, "selected": false, "text": "(?<selector>(?:(?:[^,{]+),?)*?)\\{(?:(?<name>[^}:]+):?(?<value>[^};]+);?)*?\\}\n" }, { "answer_id": 2798564, "author": "Poseidon", "author_id": 336746, "author_profile": "https://Stackoverflow.com/users/336746", "pm_score": 0, "selected": false, "text": "function trimStringArray($stringArray){\n $result = array();\n for($i=0; $i < count($stringArray); $i++){\n $trimmed = trim($stringArray[$i]);\n if($trimmed != '') $result[] = $trimmed;\n }\n return $result;\n}\n$regExp = '/\\{|\\}/';\n$rawCssData = preg_split($regExp, $style);\n\n$cssArray = array();\nfor($i=0; $i < count($rawCssData); $i++){\n if($i % 2 == 0){\n $cssStyle['selectors'] = array();\n $selectors = split(',', $rawCssData[$i]);\n $cssStyle['selectors'] = trimStringArray($selectors);\n }\n if($i % 2 == 1){\n $attributes = split(';', $rawCssData[$i]);\n $cssStyle['attributes'] = trimStringArray($attributes);\n $cssArray[] = $cssStyle;\n }\n\n}\n//return false;\necho '<pre>'.\"\\n\";\nprint_r($cssArray);\necho '</pre>'.\"\\n\";\n" }, { "answer_id": 5477827, "author": "Dan", "author_id": 88033, "author_profile": "https://Stackoverflow.com/users/88033", "pm_score": 3, "selected": false, "text": "print_r($css) $css_array = array(); // master array to hold all values\n$element = explode('}', $css);\nforeach ($element as $element) {\n // get the name of the CSS element\n $a_name = explode('{', $element);\n $name = $a_name[0];\n // get all the key:value pair styles\n $a_styles = explode(';', $element);\n // remove element name from first property element\n $a_styles[0] = str_replace($name . '{', '', $a_styles[0]);\n // loop through each style and split apart the key from the value\n $count = count($a_styles);\n for ($a=0;$a<$count;$a++) {\n if ($a_styles[$a] != '') {\n $a_key_value = explode(':', $a_styles[$a]);\n // build the master css array\n $css_array[$name][$a_key_value[0]] = $a_key_value[1];\n }\n } \n}\n Array\n(\n [body] => Array\n (\n [background] => #f00\n [font] => 12px arial\n )\n)\n" }, { "answer_id": 48937026, "author": "CTS_AE", "author_id": 349659, "author_profile": "https://Stackoverflow.com/users/349659", "pm_score": 2, "selected": false, "text": "\\s*([^{]+)\\s*\\{\\s*([^}]*?)\\s*}\n ([^:\\s]+)*\\s*:\\s*([^;]+); css cssom" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
237,006
<p>I installed SQL Server 2005 sometime ago and forgot the administrator password I set during setup. How can I connect to SQL server now?</p> <p><strong>EDIT:</strong> I think I only allowed Sql Server Authentication. Login with integrated security also does not work.</p>
[ { "answer_id": 237025, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 5, "selected": false, "text": "osql -E -S .\\SQLEXPRESS\nexec sp_password @new='changeme', @loginame='sa'\ngo\nalter login sa enable\ngo\nexit\n" }, { "answer_id": 21597062, "author": "Ilia Barahovsky", "author_id": 404099, "author_profile": "https://Stackoverflow.com/users/404099", "pm_score": 2, "selected": false, "text": "sa -m exec sp_password -m -m;" }, { "answer_id": 46377492, "author": "TheGameiswar", "author_id": 2975396, "author_profile": "https://Stackoverflow.com/users/2975396", "pm_score": 0, "selected": false, "text": "-mSQLCMD sqlcmd -s servername\\instancename\n USE [master]\nGO\nCREATE LOGIN [BUILTIN\\Administrators] FROM WINDOWS WITH DEFAULT_DATABASE=[master]\nGO\nEXEC master..sp_addsrvrolemember @loginame = N'BUILTIN\\Administrators', @rolename = N'sysadmin'\nGO\n BUILTIN\\Administrators -mSQLCMD" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,027
<p>Here's my problem: I have a virtual method defined in a .h file that I want to call in a class that inherits from the base class. Sadly though, the method in the derived class doesn't get called. Is there a better way to implement what I'm trying to do?</p> <pre><code>#ifndef ofxBASE_SND_OBJ #define ofxBASE_SND_OBJ #include "ofConstants.h" class ofxBaseSndObj { public: virtual string getType(){} string key; }; #endif </code></pre> <p>Here's my buzz class</p> <pre><code>#ifndef OFXSO_BUZZ #define OFXSO_BUZZ #include "ofxBaseSndObj.h" class ofxSOBuzz : public ofxBaseSndObj { public: string getType(); }; #endif </code></pre> <p>ofxSOBuzz.cpp</p> <pre><code>string ofxSOBuzz::getType() { string s = string("ofxSOBuzz"); printf(" ********* returning string type %s", s.c_str()); // doesn't get called! return s; } </code></pre> <p>Then in another class I try to call it this way:</p> <pre><code>string ofxSndObj::createFilter(ofxBaseSndObj obj) { string str = obj.getType(); if(str.compare("ofxSOBuzz") == 0) { printf(" all is well "); } } </code></pre> <p>In the method above I need to be able to pass in one of many kinds of objects that all extend the ofxBaseSndObj object. Any suggestsions or pointers would be greatly appreciated. Thanks!</p>
[ { "answer_id": 237034, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": true, "text": "string ofxSndObj::createFilter(ofxBaseSndObj obj)\n string ofxSndObj::createFilter(ofxBaseSndObj& obj)\n class ofxBaseSndObj\n{\n public:\n virtual string getType() const;\n // If the method does not change the object mark it const\n\n string key;\n\n};\n\nstring ofxSndObj::createFilter(ofxBaseSndObj const& obj)\n{\n // allowed to call this if getType() is a const\n string str = obj.getType();\n\n if(str.compare(\"ofxSOBuzz\") == 0)\n {\n printf(\" all is well \");\n }\n}\n" }, { "answer_id": 237059, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 2, "selected": false, "text": "class ofxBaseSndObj {\npublic:\n virtual string getType(){}\n string key;\n\nprivate:\n ofxBaseSndObj(const ofxBaseSndObj& rhs);\n ofxBaseSndObj& operator=(const ofxBaseSndObj& rhs);\n};\n" }, { "answer_id": 237134, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "string ofxSndObj::createFilter(ofxBaseSndObj& obj)\n{\n string str = obj.getType();\n if(str.compare(\"ofxSOBuzz\") == 0)\n {\n // do ofxSOBuzz - specific thing\n }\n else if(str.compare(\"some other derived class\") == 0)\n {\n // do stuff for other derived classes\n }\n // etc...\n}\n class ofxBaseSndObj {\n\npublic:\n // get rid of getType()\n virtual void HelpCreateFilter() = 0;\n};\n\n\nstring ofxSndObj::createFilter(ofxBaseSndObj& obj)\n{\n // Let the derived class do it's own specialized work.\n // This function doesn't need to know what it is.\n obj.HelpCreateFilter();\n // rest of filter creation\n}\n ofxSndObj::createFilter" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66105/" ]
237,041
<p>Does anyone know what will be in .NET 4.0?</p> <p>I found <a href="https://mef.svn.codeplex.com/svn/src/ComponentModel/System/Tuple.cs" rel="nofollow noreferrer">tuples on codeplex</a>:</p> <pre><code>.... // NOTE : this is a TEMPORARY and a very minimalistic implementation of Tuple'2, // as defined in http://devdiv/sites/docs/NetFX4/CLR/Specs/Base Class Libraries/Tuple Spec.docx // We will remove this after we move to v4 and Tuple is actually in there public struct Tuple&lt;TFirst, TSecond&gt; .... </code></pre>
[ { "answer_id": 237080, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 1, "selected": false, "text": "// Instead of this:\nobject calc = GetCalculator();\nType calcType = calc.GetType();\nobject res = calcType.InvokeMember(\"Add\", \n BindingFlags.InvokeMethod, null,\n new int[] { 10, 20 });\nint sum = Convert.ToInt32(res);\n\n// you can write this:\ndynamic calc = GetCalculator();\nint sum = calc.Add(10, 20);\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29788/" ]
237,044
<p>I'm trying to compile code from F# to use in Silverlight. I compile with:</p> <p>--noframework --cliroot "C:\program Files\Microsoft Silverlight\2.0.31005.0" --standalone</p> <p>This generates a standalone assembly that references the SL framework. But when I try to add a reference to the generated assembly, I get this error:</p> <blockquote> <p>You can only add project references to other Silverlight projects in the solution.</p> </blockquote> <p>What is the VS plugin doing to determine that this isn't a Silverlight assembly? Here's the manifest:</p> <pre><code>// Metadata version: v2.0.50727 .assembly extern mscorlib { .publickeytoken = (7C EC 85 D7 BE A7 79 8E ) // |.....y. .ver 2:0:5:0 } .assembly FSSLLibrary1 { // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 01 01 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .module 'F#-Module-FSSLLibrary1' // MVID: {49038883-5D18-7281-A745-038383880349} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04120000 </code></pre> <p>I don't understand what it's finding that it doesn't like; it's pure verifiable IL. I compared to a SL "class library" assembly, and it looks the same. The only difference was some attributes, but I deleted those and VS still let me reference the DLL. I even added unverifiable IL to the "SL library" DLL and it still loaded.</p> <p>Any suggestions?</p> <p><em>Update:</em> I've done some poking around, and it doesn't seem to be the manifest that matters. It doesn't like something in the IL from the FSharp libraries. They are peverifiable, but something in there is triggering the rejection. </p>
[ { "answer_id": 245116, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 4, "selected": true, "text": "C:\\test\\SilverlightApplication1\\FSC(0,0): error FS0193: internal error: the module/namespace 'System' from compilation unit 'mscorlib' did not contain the namespace, module or type 'MarshalByRefObject'\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27012/" ]
237,058
<p>A string will be made up of certain symbols (ax,bx,dx,c,acc for example) and numbers.</p> <p>ex: ax 5 5 dx 3 acc c ax bx</p> <p>I want to replace one or all of the symbols (randomly) with another symbol of the same set. ie, replace one of {ax,bx,dx,c,acc} with one of {ax,bx,dx,c,acc}.</p> <p>replacement example: acc 5 5 dx 3 acc c ax bx or c 5 5 dx 3 acc c ax ax</p> <p>Is there a way to do this with regexes? In Java? If so, which methods should I use?</p>
[ { "answer_id": 237097, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 0, "selected": false, "text": " String text = \"ax 5 5 dx 3 acc c ax bx\";\n System.out.println(\"Original: \" + text);\n String[] tokens = text.split(\" \");\n List<Integer> symbols = new ArrayList<Integer>();\n for(int i=0; i<tokens.length; i++) {\n try {\n Integer.parseInt(tokens[i]);\n } catch (Exception e) {\n symbols.add(i);\n }\n }\n Random rand = new Random();\n // this is the part you can do multiple times\n int source = symbols.get((rand.nextInt(symbols.size())));\n int target = symbols.get((rand.nextInt(symbols.size())));\n tokens[target] = tokens[source];\n\n String result = tokens[0];\n for(int i=1; i<tokens.length; i++) {\n result = result + \" \" + tokens[i];\n }\n System.out.println(\"Result: \" + result);\n source target" }, { "answer_id": 237181, "author": "Andreas Petersson", "author_id": 16542, "author_profile": "https://Stackoverflow.com/users/16542", "pm_score": 3, "selected": true, "text": "import java.util.*;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\npublic class ReplaceTokens {\npublic static void main(String[] args) {\n List<String> elements = Arrays.asList(\"ax\", \"bx\", \"dx\", \"c\", \"acc\");\n final String patternStr = join(elements, \"|\"); //build string \"ax|bx|dx|c|acc\" \n Pattern p = Pattern.compile(patternStr);\n Matcher m = p.matcher(\"ax 5 5 dx 3 acc c ax bx\");\n StringBuffer sb = new StringBuffer();\n Random rand = new Random();\n while (m.find()){\n String randomSymbol = elements.get(rand.nextInt(elements.size()));\n m.appendReplacement(sb,randomSymbol);\n }\n m.appendTail(sb);\n System.out.println(sb);\n}\n\n/**\n * this method is only needed to generate the string ax|bx|dx|c|acc in a clean way....\n * @see org.apache.commons.lang.StringUtils.join for a more common alternative...\n */\npublic static String join(List<String> s, String delimiter) {\n if (s.isEmpty()) return \"\";\n Iterator<String> iter = s.iterator();\n StringBuffer buffer = new StringBuffer(iter.next());\n while (iter.hasNext()) buffer.append(delimiter).append(iter.next());\n return buffer.toString();\n}\n" }, { "answer_id": 237349, "author": "Dove", "author_id": 27677, "author_profile": "https://Stackoverflow.com/users/27677", "pm_score": -1, "selected": false, "text": "private final String[] symbolsPossible = {\"ax\",\"bx\",\"cx\",\"dx\",\"foo\"};\nprivate boolean exists;\nprivate final String mutate(String s)\n{\nString[] tokens=s.split(\" \");\nfor(int j=0; j<tokens.length; j++)\nif(Math.random()<.1) //10% chance of mutation per token\n{\n//checking to see if the token is a supported symbol\nexists=false;\nfor(int i=0; i<symbolsPossible.length; i++)\n if(tokens[j].equals(symbolsPossible[i]))\n exists=true;\nif(exists)\n tokens[j]=symbolsPossible[(int)Math.random()*symbolsPossible.length];\n}\nStringBuffer result=new StringBuffer();\nfor(String t:tokens)\n result.append(t);\nreturn result;\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27677/" ]
237,061
<p>I have several strings in the rough form:</p> <pre><code>[some text] [some number] [some more text] </code></pre> <p>I want to extract the text in [some number] using the Java Regex classes.</p> <p>I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].</p> <p>EDIT: I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].</p>
[ { "answer_id": 237068, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 10, "selected": true, "text": "private static final Pattern p = Pattern.compile(\"^([a-zA-Z]+)([0-9]+)(.*)\");\npublic static void main(String[] args) {\n // create matcher for pattern p and given string\n Matcher m = p.matcher(\"Testing123Testing\");\n\n // if an occurrence if a pattern was found in a given string...\n if (m.find()) {\n // ...then you can use group() methods.\n System.out.println(m.group(0)); // whole matched expression\n System.out.println(m.group(1)); // first expression from round brackets (Testing)\n System.out.println(m.group(2)); // second one (123)\n System.out.println(m.group(3)); // third one (Testing)\n }\n}\n ^\\D+(\\d+).*\n m.group(1) ^\\D+(-?\\d+).*\n" }, { "answer_id": 237078, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 4, "selected": false, "text": "String input = \"...\";\nMatcher matcher = Pattern.compile(\"[^0-9]+([0-9]+)[^0-9]+\").matcher(input);\nif (matcher.find()) {\n String someNumberStr = matcher.group(1);\n // if you need this to be an int:\n int someNumberInt = Integer.parseInt(someNumberStr);\n}\n" }, { "answer_id": 237081, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 5, "selected": false, "text": "\"(\\\\d+)\"\n \"\\\\s+(\\\\d+)\\\\s+\"\n \"(\\\\D+)(\\\\d+)(.*)\"\n \\d" }, { "answer_id": 2061076, "author": "arturo", "author_id": 250319, "author_profile": "https://Stackoverflow.com/users/250319", "pm_score": 0, "selected": false, "text": "[^\\\\d]*([0-9]+[\\\\s]*[.,]{0,1}[\\\\s]*[0-9]*).* ," }, { "answer_id": 5553243, "author": "Tint Naing Win", "author_id": 693073, "author_profile": "https://Stackoverflow.com/users/693073", "pm_score": 2, "selected": false, "text": "Pattern p = Pattern.compile(\"^.+(\\\\d+).+\");\nMatcher m = p.matcher(\"Testing123Testing\");\n\nif (m.find()) {\n System.out.println(m.group(1));\n}\n" }, { "answer_id": 8116229, "author": "javaMan", "author_id": 771318, "author_profile": "https://Stackoverflow.com/users/771318", "pm_score": 6, "selected": false, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Regex1 {\n public static void main(String[]args) {\n Pattern p = Pattern.compile(\"\\\\d+\");\n Matcher m = p.matcher(\"hello1234goodboy789very2345\");\n while(m.find()) {\n System.out.println(m.group());\n }\n }\n}\n 1234\n789\n2345\n" }, { "answer_id": 9354651, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 4, "selected": false, "text": "\"ab123abc\".replaceFirst(\"\\\\D*(\\\\d*).*\", \"$1\")\n \\\\D" }, { "answer_id": 10730820, "author": "shounak", "author_id": 1412460, "author_profile": "https://Stackoverflow.com/users/1412460", "pm_score": 1, "selected": false, "text": "String str = \"as:\"+123+\"as:\"+234+\"as:\"+345;\nStringTokenizer st = new StringTokenizer(str,\"as:\");\n\nwhile(st.hasMoreTokens())\n{\n String k = st.nextToken(); // you will get first numeric data i.e 123\n int kk = Integer.parseInt(k);\n System.out.println(\"k string token in integer \" + kk);\n\n String k1 = st.nextToken(); // you will get second numeric data i.e 234\n int kk1 = Integer.parseInt(k1);\n System.out.println(\"new string k1 token in integer :\" + kk1);\n\n String k2 = st.nextToken(); // you will get third numeric data i.e 345\n int kk2 = Integer.parseInt(k2);\n System.out.println(\"k2 string token is in integer : \" + kk2);\n}\n" }, { "answer_id": 13916090, "author": "LukaszTaraszka", "author_id": 1816687, "author_profile": "https://Stackoverflow.com/users/1816687", "pm_score": 3, "selected": false, "text": "static final String EMAIL_PATTERN = \"[_A-Za-z0-9-\\\\+]+(\\\\.[_A-Za-z0-9-]+)*@\"\n + \"[A-Za-z0-9-]+(\\\\.[A-Za-z0-9]+)*(\\\\.[A-Za-z]{2,})\";\n\npublic List<String> getAllEmails(String message) { \n List<String> result = null;\n Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);\n\n if (matcher.find()) {\n result = new ArrayList<String>();\n result.add(matcher.group());\n\n while (matcher.find()) {\n result.add(matcher.group());\n }\n }\n\n return result;\n}\n message = \"adf@gmail.com, <another@osiem.osiem>>>> lalala@aaa.pl\"" }, { "answer_id": 23009935, "author": "user1722707", "author_id": 1722707, "author_profile": "https://Stackoverflow.com/users/1722707", "pm_score": 0, "selected": false, "text": "String input = \"first,second,third\";\n\n//To retrieve 'first' \ninput.split(\",\")[0] \n//second\ninput.split(\",\")[1]\n//third\ninput.split(\",\")[2]\n" }, { "answer_id": 23010127, "author": "seeker", "author_id": 1632156, "author_profile": "https://Stackoverflow.com/users/1632156", "pm_score": -1, "selected": false, "text": " try{\n InputStream inputStream = (InputStream) mnpMainBean.getUploadedBulk().getInputStream();\n BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));\n String line;\n //Ref:03\n while ((line = br.readLine()) != null) {\n if (line.matches(\"[A-Z],\\\\d,(\\\\d*,){2}(\\\\s*\\\\d*\\\\|\\\\d*:)+\")) {\n String[] splitRecord = line.split(\",\");\n //do something\n }\n else{\n br.close();\n //error\n return;\n }\n }\n br.close();\n\n }\n }\n catch (IOException ioExpception){\n logger.logDebug(\"Exception \" + ioExpception.getStackTrace());\n }\n" }, { "answer_id": 31014297, "author": "NoBrainer", "author_id": 1169991, "author_profile": "https://Stackoverflow.com/users/1169991", "pm_score": 2, "selected": false, "text": "// Regexplanation:\n// ^ beginning of line\n// \\\\D+ 1+ non-digit characters\n// (\\\\d+) 1+ digit characters in a capture group\n// .* 0+ any character\nString regexStr = \"^\\\\D+(\\\\d+).*\";\n\n// Compile the regex String into a Pattern\nPattern p = Pattern.compile(regexStr);\n\n// Create a matcher with the input String\nMatcher m = p.matcher(inputStr);\n\n// If we find a match\nif (m.find()) {\n // Get the String from the first capture group\n String someDigits = m.group(1);\n // ...do something with someDigits\n}\n public class MyUtil {\n private static Pattern pattern = Pattern.compile(\"^\\\\D+(\\\\d+).*\");\n private static Matcher matcher = pattern.matcher(\"\");\n\n // Assumptions: inputStr is a non-null String\n public static String extractFirstNumber(String inputStr){\n // Reset the matcher with a new input String\n matcher.reset(inputStr);\n\n // Check if there's a match\n if(matcher.find()){\n // Return the number (in the first capture group)\n return matcher.group(1);\n }else{\n // Return some default value, if there is no match\n return null;\n }\n }\n}\n\n...\n\n// Use the util function and print out the result\nString firstNum = MyUtil.extractFirstNumber(\"Testing4234Things\");\nSystem.out.println(firstNum);\n" }, { "answer_id": 39076286, "author": "Mohammadreza Tavakoli", "author_id": 4393496, "author_profile": "https://Stackoverflow.com/users/4393496", "pm_score": -1, "selected": false, "text": "Pattern p = Pattern.compile(\"(\\\\D+)(\\\\d+)(.*)\");\nMatcher m = p.matcher(\"this is your number:1234 thank you\");\nif (m.find()) {\n String someNumberStr = m.group(2);\n int someNumberInt = Integer.parseInt(someNumberStr);\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
237,064
<p>i am trying to compile this very simple piece of code</p> <pre><code>class myList { public: std::vector&lt;std::string&gt; vec; class Items { public: void Add(std::string str) { myList::vec.push_back(str); }; }items; }; int main() { myList newList; newList.items.Add("A"); } </code></pre> <p>what can i do to make this work without creating more objects that needed or overcomplicating stuff... </p>
[ { "answer_id": 237072, "author": "richq", "author_id": 4596, "author_profile": "https://Stackoverflow.com/users/4596", "pm_score": 5, "selected": true, "text": "#include <string>\n#include <vector>\nclass myList\n{\npublic:\n std::vector<std::string> vec;\n myList(): items(this) {} // Added\n class Items\n {\n public:\n Items(myList *ml): self(ml) {} // Added\n void Add(std::string str)\n {\n self->vec.push_back(str); // Changed\n };\n myList *self; //Added\n }items;\n};\n\nint main()\n{\n myList newList;\n newList.items.Add(\"A\");\n}\n" }, { "answer_id": 237073, "author": "postfuturist", "author_id": 1892, "author_profile": "https://Stackoverflow.com/users/1892", "pm_score": 4, "selected": false, "text": "class myList\n{\nprivate:\n std::vector<std::string> vec;\npublic:\n void Add(std::string str)\n {\n vec.push_back(str);\n };\n};\n\nint main()\n{\n myList newList;\n newList.Add(\"A\");\n}\n" }, { "answer_id": 1509019, "author": "phoku", "author_id": 157410, "author_profile": "https://Stackoverflow.com/users/157410", "pm_score": 0, "selected": false, "text": "typedef std::vector<std::string> myList;\n" }, { "answer_id": 14076732, "author": "nickdu", "author_id": 1769110, "author_profile": "https://Stackoverflow.com/users/1769110", "pm_score": 1, "selected": false, "text": "struct IReferenceCounted\n{\n virtual unsigned long AddRef() = 0;\n virtual unsigned long Release() = 0;\n};\n\nstruct IFoo : public IReferenceCounted\n{\n};\n\nclass Foo : public IFoo\n{\npublic:\n static IFoo* Create();\n static IFoo* Create(IReferenceCounted* outer, IReferenceCounted** inner);\n\nprivate:\n Foo();\n Foo(IReferenceCounted* outer);\n ~Foo();\n\n // IReferenceCounted\n\n unsigned long AddRef();\n unsigned long Release();\n\nprivate:\n struct EIReferenceCounted : IReferenceCounted\n {\n // IReferenceCounted\n\n unsigned long AddRef();\n unsigned long Release();\n } _inner;\n\n unsigned long _refs;\n IReferenceCounted* _outer;\n};\n #include <stdio.h>\n#include <stddef.h>\n#include \"Foo.h\"\n\n#define EmbeddorOf(class, member, this) \\\n (class *) ((char *) this - offsetof(class, member))\n\n// Foo\n\nFoo::Foo() : _refs(1), _outer(&this->_inner)\n{\n}\n\nFoo::Foo(IReferenceCounted* outer) : _refs(1), _outer(outer)\n{\n}\n\nFoo::~Foo()\n{\n printf(\"Foo::~Foo()\\n\");\n}\n\nIFoo* Foo::Create()\n{\n return new Foo();\n}\n\nIFoo* Foo::Create(IReferenceCounted* outer, IReferenceCounted** inner)\n{\n Foo* foo = new Foo(outer);\n *inner = &foo->_inner;\n return (IFoo*) foo;\n}\n\n// IReferenceCounted\n\nunsigned long Foo::AddRef()\n{\n printf(\"Foo::AddRef()\\n\");\n return this->_outer->AddRef();\n}\n\nunsigned long Foo::Release()\n{\n printf(\"Foo::Release()\\n\");\n return this->_outer->Release();\n}\n\n// Inner IReferenceCounted\n\nunsigned long Foo::EIReferenceCounted::AddRef()\n{\n Foo* pThis = EmbeddorOf(Foo, _inner, this);\n return ++pThis->_refs;\n}\n\nunsigned long Foo::EIReferenceCounted::Release()\n{\n Foo* pThis = EmbeddorOf(Foo, _inner, this);\n unsigned long refs = --pThis->_refs;\n if (refs == 0)\n {\n\n // Artifically increment so that we won't try to destroy multiple\n // times in the event that our destructor causes AddRef()'s or\n // Releases().\n\n pThis->_refs = 1;\n delete pThis;\n }\n return refs;\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28954/" ]
237,069
<p>I have a report that renders data returned from a stored procedure. Using profiler I can catch the call to the stored procedure from the reporting services.</p> <p>The report fails stating the report timed out yet I can execute the stored procedure from SSMS and it returns the data back in five to six seconds.</p> <p>Note, in the example test run only two rows are returned to the report for rendering though within the stored procedure it may have been working over thousands or even millions of records in order to collate the result passed back to reporting services.</p> <p>I know the stored procedure could be optimised more but I do not understand why SSRS would be timing out when the execution only seems to take a few seconds to execute from SSMS.</p> <p>Also another issue has surfaced. If I recreate the stored procedure, the report starts to render perfectly fine again. That is fine except after a short period of time, the report starts timing out again.</p> <p>The return of the time out seems to be related to new data being added into the main table the report is running against. In the example I was testing, just one hundred new records being inserted was enough to screw up the report.</p> <p>I imagine more correctly its not the report that is the root cause. It is the stored procedure that is causing the time out when executed from SSRS.</p> <p>Once it is timeing out again, I best fix I have so far is to recreate the stored procedure. This doesn't seem to be an ideal solution.</p> <p>The problem also only seems to be occuring on our production environment. Our test and development platforms do not seem to be exhibiting the same problem. Though dev and test do not have the same volume of records as production.</p>
[ { "answer_id": 4679353, "author": "Robert Don-Duncan", "author_id": 574124, "author_profile": "https://Stackoverflow.com/users/574124", "pm_score": 2, "selected": false, "text": "CREATE PROCEDURE [dbo].[usp_REPORT_ITD001]\n@StartDate DATETIME,\n@EndDate DATETIME,\n@ReportTab INT\nAS\n\n-- Deter parameter sniffing\nDECLARE @snf_StartDate DATETIME = @StartDate\nDECLARE @snf_EndDate DATETIME = @EndDate\nDECLARE @snf_ReportTab INT = @ReportTab\n DECLARE @MyTable AS TABLE SELECT MyCol1, MyCol2 INTO #MyTable" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19377/" ]
237,079
<p>What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows?</p>
[ { "answer_id": 237084, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 10, "selected": false, "text": "os.path.getmtime os.path.getctime import os.path, time\nprint(\"last modified: %s\" % time.ctime(os.path.getmtime(file)))\nprint(\"created: %s\" % time.ctime(os.path.getctime(file)))\n os.stat import os, time\n(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)\nprint(\"last modified: %s\" % time.ctime(mtime))\n ctime()" }, { "answer_id": 237092, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 6, "selected": false, "text": ">>> import os\n>>> statinfo = os.stat('somefile.txt')\n>>> statinfo\n(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)\n>>> statinfo.st_size\n926L\n>>> \n" }, { "answer_id": 237093, "author": "mithrandi", "author_id": 31490, "author_profile": "https://Stackoverflow.com/users/31490", "pm_score": 4, "selected": false, "text": "os.stat st_mtime st_ctime st_mtime ctime" }, { "answer_id": 237094, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 1, "selected": false, "text": ">>> import os\n>>> os.stat('feedparser.py').st_mtime\n1136961142.0\n>>> os.stat('feedparser.py').st_ctime\n1222664012.233\n>>> \n" }, { "answer_id": 367166, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "os.stat os.stat() os.stat('feedparser.py')[8]" }, { "answer_id": 1526089, "author": "Christian Oudard", "author_id": 3757, "author_profile": "https://Stackoverflow.com/users/3757", "pm_score": 9, "selected": false, "text": "os.stat(filename).st_mtime datetime import os\nimport datetime\ndef modification_date(filename):\n t = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(t)\n >>> d = modification_date('/var/log/syslog')\n>>> print d\n2009-10-06 10:50:01\n>>> print repr(d)\ndatetime.datetime(2009, 10, 6, 10, 50, 1)\n" }, { "answer_id": 28444315, "author": "Muhammad Lukman Low", "author_id": 501800, "author_profile": "https://Stackoverflow.com/users/501800", "pm_score": 0, "selected": false, "text": "os.lstat >>> os.lstat(\"2048.py\")\nposix.stat_result(st_mode=33188, st_ino=4172202, st_dev=16777218L, st_nlink=1, st_uid=501, st_gid=20, st_size=2078, st_atime=1423378041, st_mtime=1423377552, st_ctime=1423377553)\n>>> os.lstat(\"2048.py\").st_atime\n1423378041.0\n" }, { "answer_id": 39501288, "author": "Mark Amery", "author_id": 1709587, "author_profile": "https://Stackoverflow.com/users/1709587", "pm_score": 10, "selected": false, "text": "os.path.getmtime(path) path ctime os.path.getctime() .st_ctime os.stat() ctime .st_birthtime os.stat() ext4 st_crtime stat() st_crtime ext4 mtime os.path.getmtime() .st_mtime os.stat() import os\nimport platform\n\ndef creation_date(path_to_file):\n \"\"\"\n Try to get the date that a file was created, falling back to when it was\n last modified if that isn't possible.\n See http://stackoverflow.com/a/39501288/1709587 for explanation.\n \"\"\"\n if platform.system() == 'Windows':\n return os.path.getctime(path_to_file)\n else:\n stat = os.stat(path_to_file)\n try:\n return stat.st_birthtime\n except AttributeError:\n # We're probably on Linux. No easy way to get creation dates here,\n # so we'll settle for when its content was last modified.\n return stat.st_mtime\n" }, { "answer_id": 52858040, "author": "Steven C. Howell", "author_id": 3585557, "author_profile": "https://Stackoverflow.com/users/3585557", "pm_score": 8, "selected": true, "text": ">>> import pathlib\n>>> fname = pathlib.Path('test.py')\n>>> assert fname.exists(), f'No such file: {fname}' # check that the file exists\n>>> print(fname.stat())\nos.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272)\n os.stat_result fname.stat().st_mtime >>> import datetime\n>>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime, tz=datetime.timezone.utc)\n>>> print(mtime)\ndatetime.datetime(2018, 10, 17, 10, 49, 0, 249980)\n fname.stat().st_ctime >>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime, tz=datetime.timezone.utc)\n>>> print(ctime)\ndatetime.datetime(2018, 4, 11, 16, 57, 52, 151953)\n" }, { "answer_id": 53586899, "author": "Puddle", "author_id": 9312988, "author_profile": "https://Stackoverflow.com/users/9312988", "pm_score": 6, "selected": false, "text": "import os, time, datetime\n\nfile = \"somefile.txt\"\nprint(file)\n\nprint(\"Modified\")\nprint(os.stat(file)[-2])\nprint(os.stat(file).st_mtime)\nprint(os.path.getmtime(file))\n\nprint()\n\nprint(\"Created\")\nprint(os.stat(file)[-1])\nprint(os.stat(file).st_ctime)\nprint(os.path.getctime(file))\n\nprint()\n\nmodified = os.path.getmtime(file)\nprint(\"Date modified: \"+time.ctime(modified))\nprint(\"Date modified:\",datetime.datetime.fromtimestamp(modified))\nyear,month,day,hour,minute,second=time.localtime(modified)[:-3]\nprint(\"Date modified: %02d/%02d/%d %02d:%02d:%02d\"%(day,month,year,hour,minute,second))\n\nprint()\n\ncreated = os.path.getctime(file)\nprint(\"Date created: \"+time.ctime(created))\nprint(\"Date created:\",datetime.datetime.fromtimestamp(created))\nyear,month,day,hour,minute,second=time.localtime(created)[:-3]\nprint(\"Date created: %02d/%02d/%d %02d:%02d:%02d\"%(day,month,year,hour,minute,second))\n somefile.txt\nModified\n1429613446\n1429613446.0\n1429613446.0\n\nCreated\n1517491049\n1517491049.28306\n1517491049.28306\n\nDate modified: Tue Apr 21 11:50:46 2015\nDate modified: 2015-04-21 11:50:46\nDate modified: 21/04/2015 11:50:46\n\nDate created: Thu Feb 1 13:17:29 2018\nDate created: 2018-02-01 13:17:29.283060\nDate created: 01/02/2018 13:17:29\n" }, { "answer_id": 56333103, "author": "Delgan", "author_id": 2291710, "author_profile": "https://Stackoverflow.com/users/2291710", "pm_score": 2, "selected": false, "text": "crtime from crtime import get_crtimes_in_dir\n\nfor fname, date in get_crtimes_in_dir(\".\", raise_on_error=True, as_epoch=False):\n print(fname, date)\n # file_a.py Mon Mar 18 20:51:18 CET 2019\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
237,085
<p>It's possible to write <a href="http://en.wikipedia.org/wiki/Markdown" rel="noreferrer">Markdown</a> content with invalid syntax. Invalid means that the <a href="http://www.deveiate.org/projects/BlueCloth" rel="noreferrer">BlueCloth</a> library fails to parse the content and throws an exception. The <code>markdown</code> helper in Rails doesn't catch any BlueCloth exceptions and because of that the complete page fails to render (500 Server Error page is rendered instead).</p> <p>In my case, users are allowed to write Markdown content and save it to the database. If someone used invalid syntax, all successive rendering attempts of that content fail (Status Code 500 - Internal Server Error).</p> <p>How do you get around this issue? Is it possible to validate the Markdown syntax at the Model-level before saving to the database?</p>
[ { "answer_id": 237200, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 4, "selected": true, "text": "to_html protected:\n\ndef validate\n bc = BlueCloth.new(your_markdown_string_attribute)\n begin\n bc.to_html\n rescue\n errors.add(:your_markdown_string_attribute, 'has invalid markdown syntax')\n end\nend\n" }, { "answer_id": 277564, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 1, "selected": false, "text": "environment.rb begin\n require \"rdiscount\"\n BlueCloth = RDiscount\nrescue LoadError\n # BlueCloth is still the our fallback,\n # if RDiscount is not available\n require 'bluecloth'\nend\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20467/" ]
237,104
<p>What is the most concise and efficient way to find out if a JavaScript array contains a value?</p> <p>This is the only way I know to do it:</p> <pre><code>function contains(a, obj) { for (var i = 0; i &lt; a.length; i++) { if (a[i] === obj) { return true; } } return false; } </code></pre> <p>Is there a better and more concise way to accomplish this?</p> <p>This is very closely related to Stack Overflow question <em><a href="https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array">Best way to find an item in a JavaScript Array?</a></em> which addresses finding objects in an array using <code>indexOf</code>.</p>
[ { "answer_id": 237148, "author": "cic", "author_id": 4771, "author_profile": "https://Stackoverflow.com/users/4771", "pm_score": 8, "selected": false, "text": "indexOf [1, 2, 3].indexOf(1) => 0\n[\"foo\", \"bar\", \"baz\"].indexOf(\"bar\") => 1\n[1, 2, 3].indexOf(4) => -1\n indexOf" }, { "answer_id": 237176, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 9, "selected": false, "text": "while function contains(a, obj) {\n var i = a.length;\n while (i--) {\n if (a[i] === obj) {\n return true;\n }\n }\n return false;\n}\n Array.prototype.contains = function(obj) {\n var i = this.length;\n while (i--) {\n if (this[i] === obj) {\n return true;\n }\n }\n return false;\n}\n alert([1, 2, 3].contains(2)); // => true\nalert([1, 2, 3].contains('2')); // => false\n" }, { "answer_id": 238862, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 6, "selected": false, "text": "Array.indexOf if (!Array.indexOf) {\n Array.indexOf = [].indexOf ?\n function(arr, obj, from) {\n return arr.indexOf(obj, from);\n } :\n function(arr, obj, from) { // (for IE6)\n var l = arr.length,\n i = from ? parseInt((1 * from) + (from < 0 ? l : 0), 10) : 0;\n i = i < 0 ? 0 : i;\n for (; i < l; i++) {\n if (i in arr && arr[i] === obj) {\n return i;\n }\n }\n return -1;\n };\n}\n" }, { "answer_id": 1342312, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "Array for-in" }, { "answer_id": 1342459, "author": "Ken", "author_id": 121620, "author_profile": "https://Stackoverflow.com/users/121620", "pm_score": 3, "selected": false, "text": "/**\n * Array#indexOf(item[, offset = 0]) -> Number\n * - item (?): A value that may or may not be in the array.\n * - offset (Number): The number of initial items to skip before beginning the\n * search.\n *\n * Returns the position of the first occurrence of `item` within the array &mdash; or\n * `-1` if `item` doesn't exist in the array.\n**/\nfunction indexOf(item, i) {\n i || (i = 0);\n var length = this.length;\n if (i < 0) i = length + i;\n for (; i < length; i++)\n if (this[i] === item) return i;\n return -1;\n}\n" }, { "answer_id": 1473742, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 13, "selected": true, "text": "Array#includes console.log(['joe', 'jane', 'mary'].includes('jane')); //true Array#indexOf console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); //true $.inArray(value, array, [fromIndex]) _.contains(array, value) _.include _.includes dojo.indexOf(array, value, [fromIndex, findLast]) array.indexOf(value) array.indexOf(value) findValue(array, value) array.indexOf(value) Ext.Array.contains(array, value) _.includes(array, value, [from]) _.contains R.includes(value, array)" }, { "answer_id": 3406317, "author": "Dennis Allen", "author_id": 214691, "author_profile": "https://Stackoverflow.com/users/214691", "pm_score": -1, "selected": false, "text": "// usage: if ( ['a','b','c','d'].contains('b') ) { ... }\nArray.prototype.contains = function(value){\n for (var key in this)\n if (this[key] === value) return true;\n return false;\n}\n" }, { "answer_id": 4908569, "author": "Ztyx", "author_id": 260805, "author_profile": "https://Stackoverflow.com/users/260805", "pm_score": 4, "selected": false, "text": "contains(a, obj)" }, { "answer_id": 5955215, "author": "Ekim", "author_id": 725589, "author_profile": "https://Stackoverflow.com/users/725589", "pm_score": -1, "selected": false, "text": "for-in for-in length for-in function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;}\n\n function check(ra){\n return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('')\n }\n alert([\n check([{}]), check([]), check([,2,3]),\n check(['']), '\\t (a null string)', check([,,,])\n ].join('\\n'));\n There is an object in [[object Object]].\nThere is NO object in [].\nThere is an object in [,2,3].\nThere is an object in [].\n (a null string)\nThere is NO object in [,,].\n alert({}!={}); alert({}!=={}); obj = {prop:\"value\"}; \n ra1 = [obj]; \n ra2 = [{prop:\"value\"}];\n alert(ra1[0] == obj); \n alert(ra2[0] == obj);\n ra2 obj {prop:\"value\"} obj={prop:\"value\"}; ra2=[{prop:\"value\"}];\n alert(\n ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ?\n 'found' :\n 'missing' );\n" }, { "answer_id": 8758721, "author": "Carlos A", "author_id": 1134413, "author_profile": "https://Stackoverflow.com/users/1134413", "pm_score": 2, "selected": false, "text": "Array.prototype.contains = function(x){\n var retVal = -1;\n\n // x is a primitive type\n if([\"string\",\"number\"].indexOf(typeof x)>=0 ){ retVal = this.indexOf(x);}\n\n // x is a function\n else if(typeof x ==\"function\") for(var ix in this){\n if((this[ix]+\"\")==(x+\"\")) retVal = ix;\n }\n\n //x is an object...\n else {\n var sx=JSON.stringify(x);\n for(var ix in this){\n if(typeof this[ix] ==\"object\" && JSON.stringify(this[ix])==sx) retVal = ix;\n }\n }\n\n //Return False if -1 else number if numeric otherwise string\n return (retVal === -1)?false : ( isNaN(+retVal) ? retVal : +retVal);\n}\n" }, { "answer_id": 9849276, "author": "william malo", "author_id": 1145932, "author_profile": "https://Stackoverflow.com/users/1145932", "pm_score": 7, "selected": false, "text": "const array = [1, 2, 3, 4]\n 3 true false array.includes(3) // true\n // Prefixing the method with '_' to avoid name clashes\nObject.defineProperty(Array.prototype, '_includes', { value: function (v) { return this.indexOf(v) !== -1 }})\narray._includes(3) // true\n const includes = (a, v) => a.indexOf(v) !== -1\nincludes(array, 3) // true\n" }, { "answer_id": 10265443, "author": "ninjagecko", "author_id": 711085, "author_profile": "https://Stackoverflow.com/users/711085", "pm_score": 3, "selected": false, "text": "array.indexOf(x)!=-1 table[x]!==undefined ===undefined Array.prototype.toTable = function() {\n var t = {};\n this.forEach(function(x){t[x]=true});\n return t;\n}\n var toRemove = [2,4].toTable();\n[1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})\n" }, { "answer_id": 11226279, "author": "Lemex", "author_id": 983969, "author_profile": "https://Stackoverflow.com/users/983969", "pm_score": 4, "selected": false, "text": "function inArray(elem,array)\n{\n var len = array.length;\n for(var i = 0 ; i < len;i++)\n {\n if(array[i] == elem){return i;}\n }\n return -1;\n} \n" }, { "answer_id": 13532998, "author": "Andy Rohr", "author_id": 584171, "author_profile": "https://Stackoverflow.com/users/584171", "pm_score": 2, "selected": false, "text": "Array.prototype.find = function(search_lambda) {\n return this[this.map(search_lambda).indexOf(true)];\n};\n [1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 })\n=> 4\n Array.prototype.find = (search_lambda) -> @[@map(search_lambda).indexOf(true)]\n" }, { "answer_id": 15354149, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 2, "selected": false, "text": "Array.indexOf if (!Array.prototype.indexOf) {\n Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {\n \"use strict\";\n if (this == null) {\n throw new TypeError();\n }\n var t = Object(this);\n var len = t.length >>> 0;\n if (len === 0) {\n return -1;\n }\n var n = 0;\n if (arguments.length > 1) {\n n = Number(arguments[1]);\n if (n != n) { // shortcut for verifying if it's NaN\n n = 0;\n } else if (n != 0 && n != Infinity && n != -Infinity) {\n n = (n > 0 || -1) * Math.floor(Math.abs(n));\n }\n }\n if (n >= len) {\n return -1;\n }\n var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);\n for (; k < len; k++) {\n if (k in t && t[k] === searchElement) {\n return k;\n }\n }\n return -1;\n }\n}\n" }, { "answer_id": 17453323, "author": "stamat", "author_id": 1909864, "author_profile": "https://Stackoverflow.com/users/1909864", "pm_score": 2, "selected": false, "text": "var a = {'a':1,\n 'b':{'c':[1,2,[3,45],4,5],\n 'd':{'q':1, 'b':{'q':1, 'b':8},'c':4},\n 'u':'lol'},\n 'e':2};\n\n var b = {'a':1, \n 'b':{'c':[2,3,[1]],\n 'd':{'q':3,'b':{'b':3}}},\n 'e':2};\n\n var c = \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\";\n\n var hc = new HashCache([{a:3, b:2, c:5}, {a:15, b:2, c:'foo'}]); //init\n\n hc.put({a:1, b:1});\n hc.put({b:1, a:1});\n hc.put(true);\n hc.put('true');\n hc.put(a);\n hc.put(c);\n hc.put(d);\n console.log(hc.exists('true'));\n console.log(hc.exists(a));\n console.log(hc.exists(c));\n console.log(hc.exists({b:1, a:1}));\n hc.remove(a);\n console.log(hc.exists(c));\n" }, { "answer_id": 18792061, "author": "Matías Cánepa", "author_id": 702353, "author_profile": "https://Stackoverflow.com/users/702353", "pm_score": 6, "selected": false, "text": "function isInArray(array, search)\n{\n return array.indexOf(search) >= 0;\n}\n\n// Usage\nif(isInArray(my_array, \"my_value\"))\n{\n //...\n}\n" }, { "answer_id": 19208820, "author": "Mina Gabriel", "author_id": 1410185, "author_profile": "https://Stackoverflow.com/users/1410185", "pm_score": 3, "selected": false, "text": "var myArray = ['yellow', 'orange', 'red'] ;\n\nalert(!!~myArray.indexOf('red')); //true\n tilde ~" }, { "answer_id": 23938696, "author": "Pradeep Mahdevu", "author_id": 572100, "author_profile": "https://Stackoverflow.com/users/572100", "pm_score": 3, "selected": false, "text": "function isPrime(element, index, array) {\n var start = 2;\n while (start <= Math.sqrt(element)) {\n if (element % start++ < 1) return false;\n }\n return (element > 1);\n}\n\nconsole.log( [4, 6, 8, 12].find(isPrime) ); // Undefined, not found\nconsole.log( [4, 5, 8, 12].find(isPrime) ); // 5\n if (!Array.prototype.find) {\n Object.defineProperty(Array.prototype, 'find', {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function(predicate) {\n if (this == null) {\n throw new TypeError('Array.prototype.find called on null or undefined');\n }\n if (typeof predicate !== 'function') {\n throw new TypeError('predicate must be a function');\n }\n var list = Object(this);\n var length = list.length >>> 0;\n var thisArg = arguments[1];\n var value;\n\n for (var i = 0; i < length; i++) {\n if (i in list) {\n value = list[i];\n if (predicate.call(thisArg, value, i, list)) {\n return value;\n }\n }\n }\n return undefined;\n }\n });\n}\n" }, { "answer_id": 24225731, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 5, "selected": false, "text": "Array.prototype.contains = function (v) {\n return this.indexOf(v) > -1;\n}\n\nvar a = [ 'foo', 'bar' ];\n\na.contains('foo'); // true\na.contains('fox'); // false\n" }, { "answer_id": 24827594, "author": "Michael", "author_id": 599912, "author_profile": "https://Stackoverflow.com/users/599912", "pm_score": 8, "selected": false, "text": "const items = [ {a: '1'}, {a: '2'}, {a: '3'} ]\n\nitems.some(item => item.a === '3') // returns true\nitems.some(item => item.a === '4') // returns false\n if if (items.some(item => item.a === '3')) {\n // do something\n}\n Array.prototype.some()" }, { "answer_id": 25765186, "author": "dr.dimitru", "author_id": 1320932, "author_profile": "https://Stackoverflow.com/users/1320932", "pm_score": 4, "selected": false, "text": "/*\n * @function\n * @name Object.prototype.inArray\n * @description Extend Object prototype within inArray function\n *\n * @param {mix} needle - Search-able needle\n * @param {bool} searchInKey - Search needle in keys?\n *\n */\nObject.defineProperty(Object.prototype, 'inArray',{\n value: function(needle, searchInKey){\n\n var object = this;\n\n if( Object.prototype.toString.call(needle) === '[object Object]' || \n Object.prototype.toString.call(needle) === '[object Array]'){\n needle = JSON.stringify(needle);\n }\n\n return Object.keys(object).some(function(key){\n\n var value = object[key];\n\n if( Object.prototype.toString.call(value) === '[object Object]' || \n Object.prototype.toString.call(value) === '[object Array]'){\n value = JSON.stringify(value);\n }\n\n if(searchInKey){\n if(value === needle || key === needle){\n return true;\n }\n }else{\n if(value === needle){\n return true;\n }\n }\n });\n },\n writable: true,\n configurable: true,\n enumerable: false\n});\n var a = {one: \"first\", two: \"second\", foo: {three: \"third\"}};\na.inArray(\"first\"); //true\na.inArray(\"foo\"); //false\na.inArray(\"foo\", true); //true - search by keys\na.inArray({three: \"third\"}); //true\n\nvar b = [\"one\", \"two\", \"three\", \"four\", {foo: 'val'}];\nb.inArray(\"one\"); //true\nb.inArray('foo'); //false\nb.inArray({foo: 'val'}) //true\nb.inArray(\"{foo: 'val'}\") //false\n\nvar c = \"String\";\nc.inArray(\"S\"); //true\nc.inArray(\"s\"); //false\nc.inArray(\"2\", true); //true\nc.inArray(\"20\", true); //false\n" }, { "answer_id": 25813188, "author": "dansalmo", "author_id": 1355221, "author_profile": "https://Stackoverflow.com/users/1355221", "pm_score": 5, "selected": false, "text": "function contains(a, obj) {\n return a.some(function(element){return element == obj;})\n}\n" }, { "answer_id": 27727752, "author": "Oriol", "author_id": 1529630, "author_profile": "https://Stackoverflow.com/users/1529630", "pm_score": 8, "selected": false, "text": "Array.prototype.includes [1, 2, 3].includes(2); // true\n[1, 2, 3].includes(4); // false\n fromIndex [1, 2, 3].includes(3, 3); // false\n[1, 2, 3].includes(3, -1); // true\n indexOf includes NaN [1, 2, NaN].includes(NaN); // true\n indexOf includes new Array(5).includes(undefined); // true\n" }, { "answer_id": 27819913, "author": "AlonL", "author_id": 1563935, "author_profile": "https://Stackoverflow.com/users/1563935", "pm_score": 5, "selected": false, "text": "function contains(arr, x) {\n return arr.filter(function(elem) { return elem == x }).length > 0;\n}\n" }, { "answer_id": 30335438, "author": "cocco", "author_id": 2450730, "author_profile": "https://Stackoverflow.com/users/2450730", "pm_score": 4, "selected": false, "text": "indexOf lastIndexOf includes indexOf lastIndexOf contains while for while -- indexOf lastIndexOf function bidirectionalIndexOf(a, b, c, d, e){\n for(c=a.length,d=c*1; c--; ){\n if(a[c]==b) return c; //or this[c]===b\n if(a[e=d-1-c]==b) return e; //or a[e=d-1-c]===b\n }\n return -1\n}\n\n//Usage\nbidirectionalIndexOf(array,'value');\n contains indexOf lastIndexOf true index false -1 Object.defineProperty(Array.prototype,'bidirectionalIndexOf',{value:function(b,c,d,e){\n for(c=this.length,d=c*1; c--; ){\n if(this[c]==b) return c; //or this[c]===b\n if(this[e=d-1-c] == b) return e; //or this[e=d-1-c]===b\n }\n return -1\n},writable:false, enumerable:false});\n\n// Usage\narray.bidirectionalIndexOf('value');\n while function bidirectionalIndexOf(a, b, c, d){\n c=a.length; d=c-1;\n while(c--){\n if(b===a[c]) return c;\n if(b===a[d-c]) return d-c;\n }\n return c\n}\n\n// Usage\nbidirectionalIndexOf(array,'value');\n" }, { "answer_id": 33257515, "author": "l3x", "author_id": 1978383, "author_profile": "https://Stackoverflow.com/users/1978383", "pm_score": 4, "selected": false, "text": "$.inArray({'b': 2}, [{'a': 1}, {'b': 2}])\n> -1\n _.some([{'a': 1}, {'b': 2}], {'b': 2})\n> true\n $.inArray(2, [1,2])\n> 1\n (_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -1)\n" }, { "answer_id": 33735369, "author": "rlib", "author_id": 1477299, "author_profile": "https://Stackoverflow.com/users/1477299", "pm_score": 3, "selected": false, "text": "function contains(arr, obj) {\n var proxy = new Set(arr);\n if (proxy.has(obj))\n return true;\n else\n return false;\n }\n\n var arr = ['Happy', 'New', 'Year'];\n console.log(contains(arr, 'Happy'));" }, { "answer_id": 34690541, "author": "sqram", "author_id": 93026, "author_profile": "https://Stackoverflow.com/users/93026", "pm_score": 3, "selected": false, "text": "Object.defineProperty(Array.prototype, 'exists', {\n value: function(element, index) {\n\n var index = index || 0\n\n return index === this.length ? -1 : this[index] === element ? index : this.exists(element, ++index)\n }\n})\n\n\n// Outputs 1\nconsole.log(['one', 'two'].exists('two'));\n\n// Outputs -1\nconsole.log(['one', 'two'].exists('three'));\n\nconsole.log(['one', 'two', 'three', 'four'].exists('four'));" }, { "answer_id": 34704195, "author": "user2724028", "author_id": 2724028, "author_profile": "https://Stackoverflow.com/users/2724028", "pm_score": 3, "selected": false, "text": "var arrayContains = function(object) {\n return (serverList.filter(function(currentObject) {\n if (currentObject === object) {\n return currentObject\n }\n else {\n return false;\n }\n }).length > 0) ? true : false\n}\n" }, { "answer_id": 41841362, "author": "Igor Barbashin", "author_id": 283803, "author_profile": "https://Stackoverflow.com/users/283803", "pm_score": 4, "selected": false, "text": "function contains(arr, obj) {\n const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration\n return arr.some(item => JSON.stringify(item) === stringifiedObj);\n}\n contains([{a: 1}, {a: 2}], {a: 1}); // true\n function contains(arr, obj) {\n var stringifiedObj = JSON.stringify(obj)\n return arr.some(function (item) {\n return JSON.stringify(item) === stringifiedObj;\n });\n}\n\n// .some polyfill, not needed for IE9+\nif (!('some' in Array.prototype)) {\n Array.prototype.some = function (tester, that /*opt*/) {\n for (var i = 0, n = this.length; i < n; i++) {\n if (i in this && tester.call(that, this[i], i, this)) return true;\n } return false;\n };\n}\n contains([{a: 1}, {a: 2}], {a: 1}); // true\n JSON.stringify Array.indexOf Array.includes [{a: 1}, {a: 2}].includes({a: 1});\n// false, because {a: 1} is a new object\n [{a: 1}, {a: 2}].some(item => JSON.stringify(item) === JSON.stringify({a: 1));\n// true\n contains" }, { "answer_id": 44620847, "author": "Maxime Helen", "author_id": 2647671, "author_profile": "https://Stackoverflow.com/users/2647671", "pm_score": 2, "selected": false, "text": "Array.prototype.includes = function (object) {\n return !!+~this.indexOf(object);\n};\n" }, { "answer_id": 44870333, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 3, "selected": false, "text": "JSON.stringify function contains(a, obj) {\n for (var i = 0; i < a.length; i++) {\n if (JSON.stringify(a[i]) === JSON.stringify(obj)) {\n return true;\n }\n }\n return false;\n}\n" }, { "answer_id": 45460232, "author": "KRRySS", "author_id": 2023542, "author_profile": "https://Stackoverflow.com/users/2023542", "pm_score": 2, "selected": false, "text": "function include(arr,obj) { \n return !!(~arr.indexOf(obj)); \n} \n" }, { "answer_id": 45748512, "author": "Krishna Ganeriwal", "author_id": 6167785, "author_profile": "https://Stackoverflow.com/users/6167785", "pm_score": 3, "selected": false, "text": "Array.indexOf(Object) Array.includes(Object) Array.find(FunctionName) FunctionName" }, { "answer_id": 46047077, "author": "Jeeva", "author_id": 4737293, "author_profile": "https://Stackoverflow.com/users/4737293", "pm_score": 2, "selected": false, "text": "set function set(arr) {\n var res = [];\n for (var i = 0; i < arr.length; i++) {\n if (res.indexOf(arr[i]) === -1) {\n res.push(arr[i]);\n }\n }\n return res;\n}\n" }, { "answer_id": 47652283, "author": "Mitul Panchal", "author_id": 4002757, "author_profile": "https://Stackoverflow.com/users/4002757", "pm_score": 3, "selected": false, "text": "numbers.x == numbers.y var numbers = [ { x: 1, y: 1 },\n { x: 2, y: 3 },\n { x: 3, y: 3 },\n { x: 3, y: 4 },\n { x: 4, y: 5 } ];\nvar count = 0; \nvar n = numbers.length;\nfor (var i =0;i<n;i++)\n{\n if(numbers[i].x==numbers[i].y)\n {count+=1;}\n}\n\nalert(count);" }, { "answer_id": 48435485, "author": "Neil Girardi", "author_id": 1500241, "author_profile": "https://Stackoverflow.com/users/1500241", "pm_score": 2, "selected": false, "text": "function arrayHas( array, element ) {\n const s = new Set(array);\n return s.has(element)\n}\n" }, { "answer_id": 51040131, "author": "Durgpal Singh", "author_id": 1759015, "author_profile": "https://Stackoverflow.com/users/1759015", "pm_score": 2, "selected": false, "text": " var findValue = _.find(array, function(item) {\n return item.id == obj.id;\n });\n" }, { "answer_id": 52735194, "author": "Shashwat Gupta", "author_id": 7765900, "author_profile": "https://Stackoverflow.com/users/7765900", "pm_score": 1, "selected": false, "text": "let arr = [1, 2, 3, 2, 3, 2, 3, 4];\n\n arr.includes(2) // true\n\n arr.includes(93) // false\n" }, { "answer_id": 53050132, "author": "Nitesh Ranjan", "author_id": 9095122, "author_profile": "https://Stackoverflow.com/users/9095122", "pm_score": 2, "selected": false, "text": "let array = [1, 2, 3, 4, {\"key\": \"value\"}];\n\narray.some((element) => JSON.stringify(element) === JSON.stringify({\"key\": \"value\"})) // true\n\narray.some((element) => JSON.stringify(element) === JSON.stringify({})) // true\n" }, { "answer_id": 53791481, "author": "Sanjay Magar", "author_id": 8376818, "author_profile": "https://Stackoverflow.com/users/8376818", "pm_score": 3, "selected": false, "text": " function countArray(originalArray) {\n \n var compressed = [];\n // make a copy of the input array\n var copyArray = originalArray.slice(0);\n \n // first loop goes over every element\n for (var i = 0; i < originalArray.length; i++) {\n \n var count = 0; \n // loop over every element in the copy and see if it's the same\n for (var w = 0; w < copyArray.length; w++) {\n if (originalArray[i] == copyArray[w]) {\n // increase amount of times duplicate is found\n count++;\n // sets item to undefined\n delete copyArray[w];\n }\n }\n \n if (count > 0) {\n var a = new Object();\n a.value = originalArray[i];\n a.count = count;\n compressed.push(a);\n }\n }\n \n return compressed;\n };\n \n // It should go something like this:\n \n var testArray = new Array(\"dog\", \"dog\", \"cat\", \"buffalo\", \"wolf\", \"cat\", \"tiger\", \"cat\");\n var newArray = countArray(testArray);\n console.log(newArray);" }, { "answer_id": 55559625, "author": "Sumer", "author_id": 6696684, "author_profile": "https://Stackoverflow.com/users/6696684", "pm_score": 3, "selected": false, "text": "let obj = { name: 'Sumer', age: 36 };\nlet arrObj = [obj, { name: 'Kishor', age: 46 }, { name: 'Rupen', age: 26 }];\n\n\nconsole.log(arrObj.indexOf(obj));// 0\nconsole.log(arrObj.indexOf({ name: 'Sumer', age: 36 })); //-1\n\nconsole.log([1, 3, 5, 2].indexOf(2)); //3\n console.log(arrObj.includes(obj)); //true\nconsole.log(arrObj.includes({ name: 'Sumer', age: 36 })); //false\n\nconsole.log([1, 3, 5, 2].includes(2)); //true\n console.log(arrObj.find(e => e.age > 40)); //{ name: 'Kishor', age: 46 }\nconsole.log(arrObj.find(e => e.age > 40)); //{ name: 'Kishor', age: 46 }\n\nconsole.log([1, 3, 5, 2].find(e => e > 2)); //3\n console.log(arrObj.findIndex(e => e.age > 40)); //1\nconsole.log(arrObj.findIndex(e => e.age > 40)); //1\n\nconsole.log([1, 3, 5, 2].findIndex(e => e > 2)); //1\n" }, { "answer_id": 58346110, "author": "Shiva", "author_id": 6404433, "author_profile": "https://Stackoverflow.com/users/6404433", "pm_score": 4, "selected": false, "text": "find() var users = [{id: \"101\", name: \"Choose one...\"},\n{id: \"102\", name: \"shilpa\"},\n{id: \"103\", name: \"anita\"},\n{id: \"104\", name: \"admin\"},\n{id: \"105\", name: \"user\"}];\n let data = users.find(object => object['id'] === '104');\n {id: \"104\", name: \"admin\"}\n let indexToUpdate = users.indexOf(data);\nlet newObject = {id: \"104\", name: \"customer\"};\nusers[indexToUpdate] = newObject;//your new object\nconsole.log(users);\n [{id: \"101\", name: \"Choose one...\"},\n{id: \"102\", name: \"shilpa\"},\n{id: \"103\", name: \"anita\"},\n{id: \"104\", name: \"customer\"},\n{id: \"105\", name: \"user\"}];\n" }, { "answer_id": 59627901, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 5, "selected": false, "text": "JSON Set find includes for indexOf for let log = (name,f) => console.log(`${name}: 3-${f(arr,'s10')} 's7'-${f(arr,'s7')} 6-${f(arr,6)} 's3'-${f(arr,'s3')}`)\n\nlet arr = [1,2,3,4,5,'s6','s7','s8','s9','s10'];\n//arr = new Array(1000000).fill(123); arr[500000]=7;\n\nfunction A(a, val) {\n var i = -1;\n var n = a.length;\n while (i++<n) {\n if (a[i] === val) {\n return true;\n }\n }\n return false;\n}\n\nfunction B(a, val) {\n var i = a.length;\n while (i--) {\n if (a[i] === val) {\n return true;\n }\n }\n return false;\n}\n\nfunction C(a, val) {\n for (var i = 0; i < a.length; i++) {\n if (a[i] === val) return true;\n }\n return false;\n}\n\nfunction D(a,val)\n{\n var len = a.length;\n for(var i = 0 ; i < len;i++)\n {\n if(a[i] === val) return true;\n }\n return false;\n} \n\nfunction E(a, val){ \n var n = a.length-1;\n var t = n/2;\n for (var i = 0; i <= t; i++) {\n if (a[i] === val || a[n-i] === val) return true;\n }\n return false;\n}\n\nfunction F(a,val) {\n return a.includes(val);\n}\n\nfunction G(a,val) {\n return a.indexOf(val)>=0;\n}\n\nfunction H(a,val) {\n return !!~a.indexOf(val);\n}\n\nfunction I(a, val) {\n return a.findIndex(x=> x==val)>=0;\n}\n\nfunction J(a,val) {\n return a.some(x=> x===val);\n}\n\nfunction K(a, val) {\n const s = JSON.stringify(val);\n return a.some(x => JSON.stringify(x) === s);\n}\n\nfunction L(a,val) {\n return !a.every(x=> x!==val);\n}\n\nfunction M(a, val) {\n return !!a.find(x=> x==val);\n}\n\nfunction N(a,val) {\n return a.filter(x=>x===val).length > 0;\n}\n\nfunction O(a, val) {\n return new Set(a).has(val);\n}\n\nlog('A',A);\nlog('B',B);\nlog('C',C);\nlog('D',D);\nlog('E',E);\nlog('F',F);\nlog('G',G);\nlog('H',H);\nlog('I',I);\nlog('J',J);\nlog('K',K);\nlog('L',L);\nlog('M',M);\nlog('N',N);\nlog('O',O); This shippet only presents functions used in performance tests - it not perform tests itself!" }, { "answer_id": 59874619, "author": "Majedur", "author_id": 3915410, "author_profile": "https://Stackoverflow.com/users/3915410", "pm_score": 2, "selected": false, "text": "Object.keys function filterByValue(array, string) {\n return array.filter(o =>\n Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));\n}\n\nconst arrayOfObject = [{\n name: 'Paul',\n country: 'Canada',\n}, {\n name: 'Lea',\n country: 'Italy',\n}, {\n name: 'John',\n country: 'Italy'\n}];\n\nconsole.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]\nconsole.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}] Object.keys(o).some(k => o.country.toLowerCase().includes(string.toLowerCase())));\n" }, { "answer_id": 59920827, "author": "Mamunur Rashid", "author_id": 7940824, "author_profile": "https://Stackoverflow.com/users/7940824", "pm_score": 2, "selected": false, "text": "searchResults: [\n {\n name: 'Hello',\n artist: 'Selana',\n album: 'Riga',\n id: 1,\n },\n {\n name: 'Hello;s',\n artist: 'Selana G',\n album: 'Riga1',\n id: 2,\n },\n {\n name: 'Hello2',\n artist: 'Selana',\n album: 'Riga11',\n id: 3,\n }\n ],\n playlistTracks: [\n {\n name: 'Hello',\n artist: 'Mamunuus',\n album: 'Riga',\n id: 4,\n },\n {\n name: 'Hello;s',\n artist: 'Mamunuus G',\n album: 'Riga1',\n id: 2,\n },\n {\n name: 'Hello2',\n artist: 'Mamunuus New',\n album: 'Riga11',\n id: 3,\n }\n ],\n playlistName: \"New PlayListTrack\",\n };\n }\n\n // Adding an unique track in the playList\n addTrack = track => {\n if(playlistTracks.find(savedTrack => savedTrack.id === track.id)) {\n return;\n }\n playlistTracks.push(track);\n\n this.setState({\n playlistTracks\n })\n };\n" }, { "answer_id": 61404171, "author": "Riwaj Chalise", "author_id": 10003098, "author_profile": "https://Stackoverflow.com/users/10003098", "pm_score": 3, "selected": false, "text": "var fruits = [\"Apple\", \"Banana\", \"Mango\", \"Orange\", \"Papaya\"];\nvar a = \"Mango\";\ncheckArray(a, fruits);\n\n\nfunction checkArray(a, fruits) {\n // Check if a value exists in the fruits array\n if (fruits.indexOf(a) !== -1) {\n return document.write(\"true\");\n } else {\n return document.write(\"false\");\n }\n} var fruits = [\"Apple\", \"Banana\", \"Mango\", \"Orange\", \"Papaya\"];\nalert(fruits.includes(\"Banana\")); // Outputs: true\nalert(fruits.includes(\"Coconut\")); // Outputs: false\nalert(fruits.includes(\"Orange\")); // Outputs: true\nalert(fruits.includes(\"Cherry\")); // Outputs: false" }, { "answer_id": 61984190, "author": "Md. Harun Or Rashid", "author_id": 2179062, "author_profile": "https://Stackoverflow.com/users/2179062", "pm_score": 2, "selected": false, "text": "//plain array\nvar arr = ['a', 'b', 'c'];\nvar check = arr.includes('a');\nconsole.log(check); //returns true\nif (check)\n{\n // value exists in array\n //write some codes\n}\n\n// array with objects\nvar arr = [\n {x:'a', y:'b'},\n {x:'p', y:'q'}\n ];\n\n// if you want to check if x:'p' exists in arr\nvar check = arr.filter(function (elm){\n if (elm.x == 'p')\n {\n return elm; // returns length = 1 (object exists in array)\n }\n});\n\n// or y:'q' exists in arr\nvar check = arr.filter(function (elm){\n if (elm.y == 'q')\n {\n return elm; // returns length = 1 (object exists in array)\n }\n});\n\n// if you want to check, if the entire object {x:'p', y:'q'} exists in arr\nvar check = arr.filter(function (elm){\n if (elm.x == 'p' && elm.y == 'q')\n {\n return elm; // returns length = 1 (object exists in array)\n }\n});\n\n// in all cases\nconsole.log(check.length); // returns 1\n\nif (check.length > 0)\n{\n // returns true\n // object exists in array\n //write some codes\n}\n" }, { "answer_id": 62259894, "author": "da coconut", "author_id": 10105517, "author_profile": "https://Stackoverflow.com/users/10105517", "pm_score": 3, "selected": false, "text": "Array.prototype.includes const fruits = ['coconut', 'banana', 'apple']\n\nconst doesFruitsHaveCoconut = fruits.includes('coconut')// true\n\nconsole.log(doesFruitsHaveCoconut)" }, { "answer_id": 65293687, "author": "MsiLucifer", "author_id": 14013826, "author_profile": "https://Stackoverflow.com/users/14013826", "pm_score": 0, "selected": false, "text": "arrObj.findIndex(obj => obj === comparedValue) !== -1;\n" }, { "answer_id": 68500364, "author": "francis", "author_id": 11209037, "author_profile": "https://Stackoverflow.com/users/11209037", "pm_score": 1, "selected": false, "text": "console.log(new RegExp('26242').test(['23525', '26242', '25272'].join(''))) // true\n" }, { "answer_id": 70389359, "author": "Med Aziz CHETOUI", "author_id": 5253456, "author_profile": "https://Stackoverflow.com/users/5253456", "pm_score": 2, "selected": false, "text": "some() some() const array = [1, 2, 3, 4, 5];\n\n// checks whether an element is even\nconst even = (element) => element % 2 === 0;\n\nconsole.log(array.some(even));\n// expected output: true\n some find() includes()" }, { "answer_id": 70543468, "author": "Ran Turner", "author_id": 7494218, "author_profile": "https://Stackoverflow.com/users/7494218", "pm_score": 4, "selected": false, "text": "includes some find findIndex const array = [1, 2, 3, 4, 5, 6, 7];\n\nconsole.log(array.includes(3));\n//includes() determines whether an array includes a certain value among its entries\n\nconsole.log(array.some(x => x === 3)); \n//some() tests if at least one element in the array passes the test implemented by the provided function\n\nconsole.log(array.find(x => x === 3) ? true : false);\n//find() returns the value of the first element in the provided array that satisfies the provided testing function\n\nconsole.log(array.findIndex(x => x === 3) > -1);\n//findIndex() returns the index of the first element in the array that satisfies the provided testing function, else returning -1." }, { "answer_id": 72283811, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 1, "selected": false, "text": "Set Arrays Sets array.includes set.has set.has array.includes" }, { "answer_id": 73354963, "author": "Tiago Bértolo", "author_id": 1543163, "author_profile": "https://Stackoverflow.com/users/1543163", "pm_score": 0, "selected": false, "text": "function existsInArrayForIgnoreDataType(arr, targetElem) {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] == targetElem) return true\n }\n return false\n }\n" }, { "answer_id": 73824762, "author": "Aurobindo Bhuyan", "author_id": 18467842, "author_profile": "https://Stackoverflow.com/users/18467842", "pm_score": 1, "selected": false, "text": "const arr1 = [1, 2, 3, 4, 5]\nconst result = arr1.find(ele => ele === 4)\nconsole.log(result) //4\n\nconst result2 = arr1.find(ele => ele === 6)\nconsole.log(result2) //undefined\n/* \nIf the element is present inside the array\nthen it will return the first element that\nsatisfies the given condition. Otherwise\nundefined will return.\n*/\n\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
237,106
<p>I have a legacy DLL written in C that contains a function that returns a string, and I need to access this function from Delphi. The only info I have about the DLL is the VB declare for accessing the function:</p> <p>Public Declare Function DecryptStr Lib "strlib" (Str As String) As String </p> <p>I've tried the following without success:</p> <p>Declaration:</p> <pre><code>function DecryptStr(s: PChar): PChar; cdecl; external 'strlib.dll'; </code></pre> <p>Usage:</p> <pre><code>var p1, p2 : pchar; begin GetMem( p1, 255 ); StrPCopy( p2, 'some string to decrypt' ); p1 := DecryptStr( p2 ); end; </code></pre> <p>This consistently crashes the DLL with an Access Violation. I'm at a loss.</p> <p>Any suggestions ?</p>
[ { "answer_id": 237276, "author": "Mohammed Nasman", "author_id": 24462, "author_profile": "https://Stackoverflow.com/users/24462", "pm_score": 0, "selected": false, "text": "function DecryptStr(s: PChar): PChar; stdcall; external 'strlib.dll';\n" }, { "answer_id": 237690, "author": "andrius", "author_id": 19865, "author_profile": "https://Stackoverflow.com/users/19865", "pm_score": 3, "selected": false, "text": "var\n p1, p2 : pchar;\nbegin\n GetMem( p1, 255 ); // initialize\n GetMem( p2, 255 );\n StrPLCopy( p2, 'some string to decrypt', 255 ); // prevent buffer overrun\n StrPLCopy( p1, DecryptStr( p2 ), 255); // make a copy since dll will free its internal buffer\nend;\n" }, { "answer_id": 239506, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 1, "selected": false, "text": "var\n p1, p2 : pchar;\nbegin\n GetMem( p2, 255 ); // allocate memory for 'some string...'\n StrPCopy( p2, 'some string to decrypt' );\n p1 := DecryptStr( p2 );\nend;\n" }, { "answer_id": 239550, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 0, "selected": false, "text": "var\n p1, p2 : pchar;\nbegin\n GetMem( p1, 255 );\n StrPCopy( p1, 'some string to decrypt' );\n p2 := DecryptStr( p1 );\nend;\n" }, { "answer_id": 15477354, "author": "Radu", "author_id": 1658112, "author_profile": "https://Stackoverflow.com/users/1658112", "pm_score": 0, "selected": false, "text": "int __stdcall DoSomething(char * _name);\n function DoSomething(name: PAnsiChar): integer; stdcall; external 'somedll.dll';\n var s: PAnsiChar;\nbegin\n GetMem(s, 255);\n DoSomething(s);\n // s now contains the value returned from the C DLL\nend;\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31510/" ]
237,107
<p>What is the simplest way to send mail using Ruby on Rails? Is there a way to send mail directly via ruby and skip all the rails models and complexity, just like php's mail() function?</p> <p>Thanks for your help.</p>
[ { "answer_id": 774314, "author": "Joe W.", "author_id": 3459, "author_profile": "https://Stackoverflow.com/users/3459", "pm_score": 4, "selected": false, "text": "require 'net/smtp'\nNet::SMTP.start('smtp.example.com', 25) do |smtp|\n smtp.send_message \"Subject: testing from ruby\", 'from-address@example.com', ['to-address1@example.com', 'to-address2@example.com']\nend\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9776/" ]
237,112
<p>Working on a project where a sequential set of methods must be run every <code>x</code> seconds. Right now I have the methods contained within another "parent method", and just sequentially call them right after another.</p> <pre><code>class DoTheseThings() { DoThis(); NowDoThat(); NowDoThis(); MoreWork(); AndImSpent(); } </code></pre> <p>Each method must run successfully without throwing an exception before the next step can be done. So now I wrapped each of those methods with a <code>while</code> and <code>try..catch</code>, then in the <code>catch</code> execute that method again.</p> <pre><code>while( !hadError ) { try { DoThis(); } catch(Exception doThisException ) { hadError = true; } } </code></pre> <p>This seems smelly and not very dry. Is there a better way to do this so I'm not wrapping any new functionality in the same methods. Isn't some kind of Delegate collection the proper way to implement this? </p> <p>Is there a more "proper" solution?</p>
[ { "answer_id": 237122, "author": "nyxtom", "author_id": 19753, "author_profile": "https://Stackoverflow.com/users/19753", "pm_score": 0, "selected": false, "text": "lock (resource) \n{\n Dosomething(resource);\n}\n" }, { "answer_id": 237130, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 4, "selected": true, "text": "Action[] work=new Action[]{new Action(DoThis), new Action(NowDoThat), \n new Action(NowDoThis), new Action(MoreWork), new Action(AndImSpent)};\nint current =0;\nwhile(current!=work.Length)\n{\n try\n {\n work[current]();\n current++;\n }\n catch(Exception ex)\n {\n // log the error or whatever\n // maybe sleep a while to not kill the processors if a successful execution depends on time elapsed \n }\n}\n" }, { "answer_id": 237141, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 0, "selected": false, "text": "foreach" }, { "answer_id": 237238, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "Action<Action> tryForever = (action) => { \n bool success;\n do {\n try {\n action();\n success = true;\n } catch (Exception) {\n // should probably log or something here...\n }\n } while (!success);\n};\n\nvoid DoEverything() {\n tryForever(DoThis);\n tryForever(NowDoThat);\n tryForever(NowDoThis);\n tryForever(MoreWork);\n tryForever(AndImSpent);\n}\n void DoEverything() {\n Stack<Action> thingsToDo = new Stack<Action>(\n new Action[] { \n DoThis, NowDoThat, NowDoThis, MoreWork, AndImSpent \n }\n );\n\n Action action;\n while ((action = thingsToDo.Pop()) != null) {\n bool success;\n do {\n try {\n action();\n success = true;\n } catch (Exception) {\n }\n } while (!success);\n }\n" }, { "answer_id": 237245, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "public void DoTheseThings()\n{\n SafelyDoEach( new Action[]{\n DoThis,\n NowDoThat,\n NowDoThis,\n MoreWork,\n AndImSpent\n })\n}\n\npublic void SafelyDoEach( params Action[] actions )\n{\n try\n {\n foreach( var a in actions )\n a();\n }\n catch( Exception doThisException )\n {\n // blindly swallowing every exception like this is a terrible idea\n // you should really only be swallowing a specific MyAbortedException type\n return;\n }\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25300/" ]
237,124
<p>I'm doing some research work into content aggregators, and I'm curious how some of the current craigslist aggregators get data into their mashups.</p> <p>For example, www.housingmaps.com and the now closed www.chicagocrime.org</p> <p>If there is a URL that can be used for reference, that would be perfect!</p>
[ { "answer_id": 245284, "author": "cfay", "author_id": 20440, "author_profile": "https://Stackoverflow.com/users/20440", "pm_score": 4, "selected": false, "text": "//scrape category data\n$h = new http();\n$h->dir = \"../cache/\"; \n$url = \"http://craigslist.org/\";\n\nif (!$h->fetch($url, 300)) {\n echo \"<h2>There is a problem with the http request!</h2>\"; \n exit();\n}\n\n//we need to get all category abbreviations (data looks like: <option value=\"ccc\">community)\npreg_match_all (\"/<option value=\\\"(.*)\\\">([^`]*?)\\n/\", $h->body, $categoryTemp);\n\n$catNames = $categoryTemp['2']; \n\n//return the array of abreviations\nif(sizeof($catNames) > 0) \n return $catNames; \nelse\n return $emptyArray = array();\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24126/" ]
237,128
<p>I know that python has a <code>len()</code> function that is used to determine the size of a string, but I was wondering why it's not a method of the string object?</p>
[ { "answer_id": 237133, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 4, "selected": false, "text": "met% python -c 'import this' | grep 'only one'\nThere should be one-- and preferably only one --obvious way to do it.\n" }, { "answer_id": 237149, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 5, "selected": false, "text": "len >>> a = 'a string of some length'\n>>> a.__len__()\n23\n>>> a.__len__\n<method-wrapper '__len__' of str object at 0x02005650>\n" }, { "answer_id": 237150, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 9, "selected": true, "text": "__len__() len() __iter__() iter()" }, { "answer_id": 237362, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": -1, "selected": false, "text": ">>> \"abc\".__len__()\n3\n" }, { "answer_id": 14166860, "author": "SpanosAngelos", "author_id": 1944412, "author_profile": "https://Stackoverflow.com/users/1944412", "pm_score": -1, "selected": false, "text": ">> x = 'test'\n>> len(x)\n4\n" }, { "answer_id": 23192800, "author": "Luciano Ramalho", "author_id": 299724, "author_profile": "https://Stackoverflow.com/users/299724", "pm_score": 5, "selected": false, "text": "len() str list dict len() len() ob_size PyVarObject str list array.array len(o) o.__len__() __len__ __abs__ with len(s) s.len() len(s) abs(n) len() abs() #s len(s)" }, { "answer_id": 42499450, "author": "Charles D Pantoga", "author_id": 1821750, "author_profile": "https://Stackoverflow.com/users/1821750", "pm_score": 2, "selected": false, "text": "len len dir(len) >>> class List(list):\n... def len(self):\n... return len(self)\n...\n>>> class Dict(dict):\n... def len(self):\n... return len(self)\n...\n>>> class Tuple(tuple):\n... def len(self):\n... return len(self)\n...\n>>> class Set(set):\n... def len(self):\n... return len(self)\n...\n>>> my_list = List([1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'])\n>>> my_dict = Dict({'key': 'value', 'site': 'stackoverflow'})\n>>> my_set = Set({1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'})\n>>> my_tuple = Tuple((1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'))\n>>> my_containers = Tuple((my_list, my_dict, my_set, my_tuple))\n>>>\n>>> for container in my_containers:\n... print container.len()\n...\n15\n2\n15\n15\n" }, { "answer_id": 59145625, "author": "kaya3", "author_id": 12299000, "author_profile": "https://Stackoverflow.com/users/12299000", "pm_score": 2, "selected": false, "text": "len __len__ int len len(obj) obj.len() >>> class A:\n... def __len__(self):\n... return 'foo'\n...\n>>> len(A())\nTraceback (most recent call last):\n File \"<pyshell#8>\", line 1, in <module>\n len(A())\nTypeError: 'str' object cannot be interpreted as an integer\n>>> class B:\n... def __len__(self):\n... return -1\n... \n>>> len(B())\nTraceback (most recent call last):\n File \"<pyshell#13>\", line 1, in <module>\n len(B())\nValueError: __len__() should return >= 0\n len" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
237,131
<p>I have a <code>JPanel</code> extension that I've written and would like to be able to use it in the NetBeans designer. The component is simply adds some custom painting and continues to function as a container to be customised on each use. </p> <p>I have properties to expose in addition to the standard <code>JPanel</code> ones and have a custom <code>paintComponent()</code> method that I'd like to be able to see in use when building up GUIs. Ideally I'd like to associate an icon with the component as well so that its easily recognisable for my colleagues to work with.</p> <p>What's the best way of achieving this?</p>
[ { "answer_id": 242551, "author": "Chobicus", "author_id": 1514822, "author_profile": "https://Stackoverflow.com/users/1514822", "pm_score": 3, "selected": true, "text": "@Override\npublic void paint(Graphics g) {\n super.paint(g);\n Graphics2D g2 = (Graphics2D) g;\n ...\n //draw elements \n ...\n}\n public int getResolutionX() {\n return resolutionX;\n}\n\npublic void setResolutionX(int resolutionX) {\n this.resolutionX = resolutionX;\n}\n\npublic int getResolutionY() {\n return resolutionY;\n}\n\npublic void setResolutionY(int resolutionY) {\n this.resolutionY = resolutionY;\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1867/" ]
237,140
<p>I was re-reading Effective Java (2nd edition) item 18, <a href="http://my.safaribooksonline.com/9780137150021/ch04lev1sec6" rel="nofollow noreferrer">prefer interfaces to abstract classes</a>. In that item Josh Bloch provides an example of a skeletal implementation of the <code>Map.Entry&lt;K,V&gt;</code> interface:</p> <pre><code>// Skeletal Implementation public abstract class AbstractMapEntry&lt;K,V&gt; implements Map.Entry&lt;K,V&gt; { // Primitive operations public abstract K getKey(); public abstract V getValue(); // ... remainder omitted } </code></pre> <p>Two questions stem from this example:</p> <ol> <li>Why are getKey and getValue explicitly declared here as abstract methods? They are part of the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.Entry.html" rel="nofollow noreferrer">Map.Entry</a> interface, so I don't see a reason for the redundant declaration in the abstract class.</li> <li><p>Why use the idiom of leaving these primitives methods, as Mr. Bloch refers to them, as abstract? Why not just do this:</p> <p>// Skeletal Implementation public abstract class AbstractMapEntry implements Map.Entry { private K key; private V value;</p> <pre><code> // Primitive operations public K getKey() {return key;} public V getValue() {return value;} // ... remainder omitted </code></pre> <p>}</p></li> </ol> <p>The benefits of this are that each subclass doesn't have to define its own set of fields, and can still access the key and value by their accessors. If a subclass truly needs to define its own behavior for the accessors, it can implement the Map.Entry interface directly. The other downside is that in the equals method provided by the skeletal implementation, the abstract accessors are called:</p> <pre><code>// Implements the general contract of Map.Entry.equals @Override public boolean equals(Object o) { if (o == this) return true; if (! (o instanceof Map.Entry)) return false; Map.Entry&lt;?,?&gt; arg = (Map.Entry) o; return equals(getKey(), arg.getKey()) &amp;&amp; equals(getValue(), arg.getValue()); } </code></pre> <p>Bloch warns against calling overridable methods (item 17) from classes designed for inheritance as it leaves the superclass vulnerable to changes made by subclasses. Maybe this is a matter of opinion, but I was hoping to determine whether there's more to the story, as Bloch doesn't really elaborate on this in the book.</p>
[ { "answer_id": 237194, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 0, "selected": false, "text": "AbstractMapEntry#getKey getValue Map.Entry Map Map.Entry Map Map Map.Entry AbstractMapEntry#getKey getValue Map HashMap ConcurrentHashMap ConcurrentHashMap getKey getValue getKey getValue Map Properties Map Provider TabularDataSupport AbstractMapEntry#getKey getValue" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8217/" ]
237,145
<p>I have a radio button on my Windows Form. How can I determine if the CheckChanged event occurred due to a user clicking or selecting the radio button vs programatically setting the event with </p> <pre><code>this.radioButtonAdd.Checked = true; </code></pre> <p>I would like some code to take a different action depending on if the user clicked the button or I raised the event myself.</p> <p>Or maybe the better question is how do I handle the event when a user clicks vs when the state is changed in my code.</p>
[ { "answer_id": 237153, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "savedFlag = modifyingProgrammatically;\nmodifyingProgrammatically = true;\nthis.radioButtonAdd.Checked = true;\nmodifingProgrammatically = savedFlag;\n if(modifyingProgramatically) {\n // The event was raised by an assignment within the code.\n} else {\n // The event was raised by a user action.\n}\n" }, { "answer_id": 237188, "author": "Omar Shahine", "author_id": 1496, "author_profile": "https://Stackoverflow.com/users/1496", "pm_score": 3, "selected": true, "text": "radioButton.Tag = \"ignore\"\nradioButton.Checked = true\n private void radioButton_CheckedChanged(object sender, EventArgs e)\n{\n if (radioButton.Checked)\n {\n // Tag will be null in cases where the user clicks\n if (this.radioButtonAdd.Tag == null)\n {\n // do something\n }\n else\n { \n // swallow action\n // reset Tag\n this.radioButtonAdd.Tag = null;\n }\n }\n}\n" }, { "answer_id": 237541, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 1, "selected": false, "text": " private bool _mouseEvent;\n private void radioButton1_CheckedChanged(object sender, EventArgs e)\n {\n if (_mouseEvent)\n MessageBox.Show(\"Changed by mouse click.\");\n else\n MessageBox.Show(\"Changed from code.\");\n }\n\n private void radioButton1_MouseClick(object sender, MouseEventArgs e)\n {\n _mouseEvent = false;\n }\n\n private void radioButton1_MouseDown(object sender, MouseEventArgs e)\n {\n _mouseEvent = true;\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n // This simulates a change from code vs. a change from\n // a mouse click.\n if (radioButton1.Checked)\n radioButton2.Checked = true;\n else\n radioButton1.Checked = true;\n }\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1496/" ]
237,155
<p>Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow.</p> <p>Is this something I should try to farm out to some other application/driver/os_magic? or is there a library I can use to accomplish this? Language isn't a <em>HUGE</em> deal, but C, C++, and Python are preferrable.</p> <p>Thanks :)</p> <p>edit:</p> <p>Found this multi-pointer toolkit for linux (it's actually a multi-pointer x server): <a href="http://wearables.unisa.edu.au/mpx/" rel="noreferrer">http://wearables.unisa.edu.au/mpx/</a></p>
[ { "answer_id": 237190, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "IDirectInput8::EnumDevices() IDirectInputDevice8::Poll()" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
237,159
<p>I normally use the following idiom to check if a String can be converted to an integer.</p> <pre><code>public boolean isInteger( String input ) { try { Integer.parseInt( input ); return true; } catch( Exception e ) { return false; } } </code></pre> <p>Is it just me, or does this seem a bit hackish? What's a better way?</p> <hr> <p>See my answer (with benchmarks, based on the <a href="https://stackoverflow.com/a/237321/1288">earlier answer</a> by <a href="https://stackoverflow.com/users/28278/codingwithspike">CodingWithSpike</a>) to see why I've reversed my position and accepted <a href="https://stackoverflow.com/a/237204/1288">Jonas Klemming's answer</a> to this problem. I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.</p>
[ { "answer_id": 237161, "author": "Kristian", "author_id": 11429, "author_profile": "https://Stackoverflow.com/users/11429", "pm_score": 2, "selected": false, "text": "return Pattern.matches(\"-?\\\\d+\", input);\n" }, { "answer_id": 237163, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 6, "selected": false, "text": "NumberFormatException" }, { "answer_id": 237166, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": false, "text": "input.matches(\"^-?\\\\d+$\");\n Exception NumberFormatException" }, { "answer_id": 237204, "author": "Jonas K", "author_id": 26609, "author_profile": "https://Stackoverflow.com/users/26609", "pm_score": 9, "selected": true, "text": "Integer.parseInt() public static boolean isInteger(String str) {\n if (str == null) {\n return false;\n }\n int length = str.length();\n if (length == 0) {\n return false;\n }\n int i = 0;\n if (str.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i = 1;\n }\n for (; i < length; i++) {\n char c = str.charAt(i);\n if (c < '0' || c > '9') {\n return false;\n }\n }\n return true;\n}\n" }, { "answer_id": 237240, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": -1, "selected": false, "text": "Integer.valueOf(string); \n" }, { "answer_id": 237321, "author": "CodingWithSpike", "author_id": 28278, "author_profile": "https://Stackoverflow.com/users/28278", "pm_score": 5, "selected": false, "text": " public void RunTests()\n {\n String str = \"1234567890\";\n\n long startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByException(str);\n long endTime = System.currentTimeMillis();\n System.out.print(\"ByException: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByRegex(str);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByRegex: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByJonas(str);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByJonas: \");\n System.out.println(endTime - startTime);\n }\n\n private boolean IsInt_ByException(String str)\n {\n try\n {\n Integer.parseInt(str);\n return true;\n }\n catch(NumberFormatException nfe)\n {\n return false;\n }\n }\n\n private boolean IsInt_ByRegex(String str)\n {\n return str.matches(\"^-?\\\\d+$\");\n }\n\n public boolean IsInt_ByJonas(String str)\n {\n if (str == null) {\n return false;\n }\n int length = str.length();\n if (length == 0) {\n return false;\n }\n int i = 0;\n if (str.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i = 1;\n }\n for (; i < length; i++) {\n char c = str.charAt(i);\n if (c <= '/' || c >= ':') {\n return false;\n }\n }\n return true;\n }\n" }, { "answer_id": 237714, "author": "Ran Biron", "author_id": 931, "author_profile": "https://Stackoverflow.com/users/931", "pm_score": -1, "selected": false, "text": "Number number;\ntry {\n number = NumberFormat.getInstance().parse(\"123\");\n} catch (ParseException e) {\n //not a number - do recovery.\n e.printStackTrace();\n}\n//use number\n" }, { "answer_id": 237895, "author": "Rastislav Komara", "author_id": 22068, "author_profile": "https://Stackoverflow.com/users/22068", "pm_score": 4, "selected": false, "text": "str.matches(\"^-?\\\\d+$\")\n Pattern.matches(\"-?\\\\d+\", input);\n import java.util.regex.Pattern;\n\n/**\n * @author Rastislav Komara\n */\npublic class NaturalNumberChecker {\n public static final Pattern PATTERN = Pattern.compile(\"^\\\\d+$\");\n\n boolean isNaturalNumber(CharSequence input) {\n return input != null && PATTERN.matcher(input).matches();\n }\n}\n" }, { "answer_id": 237994, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": false, "text": "public void runTests()\n{\n String big_int = \"1234567890\";\n String non_int = \"1234XY7890\";\n\n long startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByException(big_int);\n long endTime = System.currentTimeMillis();\n System.out.print(\"ByException - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByException(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByException - non-integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByRegex(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByRegex - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByRegex(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByRegex - non-integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByJonas(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByJonas - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByJonas(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByJonas - non-integer data: \");\n System.out.println(endTime - startTime);\n}\n\nprivate boolean IsInt_ByException(String str)\n{\n try\n {\n Integer.parseInt(str);\n return true;\n }\n catch(NumberFormatException nfe)\n {\n return false;\n }\n}\n\nprivate boolean IsInt_ByRegex(String str)\n{\n return str.matches(\"^-?\\\\d+$\");\n}\n\npublic boolean IsInt_ByJonas(String str)\n{\n if (str == null) {\n return false;\n }\n int length = str.length();\n if (length == 0) {\n return false;\n }\n int i = 0;\n if (str.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i = 1;\n }\n for (; i < length; i++) {\n char c = str.charAt(i);\n if (c <= '/' || c >= ':') {\n return false;\n }\n }\n return true;\n}\n ByException - integer data: 47\nByException - non-integer data: 547\n\nByRegex - integer data: 390\nByRegex - non-integer data: 313\n\nByJonas - integer data: 0\nByJonas - non-integer data: 16\n" }, { "answer_id": 239470, "author": "Łukasz Bownik", "author_id": 24028, "author_profile": "https://Stackoverflow.com/users/24028", "pm_score": 5, "selected": false, "text": "org.apache.commons.lang.StringUtils.isNumeric \n" }, { "answer_id": 7324087, "author": "Felipe", "author_id": 484601, "author_profile": "https://Stackoverflow.com/users/484601", "pm_score": 5, "selected": false, "text": "private final Pattern pattern = Pattern.compile(\"^-?\\\\d+$\");\n\npublic void runTests() {\n String big_int = \"1234567890\";\n String non_int = \"1234XY7890\";\n\n long startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByException(big_int);\n long endTime = System.currentTimeMillis();\n System.out.print(\"ByException - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByException(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByException - non-integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByRegex(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByRegex - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByRegex(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByRegex - non-integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for (int i = 0; i < 100000; i++)\n IsInt_ByCompiledRegex(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByCompiledRegex - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for (int i = 0; i < 100000; i++)\n IsInt_ByCompiledRegex(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByCompiledRegex - non-integer data: \");\n System.out.println(endTime - startTime);\n\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByJonas(big_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"\\nByJonas - integer data: \");\n System.out.println(endTime - startTime);\n\n startTime = System.currentTimeMillis();\n for(int i = 0; i < 100000; i++)\n IsInt_ByJonas(non_int);\n endTime = System.currentTimeMillis();\n System.out.print(\"ByJonas - non-integer data: \");\n System.out.println(endTime - startTime);\n}\n\nprivate boolean IsInt_ByException(String str)\n{\n try\n {\n Integer.parseInt(str);\n return true;\n }\n catch(NumberFormatException nfe)\n {\n return false;\n }\n}\n\nprivate boolean IsInt_ByRegex(String str)\n{\n return str.matches(\"^-?\\\\d+$\");\n}\n\nprivate boolean IsInt_ByCompiledRegex(String str) {\n return pattern.matcher(str).find();\n}\n\npublic boolean IsInt_ByJonas(String str)\n{\n if (str == null) {\n return false;\n }\n int length = str.length();\n if (length == 0) {\n return false;\n }\n int i = 0;\n if (str.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i = 1;\n }\n for (; i < length; i++) {\n char c = str.charAt(i);\n if (c <= '/' || c >= ':') {\n return false;\n }\n }\n return true;\n}\n ByException - integer data: 45\nByException - non-integer data: 465\n\nByRegex - integer data: 272\nByRegex - non-integer data: 131\n\nByCompiledRegex - integer data: 45\nByCompiledRegex - non-integer data: 26\n\nByJonas - integer data: 8\nByJonas - non-integer data: 2\n" }, { "answer_id": 9936636, "author": "callejero", "author_id": 1302331, "author_profile": "https://Stackoverflow.com/users/1302331", "pm_score": 0, "selected": false, "text": "public static boolean isInt(String str) {\n if (str != null && str.length() != 0) {\n for (int i = 0; i < str.length(); i++) {\n if (!Character.isDigit(str.charAt(i))) return false;\n }\n }\n return true; \n}\n" }, { "answer_id": 10410242, "author": "mobra66", "author_id": 1369503, "author_profile": "https://Stackoverflow.com/users/1369503", "pm_score": 1, "selected": false, "text": "isInteger() Integer.parseInt()" }, { "answer_id": 13868966, "author": "Kaitie", "author_id": 1902372, "author_profile": "https://Stackoverflow.com/users/1902372", "pm_score": 3, "selected": false, "text": "boolean isNumeric = yourString.matches(\"[0-9]+\"); // 1 or more characters long, numbers only\nboolean isNumeric = yourString.matches(\"[0-9]*\"); // 0 or more characters long, numbers only\n" }, { "answer_id": 17874157, "author": "duggu", "author_id": 1722818, "author_profile": "https://Stackoverflow.com/users/1722818", "pm_score": 2, "selected": false, "text": " String value=\"123\";\n try \n { \n int s=Integer.parseInt(any_int_val);\n // do something when integer values comes \n } \n catch(NumberFormatException nfe) \n { \n // do something when string values comes \n } \n" }, { "answer_id": 22012491, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 2, "selected": false, "text": "NumberUtils.isCreatable(myText)\n" }, { "answer_id": 22469209, "author": "realPK", "author_id": 853001, "author_profile": "https://Stackoverflow.com/users/853001", "pm_score": 2, "selected": false, "text": "if (Character.isDigit(string.charAt(0))) {\n //Do something with int\n}\n" }, { "answer_id": 23630046, "author": "Sae1962", "author_id": 265140, "author_profile": "https://Stackoverflow.com/users/265140", "pm_score": -1, "selected": false, "text": "/**\n * Checks, if the string represents a number.\n *\n * @param string the string\n * @return true, if the string is a number\n */\npublic static boolean isANumber(final String string) {\n if (string != null) {\n final int length = string.length();\n if (length != 0) {\n int i = 0;\n if (string.charAt(0) == '-') {\n if (length == 1) {\n return false;\n }\n i++;\n }\n for (; i < length; i++) {\n final char c = string.charAt(i);\n if ((c <= PERIOD) || ((c >= COLON))) {\n final String strC = Character.toString(c).toUpperCase();\n final boolean isExponent = strC.equals(\"E\");\n final boolean isPeriod = (c == PERIOD);\n final boolean isPlus = (c == PLUS);\n\n if (!isExponent && !isPeriod && !isPlus) {\n return false;\n }\n }\n }\n return true;\n }\n }\n return false;\n}\n" }, { "answer_id": 25069800, "author": "Wayne", "author_id": 3109012, "author_profile": "https://Stackoverflow.com/users/3109012", "pm_score": 1, "selected": false, "text": "public static boolean isInteger(String str) {\n if (str == null) {\n return false;\n }\n int length = str.length();\n int i = 0;\n\n // set the length and value for highest positive int or lowest negative int\n int maxlength = 10;\n String maxnum = String.valueOf(Integer.MAX_VALUE);\n if (str.charAt(0) == '-') { \n maxlength = 11;\n i = 1;\n maxnum = String.valueOf(Integer.MIN_VALUE);\n } \n\n // verify digit length does not exceed int range\n if (length > maxlength) { \n return false; \n }\n\n // verify that all characters are numbers\n if (maxlength == 11 && length == 1) {\n return false;\n }\n for (int num = i; num < length; num++) {\n char c = str.charAt(num);\n if (c < '0' || c > '9') {\n return false;\n }\n }\n\n // verify that number value is within int range\n if (length == maxlength) {\n for (; i < length; i++) {\n if (str.charAt(i) < maxnum.charAt(i)) {\n return true;\n }\n else if (str.charAt(i) > maxnum.charAt(i)) {\n return false;\n }\n }\n }\n return true;\n}\n" }, { "answer_id": 27562595, "author": "Niroshan Abeywickrama", "author_id": 4377200, "author_profile": "https://Stackoverflow.com/users/4377200", "pm_score": 0, "selected": false, "text": "private boolean isPrimitive(String value){\n boolean status=true;\n if(value.length()<1)\n return false;\n for(int i = 0;i<value.length();i++){\n char c=value.charAt(i);\n if(Character.isDigit(c) || c=='.'){\n\n }else{\n status=false;\n break;\n }\n }\n return status;\n }\n" }, { "answer_id": 29810655, "author": "mark_infinite", "author_id": 4794229, "author_profile": "https://Stackoverflow.com/users/4794229", "pm_score": 1, "selected": false, "text": "int String if(aString.substring(j, j+1).equals(String.valueOf(i)))\n digits++;\n if(digits == aString.length())\n String aString = \"1234224245\";\n int digits = 0;//count how many digits you encountered\n for(int j=0;j<aString.length();j++){\n for(int i=0;i<=9;i++){\n if(aString.substring(j, j+1).equals(String.valueOf(i)))\n digits++;\n }\n }\n if(digits == aString.length()){\n System.out.println(\"It's an integer!!\");\n }\n else{\n System.out.println(\"It's not an integer!!\");\n }\n \n String anotherString = \"1234f22a4245\";\n int anotherDigits = 0;//count how many digits you encountered\n for(int j=0;j<anotherString.length();j++){\n for(int i=0;i<=9;i++){\n if(anotherString.substring(j, j+1).equals(String.valueOf(i)))\n anotherDigits++;\n }\n }\n if(anotherDigits == anotherString.length()){\n System.out.println(\"It's an integer!!\");\n }\n else{\n System.out.println(\"It's not an integer!!\");\n }\n String float double digits == (aString.length()-1)" }, { "answer_id": 31218166, "author": "shellbye", "author_id": 1398065, "author_profile": "https://Stackoverflow.com/users/1398065", "pm_score": -1, "selected": false, "text": "public static boolean isInteger(String self) {\n try {\n Integer.valueOf(self.trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n}\n" }, { "answer_id": 31292785, "author": "timxyz", "author_id": 359627, "author_profile": "https://Stackoverflow.com/users/359627", "pm_score": 1, "selected": false, "text": "TextUtils.isDigitsOnly(str);\n" }, { "answer_id": 34651222, "author": "abalcerek", "author_id": 3187921, "author_profile": "https://Stackoverflow.com/users/3187921", "pm_score": 4, "selected": false, "text": "import com.google.common.primitives.Ints;\n\nInteger intValue = Ints.tryParse(stringValue);\n" }, { "answer_id": 36540208, "author": "salaheddine", "author_id": 3357630, "author_profile": "https://Stackoverflow.com/users/3357630", "pm_score": -1, "selected": false, "text": "public class HelloWorld{\n\n static boolean validateIP(String s){\n String[] value = s.split(\"\\\\.\");\n if(value.length!=4) return false;\n int[] v = new int[4];\n for(int i=0;i<4;i++){\n for(int j=0;j<value[i].length();j++){\n if(!Character.isDigit(value[i].charAt(j))) \n return false;\n }\n v[i]=Integer.parseInt(value[i]);\n if(!(v[i]>=0 && v[i]<=255)) return false;\n }\n return true;\n }\n\n public static void main(String[] argv){\n String test = \"12.23.8.9j\";\n if(validateIP(test)){\n System.out.println(\"\"+test);\n }\n }\n}\n" }, { "answer_id": 36782502, "author": "Gabriel Kaffka", "author_id": 2297767, "author_profile": "https://Stackoverflow.com/users/2297767", "pm_score": 2, "selected": false, "text": "private boolean isNumber(String s) {\n boolean isNumber = true;\n for (char c : s.toCharArray()) {\n isNumber = isNumber && Character.isDigit(c);\n }\n return isNumber;\n}\n" }, { "answer_id": 40358657, "author": "Ellrohir", "author_id": 3204544, "author_profile": "https://Stackoverflow.com/users/3204544", "pm_score": 0, "selected": false, "text": "public static boolean isInteger(String str) {\n if (str == null || str.isEmpty()) {\n return false;\n }\n try {\n long value = Long.valueOf(str);\n return value >= -2147483648 && value <= 2147483647;\n } catch (Exception ex) {\n return false;\n }\n}\n" }, { "answer_id": 42985788, "author": "gil.fernandes", "author_id": 2735286, "author_profile": "https://Stackoverflow.com/users/2735286", "pm_score": 2, "selected": false, "text": "public static boolean isInteger(String str) {\n return str != null && str.length() > 0 &&\n IntStream.range(0, str.length()).allMatch(i -> i == 0 && (str.charAt(i) == '-' || str.charAt(i) == '+')\n || Character.isDigit(str.charAt(i)));\n}\n public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n Arrays.asList(\"1231231\", \"-1232312312\", \"+12313123131\", \"qwqe123123211\", \"2\", \"0000000001111\", \"\", \"123-\", \"++123\",\n \"123-23\", null, \"+-123\").forEach(s -> {\n System.out.printf(\"%15s %s%n\", s, isInteger(s));\n });\n}\n 1231231 true\n -1232312312 true\n +12313123131 true\n qwqe123123211 false\n 2 true\n 0000000001111 true\n false\n 123- false\n ++123 false\n 123-23 false\n null false\n +-123 false\n" }, { "answer_id": 45873328, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public static boolean isInt(String s) {\n if(s == null) {\n return false;\n }\n s = s.trim(); //Don't get tricked by whitespaces.\n int len = s.length();\n if(len == 0) {\n return false;\n }\n //The bottom limit of an int is -2147483648 which is 11 chars long.\n //[note that the upper limit (2147483647) is only 10 chars long]\n //Thus any string with more than 11 chars, even if represents a valid integer, \n //it won't fit in an int.\n if(len > 11) {\n return false;\n }\n char c = s.charAt(0);\n int i = 0;\n //I don't mind the plus sign, so \"+13\" will return true.\n if(c == '-' || c == '+') {\n //A single \"+\" or \"-\" is not a valid integer.\n if(len == 1) {\n return false;\n }\n i = 1;\n }\n //Check if all chars are digits\n for(; i < len; i++) {\n c = s.charAt(i);\n if(c < '0' || c > '9') {\n return false;\n }\n }\n //If we reached this point then we know for sure that the string has at\n //most 11 chars and that they're all digits (the first one might be a '+'\n // or '-' thought).\n //Now we just need to check, for 10 and 11 chars long strings, if the numbers\n //represented by the them don't surpass the limits.\n c = s.charAt(0);\n char l;\n String limit;\n if(len == 10 && c != '-' && c != '+') {\n limit = \"2147483647\";\n //Now we are going to compare each char of the string with the char in\n //the limit string that has the same index, so if the string is \"ABC\" and\n //the limit string is \"DEF\" then we are gonna compare A to D, B to E and so on.\n //c is the current string's char and l is the corresponding limit's char\n //Note that the loop only continues if c == l. Now imagine that our string\n //is \"2150000000\", 2 == 2 (next), 1 == 1 (next), 5 > 4 as you can see,\n //because 5 > 4 we can guarantee that the string will represent a bigger integer.\n //Similarly, if our string was \"2139999999\", when we find out that 3 < 4,\n //we can also guarantee that the integer represented will fit in an int.\n for(i = 0; i < len; i++) {\n c = s.charAt(i);\n l = limit.charAt(i);\n if(c > l) {\n return false;\n }\n if(c < l) {\n return true;\n }\n }\n }\n c = s.charAt(0);\n if(len == 11) {\n //If the first char is neither '+' nor '-' then 11 digits represent a \n //bigger integer than 2147483647 (10 digits).\n if(c != '+' && c != '-') {\n return false;\n }\n limit = (c == '-') ? \"-2147483648\" : \"+2147483647\";\n //Here we're applying the same logic that we applied in the previous case\n //ignoring the first char.\n for(i = 1; i < len; i++) {\n c = s.charAt(i);\n l = limit.charAt(i);\n if(c > l) {\n return false;\n }\n if(c < l) {\n return true;\n }\n }\n }\n //The string passed all tests, so it must represent a number that fits\n //in an int...\n return true;\n}\n" }, { "answer_id": 51116899, "author": "Tihamer", "author_id": 2882939, "author_profile": "https://Stackoverflow.com/users/2882939", "pm_score": 0, "selected": false, "text": "public static boolean isIntegerFromDecimalString(String possibleInteger) {\npossibleInteger = possibleInteger.trim();\ntry {\n // Integer parsing works great for \"regular\" integers like 42 or 13.\n int num = Integer.parseInt(possibleInteger);\n System.out.println(\"The possibleInteger=\"+possibleInteger+\" is a pure integer.\");\n return true;\n} catch (NumberFormatException e) {\n if (possibleInteger.equals(\".\")) {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it is only a decimal point.\");\n return false;\n } else if (possibleInteger.startsWith(\".\") && possibleInteger.matches(\"\\\\.[0-9]*\")) {\n if (possibleInteger.matches(\"\\\\.[0]*\")) {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is an integer because it starts with a decimal point and afterwards is all zeros.\");\n return true;\n } else {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it starts with a decimal point and afterwards is not all zeros.\");\n return false;\n }\n } else if (possibleInteger.endsWith(\".\") && possibleInteger.matches(\"[0-9]*\\\\.\")) {\n System.out.println(\"The possibleInteger=\"+possibleInteger+\" is an impure integer (ends with decimal point).\");\n return true;\n } else if (possibleInteger.contains(\".\")) {\n String[] partsOfPossibleInteger = possibleInteger.split(\"\\\\.\");\n if (partsOfPossibleInteger.length == 2) {\n //System.out.println(\"The possibleInteger=\" + possibleInteger + \" is split into '\" + partsOfPossibleInteger[0] + \"' and '\" + partsOfPossibleInteger[1] + \"'.\");\n if (partsOfPossibleInteger[0].matches(\"[0-9]*\")) {\n if (partsOfPossibleInteger[1].matches(\"[0]*\")) {\n System.out.println(\"The possibleInteger=\"+possibleInteger+\" is an impure integer (ends with all zeros after the decimal point).\");\n return true;\n } else if (partsOfPossibleInteger[1].matches(\"[0-9]*\")) {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it the numbers after the decimal point (\" + \n partsOfPossibleInteger[1] + \") are not all zeros.\");\n return false;\n } else {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it the 'numbers' after the decimal point (\" + \n partsOfPossibleInteger[1] + \") are not all numeric digits.\");\n return false;\n }\n } else {\n System.out.println(\"The possibleInteger=\" + possibleInteger + \" is NOT an integer because it the 'number' before the decimal point (\" + \n partsOfPossibleInteger[0] + \") is not a number.\");\n return false;\n }\n } else {\n System.out.println(\"The possibleInteger=\"+possibleInteger+\" is NOT an integer because it has a strange number of decimal-period separated parts (\" +\n partsOfPossibleInteger.length + \").\");\n return false;\n }\n } // else\n System.out.println(\"The possibleInteger='\"+possibleInteger+\"' is NOT an integer, even though it has no decimal point.\");\n return false;\n}\n}\n String[] testData = {\"0\", \"0.\", \"0.0\", \".000\", \"2\", \"2.\", \"2.0\", \"2.0000\", \"3.14159\", \".0001\", \".\", \"$4.0\", \"3E24\", \"6.0221409e+23\"};\nint i = 0;\nfor (String possibleInteger : testData ) {\n System.out.println(\"\");\n System.out.println(i + \". possibleInteger='\" + possibleInteger +\"' isIntegerFromDecimalString=\" + isIntegerFromDecimalString(possibleInteger));\n i++;\n}\n" }, { "answer_id": 56903293, "author": "Balconsky", "author_id": 939497, "author_profile": "https://Stackoverflow.com/users/939497", "pm_score": 0, "selected": false, "text": "Integer.MIN_VALUE Integer.MAX_VALUE Integer.valueOf Integer.parseInt NumberFormatException public static boolean isInt(String s) {\n try {\n Integer.parseInt(s);\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n}\n Integer.parseInt public static boolean isInt(String s) {\n int radix = 10;\n\n if (s == null) {\n return false;\n }\n\n if (radix < Character.MIN_RADIX) {\n return false;\n }\n\n if (radix > Character.MAX_RADIX) {\n return false;\n }\n\n int result = 0;\n boolean negative = false;\n int i = 0, len = s.length();\n int limit = -Integer.MAX_VALUE;\n int multmin;\n int digit;\n\n if (len > 0) {\n char firstChar = s.charAt(0);\n if (firstChar < '0') { // Possible leading \"+\" or \"-\"\n if (firstChar == '-') {\n negative = true;\n limit = Integer.MIN_VALUE;\n } else if (firstChar != '+')\n return false;\n\n if (len == 1) // Cannot have lone \"+\" or \"-\"\n return false;\n i++;\n }\n multmin = limit / radix;\n while (i < len) {\n // Accumulating negatively avoids surprises near MAX_VALUE\n digit = Character.digit(s.charAt(i++), radix);\n if (digit < 0) {\n return false;\n }\n if (result < multmin) {\n return false;\n }\n result *= radix;\n if (result < limit + digit) {\n return false;\n }\n result -= digit;\n }\n } else {\n return false;\n }\n return true;\n}\n" }, { "answer_id": 62519971, "author": "Guildenstern", "author_id": 1725151, "author_profile": "https://Stackoverflow.com/users/1725151", "pm_score": 0, "selected": false, "text": "long long int com.google.common.primitives.Ints.tryParse(String) // Credit to Rastislav Komara’s answer: https://stackoverflow.com/a/237895/1725151\nprivate static final Pattern nonZero = Pattern.compile(\"^-?[1-9]\\\\d*$\");\n\n// See if `str` can be parsed as an `int` (does not trim)\n// Strings like `0023` are rejected (leading zeros).\npublic static boolean parsableAsInt(@Nonnull String str) {\n if (str.isEmpty()) {\n return false;\n }\n if (str.equals(\"0\")) {\n return true;\n }\n if (canParseAsLong(str)) {\n long value = Long.valueOf(str);\n if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {\n return true;\n }\n }\n return false;\n}\n\nprivate static boolean canParseAsLong(String str) {\n final int intMaxLength = 11;\n return str.length() <= intMaxLength && nonZero.matcher(str).matches();\n}\n Optional<Integer> if (canParseAsLong(str)) {\n long value = Long.valueOf(str);\n if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {\n return Optional.of((int) value);\n }\n}\n" }, { "answer_id": 63143029, "author": "Yossarian42", "author_id": 9905745, "author_profile": "https://Stackoverflow.com/users/9905745", "pm_score": 0, "selected": false, "text": "\"*\" public boolean isInteger(String str) {\n // null pointer\n if (str == null) {\n return false;\n }\n int len = str.length();\n // empty string\n if (len == 0) {\n return false;\n }\n // one digit, cannot begin with 0\n if (len == 1) {\n char c = str.charAt(0);\n if ((c < '1') || (c > '9')) {\n return false;\n }\n }\n\n for (int i = 0; i < len; i++) {\n char c = str.charAt(i);\n // check positive, negative sign\n if (i == 0) {\n if (c == '-' || c == '+') {\n continue;\n }\n }\n // check each character matches [0-9]\n if ((c < '0') || (c > '9')) {\n return false;\n }\n }\n return true;\n}\n\n" }, { "answer_id": 64089400, "author": "Anu", "author_id": 7713486, "author_profile": "https://Stackoverflow.com/users/7713486", "pm_score": 0, "selected": false, "text": "public static int parseInt(String s, int radix) throws NumberFormatException\n{\n /*\n * WARNING: This method may be invoked early during VM initialization\n * before IntegerCache is initialized. Care must be taken to not use\n * the valueOf method.\n */\n\n if (s == null) {\n throw new NumberFormatException(\"null\");\n }\n\n if (radix < Character.MIN_RADIX) {\n throw new NumberFormatException(\"radix \" + radix +\n \" less than Character.MIN_RADIX\");\n }\n\n if (radix > Character.MAX_RADIX) {\n throw new NumberFormatException(\"radix \" + radix +\n \" greater than Character.MAX_RADIX\");\n }\n\n int result = 0;\n boolean negative = false;\n int i = 0, len = s.length();\n int limit = -Integer.MAX_VALUE;\n int multmin;\n int digit;\n\n if (len > 0) {\n char firstChar = s.charAt(0);\n if (firstChar < '0') { // Possible leading \"+\" or \"-\"\n if (firstChar == '-') {\n negative = true;\n limit = Integer.MIN_VALUE;\n } else if (firstChar != '+')\n throw NumberFormatException.forInputString(s);\n\n if (len == 1) // Cannot have lone \"+\" or \"-\"\n throw NumberFormatException.forInputString(s);\n i++;\n }\n multmin = limit / radix;\n while (i < len) {\n // Accumulating negatively avoids surprises near MAX_VALUE\n digit = Character.digit(s.charAt(i++),radix);\n if (digit < 0) {\n throw NumberFormatException.forInputString(s);\n }\n if (result < multmin) {\n throw NumberFormatException.forInputString(s);\n }\n result *= radix;\n if (result < limit + digit) {\n throw NumberFormatException.forInputString(s);\n }\n result -= digit;\n }\n } else {\n throw NumberFormatException.forInputString(s);\n }\n return negative ? result : -result;\n}\n" }, { "answer_id": 64694246, "author": "Old Nick", "author_id": 5227689, "author_profile": "https://Stackoverflow.com/users/5227689", "pm_score": 0, "selected": false, "text": "boolean isInteger = returnValue.chars().allMatch(Character::isDigit);\n" }, { "answer_id": 65262555, "author": "Gk Mohammad Emon", "author_id": 7200133, "author_profile": "https://Stackoverflow.com/users/7200133", "pm_score": 0, "selected": false, "text": "isDigitsOnly() TextUtils.isDigitsOnly() String /** For kotlin*/\nvar str = \"-123\" \nstr.isDigitsOnly() //Result will be false \n\n/** For Java */\nString str = \"-123\"\nTextUtils.isDigitsOnly(str) //Result will be also false \n var isDigit=str.matches(\"-?\\\\d+(\\\\.\\\\d+)?\".toRegex()) \n/** Result will be true for now*/\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
237,196
<p>I'm experimenting with the NavBar sample project for iPhone. When I tap on one of the rows in the table in the default view a new view slides in (so far so good). I want to remove the UINavigationBar bar at the top of the new view that slides in. How can I do this? </p> <p>EDIT: I meant "UINavigationBar". Thanks to everyone who responded!</p>
[ { "answer_id": 237202, "author": "user31517", "author_id": 31517, "author_profile": "https://Stackoverflow.com/users/31517", "pm_score": 2, "selected": false, "text": "[[UIApplication sharedApplication]setHidesStatusBar:YES];\n" }, { "answer_id": 237208, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 5, "selected": true, "text": " [UIApplication sharedApplication].statusBarHidden = YES; -applicationDidFinishLaunching: navigationBarHidden" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
237,201
<p>I'm trying to perform a simple LINQ query on the Columns property of a DataTable:</p> <pre><code>from c in myDataTable.Columns.AsQueryable() select c.ColumnName </code></pre> <p>However, what I get is this:</p> <blockquote> <p>Could not find an implementation of the query pattern for source type 'System.Linq.IQueryable'. 'Select' not found. Consider explicitly specifying the type of the range variable 'c'.</p> </blockquote> <p>How can I get the DataColumnCollection to play nice with LINQ?</p>
[ { "answer_id": 237224, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 8, "selected": true, "text": "var x = from c in dt.Columns.Cast<DataColumn>()\n select c.ColumnName;\n" }, { "answer_id": 9996173, "author": "Cobra", "author_id": 1071574, "author_profile": "https://Stackoverflow.com/users/1071574", "pm_score": 4, "selected": false, "text": "var x = from DataColumn c in myDataTable.Columns\n select c.ColumnName\n Enumerable.Cast<TResult> Method" }, { "answer_id": 49302799, "author": "MarkusE", "author_id": 3405498, "author_profile": "https://Stackoverflow.com/users/3405498", "pm_score": 4, "selected": false, "text": "var x = myDataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName);\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31516/" ]
237,209
<p>Any python libs for parsing apache config files or if not python anyone aware of such thing in other languages (perl, php, java, c#)? As i'll be able to rewrite them in python.</p>
[ { "answer_id": 237215, "author": "Michael Gundlach", "author_id": 4105, "author_profile": "https://Stackoverflow.com/users/4105", "pm_score": 1, "selected": false, "text": "Package: libapache-configfile-perl\nPriority: optional\nSection: interpreters\nInstalled-Size: 124\nMaintainer: Michael Alan Dorman\nVersion: 1.18-1\nDepends: perl (>= 5.6.0-16)\nDescription: Parse an Apache style httpd.conf configuration file\n\nThis module parses the Apache httpd.conf, or any\ncompatible config file, and provides methods for\nyou to access the values from the config file.\n" }, { "answer_id": 10617432, "author": "VisioN", "author_id": 1249581, "author_profile": "https://Stackoverflow.com/users/1249581", "pm_score": 1, "selected": false, "text": "import apache_conf_parser\nimport pprint\n\nDEFAULT_VHOST = '/etc/apache2/sites-available/000-default.conf'\n\nvhost_default = apache_conf_parser.ApacheConfParser(DEFAULT_VHOST)\n\nprint vhost_default.nodes\nprint vhost_default.nodes[0].body.nodes\n\npprint.pprint( \n {\n i.name: [i.arguments for i in vhost_default.nodes[0].body.nodes]\n }\n)\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9789/" ]
237,218
<p>I am working on an application that uses several large canvas controls (several thousand pixels across), layered on top of each other. The canvas controls themselves are completely invisible, but each contains a number of controls, mainly images.</p> <p>My question is, is there a recommended maximum size for a canvas, or is it purely a memory issue? And also, are we better off setting the Canvas size to (0, 0) and making use of the fact that we can happily render controls outside of the bounds of the canvas?</p> <p>Thanks,</p> <p>G</p>
[ { "answer_id": 241465, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": true, "text": "Canvas Canvas" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10086/" ]
237,220
<p>I'm looking for an algorithm that places tick marks on an axis, given a range to display, a width to display it in, and a function to measure a string width for a tick mark.</p> <p>For example, given that I need to display between 1e-6 and 5e-6 and a width to display in pixels, the algorithm would determine that I should put tickmarks (for example) at 1e-6, 2e-6, 3e-6, 4e-6, and 5e-6. Given a smaller width, it might decide that the optimal placement is only at the even positions, i.e. 2e-6 and 4e-6 (since putting more tickmarks would cause them to overlap).</p> <p>A smart algorithm would give preference to tickmarks at multiples of 10, 5, and 2. Also, a smart algorithm would be symmetric around zero.</p>
[ { "answer_id": 42593802, "author": "Giorgio Barchiesi", "author_id": 681877, "author_profile": "https://Stackoverflow.com/users/681877", "pm_score": 1, "selected": false, "text": "protected double calculateInterval(double range) {\n double x = Math.pow(10.0, Math.floor(Math.log10(range)));\n if (range / x >= 5)\n return x;\n else if (range / (x / 2.0) >= 5)\n return x / 2.0;\n else\n return x / 5.0;\n}\n protected double calculateInterval(double range) {\n double x = Math.pow(10.0, Math.floor(Math.log10(range)));\n if (range / (x / 2.0) >= 10)\n return x / 2.0;\n else if (range / (x / 5.0) >= 10)\n return x / 5.0;\n else\n return x / 10.0;\n}\n" }, { "answer_id": 49911176, "author": "Andrew", "author_id": 2321042, "author_profile": "https://Stackoverflow.com/users/2321042", "pm_score": 4, "selected": false, "text": "if-else if Tuple private static Tuple<decimal, decimal, decimal> GetScaleDetails(decimal min, decimal max)\n{\n // Minimal increment to avoid round extreme values to be on the edge of the chart\n decimal epsilon = (max - min) / 1e6m;\n max += epsilon;\n min -= epsilon;\n decimal range = max - min;\n\n // Target number of values to be displayed on the Y axis (it may be less)\n int stepCount = 20;\n // First approximation\n decimal roughStep = range / (stepCount - 1);\n\n // Set best step for the range\n decimal[] goodNormalizedSteps = { 1, 1.5m, 2, 2.5m, 5, 7.5m, 10 }; // keep the 10 at the end\n // Or use these if you prefer: { 1, 2, 5, 10 };\n\n // Normalize rough step to find the normalized one that fits best\n decimal stepPower = (decimal)Math.Pow(10, -Math.Floor(Math.Log10((double)Math.Abs(roughStep))));\n var normalizedStep = roughStep * stepPower;\n var goodNormalizedStep = goodNormalizedSteps.First(n => n >= normalizedStep);\n decimal step = goodNormalizedStep / stepPower;\n\n // Determine the scale limits based on the chosen step.\n decimal scaleMax = Math.Ceiling(max / step) * step;\n decimal scaleMin = Math.Floor(min / step) * step;\n\n return new Tuple<decimal, decimal, decimal>(scaleMin, scaleMax, step);\n}\n\nstatic void Main()\n{\n // Dummy code to show a usage example.\n var minimumValue = data.Min();\n var maximumValue = data.Max();\n var results = GetScaleDetails(minimumValue, maximumValue);\n chart.YAxis.MinValue = results.Item1;\n chart.YAxis.MaxValue = results.Item2;\n chart.YAxis.Step = results.Item3;\n}\n" }, { "answer_id": 73313693, "author": "Gregor Watters Härtl", "author_id": 18413363, "author_profile": "https://Stackoverflow.com/users/18413363", "pm_score": 2, "selected": false, "text": "10**n 2*10**n 4*10**n 5*10**n % import math\n\n\ndef get_tick_positions(data: list):\n if len(data) == 0:\n return []\n retpoints = []\n data_range = max(data) - min(data)\n lower_bound = min(data) - data_range/10\n upper_bound = max(data) + data_range/10\n view_range = upper_bound - lower_bound\n num = lower_bound\n n = math.floor(math.log10(view_range) - 1)\n interval = 10**n\n num_ticks = 1\n while num <= upper_bound:\n num += interval\n num_ticks += 1\n if num_ticks > 10:\n if interval == 10 ** n:\n interval = 2 * 10 ** n\n elif interval == 2 * 10 ** n:\n interval = 4 * 10 ** n\n elif interval == 4 * 10 ** n:\n interval = 5 * 10 ** n\n else:\n n += 1\n interval = 10 ** n\n num = lower_bound\n num_ticks = 1\n if view_range >= 10:\n copy_interval = interval\n else:\n if interval == 10 ** n:\n copy_interval = 1\n elif interval == 2 * 10 ** n:\n copy_interval = 2\n elif interval == 4 * 10 ** n:\n copy_interval = 4\n else:\n copy_interval = 5\n first_val = 0\n prev_val = 0\n times = 0\n temp_log = math.log10(interval)\n if math.isclose(lower_bound, 0):\n first_val = 0\n elif lower_bound < 0:\n if upper_bound < -2*interval:\n if n < 0:\n copy_ub = round(upper_bound*10**(abs(temp_log) + 1))\n times = copy_ub // round(interval*10**(abs(temp_log) + 1)) + 2\n else:\n times = upper_bound // round(interval) + 2\n while first_val >= lower_bound:\n prev_val = first_val\n first_val = times * copy_interval\n if n < 0:\n first_val *= (10**n)\n times -= 1\n first_val = prev_val\n times += 3\n else:\n if lower_bound > 2*interval:\n if n < 0:\n copy_ub = round(lower_bound*10**(abs(temp_log) + 1))\n times = copy_ub // round(interval*10**(abs(temp_log) + 1)) - 2\n else:\n times = lower_bound // round(interval) - 2\n while first_val < lower_bound:\n first_val = times*copy_interval\n if n < 0:\n first_val *= (10**n)\n times += 1\n if n < 0:\n retpoints.append(first_val)\n else:\n retpoints.append(round(first_val))\n val = first_val\n times = 1\n while val <= upper_bound:\n val = first_val + times * interval\n if n < 0:\n retpoints.append(val)\n else:\n retpoints.append(round(val))\n times += 1\n retpoints.pop()\n return retpoints\n points = [-0.00493, -0.0003892, -0.00003292] [-0.005, -0.004, -0.003, -0.002, -0.001, 0.0] points = [1.399, 38.23823, 8309.33, 112990.12] [0, 20000, 40000, 60000, 80000, 100000, 120000] points = [-54, -32, -19, -17, -13, -11, -8, -4, 12, 15, 68] [-60, -40, -20, 0, 20, 40, 60, 80]" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
237,222
<p>This code:</p> <pre><code>public class WidgetPlatform { public Widget LeftmostWidget { get; set; } public Widget RightmostWidget { get; set; } public String GetWidgetNames() { return LeftmostWidget.Name + " " + RightmostWidget.Name; } } </code></pre> <p>doesn't contain any repetition worth worrying about, but it isn't particularly robust. Because the Widgets aren't null-checked, we're leaving an opening for a bug. We could do a null check, but that feels like work. Here's what I really want:</p> <pre><code>public class WidgetPlatform { [Required] public Widget LeftmostWidget { get; set; } [Required] public Widget RightmostWidget { get; set; } public String GetWidgetNames() { return LeftmostWidget.Name + " " + RightmostWidget.Name; } } </code></pre> <p>Ideally, it would cause a compile error (the best sort of error) if the object was instantiated without setting the Widgets, but that seems like a tall order. Is there a way to make this syntax work that at least throws an error on instantiation? There's a (relatively) obvious way to do it with reflection if all of the null-checked objects inherit from the same type, but without multiple inheritance that will get ugly pretty fast.</p>
[ { "answer_id": 237248, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": false, "text": "public class WidgetPlatform\n{\n public Widget LeftmostWidget { get; set; }\n public Widget RightmostWidget { get; set; }\n\n public WidgetPlatform()\n {\n this.LeftMostWidget = new Widget();\n this.RightMostWidget = new Widget();\n }\n\n public WidgetPlatform(Widget left, Widget right)\n {\n if(left == null || right == null)\n throw new ArgumentNullException(\"Eeep!\");\n\n this.LeftMostWidget = left;\n this.RightMostWidget = right;\n }\n\n\n public String GetWidgetNames()\n {\n return LeftmostWidget.Name + \" \" + RightmostWidget.Name;\n }\n}\n" }, { "answer_id": 237442, "author": "user25306", "author_id": 25306, "author_profile": "https://Stackoverflow.com/users/25306", "pm_score": 0, "selected": false, "text": "public class WidgetPlatform\n {\n /// <summary>\n /// Hide the constructor.\n /// </summary>\n private WidgetPlatform(Widget left, Widget right)\n {\n this.LeftmostWidget = left;\n this.RightmostWidget = right;\n }\n\n public Widget LeftmostWidget\n {\n get;\n private set;\n }\n\n public Widget RightmostWidget\n {\n get;\n private set;\n }\n\n public static WidgetPlatform GetInstance(Widget left, Widget right)\n {\n return new WidgetPlatform(left, right);\n }\n }\n" }, { "answer_id": 237478, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "public class WidgetPlatform\n{\n public Widget LeftWidget\n {\n get;\n private set;\n }\n\n public Widget RightWidget\n {\n get;\n private set;\n }\n\n WidgetPlatForm(Widget w1, Widget w2)\n {\n if (w1 == null || w2 == null)\n throw new ArgumentException();\n\n this.LeftWidget = w1;\n this.RightWidget = w2; \n }\n\n // Etc\n}\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/237222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30761/" ]
237,235
<p>In my django application I am using a template to construct email body, one of the parameters is url, note there are two parametes separated by ampersand in the url.</p> <pre><code>t = loader.get_template("sometemplate") c = Context({ 'foo': 'bar', 'url': 'http://127.0.0.1/test?a=1&amp;b=2', }) print t.render(c) </code></pre> <p>After rendering it produces: <code>http://127.0.0.1/test?a=1&amp;amp;amp;b=2</code></p> <p>Note the ampersand is HTML encoded as "&amp;amp;". One way around the problem is to pass each parameter separately to my template and construct the url in the template, however I'd like to avoid doing that.</p> <p>Is there a way to disable HTML encoding of context parameters or at the very least avoid encoding of ampersands?</p>
[ { "answer_id": 237243, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": true, "text": "mark_safe from django.utils.safestring import mark_safe\n\nt = loader.get_template(\"sometemplate\")\nc = Context({\n 'foo': 'bar',\n 'url': mark_safe('http://127.0.0.1/test?a=1&b=2'),\n})\nprint t.render(c)\n autoescape Context c = Context({\n 'foo': 'bar',\n 'url': 'http://127.0.0.1/test?a=1&b=2',\n}, autoescape=False)\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26592/" ]
237,254
<p>The <a href="http://docs.jquery.com/Events/bind#typedatafn" rel="noreferrer">jQuery documentation</a> says the library has built-in support for the following events: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and error.</p> <p>I need to handle cut, copy, and paste events. How best to do that? FWIW, I only need to worry about WebKit (lucky me!).</p> <p>UPDATE: I'm working on a "widget" in a Dashboard-like environment. It uses WebKit, so it only really matters (for my purposes) whether these events are supported there, which it looks like they are.</p>
[ { "answer_id": 238835, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 8, "selected": true, "text": ".on() off() jQuery(document).on('paste', function(e){ alert('pasting!') });\n jQuery('p').on('foobar2000', function(e){ alert(e.type); });\n .trigger() jQuery('p').trigger('foobar2000');\n" }, { "answer_id": 241158, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 3, "selected": false, "text": " this.addEventListener('input',\n function(){//stuff here},\n false\n );\n" }, { "answer_id": 32357998, "author": "Yan Pak", "author_id": 1068013, "author_profile": "https://Stackoverflow.com/users/1068013", "pm_score": 1, "selected": false, "text": "$('#someElementId').bind('paste', function(){return false;});\n $('#someElementId').bind('copy', function(){return alert('Hey fella! Do not forget about copyrights!');});\n $('#someElementId').unbind('copy');\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
237,268
<p>Doing like so:</p> <p><code>Shell ("C:\Program Files\Internet Explorer\iexplore.exe -embedding http://www.websiteurl.com")</code></p> <p>Doesn't work how I need it as I essentially need it to be able to redirect and prompt a user to download a file. Any ideas?</p>
[ { "answer_id": 237271, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "wget" }, { "answer_id": 239493, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "WinHTTPRequest Dim HttpRequest As New WinHttp.WinHttpRequest\nDim TargetUrl As String\nDim TargetFile As String\nDim FileNum As Integer\n\nTargetFile = \"C:\\foo.doc\"\n\nTargetUrl = \"http://www.websiteurl.com\"\nHttpRequest.Open Method:=\"GET\", Url:=TargetUrl, Async:=False\nHttpRequest.Send\n\nIf HttpRequest.Status = 302 Then\n\n TargetUrl = HttpRequest.GetResponseHeader(\"Location\")\n HttpRequest.Open Method:=\"GET\", Url:=TargetUrl, Async:=False\n HttpRequest.Send\n\n If HttpRequest.Status = \"200\" Then\n\n FileNum = FreeFile\n Open TargetFile For Binary As #FileNum\n Put #FileNum, 1, HttpRequest.ResponseBody\n Close FileNum \n\n Debug.Print \"Successfully witten \" & TargetFile\n Else\n Debug.Print \"Download failed. Received HTTP status: \" & HttpRequest.Status\n End If\nElse\n Debug.Print \"Expected Redirect. Received HTTP status: \" & HttpRequest.Status\nEnd If\n \"C:\\foo.doc\" \"Content-Type\" \"Content-Disposition\"" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,269
<p>I am thinking of running this custom targets to find out more about my project build status - jalopy - jdepend - cvs tagdiff report - custom task for NoUnit - generate UML diagram. ESS-Model</p> <p>What are your views?</p>
[ { "answer_id": 240701, "author": "jim", "author_id": 27628, "author_profile": "https://Stackoverflow.com/users/27628", "pm_score": 1, "selected": false, "text": "<target name=\"statsAll\">\n <!-- master file that describes where everything is -->\n <property file=\"./ant/ant-global.properties\" prefix=\"ant-global\" />\n <tstamp>\n <format property=\"gen.time\" pattern=\"yyyyMMdd_hh\"/>\n </tstamp>\n <echo message=\"LOG:./ant/logs/jdepend.${version.FILETAG}.${gen.time}.rpt\"/>\n <!-- generate stats to see if we're improving -->\n <jdepend \n outputfile=\"./ant/logs/jdepend.${version.FILETAG}.${gen.time}.rpt\" >\n <exclude name=\"java.*\"/>\n <exclude name=\"javax.*\"/>\n <classespath>\n <pathelement location=\"./jar\" />\n </classespath>\n <classpath location=\"./jar\" />\n </jdepend>\n</target>\n\n<target name=\"doJDepend\" depends=\"getVersion,statsAll\">\n <echo message=\"FTP'ing report\"/>\n <ftp verbose=\"yes\" passive=\"yes\" depends=\"yes\"\n remotedir=\"/videojet/metrics\" server=\"xxxxx\"\n userid=\"xxxx\" password=\"xxxxx\"\n binary=\"no\"\n systemTypeKey=\"UNIX\">\n <fileset dir=\"./ant/logs/\" casesensitive=\"no\">\n <include name=\"**/jdepend.${version.FILETAG}*.rpt\"/>\n <exclude name=\"**/*.txt\"/>\n </fileset>\n </ftp>\n</target>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,275
<p>I'm constructing a method to take in an ArrayList(presumably full of objects) and then list all the fields(and their values) for each object in the ArrayList.</p> <p>Currently my code is as follows:</p> <pre><code>public static void ListArrayListMembers(ArrayList list) { foreach (Object obj in list) { Type type = obj.GetType(); string field = type.GetFields().ToString(); Console.WriteLine(field); } } </code></pre> <p>Of course, I understand the immediate issue with this code: if it worked it'd only print one field per object in the ArrayList. I'll fix this later - right now I'm just curious how to get all of the public fields associated with an object.</p>
[ { "answer_id": 237278, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 6, "selected": true, "text": "foreach (Object obj in list) {\n Type type = obj.GetType();\n\n foreach (var f in type.GetFields().Where(f => f.IsPublic)) {\n Console.WriteLine(\n String.Format(\"Name: {0} Value: {1}\", f.Name, f.GetValue(obj));\n } \n}\n" }, { "answer_id": 237292, "author": "nyxtom", "author_id": 19753, "author_profile": "https://Stackoverflow.com/users/19753", "pm_score": 2, "selected": false, "text": "public static void ListArrayListMembers(ArrayList list)\n{\n foreach (Object obj in list)\n {\n Type type = obj.GetType();\n Console.WriteLine(\"{0} -- \", type.Name);\n Console.WriteLine(\" Properties: \");\n foreach (PropertyInfo prop in type.GetProperties())\n {\n Console.WriteLine(\"\\t{0} {1} = {2}\", prop.PropertyType.Name, \n prop.Name, prop.GetValue(obj, null));\n }\n Console.WriteLine(\" Fields: \");\n foreach (FieldInfo field in type.GetFields())\n {\n Console.WriteLine(\"\\t{0} {1} = {2}\", field.FieldType.Name, \n field.Name, field.GetValue(obj));\n }\n }\n}\n" }, { "answer_id": 237295, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 1, "selected": false, "text": " static void ListArrayListMembers(ArrayList list)\n {\n foreach (object obj in list)\n {\n Type type = obj.GetType();\n foreach (FieldInfo field in type.GetFields(BindingFlags.Public))\n {\n Console.WriteLine(field.Name + \" = \" + field.GetValue(obj).ToString());\n }\n }\n }\n" }, { "answer_id": 237308, "author": "Jonathan Webb", "author_id": 1518, "author_profile": "https://Stackoverflow.com/users/1518", "pm_score": 3, "selected": false, "text": "GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)\n GetFields(BindingFlags.Public | BindingFlags.Instance)\n" }, { "answer_id": 237817, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "DataTable DataView TypeDescriptor foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))\n {\n Console.WriteLine(\"{0}={1}\", prop.Name, prop.GetValue(obj));\n }\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2153/" ]
237,282
<p>At work, we have one of those nasty communal urinals. There is no flush handle. Rather, it has a motion sensor that sometimes triggers when you stand in front of it and sometimes doesn't. When it triggers, a tank fills, which when full is used to flush the urinal.</p> <p>In my many trips before this nastraption, I have pondered both what the algorithm is the box uses to determine when to turn on and what would be the optimal algorithm, in terms of conserving water while still maintaining a relatively pleasant urinal experience.</p> <p>I'll share my answer once folks have had a chance to share their ideas.</p>
[ { "answer_id": 237315, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 5, "selected": true, "text": "OnUserEnter()\n{\n if (UsersDetected == 0)\n {\n FirstDetectionTime = Now();\n }\n UsersDetected++;\n CurrentlyInUse = true;\n}\n\nOnUserExit()\n{\n CurrentlyInUse = false;\n if (UsersDetected >= MaxUsersBetweenFlushes || \n Now() - FirstDetectionTime > StinkInterval)\n {\n Flush();\n }\n}\n\nOnTimer()\n{\n if (!CurrentlyInUse && \n UsersDetected > 0 && \n Now() - FirstDetectionTime > StinkInterval)\n {\n Flush();\n }\n}\n\nFlush()\n{\n FlushTheUrinal();\n UsersDetected = 0;\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
237,285
<p>At my workplace, we tend to use <strong>iostream</strong>, <strong>string</strong>, <strong>vector</strong>, <strong>map</strong>, and the odd <strong>algorithm</strong> or two. We haven't actually found many situations where template techniques were a best solution to a problem.</p> <p>What I am looking for here are ideas, and optionally sample code that shows how you used a template technique to create a new solution to a problem that you encountered in real life.</p> <p>As a bribe, expect an up vote for your answer.</p>
[ { "answer_id": 237294, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "template <int N>\nstruct Factorial \n{\n enum { value = N * Factorial<N - 1>::value };\n};\n\ntemplate <>\nstruct Factorial<0> \n{\n enum { value = 1 };\n};\n\n// Factorial<4>::value == 24\n// Factorial<0>::value == 1\nvoid foo()\n{\n int x = Factorial<4>::value; // == 24\n int y = Factorial<0>::value; // == 1\n}\n" }, { "answer_id": 237341, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 4, "selected": true, "text": "ExeFile std::string std::wstring ExeFile #ifdef WIN64" }, { "answer_id": 237356, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 2, "selected": false, "text": "template <typename T>\nbool ContainsNanT<T>(T * values, int len) { ... actual code goes here } ;\n template <typename T>\nvoid BinStream::Serialize(T & value) { ... }\n\n// to make a type serializable, you need to implement\nvoid SerializeElement(BinStream & strean, Foo & element);\nvoid DeserializeElement(BinStream & stream, Foo & element)\n" }, { "answer_id": 237883, "author": "Jackson", "author_id": 29061, "author_profile": "https://Stackoverflow.com/users/29061", "pm_score": 3, "selected": false, "text": "class TpQueue {\npublic:\n void enqueue(...)\n void dequeue(...)\n ...\n}\n class OwnTransaction {\npublic:\n begin(...) // Suspend any open transaction and start a new one\n commit(..) // Commit my transaction and resume any suspended one\n abort(...)\n}\n\nclass SharedTransaction {\npublic:\n begin(...) // Join the currently active transaction or start a new one if there isn't one\n ...\n}\n template <typename TXNPOLICY = SharedTransaction>\nclass TpQueue : public TXNPOLICY {\n ...\n}\n TpQueue<SharedTransaction> queue1 ;\nTpQueue<OwnTransaction> queue2 ;\n" }, { "answer_id": 237928, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 2, "selected": false, "text": "IServiceProvider // Get interface either via QueryInterface of via QueryService\ntemplate <class IFace>\nCComPtr<IFace> GetIFace(IUnknown* unk)\n{\n CComQIPtr<IFace> ret = unk; // Try QueryInterface\n if (ret == NULL) { // Fallback to QueryService\n if(CComQIPtr<IServiceProvider> ser = unk)\n ser->QueryService(__uuidof(IFace), __uuidof(IFace), (void**)&ret);\n }\n return ret;\n}\n" }, { "answer_id": 237989, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "bool getValue(wxString key, wxString& value);\nbool getValue(wxString key, int& value);\nbool getValue(wxString key, double& value);\nbool getValue(wxString key, bool& value);\nbool getValue(wxString key, StorageGranularity& value);\nbool getValue(wxString key, std::vector<wxString>& value);\n template <typename T>\nT get(wxString key, const T& defaultValue)\n{\n T temp;\n if (getValue(key, temp))\n return temp;\n else\n return defaultValue;\n}\n" }, { "answer_id": 238134, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 1, "selected": false, "text": "void doSomethingGeneric1(SomeClass * c, SomeClass & d)\n{\n // three lines of code\n callFunctionGeneric1(c) ;\n // three lines of code\n}\n void doSomethingGeneric2(SomeClass * c, SomeClass & d)\nvoid doSomethingGeneric3(SomeClass * c, SomeClass & d)\nvoid doSomethingGeneric4(SomeClass * c, SomeClass & d)\n// Etc\n template<typename T>\nvoid doSomethingGenericAnything(SomeClass * c, SomeClass & d, T t)\n{\n // three lines of code\n t(c) ;\n // three lines of code\n}\n void doSomethingGeneric1(SomeClass * c, SomeClass & d)\n{\n doSomethingGenericAnything(c, d, callFunctionGeneric1) ;\n}\n\nvoid doSomethingGeneric2(SomeClass * c, SomeClass & d)\n{\n doSomethingGenericAnything(c, d, callFunctionGeneric2) ;\n}\n" }, { "answer_id": 245852, "author": "Dean Michael", "author_id": 11274, "author_profile": "https://Stackoverflow.com/users/11274", "pm_score": 1, "selected": false, "text": "template <class Derived>\nstruct handler_base : Derived {\n void pre_call() {\n // do any universal pre_call handling here\n static_cast<Derived *>(this)->pre_call();\n };\n\n void post_call(typename Derived::result_type & result) {\n static_cast<Derived *>(this)->post_call(result);\n // do any universal post_call handling here\n };\n\n typename Derived::result_type\n operator() (typename Derived::arg_pack const & args) {\n pre_call();\n typename Derived::result_type temp = static_cast<Derived *>(this)->eval(args);\n post_call(temp);\n return temp;\n };\n struct my_handler : handler_base<my_handler> {\n typedef int result_type; // required to compile\n typedef tuple<int, int> arg_pack; // required to compile\n void pre_call(); // required to compile\n void post_call(int &); // required to compile\n int eval(arg_pack const &); // required to compile\n};\n template <class T, class Arg0, class Arg1>\ntypename T::result_type\ninvoke(handler_base<T> & handler, Arg0 const & arg0, Arg1 const & arg1) {\n return handler(make_tuple(arg0, arg1));\n};\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
237,289
<p>I'm looking for a way to configure the color used for line numbering (as in: <code>:set nu</code>) in Vim. The default on most platforms seems to be yellow (which is also used for some highlighted tokens). I would <em>like</em> to color the line numbers a dim gray; somewhere in the vicinity of <code>#555</code>. I'm not picky though, any subdued color would be acceptable.</p>
[ { "answer_id": 237293, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "help hl-LineNr\n help 'number'\n 'number' :number :highlight LineNr ctermfg=grey\n :highlight LineNr guifg=#050505\n" }, { "answer_id": 12344075, "author": "Roshambo", "author_id": 610051, "author_profile": "https://Stackoverflow.com/users/610051", "pm_score": 4, "selected": false, "text": "CursorLineNr hi CursorLineNr guifg=#050505" }, { "answer_id": 32128209, "author": "qasimalbaqali", "author_id": 4708186, "author_profile": "https://Stackoverflow.com/users/4708186", "pm_score": 5, "selected": false, "text": ".vimrc highlight LineNr term=bold cterm=NONE ctermfg=DarkGrey ctermbg=NONE gui=NONE guifg=DarkGrey guibg=NONE ctermfg guifg" }, { "answer_id": 37102917, "author": "Jabba", "author_id": 232485, "author_profile": "https://Stackoverflow.com/users/232485", "pm_score": 2, "selected": false, "text": "colorscheme trivial256 \" for light background\nhi LineNr term=bold cterm=bold ctermfg=2 guifg=Grey guibg=Grey90\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9815/" ]
237,310
<p>I'm currently displaying a UIViewController like this:</p> <pre><code>[[self navigationController] presentModalViewController:modalViewController animated:YES]; </code></pre> <p>and hiding it like this:</p> <pre><code>[self.navigationController dismissModalViewControllerAnimated:YES]; </code></pre> <p>The animation is "slide up from the bottom"... then slide back down. How can I change the animation style? Can I made it fade in/out?</p> <p>Cheers!</p>
[ { "answer_id": 237355, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 7, "selected": true, "text": "UIViewController *controller = [[[MyViewController alloc] init] autorelease];\nUIViewAnimationTransition trans = UIViewAnimationTransitionCurlUp;\n[UIView beginAnimations: nil context: nil];\n[UIView setAnimationTransition: trans forView: [self window] cache: YES];\n[navController presentModalViewController: controller animated: NO];\n[UIView commitAnimations];\n UIViewController *controller = [[[MyViewController alloc] init] autorelease];\ncontroller.view.alpha = 0.0;\n[navController presentModalViewController: controller animated: NO];\n[UIView beginAnimations: nil context: nil];\ncontroller.view.alpha = 1.0;\n[UIView commitAnimations];\n" }, { "answer_id": 2006694, "author": "Simo Salminen", "author_id": 72544, "author_profile": "https://Stackoverflow.com/users/72544", "pm_score": 8, "selected": false, "text": "modalViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;\n[[self navigationController] presentModalViewController:modalViewController\n animated:YES];\n" }, { "answer_id": 3632081, "author": "user412500", "author_id": 412500, "author_profile": "https://Stackoverflow.com/users/412500", "pm_score": 2, "selected": false, "text": "[self.view.window]" }, { "answer_id": 3892490, "author": "Peter DeWeese", "author_id": 431053, "author_profile": "https://Stackoverflow.com/users/431053", "pm_score": 3, "selected": false, "text": "modalController.view.alpha = 0.0;\n[self.view.window.rootViewController presentModalViewController:modalController animated:NO];\n[UIView animateWithDuration:0.5\n animations:^{modalController.view.alpha = 1.0;}];\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
237,322
<p>You'd think it would be easy, but keep reading. I can change many of the styles associated with a resizable JQuery Dialog, but not the handles. The code below isolates the problem. Why does the handle disappear entirely? There must be some logic I'm interfering with in ui.resizable.js, but I don't see it.</p> <pre><code>&lt;script type="text/javascript" language="JavaScript" src="jquery126.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="JavaScript" src="ui/ui.core.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="JavaScript" src="ui/ui.dialog.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="JavaScript" src="ui/ui.resizable.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="JavaScript" src="ui/ui.draggable.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(foo); function foo() { $("#dlg").dialog() } &lt;/script&gt; &lt;style type="text/css"&gt; .ui-resizable-n { background: green; } &lt;/style&gt; &lt;div id=dlg title="my title"&gt;this is&lt;br&gt;my text&lt;/div&gt; </code></pre>
[ { "answer_id": 237393, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": ".ui-resizable-n{\n background-image:none;\n background-color:green;\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
237,326
<p>In particular, would it be possible to have <strong>code similar to this c++ code executed at compile time in c#</strong>?</p> <pre><code>template &lt;int N&gt; struct Factorial { enum { value = N * Factorial&lt;N - 1&gt;::value }; }; template &lt;&gt; struct Factorial&lt;0&gt; { enum { value = 1 }; }; // Factorial&lt;4&gt;::value == 24 // Factorial&lt;0&gt;::value == 1 void foo() { int x = Factorial&lt;4&gt;::value; // == 24 int y = Factorial&lt;0&gt;::value; // == 1 } </code></pre>
[ { "answer_id": 237513, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "static string SomeFunc<T>(T value) {\n return \"Generic\";\n}\nstatic string SomeFunc(int value) {\n return \"Non-Generic\";\n}\n\nstatic void Example() {\n SomeFunc(42); // Non-Generic\n SomeFunc((object)42); // Generic\n}\n" }, { "answer_id": 19924853, "author": "piojo", "author_id": 1682146, "author_profile": "https://Stackoverflow.com/users/1682146", "pm_score": 2, "selected": false, "text": "abstract class Integer\n{\n public abstract int Get { get; }\n}\n\npublic class One : Integer { public override int Get { return 1; } } }\npublic class Two : Integer { public override int Get { return 2; } } }\npublic class Three : Integer { public override int Get { return 3; } } }\n\npublic class FixedStorage<T, N> where N : Integer, new()\n{\n T[] storage;\n public FixedStorage()\n {\n storage = new T[new N().Get];\n }\n public T Get(int i)\n {\n return storage[i];\n }\n}\n public class Vector3 : FixedStorage<float, Three> {}\npublic class Vector2 : FixedStorage<float, Two> {}\npublic class GridCell : FixedStorage<int, Two> {}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
237,327
<p>The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data:</p> <pre><code>if table t has a row exists that has key X: update t set mystuff... where mykey=X else insert into t mystuff... </code></pre> <p>Since Oracle doesn't have a specific UPSERT statement, what's the best way to do this?</p>
[ { "answer_id": 237328, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 8, "selected": false, "text": "create or replace\nprocedure ups(xa number)\nas\nbegin\n merge into mergetest m using dual on (a = xa)\n when not matched then insert (a,b) values (xa,1)\n when matched then update set b = b+1;\nend ups;\n/\ndrop table mergetest;\ncreate table mergetest(a number, b number);\ncall ups(10);\ncall ups(10);\ncall ups(20);\nselect * from mergetest;\n\nA B\n---------------------- ----------------------\n10 2\n20 1\n" }, { "answer_id": 239579, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 7, "selected": true, "text": "begin\n insert into t (mykey, mystuff) \n values ('X', 123);\nexception\n when dup_val_on_index then\n update t \n set mystuff = 123 \n where mykey = 'X';\nend; \n" }, { "answer_id": 243564, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 6, "selected": false, "text": "UPDATE tablename\n SET val1 = in_val1,\n val2 = in_val2\n WHERE val3 = in_val3;\n\nIF ( sql%rowcount = 0 )\n THEN\n INSERT INTO tablename\n VALUES (in_val1, in_val2, in_val3);\nEND IF;\n" }, { "answer_id": 2233798, "author": "Anon", "author_id": 269949, "author_profile": "https://Stackoverflow.com/users/269949", "pm_score": -1, "selected": false, "text": "INSERT\nFIRST WHEN\n credit_limit >=100000\nTHEN INTO\n rich_customers\nVALUES(cust_id,cust_credit_limit)\n INTO customers\nELSE\n INTO customers SELECT * FROM new_customers;\n" }, { "answer_id": 2692441, "author": "MyDeveloperDay", "author_id": 323236, "author_profile": "https://Stackoverflow.com/users/323236", "pm_score": 7, "selected": false, "text": "MERGE INTO Employee USING dual ON ( \"id\"=2097153 )\nWHEN MATCHED THEN UPDATE SET \"last\"=\"smith\" , \"name\"=\"john\"\nWHEN NOT MATCHED THEN INSERT (\"id\",\"last\",\"name\") \n VALUES ( 2097153,\"smith\", \"john\" )\n" }, { "answer_id": 5307242, "author": "r4bitt", "author_id": 442005, "author_profile": "https://Stackoverflow.com/users/442005", "pm_score": -1, "selected": false, "text": "insert into b_building_property (\n select\n 'AREA_IN_COMMON_USE_DOUBLE','Area in Common Use','DOUBLE', null, 9000, 9\n from dual\n)\nminus\n(\n select * from b_building_property where id = 9\n)\n;\n" }, { "answer_id": 14031952, "author": "Hubbitus", "author_id": 307525, "author_profile": "https://Stackoverflow.com/users/307525", "pm_score": 5, "selected": false, "text": "MERGE INTO KBS.NUFUS_MUHTARLIK B\nUSING (\n SELECT '028-01' CILT, '25' SAYFA, '6' KUTUK, '46603404838' MERNIS_NO\n FROM DUAL\n) E\nON (B.MERNIS_NO = E.MERNIS_NO)\nWHEN MATCHED THEN\n UPDATE SET B.CILT = E.CILT, B.SAYFA = E.SAYFA, B.KUTUK = E.KUTUK\nWHEN NOT MATCHED THEN\n INSERT ( CILT, SAYFA, KUTUK, MERNIS_NO)\n VALUES (E.CILT, E.SAYFA, E.KUTUK, E.MERNIS_NO); \n" }, { "answer_id": 22777749, "author": "Evgeniy Berezovsky", "author_id": 709537, "author_profile": "https://Stackoverflow.com/users/709537", "pm_score": 5, "selected": false, "text": "PROCEDURE MyProc (\n ...\n) IS\nBEGIN\n LOOP\n BEGIN\n MERGE INTO Employee USING dual ON ( \"id\"=2097153 )\n WHEN MATCHED THEN UPDATE SET \"last\"=\"smith\" , \"name\"=\"john\"\n WHEN NOT MATCHED THEN INSERT (\"id\",\"last\",\"name\") \n VALUES ( 2097153,\"smith\", \"john\" );\n EXIT; -- success? -> exit loop\n EXCEPTION\n WHEN NO_DATA_FOUND THEN -- the entry was concurrently deleted\n NULL; -- exception? -> no op, i.e. continue looping\n WHEN DUP_VAL_ON_INDEX THEN -- an entry was concurrently inserted\n NULL; -- exception? -> no op, i.e. continue looping\n END;\n END LOOP;\nEND; \n SERIALIZABLE" }, { "answer_id": 27906848, "author": "Arturo Hernandez", "author_id": 937703, "author_profile": "https://Stackoverflow.com/users/937703", "pm_score": 4, "selected": false, "text": "UPDATE tablename SET val1 = in_val1, val2 = in_val2\n WHERE val3 = in_val3;\nIF ( sql%notfound ) THEN\n INSERT INTO tablename\n VALUES (in_val1, in_val2, in_val3);\nEND IF;\n MERGE INTO tablename USING dual ON ( val3 = in_val3 )\nWHEN MATCHED THEN UPDATE SET val1 = in_val1, val2 = in_val2\nWHEN NOT MATCHED THEN INSERT \n VALUES (in_val1, in_val2, in_val3)\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
237,350
<p>I am trying to call a setTimeout from within a setInterval callback:</p> <pre><code>function callback() { //assign myVar var myVar = document.getElementById("givenID"); //... //now wait 2 secs then call some code that uses myVAr setTimeout("myVar.innerHTML = 'TEST'", 2000); } setInterval("callback();", 10000); </code></pre> <p>setInterval works as expected but setTimeout call is failing. I guess the problem is related to the fact that I am referencing a variable (myVar) that's not in scope.</p> <p>What's the best way to solve this?</p>
[ { "answer_id": 237375, "author": "Michael Gundlach", "author_id": 4105, "author_profile": "https://Stackoverflow.com/users/4105", "pm_score": 1, "selected": false, "text": "\"someFunction();\" \"alert('hi')\"" }, { "answer_id": 237387, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 2, "selected": false, "text": "setTimeout setInterval eval setInterval(function () {\n // do stuff\n // ...\n // now wait 2 secs then call someFunction\n setTimeout(someFunction, 2000);\n}, 10000);\n" }, { "answer_id": 237388, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 6, "selected": true, "text": "setInterval(\n function ()\n {\n var myVar = document.getElementById(\"givenID\");\n setTimeout(\n function()\n {\n // myVar is available because the inner closure \n // gets the outer closures scope\n myVar.innerHTML = \"Junk\";\n },2000);\n }, 10000);\n" }, { "answer_id": 6884195, "author": "svinec", "author_id": 870802, "author_profile": "https://Stackoverflow.com/users/870802", "pm_score": 4, "selected": false, "text": "function myObject() {\n\n this.egoist = function() {\n setTimeout( 'this.egoist()', 200 );\n }\n\n}\n\nmyObject001 = new myObject();\nmyObject001.egoist();\n ... setTimeout( egoist, 200 );\n... setTimeout( egoist(), 200 );\n... setTimeout( this.egoist, 200 );\n... setTimeout( this.egoist(), 200 );\n... setTimeout( function() { this.egoist() }, 200 );\n function myObject() {\n\n this.egoist = function() {\n with (this) { setTimeout( function() { egoist() }, 200 );}\n }\n\n}\n\nmyObject001 = new myObject();\nmyObject001.egoist();\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311500/" ]
237,367
<p>When I connect to a MySQL database using PDO, the way I need to connect is:</p> <pre><code>$pdoConnection = new PDO("mysql:host=hostname;dbname=databasename",user,password); </code></pre> <p>But, for PostgreSQL, the DSN is more standard (IMO):</p> <pre><code>$pdoConnection = new PDO("pgsql:host=hostname;dbname=databasename;user=username;password=thepassword"); </code></pre> <p>Is there any reason why MySQL cannot use a single string? Or is this just because of the versions I am using (PHP 5.2, MySQL 5.0, PostgreSQL 8.1)?</p>
[ { "answer_id": 37436321, "author": "mindplay.dk", "author_id": 283851, "author_profile": "https://Stackoverflow.com/users/283851", "pm_score": 2, "selected": false, "text": "parse_str($connection_string, $params);\n\n$pdo = new PDO($params['dsn'], @$params['username'], @$params['password']);\n $connection_string dsn=pgsql:host=localhost;dbname=test;user=root;password=root\n dsn=mysql:host=localhost;dbname=testdb&username=root&password=root\n" }, { "answer_id": 59037037, "author": "Shish", "author_id": 982134, "author_profile": "https://Stackoverflow.com/users/982134", "pm_score": 0, "selected": false, "text": "class MyPDO extends PDO {\n public function __construct($dsn, $options = null) {\n $user=null;\n $pass=null;\n\n if (preg_match(\"/user=([^;]*)/\", $dsn, $matches)) {\n $user=$matches[1];\n }\n if (preg_match(\"/password=([^;]*)/\", $dsn, $matches)) {\n $pass=$matches[1];\n }\n\n parent::__construct($dsn, $user, $pass, $options);\n }\n}\n" }, { "answer_id": 62587863, "author": "Alexios Tsiaparas", "author_id": 1231926, "author_profile": "https://Stackoverflow.com/users/1231926", "pm_score": 3, "selected": false, "text": "$dbh = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8mb4;user=root;password=')\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23089/" ]
237,370
<p>In some code I've inherited, I see frequent use of <code>size_t</code> with the <code>std</code> namespace qualifier. For example:</p> <pre><code>std::size_t n = sizeof( long ); </code></pre> <p>It compiles and runs fine, of course. But it seems like bad practice to me (perhaps carried over from C?).</p> <p>Isn't it true that <code>size_t</code> is built into C++ and therefore in the global namespace? Is a header file include needed to use <code>size_t</code> in C++?</p> <p>Another way to ask this question is, would the following program (with <em>no</em> includes) be expected to <em>compile</em> on all C++ compilers?</p> <pre><code>size_t foo() { return sizeof( long ); } </code></pre>
[ { "answer_id": 237395, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 2, "selected": false, "text": "int main(int argc, char** argv) {\nsize_t size;\n}\n <cstdlib>" }, { "answer_id": 237882, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 4, "selected": false, "text": "size_t <stddef.h> <cstddef>" }, { "answer_id": 283023, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 8, "selected": true, "text": "::size_t stddef.h ANSI/ISO C ISO C++ stddef.h cstddef std::size_t ::size_t" }, { "answer_id": 850430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "std::size_t ::size_t ::size_t std::size_t ----\n// a.hpp \n#include <string>\n\nvoid Foo( const std::string & name, size_t value );\n\n-----\n// a.cpp\n#include \"a.hpp\"\n\nusing namespace std;\n\nvoid Foo( const string & name, size_t value ) \n{\n ...\n}\n ::size_t std::size_t" }, { "answer_id": 1238084, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 2, "selected": false, "text": "std::size_t n = sizeof( long );\n size_t foo()\n{\n return sizeof( long );\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
237,377
<p>Is there a better way to do this?</p> <pre><code>string[] s = {"zero", "one", "two", "three", "four", "five"}; var x = s .Select((a,i) =&gt; new {Value = a, Index = i}) .Where(b =&gt; b.Value.StartsWith("t")) .Select(c =&gt; c.Index); </code></pre> <p>i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria.</p>
[ { "answer_id": 237379, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 3, "selected": false, "text": ".Select((Value, Index) => new {Value, Index})\n" }, { "answer_id": 237451, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "string[] s = {\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\"};\nList<int> matchingIndices = new List<int>();\n\nfor (int i = 0; i < s.Length; ++i) \n{\n if (s[i].StartWith(\"t\"))\n {\n matchingIndices.Add(i);\n }\n}\n" }, { "answer_id": 237685, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)\n{\n int index=0;\n foreach (T element in source)\n {\n if (predicate(element))\n {\n yield return index;\n }\n index++;\n }\n}\n string[] s = {\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\"};\nvar x = s.IndexesWhere(t => t.StartsWith(\"t\"));\n" }, { "answer_id": 1036228, "author": "Terrence", "author_id": 84522, "author_profile": "https://Stackoverflow.com/users/84522", "pm_score": 1, "selected": false, "text": "var x = s.Select((a, i) => i).Where(i => s[i].StartsWith(\"t\"));\n" }, { "answer_id": 7829692, "author": "MPelletier", "author_id": 210916, "author_profile": "https://Stackoverflow.com/users/210916", "pm_score": 0, "selected": false, "text": "IEnumerable<T> foreach foreach foreach public static int[] GetIndexes<T>(this T[]source, Func<T, bool> predicate)\n{\n List<int> matchingIndexes = new List<int>();\n\n for (int i = 0; i < source.Length; ++i) \n {\n if (predicate(source[i]))\n {\n matchingIndexes.Add(i);\n }\n }\n return matchingIndexes.ToArray();\n}\n List.ToArray" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
237,383
<p>Is possible to insert a line break where the cursor is in Vim without entering into insert mode? Here's an example (<code>[x]</code> means cursor is on <code>x</code>):</p> <pre><code>if (some_condition) {[ ]return; } </code></pre> <p>Occasionally, I might want to enter some more code. So I'd press <kbd>i</kbd> to get into insert mode, press <kbd>Enter</kbd> to insert the line break and then delete the extra space. Next, I'd enter normal mode and position the cursor before the closing brace and then do the same thing to get it on its own line.</p> <p>I've been doing this a while, but there's surely a better way to do it?</p>
[ { "answer_id": 237436, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 4, "selected": false, "text": ":map g i[Ctrl+V][Enter][Ctrl+V][Esc][Enter]\n :map g i^M^[\n f}i^M^[O" }, { "answer_id": 237471, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 1, "selected": false, "text": "autoindent s i cw" }, { "answer_id": 237512, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": -1, "selected": false, "text": ":map g ^f{malr<CR>`a%hr<CR>`a\n" }, { "answer_id": 237522, "author": "slothbear", "author_id": 2464, "author_profile": "https://Stackoverflow.com/users/2464", "pm_score": 3, "selected": false, "text": ":s/{/{\\r/\n :map <F7> :s/{/{\\r/ ^M :s/}/\\r}/ ^M\n :help map-which-keys" }, { "answer_id": 941991, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": ":nmap <c-cr> i<cr><Esc>" }, { "answer_id": 6881163, "author": "Kiddo", "author_id": 804202, "author_profile": "https://Stackoverflow.com/users/804202", "pm_score": 0, "selected": false, "text": ":map <C-m> i<CR><Esc>h\n" }, { "answer_id": 29820351, "author": "Hotschke", "author_id": 1057593, "author_profile": "https://Stackoverflow.com/users/1057593", "pm_score": 0, "selected": false, "text": "gs nmap gs i<CR><ESC>\n" }, { "answer_id": 35784669, "author": "ctrl", "author_id": 3701295, "author_profile": "https://Stackoverflow.com/users/3701295", "pm_score": 1, "selected": false, "text": "\"Have K split lines the way J joins lines\nnnoremap <expr>K getline('.')[col('.')-1]==' ' ? \"r<CR>\" : \"i<CR><Esc>\"\n <expr> getline('.')[col('.')-1]==' ' ? : r<CR> i<CR><Esc> J" }, { "answer_id": 40598115, "author": "mondaugen", "author_id": 1082233, "author_profile": "https://Stackoverflow.com/users/1082233", "pm_score": 2, "selected": false, "text": "K ' :nmap K m'a<CR><Esc>`'\n" }, { "answer_id": 43011315, "author": "Nathan", "author_id": 7764790, "author_profile": "https://Stackoverflow.com/users/7764790", "pm_score": 1, "selected": false, "text": ": s/\\s/\\r/g" }, { "answer_id": 43712932, "author": "Yarden Akin", "author_id": 6422027, "author_profile": "https://Stackoverflow.com/users/6422027", "pm_score": 1, "selected": false, "text": "aaa bbb ccc ddd\n aaa\nbbb\nccc\nddd\n f r<ENTER>;.;.\n" }, { "answer_id": 53782580, "author": "JaredMcAteer", "author_id": 577926, "author_profile": "https://Stackoverflow.com/users/577926", "pm_score": 0, "selected": false, "text": "J nnoremap S i<cr><esc>^mwgk:silent! s/\\v +$//<cr>:noh<cr>`w\n w w" }, { "answer_id": 62144795, "author": "logbasex", "author_id": 10393067, "author_profile": "https://Stackoverflow.com/users/10393067", "pm_score": 1, "selected": false, "text": "o ESC" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103052/" ]
237,408
<p>I have a local Git repository I've been developing under for a few days: it has eighteen commits so far. Tonight, I created a private Github repository I was hoping to push it to; however, when I did so, it only ended up pushing eight of the eighteen commits to Github. I deleted the Github repo and retried, with the same result.</p> <p>Any thoughts on why this might be happening? I've done this procedure before without a few times successfully, so I'm a bit stumped.</p> <p><strong>Update</strong>: There is, and has always been, only the master branch in this repo. Just to address a few of the posted answers...</p>
[ { "answer_id": 237409, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "git fsck" }, { "answer_id": 237517, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "gitk --all" }, { "answer_id": 276409, "author": "farktronix", "author_id": 677, "author_profile": "https://Stackoverflow.com/users/677", "pm_score": 5, "selected": true, "text": "git checkout [commit id] -- D -- E -- F\n / ^\n A -- B -- C - |\n ^ ^ HEAD\n | |\n remote master\n A C remote C D F $ git branch\n* (no branch)\nmaster\n master F git checkout -b tmp tmp F master tmp git checkout master git merge tmp master F git branch -d tmp" }, { "answer_id": 276418, "author": "farktronix", "author_id": 677, "author_profile": "https://Stackoverflow.com/users/677", "pm_score": 1, "selected": false, "text": "gitk --all gitk HEAD master" }, { "answer_id": 276495, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "git checkout -B master\n -b -B master master master git branch -D master\n master git checkout -b master\n master HEAD master HEAD master master" }, { "answer_id": 495945, "author": "Matthew Maravillas", "author_id": 2186, "author_profile": "https://Stackoverflow.com/users/2186", "pm_score": 0, "selected": false, "text": "git rebase -i git commit --amend git commit -a git rebase --continue" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23498/" ]
237,415
<p>I'm attempting to use LINQ to insert a record into a child table and I'm receiving a "Specified cast is not valid" error that has something to do w/ the keys involved. The stack trace is:</p> <blockquote> <p>Message: Specified cast is not valid.</p> <p>Type: System.InvalidCastException Source: System.Data.Linq TargetSite: Boolean TryCreateKeyFromValues(System.Object[], V ByRef) HelpLink: null Stack: at System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager<code>2.TryCreateKeyFromValues(Object[] values, V&amp; v) at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache</code>2.Find(Object[] keyValues) at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues) at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues) at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) at System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges()</p> <p>(.....)</p> </blockquote> <p>This error is being thrown on the following code:</p> <pre><code> ResponseDataContext db = new ResponseDataContext(m_ConnectionString); CodebookVersion codebookVersion = db.CodebookVersions.Single(cv =&gt; cv.VersionTag == m_CodebookVersionTag); ResponseCode rc = new ResponseCode() { SurveyQuestionName = "Q11", Code = 3, Description = "Yet another code" }; codebookVersion.ResponseCodes.Add(rc); db.SubmitChanges(); //exception gets thrown here </code></pre> <p>The tables in question have a FK relationship between the two of them.<br> The parent table's column is called 'id', is the PK, and is of type: INT NOT NULL IDENTITY<br> The child table's column is called 'responseCodeTableId' and is of type: INT NOT NULL.</p> <p>codebookVersion (parent class) maps to table tblResponseCodeTable<br> responseCode (childClass) maps to table tblResponseCode</p> <p>If I execute SQL directly, it works. e.g. </p> <pre><code>INSERT INTO tblResponseCode (responseCodeTableId, surveyQuestionName, code, description) VALUES (13683, 'Q11', 3, 'Yet another code') </code></pre> <p>Updates to the same class work properly. e.g. </p> <pre><code>codebookVersion.ResponseCodes[0].Description = "BlahBlahBlah"; db.SubmitChanges(); //no exception - change is committed to db </code></pre> <p>I've examined the variable, rc, after the .Add() operation and it does, indeed, receive the proper responseCodeTableId, just as I would expect since I'm adding it to that collection.</p> <pre><code>tblResponseCodeTable's full definition: COLUMN_NAME TYPE_NAME id int identity responseCodeTableId int surveyQuestionName nvarchar code smallint description nvarchar dtCreate smalldatetime </code></pre> <p>dtCreate has a default value of GetDate().</p> <p>The only other bit of useful information that I can think of is that no SQL is ever tried against the database, so LINQ is blowing up before it ever tries (hence the error not being a SqlException). I've profiled and verified that no attempt is made to execute any statements on the database.</p> <p>I've read around and seen the problem when you have a relationship to a non PK field, but that doesn't fit my case.</p> <p>Can anyone shed any light on this situation for me? What incredibly obvious thing am I missing here? </p> <p>Many thanks.<br> Paul Prewett</p>
[ { "answer_id": 237426, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "ResponseCode rc = new ResponseCode()\n {\n SurveyQuestionName = \"Q11\",\n Code = 3,\n Description = \"Yet another code\"\n };\n INSERT INTO tblResponseCode \n(responseCodeTableId, surveyQuestionName, code, description)\nVALUES (13683, 'Q11', 3, 'Yet another code')\n" }, { "answer_id": 237427, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "codebookVersion.ResponseCodes.Add(rc);\ndb.SubmitChanges(); //exception gets thrown here\n InsertOnSubmit Add codebookVersion.ResponseCodes.InsertOnSubmit(rc);\n Add" }, { "answer_id": 237459, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "ResponseCode rc = new ResponseCode();\n\nrc.SurveyQuestName = \"Q11\";\nrc.Code = 3;\nrc.Description = \"Yet Another Code\";\n" }, { "answer_id": 237484, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "tblResponseTable definition (which maps to CodebookVersion)\nCOLUMN_NAME TYPE_NAME\nid int identity\nversionTag nvarchar\nresponseVersionTag nvarchar\n" }, { "answer_id": 238051, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "[Table(Name=\"dbo.tblResponseCode\")]\npublic partial class ResponseCode : ...\n ...\n [Association(Name=\"CodebookVersion_tblResponseCode\", Storage=\"_CodebookVersion\", ThisKey=\"ResponseCodeTableId\", OtherKey=\"Id\", IsForeignKey=true)]\n public CodebookVersion CodebookVersion\n {\n ...\n }\n\n[Table(Name=\"dbo.tblResponseCodeTable\")]\n public partial class CodebookVersion : ...\n ...\n [Association(Name=\"CodebookVersion_tblResponseCode\", Storage=\"_ResponseCodes\", ThisKey=\"Id\", OtherKey=\"ResponseCodeTableId\")]\n public EntitySet<ResponseCode> ResponseCodes\n {\n ...\n }\n" }, { "answer_id": 238121, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "ResponseCode rc = new ResponseCode()\n{\n CodebookVersion = codebookVersion,\n SurveyQuestionName = \"Q11\",\n Code = 3,\n Description = \"Yet another code\"\n};\ndb.ResponseCodes.InsertOnSubmit(rc);\ndb.SubmitChanges();\n" }, { "answer_id": 313104, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " ResponseDataContext db = new ResponseDataContext(m_ConnectionString);\n CodebookVersion codebookVersion = db.CodebookVersions.Single(cv => cv.VersionTag == m_CodebookVersionTag); \n ResponseCode rc = new ResponseCode()\n { \n ResponseCodeTableId = codebookVersion.Id, \n SurveyQuestionName = \"Q11\", \n Code = 3, \n Description = \"Yet another code\"\n };\n db.ResponseCodes.InsertOnSubmit(rc);\n db.SubmitChanges();\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,423
<p>I have written this generator code but it returns 'can't convert nil into String' when I call m.directory inside the manifest. Anyone know what had happened?</p> <pre><code>class AuthGenerator &lt; Rails::Generator::NamedBase attr_reader :user_class_name def initialize(runtime_args, runtime_options={}) @user_class_name="User" @controller_class_name="AccountController" @user_class_file_name="#{@user_class_name}.rb" @controller_class_file_name="#{@controller_class_name}.rb" end def manifest record do |m| m.class_collisions @controller_class_name, @user_class puts @user_class_name m.directory File.join('app/models', @user_class_name) end end </code></pre> <p>end</p>
[ { "answer_id": 238252, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 1, "selected": false, "text": "directory m.directory File.join('app/models')\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16371/" ]
237,425
<p>What are the coolest examples of metaprogramming that you've seen in C++?<br> What are some practical uses of metaprogramming that you've seen in C++?</p>
[ { "answer_id": 237499, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 5, "selected": false, "text": " void SomeMethod(IFoo* pFoo) {\n CFooImpl *p = (CFooImpl)pFoo;\n }\n template <typename T>\nCComPtr<T>& operator=(const T* pT) { \n// CComPTr Assign logic\n}\ntemplate <>\nCComPtr<IFoo> operator=<IFoo>(const IFoo* pT) {\n COMPILE_ERROR();\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
237,432
<p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p> <pre><code>class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44 </code></pre> <p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p> <pre><code>age = property(lambda self: self._get_age()) </code></pre> <p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
[ { "answer_id": 237461, "author": "Kozyarchuk", "author_id": 52490, "author_profile": "https://Stackoverflow.com/users/52490", "pm_score": 2, "selected": false, "text": "class HackedProperty(object):\n def __init__(self, f):\n self.f = f\n def __get__(self, inst, owner): \n return getattr(inst, self.f.__name__)()\n\nclass Foo(object):\n def _get_age(self):\n return 11\n age = HackedProperty(_get_age)\n\nclass Bar(Foo):\n def _get_age(self):\n return 44\n\nprint Bar().age\nprint Foo().age\n" }, { "answer_id": 237858, "author": "piro", "author_id": 10138, "author_profile": "https://Stackoverflow.com/users/10138", "pm_score": 7, "selected": true, "text": "property() @classmethod property class Foo(object):\n @property\n def age(self):\n return 11\n\nclass Bar(Foo):\n @property\n def age(self):\n return 44\n setter deleter class C(object):\n @property\n def x(self):\n return self._x\n\n @x.setter\n def x(self, value):\n self._x = value\n" }, { "answer_id": 291707, "author": "Kamil Kisiel", "author_id": 15061, "author_profile": "https://Stackoverflow.com/users/15061", "pm_score": 4, "selected": false, "text": "class Foo(object):\n def _get_age(self):\n return 11\n\n def _set_age(self, age):\n self._age = age\n\n age = property(_get_age, _set_age)\n\n\nclass Bar(Foo):\n def _get_age(self):\n return 44\n\n age = property(_get_age, Foo._set_age)\n" }, { "answer_id": 14349742, "author": "Mr. B", "author_id": 712522, "author_profile": "https://Stackoverflow.com/users/712522", "pm_score": 4, "selected": false, "text": "lambda self: self.<property func> class Foo(object):\n def _get_meow(self):\n return self._meow + ' from a Foo'\n def _set_meow(self, value):\n self._meow = value\n meow = property(fget=lambda self: self._get_meow(),\n fset=lambda self, value: self._set_meow(value))\n class Bar(Foo):\n def _get_meow(self):\n return super(Bar, self)._get_meow() + ', altered by a Bar'\n >>> foo = Foo()\n>>> bar = Bar()\n>>> foo.meow, bar.meow = \"meow\", \"meow\"\n>>> foo.meow\n\"meow from a Foo\"\n>>> bar.meow\n\"meow from a Foo, altered by a Bar\"\n" }, { "answer_id": 30600839, "author": "andrew pate", "author_id": 2668869, "author_profile": "https://Stackoverflow.com/users/2668869", "pm_score": 0, "selected": false, "text": "import threading\n\n\nclass Foo(object):\n def __init__(self):\n self._age = 0\n\n def _get_age(self):\n return self._age\n\n def _set_age(self, age):\n self._age = age\n\n age = property(_get_age, _set_age)\n\n\nclass ThreadsafeFoo(Foo):\n\n def __init__(self):\n super(ThreadsafeFoo, self).__init__()\n self.__lock = threading.Lock()\n self.wrinkled = False\n\n def _get_age(self):\n with self.__lock:\n return super(ThreadsafeFoo, self).age\n\n def _set_age(self, value):\n with self.__lock:\n self.wrinkled = True if value > 40 else False\n super(ThreadsafeFoo, self)._set_age(value)\n\n age = property(_get_age, _set_age)\n" }, { "answer_id": 37355919, "author": "Nizam Mohamed", "author_id": 4522780, "author_profile": "https://Stackoverflow.com/users/4522780", "pm_score": 2, "selected": false, "text": "class Foo(object):\n def _get_meow(self):\n return self._meow + ' from a Foo'\n def _set_meow(self, value):\n self._meow = value\n @property\n def meow(self):\n return self._get_meow()\n @meow.setter\n def meow(self, value):\n self._set_meow(value)\n class Bar(Foo):\n def _get_meow(self):\n return super(Bar, self)._get_meow() + ', altered by a Bar'\n" }, { "answer_id": 57619695, "author": "Robin", "author_id": 9610758, "author_profile": "https://Stackoverflow.com/users/9610758", "pm_score": -1, "selected": false, "text": "class Foo:\n # Template method\n @property\n def age(self):\n return self.dothis()\n # Hook method of TM is accessor method of property at here\n def dothis(self):\n return 11\nclass Bar(Foo):\n def dothis(self):\n return 44\n" }, { "answer_id": 59594225, "author": "Vladimir Zolotykh", "author_id": 4422949, "author_profile": "https://Stackoverflow.com/users/4422949", "pm_score": 2, "selected": false, "text": "class Foo:\n def __init__(self, age):\n self.age = age\n\n @property\n def age(self):\n print('Foo: getting age')\n return self._age\n\n @age.setter\n def age(self, value):\n print('Foo: setting age')\n self._age = value\n\n\nclass Bar(Foo):\n def __init__(self, age):\n self.age = age\n\n @property\n def age(self):\n return super().age\n\n @age.setter\n def age(self, value):\n super(Bar, Bar).age.__set__(self, value)\n\nif __name__ == '__main__':\n f = Foo(11)\n print(f.age)\n b = Bar(44)\n print(b.age)\n Foo: setting age\nFoo: getting age\n11\nFoo: setting age\nFoo: getting age\n44\n" }, { "answer_id": 67559102, "author": "Bastian Ebeling", "author_id": 617339, "author_profile": "https://Stackoverflow.com/users/617339", "pm_score": 0, "selected": false, "text": "class Foo:\n def __init__(self, age):\n self.age = age\n\n @property\n def age(self):\n print(\"Foo: getting age\")\n return self._age\n\n @age.setter\n def age(self, value):\n print(\"Foo: setting age\")\n self._age = value\n\n\nclass Bar(Foo):\n def __init__(self, age):\n super().__init__(age)\n\n\nif __name__ == \"__main__\":\n a = Foo(11)\n print(a.age)\n b = Bar(44)\n print(b.age)\n Foo: setting age\nFoo: getting age\n11\nFoo: setting age\nFoo: getting age\n44\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720/" ]
237,440
<p>I have a problem whereby I want to display a view differently (a different master page), depending on where it came from, but don't know where to start...</p> <p>I have several routes which catch various different types of urls that contain different structures.</p> <p>In the code snippet below, I have a product route, and then I have a partner site route which could also go to a product page, but let's say that this partner is Pepsi, and they want their branding on the master page, rather than our own default styling. Lets say I go to <a href="http://mysite.com/products/cola.htm" rel="nofollow noreferrer">products/cola.htm</a>. This should go to the same url as <a href="http://mysite.com/partners/pepsi/products/cola.htm" rel="nofollow noreferrer">partners/pepsi/products/cola.htm</a>, and the PartnerRedirect would be able to handle the url based on the wildcard, by translating the url wildcard (in this case, "products/cola.htm") into a controller action, and forward the user on, (but simply change the master page in the view).</p> <pre><code>routes.MapRoute( "Product", "products/{product}.htm", new { controller = "Product", action = "ShowProduct" } ); routes.MapRoute( "ProductReview", "products/{product}/reviews.htm", new { controller = "Product", action = "ShowProductReview" } ); routes.MapRoute( "Partner", "partners/{partner}/{*wildcard}", new { controller = "Partners", action = "PartnerRedirect" } ); </code></pre> <p>Is this possible? And if so, how?</p> <p>Many thanks in advance.</p>
[ { "answer_id": 362423, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public class FriViewPage : ViewPage\n{\n public override string MasterPageFile\n {\n get\n {\n return \"~/Views/Shared/Site.Master\"; // base.MasterPageFile;\n }\n set\n {\n if (ViewData[\"agent\"].ToString() == \"steve\")\n base.MasterPageFile = \"~/Views/Shared/Site.Master\";\n else\n base.MasterPageFile = \"~/Views/Shared/Site2.Master\";\n }\n }\n}\n" }, { "answer_id": 364718, "author": "Matthew", "author_id": 20162, "author_profile": "https://Stackoverflow.com/users/20162", "pm_score": 0, "selected": false, "text": "public ActionResult TestMP(int? id)\n{\n ViewData[\"Title\"] = \"MasterPage Test Page\";\n ViewData[\"Message\"] = \"Welcome to ASP.NET MVC!\";\n ViewResult result = View(\"Index\");\n if (id.HasValue)\n {\n result.MasterName = \"Site2\";\n }\n return result;\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31532/" ]
237,464
<p>Many languages have a facility to check to see if an Object is of a certain type (including parent subclasses), implemented with 'is' and used like this:</p> <pre><code>if(obj is MyType) </code></pre> <p>Or slightly more tediously you can in other languages check by using the 'as' keyword to do a soft typecast and seeing if the result null. </p> <p>I haven't used Java in years and I'm getting back up to speed on it but surely Java has a way to easily do this without delving deep into the Reflection APIs?</p> <p>Thanks in advance for answers. I have searched both here and other places but the keywords involved are so generic that even though I'm sure this has a simple answer, googling for it is hard.</p>
[ { "answer_id": 237467, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "if (objectReference instanceof type){\n //Your code goes here\n}\n" }, { "answer_id": 237469, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 1, "selected": false, "text": "obj instanceof TargetType TargetType obj" }, { "answer_id": 238007, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 3, "selected": false, "text": "instanceof Class type = String.class;\n\nif (myObj instanceof String) // will compile\n\nif (myObj instanceof type) //will not compile\n Class.isInstance if (type.isInstance(myObj)) // will compile\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,487
<p>I am working with a peripheral device that needs to be communicated through serial. I can send it commands using HyperTerminal, but now I need to write programs that will let me do it without HyperTerminal. Can somebody point me to a website and/or show me a sample hello world program to get me started? I have searched through many sites which give me uncompilable/ancient VC6 code.</p>
[ { "answer_id": 237491, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "CreateFile() ReadFile() WriteFile() fopen() fread() fwrite()" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,542
<p>I'm using GCC; __FILE__ returns the current source file's entire path and name: <code>/path/to/file.cpp</code>. Is there a way to get just the file's name <code>file.cpp</code> (without its path) at compile time? Is it possible to do this in a portable way? Can template meta programming be applied to strings?</p> <p>I am using this in an error logging macro. I really do not want my source's full path making its way into the executable.</p>
[ { "answer_id": 237563, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 3, "selected": false, "text": "#line 1 \"filename.c\"\n __FILE__ __FILE__" }, { "answer_id": 237633, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "#define LOG(message) _log(__FILE__, message)\n\nvoid _log(file, message)\n{\n #ifndef DEBUG\n strippath(file); // in some suitable way\n #endif\n\n cerr << \"Log: \" << file << \": \" << message; // or whatever\n}\n" }, { "answer_id": 237635, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": true, "text": "make gcc makefile file.o: file.c\n gcc -c -o file.o src/file.c\n file.o: src/file.c\n gcc \"-DMYFILE=\\\"`basename $<`\\\"\" -c -o file.o src/file.c\n MYFILE __FILE__ basename $< .c.o makefile mainprog: main.o makefile\n gcc -o mainprog main.o\n\nmain.o: src/main.c makefile\n gcc \"-DMYFILE=\\\"`basename $<`\\\"\" -c -o main.o src/main.c\n src/main.c #include <stdio.h>\n\nint main (int argc, char *argv[]) {\n printf (\"file = %s\\n\", MYFILE);\n return 0;\n}\n pax:~$ mainprog\nfile = main.c\n file =" }, { "answer_id": 238528, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\nint main(void)\n{\n puts(__FILE__);\n return(0);\n}\n gcc -o x x.c && ./x\n x.c gcc -o x $PWD/x.c && ./x\n /work1/jleffler/tmp/x.c gcc -o x ../tmp/x.c && ./x\n ../tmp/x.c" }, { "answer_id": 238538, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "#line 1 MY_FILE_NAME\n#include <stdio.h>\n\nint main(void)\n{\n puts(__FILE__);\n return(0);\n}\n gcc -DMY_FILE_NAME='\"abcd.c\"' -o x x.c\n abcd.c" }, { "answer_id": 305927, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 1, "selected": false, "text": "__FILE__" }, { "answer_id": 2250739, "author": "tHeDoc", "author_id": 271711, "author_profile": "https://Stackoverflow.com/users/271711", "pm_score": 0, "selected": false, "text": "static char * file_bname = NULL;\n#define __STRIPPED_FILE__ (file_bname ?: (file_bname = basename(__FILE__)))\n" }, { "answer_id": 22161316, "author": "fenugrec", "author_id": 3377192, "author_profile": "https://Stackoverflow.com/users/3377192", "pm_score": 3, "selected": false, "text": "set(SRCS a/a.cpp b/b.cpp c/c.cpp d/d.cpp)\n\nforeach(f IN LISTS SRCS)\n get_filename_component(b ${f} NAME)\n set_source_files_properties(${f} PROPERTIES\n COMPILE_DEFINITIONS \"MYSRCNAME=${b}\")\nendforeach()\n\nadd_executable(foo ${SRCS})\n COMPILE_DEFINITIONS \"MYSRCNAME=\\\"${b}\\\"\")\n" }, { "answer_id": 54377777, "author": "puchu", "author_id": 404949, "author_profile": "https://Stackoverflow.com/users/404949", "pm_score": 2, "selected": false, "text": "DefineRelativeFilePaths.cmake function (cmake_define_relative_file_paths SOURCES)\n foreach (SOURCE IN LISTS SOURCES)\n file (\n RELATIVE_PATH RELATIVE_SOURCE_PATH\n ${PROJECT_SOURCE_DIR} ${SOURCE}\n )\n\n set_source_files_properties (\n ${SOURCE} PROPERTIES\n COMPILE_DEFINITIONS __RELATIVE_FILE_PATH__=\"${RELATIVE_SOURCE_PATH}\"\n )\n endforeach ()\nendfunction ()\n CMakeLists.txt set (SOURCES ${SOURCES}\n \"${CMAKE_CURRENT_SOURCE_DIR}/common.c\"\n \"${CMAKE_CURRENT_SOURCE_DIR}/main.c\"\n)\n\ninclude (DefineRelativeFilePaths)\ncmake_define_relative_file_paths (\"${SOURCES}\")\n cmake .. && make clean && make VERBOSE=1 cc ... -D__RELATIVE_FILE_PATH__=\"src/main.c\" ... -c src/main.c\n #define ..._LOG_HEADER(target) \\\n fprintf(target, \"%s %s:%u - \", __func__, __RELATIVE_FILE_PATH__, __LINE__);\n config.h.in config.h #ifndef __RELATIVE_FILE_PATH__\n#define __RELATIVE_FILE_PATH__ __FILE__\n#endif\n" }, { "answer_id": 64107772, "author": "Akira Cleber Nakandakare", "author_id": 1669975, "author_profile": "https://Stackoverflow.com/users/1669975", "pm_score": 2, "selected": false, "text": "__FILE__ __BASE_FILE__ __builtin_FILE() -fmacro-prefix-map=\"../Sources/\"=." } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
237,553
<p>Google chrome doesn't behave the same as other browsers when encountering this nugget:</p> <pre><code>&lt;?php while (true) { echo "&lt;script type='text/javascript'&gt;\n"; echo "alert('hello');\n"; echo "&lt;/script&gt;"; flush(); sleep(5); } ?&gt; </code></pre> <p>It seems that it's waiting for the connection to terminate before doing anything.</p> <p>Other than polling how can I do a similar thing in Google Chrome?</p>
[ { "answer_id": 237616, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 1, "selected": false, "text": "</script> <script>" }, { "answer_id": 796691, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<?php\n$i = 0;\nwhile (true) {\n if($i == 0) {\n echo \"<html><body>\";\n }\n echo \"<script type='text/javascript'>\\n\";\n echo \"alert('hello');\\n\";\n echo \"</script>\";\n if($i == 0 ) {\n $padstr = str_pad(\"\",2048,\"&nbsp;\");\n echo $padstr;\n echo \"</body></html>\";\n }\n flush();\n\n sleep(5);\n $i = $i + 1;\n}\n?>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
237,561
<p>Edit: This code is fine. I found a logic bug somewhere that doesn't exist in my pseudo code. I was blaming it on my lack of Java experience.</p> <p>In the <strong>pseudo code</strong> below, I'm trying to parse the XML shown. A silly example maybe but my code was too large/specific for anyone to get any real value out of seeing it and learning from answers posted. So, this is more entertaining and hopefully others can learn from the answer as well as me.</p> <p>I'm new to Java but an experienced C++ programmer which makes me believe my problem lies in my understanding of the Java language.</p> <p>Problem: When the parser finishes, my Vector is full of uninitialized Cows. I create the Vector of Cows with a default capacity (which shouldn't effect it's "size" if it's anything like C++ STL Vector). When I print the contents of the Cow Vector out after the parse, it gives the right size of Vector but all the values appear never to have been set.</p> <p>Info: I have successfully done this with other parsers that don't have Vector <em>fields</em> but in this case, I'd like to use a Vector to accumulate Cow properties.</p> <p>MoreInfo: I can't use generics (Vector&lt; Cow >) so please don't point me there. :)</p> <p>Thanks in advance.</p> <pre><code>&lt;pluralcow&gt; &lt;cow&gt; &lt;color&gt;black&lt;/color&gt; &lt;age&gt;1&lt;/age&gt; &lt;/cow&gt; &lt;cow&gt; &lt;color&gt;brown&lt;/color&gt; &lt;age&gt;2&lt;/age&gt; &lt;/cow&gt; &lt;cow&gt; &lt;color&gt;blue&lt;/color&gt; &lt;age&gt;3&lt;/age&gt; &lt;/cow&gt; &lt;/pluralcow&gt; public class Handler extends DefaultHandler{ // vector to store all the cow knowledge private Vector m_CowVec; // temp variable to store cow knowledge until // we're ready to add it to the vector private Cow m_WorkingCow; // flags to indicate when to look at char data private boolean m_bColor; private boolean m_bAge; public void startElement(...tag...) { if(tag == pluralcow){ // rule: there is only 1 pluralcow tag in the doc // I happen to magically know how many cows there are here. m_CowVec = new Vector(numcows); }else if(tag == cow ){ // rule: multiple cow tags exist m_WorkingCow = new Cow(); }else if(tag == color){ // rule: single color within cow m_bColor = true; }else if(tag == age){ // rule: single age within cow m_bAge = true; } } public void characters(...chars...) { if(m_bColor){ m_WorkingCow.setColor(chars); }else if(m_bAge){ m_WorkingCow.setAge(chars); } } public void endElement(...tag...) { if(tag == pluralcow){ // that's all the cows }else if(tag == cow ){ m_CowVec.addElement(m_WorkingCow); }else if(tag == color){ m_bColor = false; }else if(tag == age){ m_bAge = false; } } } </code></pre>
[ { "answer_id": 237596, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": true, "text": "characters() setColor() setAge()" }, { "answer_id": 237774, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 2, "selected": false, "text": "public void startElement(...tag...)\n {\n if(tag == pluralcow){ // rule: there is only 1 pluralcow tag in the doc\n // I happen to magically know how many cows there are here. \n m_CowVec = new Vector(numcows);\n }else if(tag == cow ){ // rule: multiple cow tags exist\n m_WorkingCow = new Cow();\n }else if(tag == color){ // rule: single color within cow\n m_bColor = true;\n }else if(tag == age){ // rule: single age within cow\n m_bAge = true;\n }\n }\n public void characters(...chars...)\n{\n if(m_bColor){\n m_WorkingCow.setColor(chars); \n }else if(m_bAge){\n m_WorkingCow.setAge(chars);\n }\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22917/" ]
237,585
<p>At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)</p>
[ { "answer_id": 237892, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 4, "selected": false, "text": "catch(ExistingException e) {\n if({condition}) {\n { some stuff here}\n }\n else {\n { different stuff here}\n }\n}\n interface MyInterface {\n void methodA();\n}\n\nclass MyImplA {\n void methodA() throws SQLException { ... }\n}\n\nclass MyImplB {\n void methodA() throws IOException { ... }\n}\n" }, { "answer_id": 237934, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 3, "selected": false, "text": "catch (Exception e) {\n ...\n}\n try {\n if(myShape.isHidden()) {\n throw new Exception();\n }\n // More logic\n} catch (Exception e) {\n MyApp.notify(\"Can't munge a hidden shape\");\n}\n" }, { "answer_id": 238322, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "DataFormatException" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30323/" ]
237,621
<p>I'm new with Objective-C, so there probably is a simple solution to this.</p> <p>I want a number to increment, but each iteration to be show on a label. (for example, it shows 1, 2, 3, 4, 5... displayed apart by an amount of time).</p> <p>I tried:</p> <pre><code>#import "testNums.h" @implementation testNums - (IBAction)start:(id)sender { int i; for(i = 0; i &lt; 10; ++i) { [outputNum setIntValue:i]; sleep(1); } } @end </code></pre> <p>and all it did was wait for 9 seconds (apparently frozen) and then displayed 9 in the text box.</p>
[ { "answer_id": 237629, "author": "jtbandes", "author_id": 23649, "author_profile": "https://Stackoverflow.com/users/23649", "pm_score": 2, "selected": false, "text": "NSTimer" }, { "answer_id": 237683, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 4, "selected": true, "text": "NSTimer - (IBAction) start:(id)sender {\n [self performSelector:@selector(updateTextFieldWithNumber:) withObject:[NSNumber numberWithInt:0] afterDelay:1.0];\n}\n\n- (void) updateTextFieldWithNumber:(NSNumber *)num {\n int i = [num intValue];\n [outputField setIntValue:i];\n if (i < 10)\n [self performSelector:@selector(updateTextFieldWithNumber:) withObject:[NSNumber numberWithInt:++i] afterDelay:1.0];\n}\n @interface TestNums: NSObject\n{\n IBOutlet NSTextField *outputField;\n NSTimer *timer;\n int currentNumber;\n}\n\n@end\n\n@implementation TestNums\n\n- (IBAction) start:(id)sender {\n timer = [[NSTimer scheduledTimerWithTimeInterval:1.0\n target:self\n selector:@selector(updateTextField:)\n userInfo:nil\n repeats:YES] retain];\n\n //Set the field's value immediately to 0\n currentNumber = 0;\n [outputField setIntValue:currentNumber];\n}\n\n- (void) updateTextField:(NSTimer *)timer {\n [outputField setIntValue:++currentNumber];\n}\n\n@end\n currentNumber @interface TestNums: NSObject\n{\n //NOTE: No outlet this time.\n NSTimer *timer;\n int currentNumber;\n}\n\n@property int currentNumber;\n\n@end\n\n@implementation TestNums\n\n@synthesize currentNumber;\n\n- (IBAction) start:(id)sender {\n timer = [[NSTimer scheduledTimerWithTimeInterval:1.0\n target:self\n selector:@selector(updateTextField:)\n userInfo:nil\n repeats:YES] retain];\n\n //Set the field's value immediately to 0\n self.currentNumber = 0;\n}\n\n- (void) updateTextField:(NSTimer *)timer {\n self.currentNumber = ++currentNumber;\n}\n\n@end\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31549/" ]
237,631
<p>I have two PHP files that I need to link. How can I link the files together using PHP? The effect I want is to have the user click a button, some information is proccessed on the page, and then the result is displayed in a different page, depending on the button the user clicked.Thanks</p>
[ { "answer_id": 237637, "author": "jtbandes", "author_id": 23649, "author_profile": "https://Stackoverflow.com/users/23649", "pm_score": 3, "selected": false, "text": "<form method=\"post\" action=\"other_file.php\">\n <input name=\"foo\" type=\"...\"... /> ...\n</form>\n $_POST[\"foo\"]" }, { "answer_id": 237680, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 0, "selected": false, "text": " if (isset($_POST['foo'])) { ... }\n if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }\n" }, { "answer_id": 237838, "author": "noob source", "author_id": 29838, "author_profile": "https://Stackoverflow.com/users/29838", "pm_score": 3, "selected": true, "text": "<?php\n\nif ($_SERVER['REQUEST_METHOD'] == 'POST') {\n switch ($_POST['command']) {\n case 'show_file_1':\n include 'file_1.php';\n break;\n case 'show_file_2':\n include 'file_2.php';\n break;\n } \n exit;\n} \n\n?>\n<form method=\"POST\">\n <button name=\"command\" value=\"show_file_1\">Show file 1</button>\n <button name=\"command\" value=\"show_file_2\">Show file 2</button>\n</form>\n <html> <head> <body> include include 'file_1.php';\n header('Location: http://mysite.com/file_1.php');\n ; : ; case 'show_file_1' case 'show_file_2'" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24391/" ]
237,675
<p>Here's what I am trying to do:</p> <p>Select text from a webpage I pulled up using my web browser control.After clicking a button while this text is still selected I would like a message box to pop-up displaying the text that was highlighted by the user. How do I get this functionality to work in my wpf application?</p> <p>I think I'm on the right track using mshtml but I get an error that says:</p> <blockquote> <p>Error HRESULT E_FAIL has been returned from a call to a COM component.</p> </blockquote> <p>This error will happen even when I try something small on the document like changing the title.</p> <p>The code is below:</p> <pre><code>IHTMLDocument2 doc = (IHTMLDocument2)this.webBookText.Document; doc.title = "l"; </code></pre>
[ { "answer_id": 237710, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "WebBrowser WebBrowser webBook.Document.Title = \"foo\";\n .Document.ActiveElement" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,691
<p>I been waiting for sometime now to bring my Asp.net Preview 4 project up to snuff, totally skipping Preview 5 just because I knew I would have some issues.</p> <p>Anyhow, here is the question and dilemma.</p> <p>I have a few areas on the site which I have an ajax update type panel that renders content from a view using this technique found here. <a href="http://www.singingeels.com/Articles/AJAX_Panels_with_ASPNET_MVC.aspx" rel="nofollow noreferrer">AJAX Panels with ASP.NET MVC</a></p> <p>This worked fine in preview 4 but now in the beta I keep getting this ..</p> <pre><code>Sys.ArgumentNullException: Value cannot be null Parameter name eventObject </code></pre> <p>It has been driving me nuts... </p> <p>My code looks like this</p> <pre><code>&lt;% using (this.Ajax.BeginForm("ReportOne", "Reports", null, new AjaxOptions { UpdateTargetId = "panel1" }, new { id = "panelOneForm" })) { } %&gt; &lt;div class="panel" id="panel1"&gt;&lt;img src="/Content/ajax-loader.gif" /&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; $get("panelOneForm").onsubmit(); &lt;/script&gt; </code></pre> <p>so basically what its doing is forcing the submit on the form, which updates panel1 with the contents from the view ReportOne.</p> <p>What am I missing? Why am I getting this error? Why did they go and change things? I love MVC but this is making me crazy.</p>
[ { "answer_id": 258943, "author": "Andrew Stanton-Nurse", "author_id": 29813, "author_profile": "https://Stackoverflow.com/users/29813", "pm_score": 1, "selected": false, "text": "<% using (this.Ajax.BeginForm(\"ReportOne\", \"Reports\", null, new AjaxOptions { UpdateTargetId = \"panel1\" }, new { id = \"panelOneForm\" })) { } %>\n<div class=\"panel\" id=\"panel1\"><img src=\"/Content/ajax-loader.gif\" /></div>\n<script type=\"text/javascript\">\n $get(\"panelOneForm\").onsubmit({ preventDefault: function() {} });\n</script>\n" }, { "answer_id": 353344, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": true, "text": "\nvar event = new Object();\nfunction refreshInformation(){\ndocument.forms['MyForm'].onsubmit({preventDefault: function(){} });\n}\n \n<img src=\"myimg.gif\" onmouseover=\"showmousepos(event)\" />\n onsubmit({preventDefault: function(){} } Sys.ArgumentNullException: Value cannot be null Parameter name eventObject submit()" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22093/" ]
237,699
<p>So lets say I'm using Python's <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow noreferrer">ftplib</a> to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.</p>
[ { "answer_id": 237704, "author": "Mohit Ranka", "author_id": 2220518, "author_profile": "https://Stackoverflow.com/users/2220518", "pm_score": 0, "selected": false, "text": "file_name_list = [' '.join(each_file.split()).split()[-1] for each_file_detail in file_list_from_log]\n" }, { "answer_id": 237708, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 1, "selected": false, "text": "filenames = []\nftp.retrlines('LIST', lambda line: filenames.append(line.split()[-1]))\n" }, { "answer_id": 237709, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 . lines = ftp.retrlines('LIST')\nlines = lines.split(\"\\n\") # This should split the string into an array of lines\n\nfilename_index = len(lines[0]) - 1\nfiles = []\n\nfor line in lines:\n files.append(line[filename_index:])\n" }, { "answer_id": 237769, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 3, "selected": false, "text": "ftp.nlst() ftp.retrlines() # empty list that will receive all the log entry\nlog = [] \n# we pass a callback function bypass the print_line that would be called by retrlines\n# we do that only because we cannot use something better than retrlines\nftp.retrlines('LIST', callback=log.append)\n# we use rsplit because it more efficient in our case if we have a big file\nfiles = (line.rsplit(None, 1)[1] for line in log)\n# get you file list\nfiles_list = list(files)\n files_list retrlines files = (line.rsplit(None, 1)[1] for line in log)\n # join split the line, get all the item from the field 8 then join them\nfiles = (' '.join(line.split()[8:]) for line in log)\n" }, { "answer_id": 3114591, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "MLSD ftpd FTPDirectory .getdata ftplib.FTP directory_filenames= [ftpfile.name for ftpfile in ftpd.files]\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
237,703
<p>In cmd.exe, I can execute the command "copy c:\hello.txt c:\hello2.txt" and it worked fine. But in my C program, I ran this piece of code and got the following error:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { system("copy c:\hello.txt c:\hello2.txt"); system("pause"); return 0; } </code></pre> <p>Output: The system cannot find the file specified.</p> <p>Anybody know what is going on here?</p>
[ { "answer_id": 237706, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": true, "text": "\\ \\\\ \\t \\r \\n \\ '\\' \\\\ system(\"copy c:\\\\hello.txt c:\\\\hello2.txt\");\n FILE *fh = fopen (\"c:\\text.dat\", \"w\");\n \\t tab" }, { "answer_id": 1809058, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "system(\"copy c:/hello.txt c:/hello2.txt\");\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,716
<p>std::next_permutation (and std::prev_permutation) permute all values in the range <code>[first, last)</code> given for a total of n! permutations (assuming that all elements are unique).</p> <p>is it possible to write a function like this:</p> <pre><code>template&lt;class Iter&gt; bool next_permutation(Iter first, Iter last, Iter choice_last); </code></pre> <p>That permutes the elements in the range <code>[first, last)</code> but only chooses elements in the range <code>[first, choice_last)</code>. ie we have maybe 20 elements and want to iterate through all permutations of 10 choices of them, 20 P 10 options vs 20 P 20.</p> <ul> <li>Iter is a random access iterator for my purposes, but if it can be implemented as a bidirectional iterator, then great!</li> <li>The less amount of external memory needed the better, but for my purposes it doesn't matter.</li> <li>The chosen elements on each iteration are input to the first elements of the sequence.</li> </ul> <p><em>Is such a function possible to implement? Does anyone know of any existing implementations?</em></p> <p>Here is essentially what I am doing to hack around this. Suggestions on how to improve this are also welcome.</p> <ul> <li>Start with a vector <code>V</code> of <code>N</code> elements of which I want to visit each permutation of <code>R</code> elements chosen from it (<code>R &lt;= N</code>).</li> <li>Build a vector <code>I</code> of length <code>R</code> with values <code>{ 0, 1, 2, ... R - 1 }</code> to serve as an index to the elements of <code>V</code></li> <li>On each iteration, build a vector <code>C</code> of length <code>R</code> with values <code>{ V[I[0]], V[I[1]], ... V[I[R - 1]] }</code></li> <li>Do something with the values in <code>C</code>.</li> <li>Apply a function to permute the elements of <code>I</code> and iterate again if it was able to.</li> </ul> <p>That function looks like this:</p> <pre><code>bool NextPermutationIndices(std::vector&lt;int&gt; &amp;I, int N) { const int R = I.size(); for (int i = R - 1; ; --i) { if (I[i] &lt; N - R + i) { ++I[i]; return true; } if (i == 0) return false; if (I[i] &gt; I[i-1] + 1) { ++I[i-1]; for (int j = i; j &lt; R; ++j) I[j] = I[j-1] + 1; return true; } } } </code></pre> <p>That function is very complicated due to all the possible off-by-one errors, as well everything using it are more complicated than is probably necessary.</p> <hr> <p><strong><em>EDIT:</em></strong></p> <p>It turns out that it was <strong>significantly</strong> easier than I had even imagined. From <a href="http://photon.poly.edu/~hbr/boost/combinations.html" rel="nofollow noreferrer">here</a>, I was able to find exact implementations of many of the exact algorithms I needed (combinations, permutations, etc.).</p> <pre><code>template&lt;class BidirectionalIterator&gt; bool next_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { std::reverse(middle, last); return std::next_permutation(first, last); } </code></pre> <p>Plus there is a combination algorithm there that works in a similar way. The implementation of that is much more complication though.</p>
[ { "answer_id": 237779, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 3, "selected": true, "text": "for_each_permutation() next_permutation()" }, { "answer_id": 237802, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 0, "selected": false, "text": "R (N-R)" }, { "answer_id": 238692, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 0, "selected": false, "text": "template<class Iter>\nbool next_choice_permutation(Iter first, Iter choice, Iter last)\n{\n if (first == choice)\n return false;\n\n Iter i = choice;\n --i;\n if (*i < *choice) {\n std::rotate(i, choice, last);\n return true;\n }\n\n while (i != first) {\n Iter j = i;\n ++j;\n std::rotate(i, j, last);\n --i;\n --j;\n for (; j != last; ++j) {\n if (*i < *j)\n break;\n }\n if (j != last) {\n std::iter_swap(i, j);\n return true;\n }\n }\n std::rotate(first, ++Iter(first), last);\n return false;\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
237,725
<p>I've tried downloading the Rails package and installing it on Windows, but have no idea to make it work.</p> <p>I have had some experience with this commbination:</p> <ul> <li>PHP 4.x + 5.x (Windows)</li> <li>LIGHTTPD (Windows)</li> <li>Connecting to a Firebird Database (Windows)</li> </ul> <p>Can anybody enlighten me?</p>
[ { "answer_id": 241206, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 4, "selected": true, "text": "ruby setup.rb gem install rails" }, { "answer_id": 1717151, "author": "Luis Lavena", "author_id": 117298, "author_profile": "https://Stackoverflow.com/users/117298", "pm_score": 0, "selected": false, "text": "--source http://gems.rubyinstaller.org" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30787/" ]
237,733
<p>I've been a bad programmer because I am doing a copy and paste. An example is that everytime i connect to a database and retrieve a recordset, I will copy the previous code and edit, copy the code that sets the datagridview and edit. I am aware of the phrase code reuse, but I have not actually used it. How can i utilize code reuse so that I don't have to copy and paste the database code and the datagridview code.,</p>
[ { "answer_id": 237773, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 3, "selected": false, "text": "printf printf write //convert theInt to a string and write it out.\nchar c[24];\nitoa(theInt, c, 10);\nputs(c);\n printf(\"%d\", theInt);\n printf void print_int(int theInt)\n{\n char c[24];\n itoa(theInt, c, 10);\n puts(c);\n}\n print_int void print_int(int theInt)\n{\n fprintf(stderr, \"%d\", theInt);\n}\n" }, { "answer_id": 237967, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": true, "text": "Function GetCustomer(ID) as Customer\n Dim CMD as New DBCmd(\"SQL or Stored Proc\")\n CMD.Paramaters.Add(\"CustID\",DBType,Length).Value = ID\n Dim DHelper as New DatabaseHelper\n DR = DHelper.GetReader(CMD)\n Dim RtnCust as New Customer(Dx)\n Return RtnCust\nEnd Function\n\nClass DataHelper\n Public Function GetDataTable(cmd) as DataTable\n Write the DB access code stuff here.\n GetConnectionString\n OpenConnection\n Do DB Operation\n Close Connection\n End Function\n Public Function GetDataReader(cmd) as DataReader\n Public Function GetDataSet(cmd) as DataSet\n ... And So on ...\nEnd Class\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26087/" ]
237,745
<p>Does any one know of some kind of Comparator factory in Java, with a </p> <pre><code>public Comparator getComparatorForClass(Class clazz) {} </code></pre> <p>It would return Comparators for stuff like String, Double, Integer but would have a</p> <pre><code>public void addComparatorForClass(Class clazz, Comparator comparator) {} </code></pre> <p>For arbitrary types.</p>
[ { "answer_id": 237752, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 4, "selected": false, "text": "factory.getComparatorForClass(x.getClass()).compare(x, y)\n Comparable x.compareTo(y)\n Comparable" }, { "answer_id": 237753, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 2, "selected": false, "text": "java.lang.Comparable Comparable#compareTo(Object) : int" }, { "answer_id": 237755, "author": "IAdapter", "author_id": 30453, "author_profile": "https://Stackoverflow.com/users/30453", "pm_score": 3, "selected": false, "text": "CompareToBuilder public class MyClass {\n String field1;\n int field2;\n boolean field3;\n\n ...\n\n public int compareTo(Object o) {\n MyClass myClass = (MyClass) o;\n return new CompareToBuilder()\n .appendSuper(super.compareTo(o)\n .append(this.field1, myClass.field1)\n .append(this.field2, myClass.field2)\n .append(this.field3, myClass.field3)\n .toComparison();\n }\n}\n" }, { "answer_id": 5439379, "author": "Aetherus", "author_id": 677605, "author_profile": "https://Stackoverflow.com/users/677605", "pm_score": 0, "selected": false, "text": "Searcher(Comparator<T> comparator) {\n this.comparator = comparator;\n}\n\nSearcher() {\n this(new DefaultComparator<T>());\n}\n\nint search(...) {\n ...\n}\n\nprivate static class DefaultComparator<E extends Comparable<E>> \n implements Comparator<E> {\n public int compare(E o1, E o2) {\n return o1.compareTo(o2);\n }\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,757
<p>I have a php script that is executing an executable that writes to a serial port. However, everytime it runs <pre>system("c:\Untitled1.exe")</pre> it just opens up a cmd window and freezes.</p> <p>Anybody know how to fix this? Or if there is an easier way to get PHP to write to the serial port directly? (I've already tried these two: <a href="http://blogs.vinuthomas.com/2007/04/09/php-and-serial-ports/" rel="nofollow noreferrer">http://blogs.vinuthomas.com/2007/04/09/php-and-serial-ports/</a> and they don't work for me)</p> <p>P.S. I am on Windows XP</p>
[ { "answer_id": 237797, "author": "lacop", "author_id": 894, "author_profile": "https://Stackoverflow.com/users/894", "pm_score": 0, "selected": false, "text": "system() popen() fread() pclose()" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,763
<p>I have a CSV file that has a column that contains strings that look like integers. That is they should be dealt with as strings, but since they are numbers they appear to be imported as integers (dropping off the leading zeroes).</p> <p>Example Data:</p> <ul> <li>0000000000079</li> <li>0000999000012</li> <li>0001002000005 </li> <li>0004100000007</li> </ul> <p>The problem I'm seeing is that the last example data point comes through as DBNull.Value. I'm assuming this is because OleDB is treating that column as an integer (the data points come through without their leading zeroes also) and that 0004100000007 is greater than the largest integer value.</p> <p>Is there some way to say "column [0] is a string, don't read it as an integer"? When reading the data?</p> <p>The code I am currently using is:</p> <pre><code>OleDbConnection dbConn = new OleDbConnection(SourceConnectionString); OleDbCommand dbCommand = new OleDbCommand("SELECT * FROM test.csv", dbConn); dbConn.Open(); OleDbDataReader dbReader = dbCommand.ExecuteReader(); while (dbReader.Read()) { if (dbReader[0] != DBNull.Value) { // do some work } } </code></pre>
[ { "answer_id": 237823, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 2, "selected": false, "text": "string myStringValue = reader.GetString(0);\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25719/" ]
237,804
<p><a href="http://en.wikipedia.org/wiki/C%2B%2B11" rel="noreferrer">C++11</a> introduces <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2378.pdf" rel="noreferrer">user-defined literals</a> which will allow the introduction of new literal syntax based on existing literals (<code>int</code>, <code>hex</code>, <code>string</code>, <code>float</code>) so that any type will be able to have a literal presentation.</p> <p><strong>Examples:</strong></p> <pre><code>// imaginary numbers std::complex&lt;long double&gt; operator "" _i(long double d) // cooked form { return std::complex&lt;long double&gt;(0, d); } auto val = 3.14_i; // val = complex&lt;long double&gt;(0, 3.14) // binary values int operator "" _B(const char*); // raw form int answer = 101010_B; // answer = 42 // std::string std::string operator "" _s(const char* str, size_t /*length*/) { return std::string(str); } auto hi = "hello"_s + " world"; // + works, "hello"_s is a string not a pointer // units assert(1_kg == 2.2_lb); // give or take 0.00462262 pounds </code></pre> <p>At first glance this looks very cool but I'm wondering how applicable it really is, when I tried to think of having the suffixes <code>_AD</code> and <code>_BC</code> create dates I found that it's problematic due to operator order. <code>1974/01/06_AD</code> would first evaluate <code>1974/01</code> (as plain <code>int</code>s) and only later the <code>06_AD</code> (to say nothing of August and September having to be written without the <code>0</code> for octal reasons). This can be worked around by having the syntax be <code>1974-1/6_AD</code> so that the operator evaluation order works but it's clunky. </p> <p>So what my question boils down to is this, do you feel this feature will justify itself? What other literals would you like to define that will make your C++ code more readable?</p> <hr> <p>Updated syntax to fit the final draft on June 2011</p>
[ { "answer_id": 237821, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 5, "selected": false, "text": "double operator \"\"_deg(long double d)\n{ \n // returns radians\n return d*M_PI/180; \n}\n int operator \"\"_fix(long double d)\n{ \n // returns d as a 1.15.16 fixed point number\n return (int)(d*65536.0f); \n}\n" }, { "answer_id": 237837, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 3, "selected": false, "text": "assert(1_kg == 2.2_lb); // give or take 0.00462262 pounds\n assert(KG(1.0f) == LB(2.2f));\n" }, { "answer_id": 237885, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": -1, "selected": false, "text": "auto val = 3.14_i\n std::complex<double> operator \"\"_i(long double d) // cooked form\n{ \n return std::complex(0, d);\n}\n std::complex<double> val = 3.14i\n std::complex<double> val = std::complex(0, 3.14);\n complex = std::complex<double>;\n typedef std::complex<double> complex;\n\ncomplex val = std::complex(0, 3.14);\n" }, { "answer_id": 238057, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 8, "selected": false, "text": "// C89:\nMyComplex z1 = { 1, 2 } ;\n\n// C99: You'll note I is a macro, which can lead\n// to very interesting situations...\ndouble complex z1 = 1 + 2*I;\n\n// C++:\nstd::complex<double> z1(1, 2) ;\n\n// C++11: You'll note that \"i\" won't ever bother\n// you elsewhere\nstd::complex<double> z1 = 1 + 2_i ;\n Point p = 25_x + 13_y + 3_z ; // 3D point\n css::Font::Size p0 = 12_pt ; // Ok\ncss::Font::Size p1 = 50_percent ; // Ok\ncss::Font::Size p2 = 15_px ; // Ok\ncss::Font::Size p3 = 10_em ; // Ok\ncss::Font::Size p4 = 15 ; // ERROR : Won't compile !\n 1974/01/06AD\n ^ ^ ^\n \"1974-01-06\"_AD ; // ISO-like notation\n\"06/01/1974\"_AD ; // french-date-like notation\n\"jan 06 1974\"_AD ; // US-date-like notation\n19740106_AD ; // integer-date-like notation\n" }, { "answer_id": 238399, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 4, "selected": false, "text": "3.14std::i s std::string i" }, { "answer_id": 4051289, "author": "Diego Sevilla", "author_id": 62365, "author_profile": "https://Stackoverflow.com/users/62365", "pm_score": 4, "selected": false, "text": "typedef ::ecore::Class< Attribute<int>, Attribute<int> > MyClass;\n typedef ::ecore::Class< \"MyClass\", Attribute< \"x\", int>, Attribute<\"y\", int> > MyClass;\n typedef ::ecore::Class< MyClass_n, Attribute< x_n, int>, Attribute<y_n, int> > MyClass;\n" }, { "answer_id": 7906630, "author": "emsr", "author_id": 680359, "author_profile": "https://Stackoverflow.com/users/680359", "pm_score": 7, "selected": true, "text": "#include <bitset>\n#include <iostream>\n\ntemplate<char... Bits>\n struct checkbits\n {\n static const bool valid = false;\n };\n\ntemplate<char High, char... Bits>\n struct checkbits<High, Bits...>\n {\n static const bool valid = (High == '0' || High == '1')\n && checkbits<Bits...>::valid;\n };\n\ntemplate<char High>\n struct checkbits<High>\n {\n static const bool valid = (High == '0' || High == '1');\n };\n\ntemplate<char... Bits>\n inline constexpr std::bitset<sizeof...(Bits)>\n operator\"\" _bits() noexcept\n {\n static_assert(checkbits<Bits...>::valid, \"invalid digit in binary string\");\n return std::bitset<sizeof...(Bits)>((char []){Bits..., '\\0'});\n }\n\nint\nmain()\n{\n auto bits = 0101010101010101010101010101010101010101010101010101010101010101_bits;\n std::cout << bits << std::endl;\n std::cout << \"size = \" << bits.size() << std::endl;\n std::cout << \"count = \" << bits.count() << std::endl;\n std::cout << \"value = \" << bits.to_ullong() << std::endl;\n\n // This triggers the static_assert at compile time.\n auto badbits = 2101010101010101010101010101010101010101010101010101010101010101_bits;\n\n // This throws at run time.\n std::bitset<64> badbits2(\"2101010101010101010101010101010101010101010101010101010101010101_bits\");\n}\n" }, { "answer_id": 32250622, "author": "rr-", "author_id": 2016221, "author_profile": "https://Stackoverflow.com/users/2016221", "pm_score": 2, "selected": false, "text": " \"asd\\0\\0\\0\\1\"_b\n std::string(str, n) \\0 std::string std::vector" }, { "answer_id": 38163546, "author": "Martin Moene", "author_id": 437272, "author_profile": "https://Stackoverflow.com/users/437272", "pm_score": 3, "selected": false, "text": "auto force = 2_N; \nauto dx = 2_m; \nauto energy = force * dx; \n\nassert(energy == 4_J); \n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
237,807
<p>.NET's <code>SslStream</code> class does not send the <code>close_notify</code> alert before closing the connection.</p> <p>How can I send the <code>close_notify</code> alert manually?</p>
[ { "answer_id": 22626756, "author": "Neco", "author_id": 1655991, "author_profile": "https://Stackoverflow.com/users/1655991", "pm_score": 5, "selected": false, "text": "public class FixedSslStream : SslStream {\n public FixedSslStream(Stream innerStream)\n : base(innerStream) {\n }\n public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen)\n : base(innerStream, leaveInnerStreamOpen) {\n }\n public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)\n : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback) {\n }\n public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback)\n : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback) {\n }\n public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy)\n : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, encryptionPolicy) {\n }\n public override void Close() {\n try {\n SslDirectCall.CloseNotify(this);\n } finally {\n base.Close();\n }\n }\n}\n public unsafe static class SslDirectCall {\n public static void CloseNotify(SslStream sslStream) {\n if (sslStream.IsAuthenticated) {\n bool isServer = sslStream.IsServer;\n\n byte[] result;\n int resultSz;\n var asmbSystem = typeof(System.Net.Authorization).Assembly;\n\n int SCHANNEL_SHUTDOWN = 1;\n var workArray = BitConverter.GetBytes(SCHANNEL_SHUTDOWN);\n\n var sslstate = ReflectUtil.GetField(sslStream, \"_SslState\");\n var context = ReflectUtil.GetProperty(sslstate, \"Context\");\n\n var securityContext = ReflectUtil.GetField(context, \"m_SecurityContext\");\n var securityContextHandleOriginal = ReflectUtil.GetField(securityContext, \"_handle\");\n NativeApi.SSPIHandle securityContextHandle = default(NativeApi.SSPIHandle);\n securityContextHandle.HandleHi = (IntPtr)ReflectUtil.GetField(securityContextHandleOriginal, \"HandleHi\");\n securityContextHandle.HandleLo = (IntPtr)ReflectUtil.GetField(securityContextHandleOriginal, \"HandleLo\");\n\n var credentialsHandle = ReflectUtil.GetField(context, \"m_CredentialsHandle\");\n var credentialsHandleHandleOriginal = ReflectUtil.GetField(credentialsHandle, \"_handle\");\n NativeApi.SSPIHandle credentialsHandleHandle = default(NativeApi.SSPIHandle);\n credentialsHandleHandle.HandleHi = (IntPtr)ReflectUtil.GetField(credentialsHandleHandleOriginal, \"HandleHi\");\n credentialsHandleHandle.HandleLo = (IntPtr)ReflectUtil.GetField(credentialsHandleHandleOriginal, \"HandleLo\");\n\n int bufferSize = 1;\n NativeApi.SecurityBufferDescriptor securityBufferDescriptor = new NativeApi.SecurityBufferDescriptor(bufferSize);\n NativeApi.SecurityBufferStruct[] unmanagedBuffer = new NativeApi.SecurityBufferStruct[bufferSize];\n\n fixed (NativeApi.SecurityBufferStruct* ptr = unmanagedBuffer)\n fixed (void* workArrayPtr = workArray) {\n securityBufferDescriptor.UnmanagedPointer = (void*)ptr;\n\n unmanagedBuffer[0].token = (IntPtr)workArrayPtr;\n unmanagedBuffer[0].count = workArray.Length;\n unmanagedBuffer[0].type = NativeApi.BufferType.Token;\n\n NativeApi.SecurityStatus status;\n status = (NativeApi.SecurityStatus)NativeApi.ApplyControlToken(ref securityContextHandle, securityBufferDescriptor);\n if (status == NativeApi.SecurityStatus.OK) {\n unmanagedBuffer[0].token = IntPtr.Zero;\n unmanagedBuffer[0].count = 0;\n unmanagedBuffer[0].type = NativeApi.BufferType.Token;\n\n NativeApi.SSPIHandle contextHandleOut = default(NativeApi.SSPIHandle);\n NativeApi.ContextFlags outflags = NativeApi.ContextFlags.Zero;\n long ts = 0;\n\n var inflags = NativeApi.ContextFlags.SequenceDetect |\n NativeApi.ContextFlags.ReplayDetect |\n NativeApi.ContextFlags.Confidentiality |\n NativeApi.ContextFlags.AcceptExtendedError |\n NativeApi.ContextFlags.AllocateMemory |\n NativeApi.ContextFlags.InitStream;\n\n if (isServer) {\n status = (NativeApi.SecurityStatus)NativeApi.AcceptSecurityContext(ref credentialsHandleHandle, ref securityContextHandle, null,\n inflags, NativeApi.Endianness.Native, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts);\n } else {\n status = (NativeApi.SecurityStatus)NativeApi.InitializeSecurityContextW(ref credentialsHandleHandle, ref securityContextHandle, null,\n inflags, 0, NativeApi.Endianness.Native, null, 0, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts);\n }\n if (status == NativeApi.SecurityStatus.OK) {\n byte[] resultArr = new byte[unmanagedBuffer[0].count];\n Marshal.Copy(unmanagedBuffer[0].token, resultArr, 0, resultArr.Length);\n Marshal.FreeCoTaskMem(unmanagedBuffer[0].token);\n result = resultArr;\n resultSz = resultArr.Length;\n } else {\n throw new InvalidOperationException(string.Format(\"AcceptSecurityContext/InitializeSecurityContextW returned [{0}] during CloseNotify.\", status));\n }\n } else {\n throw new InvalidOperationException(string.Format(\"ApplyControlToken returned [{0}] during CloseNotify.\", status));\n }\n }\n\n var innerStream = (Stream)ReflectUtil.GetProperty(sslstate, \"InnerStream\");\n innerStream.Write(result, 0, resultSz);\n }\n }\n}\n public unsafe static class NativeApi {\n internal enum BufferType {\n Empty,\n Data,\n Token,\n Parameters,\n Missing,\n Extra,\n Trailer,\n Header,\n Padding = 9,\n Stream,\n ChannelBindings = 14,\n TargetHost = 16,\n ReadOnlyFlag = -2147483648,\n ReadOnlyWithChecksum = 268435456\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n internal struct SSPIHandle {\n public IntPtr HandleHi;\n public IntPtr HandleLo;\n public bool IsZero {\n get {\n return this.HandleHi == IntPtr.Zero && this.HandleLo == IntPtr.Zero;\n }\n }\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]\n internal void SetToInvalid() {\n this.HandleHi = IntPtr.Zero;\n this.HandleLo = IntPtr.Zero;\n }\n public override string ToString() {\n return this.HandleHi.ToString(\"x\") + \":\" + this.HandleLo.ToString(\"x\");\n }\n }\n [StructLayout(LayoutKind.Sequential)]\n internal class SecurityBufferDescriptor {\n public readonly int Version;\n public readonly int Count;\n public unsafe void* UnmanagedPointer;\n public SecurityBufferDescriptor(int count) {\n this.Version = 0;\n this.Count = count;\n this.UnmanagedPointer = null;\n }\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct SecurityBufferStruct {\n public int count;\n public BufferType type;\n public IntPtr token;\n public static readonly int Size = sizeof(SecurityBufferStruct);\n }\n\n internal enum SecurityStatus {\n OK,\n ContinueNeeded = 590610,\n CompleteNeeded,\n CompAndContinue,\n ContextExpired = 590615,\n CredentialsNeeded = 590624,\n Renegotiate,\n OutOfMemory = -2146893056,\n InvalidHandle,\n Unsupported,\n TargetUnknown,\n InternalError,\n PackageNotFound,\n NotOwner,\n CannotInstall,\n InvalidToken,\n CannotPack,\n QopNotSupported,\n NoImpersonation,\n LogonDenied,\n UnknownCredentials,\n NoCredentials,\n MessageAltered,\n OutOfSequence,\n NoAuthenticatingAuthority,\n IncompleteMessage = -2146893032,\n IncompleteCredentials = -2146893024,\n BufferNotEnough,\n WrongPrincipal,\n TimeSkew = -2146893020,\n UntrustedRoot,\n IllegalMessage,\n CertUnknown,\n CertExpired,\n AlgorithmMismatch = -2146893007,\n SecurityQosFailed,\n SmartcardLogonRequired = -2146892994,\n UnsupportedPreauth = -2146892989,\n BadBinding = -2146892986\n }\n [Flags]\n internal enum ContextFlags {\n Zero = 0,\n Delegate = 1,\n MutualAuth = 2,\n ReplayDetect = 4,\n SequenceDetect = 8,\n Confidentiality = 16,\n UseSessionKey = 32,\n AllocateMemory = 256,\n Connection = 2048,\n InitExtendedError = 16384,\n AcceptExtendedError = 32768,\n InitStream = 32768,\n AcceptStream = 65536,\n InitIntegrity = 65536,\n AcceptIntegrity = 131072,\n InitManualCredValidation = 524288,\n InitUseSuppliedCreds = 128,\n InitIdentify = 131072,\n AcceptIdentify = 524288,\n ProxyBindings = 67108864,\n AllowMissingBindings = 268435456,\n UnverifiedTargetName = 536870912\n }\n internal enum Endianness {\n Network,\n Native = 16\n }\n\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]\n [DllImport(\"secur32.dll\", ExactSpelling = true, SetLastError = true)]\n internal static extern int ApplyControlToken(ref SSPIHandle contextHandle, [In] [Out] SecurityBufferDescriptor outputBuffer);\n\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]\n [DllImport(\"secur32.dll\", ExactSpelling = true, SetLastError = true)]\n internal unsafe static extern int AcceptSecurityContext(ref SSPIHandle credentialHandle, ref SSPIHandle contextHandle, [In] SecurityBufferDescriptor inputBuffer, [In] ContextFlags inFlags, [In] Endianness endianness, ref SSPIHandle outContextPtr, [In] [Out] SecurityBufferDescriptor outputBuffer, [In] [Out] ref ContextFlags attributes, out long timeStamp);\n\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]\n [DllImport(\"secur32.dll\", ExactSpelling = true, SetLastError = true)]\n internal unsafe static extern int InitializeSecurityContextW(ref SSPIHandle credentialHandle, ref SSPIHandle contextHandle, [In] byte* targetName, [In] ContextFlags inFlags, [In] int reservedI, [In] Endianness endianness, [In] SecurityBufferDescriptor inputBuffer, [In] int reservedII, ref SSPIHandle outContextPtr, [In] [Out] SecurityBufferDescriptor outputBuffer, [In] [Out] ref ContextFlags attributes, out long timeStamp);\n}\n public static class ReflectUtil {\n public static object GetField(object obj, string fieldName) {\n var tp = obj.GetType();\n var info = GetAllFields(tp)\n .Where(f => f.Name == fieldName).Single();\n return info.GetValue(obj);\n }\n public static void SetField(object obj, string fieldName, object value) {\n var tp = obj.GetType();\n var info = GetAllFields(tp)\n .Where(f => f.Name == fieldName).Single();\n info.SetValue(obj, value);\n }\n public static object GetStaticField(Assembly assembly, string typeName, string fieldName) {\n var tp = assembly.GetType(typeName);\n var info = GetAllFields(tp)\n .Where(f => f.IsStatic)\n .Where(f => f.Name == fieldName).Single();\n return info.GetValue(null);\n }\n\n public static object GetProperty(object obj, string propertyName) {\n var tp = obj.GetType();\n var info = GetAllProperties(tp)\n .Where(f => f.Name == propertyName).Single();\n return info.GetValue(obj, null);\n }\n public static object CallMethod(object obj, string methodName, params object[] prm) {\n var tp = obj.GetType();\n var info = GetAllMethods(tp)\n .Where(f => f.Name == methodName && f.GetParameters().Length == prm.Length).Single();\n object rez = info.Invoke(obj, prm);\n return rez;\n }\n public static object NewInstance(Assembly assembly, string typeName, params object[] prm) {\n var tp = assembly.GetType(typeName);\n var info = tp.GetConstructors()\n .Where(f => f.GetParameters().Length == prm.Length).Single();\n object rez = info.Invoke(prm);\n return rez;\n }\n public static object InvokeStaticMethod(Assembly assembly, string typeName, string methodName, params object[] prm) {\n var tp = assembly.GetType(typeName);\n var info = GetAllMethods(tp)\n .Where(f => f.IsStatic)\n .Where(f => f.Name == methodName && f.GetParameters().Length == prm.Length).Single();\n object rez = info.Invoke(null, prm);\n return rez;\n }\n public static object GetEnumValue(Assembly assembly, string typeName, int value) {\n var tp = assembly.GetType(typeName);\n object rez = Enum.ToObject(tp, value);\n return rez;\n }\n\n private static IEnumerable<FieldInfo> GetAllFields(Type t) {\n if (t == null)\n return Enumerable.Empty<FieldInfo>();\n\n BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |\n BindingFlags.Static | BindingFlags.Instance |\n BindingFlags.DeclaredOnly;\n return t.GetFields(flags).Concat(GetAllFields(t.BaseType));\n }\n private static IEnumerable<PropertyInfo> GetAllProperties(Type t) {\n if (t == null)\n return Enumerable.Empty<PropertyInfo>();\n\n BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |\n BindingFlags.Static | BindingFlags.Instance |\n BindingFlags.DeclaredOnly;\n return t.GetProperties(flags).Concat(GetAllProperties(t.BaseType));\n }\n private static IEnumerable<MethodInfo> GetAllMethods(Type t) {\n if (t == null)\n return Enumerable.Empty<MethodInfo>();\n\n BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |\n BindingFlags.Static | BindingFlags.Instance |\n BindingFlags.DeclaredOnly;\n return t.GetMethods(flags).Concat(GetAllMethods(t.BaseType));\n }\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
237,816
<p>Say each row in a table has data pertaining to one particular user. The user has a password to access the system.</p> <p>How do I encrypt a column of data using InnoDB so that no one other than the user who's data it is can read the data ? I was thinking of something like using one of the MySQL encryption functions (say AES) with a key based on a hash calculated from the user's password.</p> <p>Does any one have any pointers to how I could do this ? Am I on the right track ?</p> <p>One of the answers below</p> <blockquote> <p>The issue of modifying user's password involves re-encrypting the user key by means of the new password which is much more straight forward than re-encrypting the whole bunch of user's data that can be arbitrarily large. The user key remains the same accross the life of the user data in the system.</p> </blockquote> <p>How does this help ? Say the password is pass1. And there are a bunch of records encrypted with a key generated from this. If the user now resets the password to pass2, I have no way of decrypting the data that was encrypted using pass1. In the case of a user forgetting the password entirely, all his encrypted data will be lost.</p>
[ { "answer_id": 237839, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 3, "selected": false, "text": "INSERT INTO secure_table VALUES (\n 1,\n AES_ENCRYPT(\n 'plain text data',\n CONCAT(@application_password, @user_password))\n);\n" }, { "answer_id": 17015513, "author": "sagunms", "author_id": 1297184, "author_profile": "https://Stackoverflow.com/users/1297184", "pm_score": 1, "selected": false, "text": "extra password extra password salt-like string private key private key extra password read public key write extra password private key salt-like string" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31574/" ]
237,843
<p>my shared hosting only allows me to create 2 virtual directories. and i want to host multiple webapps... say an asp.net mvc blog, a forum, a personal site etc... </p> <p>isnt there any other way of doing this? cant i simply just ftp the blog folder to one of my virtual directories and then access it online??</p>
[ { "answer_id": 243883, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 3, "selected": true, "text": "~/images/logo.gif\n /vd1/app1/images/logo.gif\n /vd1/images/logo.gif\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30007/" ]
237,859
<p>I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like </p> <pre><code>[(u'BC',45) (u'CHM',25) (u'CPM',30)] </code></pre> <p>I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython.</p> <p>I've tried iterating through the list and tuples. If I use a <em>print</em> statement, the output is fine. But when I replace the <em>print</em> statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple.</p> <p>I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both.</p> <p>Any suggestions?</p> <hr> <p><strong>Edit:</strong> Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like:</p> <pre><code>BC 45 CHM 25 CMP 30 </code></pre> <p>Nothing special, just simply pulling each value from each tuple and making a visual list.</p> <p>I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.</p>
[ { "answer_id": 237872, "author": "derfred", "author_id": 10286, "author_profile": "https://Stackoverflow.com/users/10286", "pm_score": 0, "selected": false, "text": ">>> import pprint\n>>> pprint.pformat({ \"my key\": \"my value\"})\n\"{'my key': 'my value'}\"\n>>> \n" }, { "answer_id": 237937, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "text_for_display = '\\n'.join(item + u' ' + unicode(value) for item, value in my_dictionary.items())\n" }, { "answer_id": 237941, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "\"%10s - %d\" % dict.items()[0]\n '\\n'.join((\"%10s - %d\" % t) for t in dict.items())\n" }, { "answer_id": 238453, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 3, "selected": false, "text": "def getNiceDictRepr(aDict):\n return '\\n'.join('%s %s' % t for t in aDict.iteritems())\n >>> myDict = dict([(u'BC',45), (u'CHM',25), (u'CPM',30)])\n>>> print getNiceDictRepr(myDict)\nBC 45\nCHM 25\nCPM 30\n SetValue self.textCtrl.SetValue(getNiceDictRepr(myDict))\n" }, { "answer_id": 297811, "author": "crystalattice", "author_id": 18676, "author_profile": "https://Stackoverflow.com/users/18676", "pm_score": 0, "selected": false, "text": "for key, value in sorted(self.dict.items()):\n self.current_list.WriteText(key + \" \" + str(self.dict[key]) + \"\\n\")\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
237,876
<p>I'm making a game and one of the methods calculates a character's base hit numbers based on skill values. The method currently calculates each value individually, since each skill can be used at short, medium, and long range.</p> <p>I originally thought I could combine the skills into a tuple and iterate over it, dynamically creating each hit number. But I don't know if it's actually possible, since I currently have each hit number assigned to it's own variable.</p> <p>I also thought about creating a method for each range, and passing the tuple as an argument. I could create a new tuple or list with the resulting values and then assign them to the individual variables, but I don't see how it would be any better than do it this way, except that it won't look so copy &amp; pasted.</p> <p>Here's what I currently have:</p> <pre><code> def calcBaseHitNumbers(self, dict): """Calculate character's base hit numbers depending on skill level.""" self.skill_dict = dict self.rifle = self.skill_dict.get('CRM', 0) self.pistol = self.skill_dict.get('PST', 0) self.big_gun = self.skill_dict.get('LCG', 0) self.heavy_weapon = self.skill_dict.get('HW', 0) self.bow = self.skill_dict.get('LB', 0) #self.skill_tuple = (self.rifle, self.pistol, self.big_gun, self.heavy_weapon, # self.bow) #---Short range ## for skill in self.skill_tuple: ## self.base_hit_short = skill * 0.6 self.charAttribs.bhCRM_short = self.rifle * 0.6 self.charAttribs.bhPST_short = self.pistol * 0.6 self.charAttribs.bhHW_short = self.heavy_weapon * 0.6 self.charAttribs.bhLCG_short = self.big_gun * 0.6 self.charAttribs.bhLB_short = self.bow * 0.6 #---Med range self.charAttribs.bhCRM_med = self.rifle * 0.3 self.charAttribs.bhPST_med = self.pistol * 0.3 self.charAttribs.bhHW_med = self.heavy_weapon * 0.3 self.charAttribs.bhLCG_med = self.big_gun * 0.3 self.charAttribs.bhLB_med = self.bow * 0.3 #---Long range self.charAttribs.bhCRM_long = self.rifle * 0.1 self.charAttribs.bhPST_long = self.pistol * 0.1 self.charAttribs.bhHW_long = self.heavy_weapon * 0.1 self.charAttribs.bhLCG_long = self.big_gun * 0.1 self.charAttribs.bhLB_long = self.bow * 0.1 </code></pre> <p>How would you refactor this so it's more dynamic?</p> <hr> <p><strong>Edit:</strong> I guess what I want to do is something like this: Have a tuple (like the one I commented out) and iterate over it 3 times, each time making a new value (for each skill) based on the modifier for each particular range. The resulting value is then automatically assigned to it's respective variable.</p> <p>In my head, it makes sense. But when I actually try to code it, I get lost. The problem, I think, is that this is the first "real" program I've written; all I've done before are small scripts.</p> <p>This is only the 0.1 version of my program, so it's not critical to refactor it now. However, it seems very un-Pythonic to do this manually and I also want to "future-proof" this in case things change down the road.</p>
[ { "answer_id": 237905, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "current_weapon * self.medium\n class Weapon\n hit = 1\n #other properties of weapon\n\nclass Rifle(Weapon)\n #other properties of Rifle\n\nclass Pistol(Weapon)\n #other properties of Pistol\n\nclass Character\n weapon = Rifle()\n long=0.6\n def calcHit()\n return self.long*weapon.hit\n\njohn = Character()\njohn.weapon= Rifle()\njohn.calcHit\n" }, { "answer_id": 237906, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 0, "selected": false, "text": "def bh_short(self, key)\n skill = self.skill_dict.get(key, 0)\n return skill * 0.6\n" }, { "answer_id": 237907, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 3, "selected": false, "text": "SHORT_RANGE = 'S'\nMEDIUM_RANGE = 'M'\nLONG_RANGE = 'L'\nSHORT_RANGE_MODIFIER = 0.6\nMEDIUM_RANGE_MODIFIER = 0.3\nLONG_RANGE_MODIFIER = 0.1\n\nclass Weapon(object):\n def __init__(self, code_name, full_name, base_hit_value,\n short_range_modifier=None, medium_range_modifier=None,\n long_range_modifier=None):\n self.code_name, self.full_name = code_name, full_name\n self.base_hit_value = base_hit_value\n self.range_modifiers = {\n SHORT_RANGE: short_range_modifier or SHORT_RANGE_MODIFIER,\n MEDIUM_RANGE: medium_range_modifier or MEDIUM_RANGE_MODIFIER,\n LONG_RANGE: long_range_modifier or LONG_RANGE_MODIFIER,\n }\n\n def hit_value(self, range, modifier=1):\n return self.base_hit_value * self.range_modifiers[range] * modifier\n self.rifle = Weapon('CRM', 'rifle', 5)\n self.pistol = Weapon('PST', 'pistol', 10)\n hit_value = self.pistol.hit_value(SHORT_RANGE)\n" }, { "answer_id": 239131, "author": "monopocalypse", "author_id": 17142, "author_profile": "https://Stackoverflow.com/users/17142", "pm_score": 0, "selected": false, "text": "class WeaponAttribute(object):\n\n short_mod = 0.6\n med_mod = 0.3\n long_mod = 0.1\n\n def __init__(self, base):\n self.base = base\n\n @property\n def short(self):\n return self.base * self.short_mod\n\n @property\n def med(self):\n return self.base * self.med_mod\n\n @property\n def long(self):\n return self.base * self.long_mod\n\n\nclass CharacterAttributes(object):\n\n def __init__(self, attributes):\n for weapon, base in attributes.items():\n setattr(self, weapon, WeaponAttribute(base))\n CharacterAttributes # Initialise\nself.charAttribs = CharacterAttributes(self.skill_dict)\n# Get some values\nprint self.charAttribs.CRM.short\nprint self.charAttribs.PST.med\nprint self.charAttribs.LCG.long\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
237,899
<p>I am using freeglut for opengl rendering...</p> <p>I need to draw an envelop looking like a cone (2D) that has to be filled with some color and some transparency applied.</p> <p>Is the freeglut toolkit equipped with such an inbuilt functionality to draw filled geometries(or some trick)? or is there some other api that has an inbuilt support for filled up geometries..</p> <p><strong>Edit1:</strong> just to clarify the 2D cone thing... the envelop is the graphical interpretation of the coverage area of an aircraft during interception(of an enemy aircraft)...that resembles a sector of a circle..i should have mentioned sector instead..</p> <p>and glutSolidCone doesnot help me as i want to draw a filled sector of a circle...which i have already done...what remains to do is to fill it with some color... how to fill geometries with color in opengl?</p> <p><strong>Edit2:</strong> All the answers posted to this questions can work for my problem in a way.. But i would definitely would want to know a way how to fill a geometry with some color. Say if i want to draw an envelop which is a parabola...in that case there would be no default glut function to actually draw a filled parabola(or is there any?).. So to generalise this question...how to draw a custom geometry in some solid color?</p> <p><strong>Edit3:</strong> The answer that mstrobl posted works for GL_TRIANGLES but for such a code:</p> <pre><code>glBegin(GL_LINE_STRIP); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glEnd(); </code></pre> <p>which draws a square...only a wired square is drawn...i need to fill it with blue color.</p> <p>anyway to do it?</p> <p>if i put some drawing commands for a closed curve..like a pie..and i need to fill it with a color is there a way to make it possible...</p> <p>i dont know how its possible for GL_TRIANGLES... but how to do it for any closed curve?</p>
[ { "answer_id": 237905, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "current_weapon * self.medium\n class Weapon\n hit = 1\n #other properties of weapon\n\nclass Rifle(Weapon)\n #other properties of Rifle\n\nclass Pistol(Weapon)\n #other properties of Pistol\n\nclass Character\n weapon = Rifle()\n long=0.6\n def calcHit()\n return self.long*weapon.hit\n\njohn = Character()\njohn.weapon= Rifle()\njohn.calcHit\n" }, { "answer_id": 237906, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 0, "selected": false, "text": "def bh_short(self, key)\n skill = self.skill_dict.get(key, 0)\n return skill * 0.6\n" }, { "answer_id": 237907, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 3, "selected": false, "text": "SHORT_RANGE = 'S'\nMEDIUM_RANGE = 'M'\nLONG_RANGE = 'L'\nSHORT_RANGE_MODIFIER = 0.6\nMEDIUM_RANGE_MODIFIER = 0.3\nLONG_RANGE_MODIFIER = 0.1\n\nclass Weapon(object):\n def __init__(self, code_name, full_name, base_hit_value,\n short_range_modifier=None, medium_range_modifier=None,\n long_range_modifier=None):\n self.code_name, self.full_name = code_name, full_name\n self.base_hit_value = base_hit_value\n self.range_modifiers = {\n SHORT_RANGE: short_range_modifier or SHORT_RANGE_MODIFIER,\n MEDIUM_RANGE: medium_range_modifier or MEDIUM_RANGE_MODIFIER,\n LONG_RANGE: long_range_modifier or LONG_RANGE_MODIFIER,\n }\n\n def hit_value(self, range, modifier=1):\n return self.base_hit_value * self.range_modifiers[range] * modifier\n self.rifle = Weapon('CRM', 'rifle', 5)\n self.pistol = Weapon('PST', 'pistol', 10)\n hit_value = self.pistol.hit_value(SHORT_RANGE)\n" }, { "answer_id": 239131, "author": "monopocalypse", "author_id": 17142, "author_profile": "https://Stackoverflow.com/users/17142", "pm_score": 0, "selected": false, "text": "class WeaponAttribute(object):\n\n short_mod = 0.6\n med_mod = 0.3\n long_mod = 0.1\n\n def __init__(self, base):\n self.base = base\n\n @property\n def short(self):\n return self.base * self.short_mod\n\n @property\n def med(self):\n return self.base * self.med_mod\n\n @property\n def long(self):\n return self.base * self.long_mod\n\n\nclass CharacterAttributes(object):\n\n def __init__(self, attributes):\n for weapon, base in attributes.items():\n setattr(self, weapon, WeaponAttribute(base))\n CharacterAttributes # Initialise\nself.charAttribs = CharacterAttributes(self.skill_dict)\n# Get some values\nprint self.charAttribs.CRM.short\nprint self.charAttribs.PST.med\nprint self.charAttribs.LCG.long\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30868/" ]
237,914
<p>Ok, I am trying to use Tail to monitor a log file, but I cannot get the same behavior programatically as when I manually run it through cmd prompt using the same parameters.</p> <p>When run through cmd prompt it displays the new lines <strong>instantly</strong>. Programatically though, I have to wait for about <strong>75+ new lines</strong> in log file before the 'buffer' unleashes all the lines.</p> <p>Here's the code I have now.</p> <pre><code>private const string tailExecutable = @&quot;C:\tail.exe&quot;; private const string logFile = @&quot;C:\test.log&quot;; private static void ReadStdOut() { var psi = new ProcessStartInfo { FileName = tailExecutable, Arguments = String.Format(&quot;-f \&quot;{0}\&quot;&quot;, logFile), UseShellExecute = false, RedirectStandardOutput = true }; // Running same exe -args through cmd.exe // works perfectly, but not programmatically. Console.WriteLine(&quot;{0} {1}&quot;, psi.FileName, psi.Arguments); var tail = new Process(); tail.StartInfo = psi; tail.OutputDataReceived += tail_OutputDataReceived; tail.Start(); tail.BeginOutputReadLine(); } static void tail_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } </code></pre> <p>I have used the OutputDataReceived event before but never had these buffering/spamming problems.</p> <p>I am so confused with about right now.</p> <h2>* <strong>Edit</strong> *</h2> <p>I found <a href="http://www.codeproject.com/KB/cs/wintail.aspx" rel="nofollow noreferrer">this wintail project on CodeProject</a> and am going to be switching to that because the buffer makes this solution way too slow.</p> <p>Thanks for the answers.</p>
[ { "answer_id": 237956, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 1, "selected": false, "text": "\n System.Console.Error\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1147/" ]
237,921
<p>I have a tabview controller to which I added a UIViewController to each tab. I want to have multiple UIViews inside the UIViewController.</p> <p>So in the implementation of the UIViewController class I added [self.view addSubView:uiview1] and [self.view addSubView:uiview2]. The problem is that when I run the app, it crahes on load.</p> <p>However, if I only used a single UIView and did: self.view = UIView1 that would work fine.</p> <p>Does anyone know what is causing the problem? Or if I'm doing something fundamentally wrong?</p>
[ { "answer_id": 238269, "author": "Mike McMaster", "author_id": 544, "author_profile": "https://Stackoverflow.com/users/544", "pm_score": 3, "selected": true, "text": "self.view = [[[UIView alloc] initWithFrame:someFrame] autorelease];\n [self.view addSubview:uiview1];\n[self.view addSubview:uiview2];\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
237,938
<p>We have a few XML based interfaces that is quite well documented in XSD schemas. The interfaces are now going to be publicly available and we would like to create reference documentation for them.</p> <p>Is there a tool that can automatically convert XSD files into some more readable format?</p>
[ { "answer_id": 2176503, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"xs3p.xsl\"?>\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918/" ]
237,966
<p>The framework I am developing for my application relies very heavily on dynamically generated domain objects. I recently started using Spring WebFlow and now need to be able to serialize my domain objects that will be kept in flow scope. </p> <p>I have done a bit of research and figured out that I can use <code>writeReplace()</code> and <code>readResolve()</code>. The only catch is that I need to look-up a factory in the Spring context. I tried to use <code>@Configurable(preConstruction = true)</code> in conjunction with the BeanFactoryAware marker interface. </p> <p>But <code>beanFactory</code> is always <code>null</code> when I try to use it in my <code>createEntity()</code> method. Neither the default constructor nor the <code>setBeanFactory()</code> injector are called.</p> <p>Has anybody tried this or something similar? I have included relevant class below.</p> <p>Thanks in advance, Brian</p> <pre><code>/* * Copyright 2008 Brian Thomas Matthews Limited. * All rights reserved, worldwide. * * This software and all information contained herein is the property of * Brian Thomas Matthews Limited. Any dissemination, disclosure, use, or * reproduction of this material for any reason inconsistent with the * express purpose for which it has been disclosed is strictly forbidden. */ package com.btmatthews.dmf.domain.impl.cglib; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.util.StringUtils; import com.btmatthews.dmf.domain.IEntity; import com.btmatthews.dmf.domain.IEntityFactory; import com.btmatthews.dmf.domain.IEntityID; import com.btmatthews.dmf.spring.IEntityDefinitionBean; /** * This class represents the serialized form of a domain object implemented * using CGLib. The readResolve() method recreates the actual domain object * after it has been deserialized into Serializable. You must define * &amp;lt;spring-configured/&amp;gt; in the application context. * * @param &lt;S&gt; * The interface that defines the properties of the base domain * object. * @param &lt;T&gt; * The interface that defines the properties of the derived domain * object. * @author &lt;a href="mailto:brian@btmatthews.com"&gt;Brian Matthews&lt;/a&gt; * @version 1.0 */ @Configurable(preConstruction = true) public final class SerializedCGLibEntity&lt;S extends IEntity&lt;S&gt;, T extends S&gt; implements Serializable, BeanFactoryAware { /** * Used for logging. */ private static final Logger LOG = LoggerFactory .getLogger(SerializedCGLibEntity.class); /** * The serialization version number. */ private static final long serialVersionUID = 3830830321957878319L; /** * The application context. Note this is not serialized. */ private transient BeanFactory beanFactory; /** * The domain object name. */ private String entityName; /** * The domain object identifier. */ private IEntityID&lt;S&gt; entityId; /** * The domain object version number. */ private long entityVersion; /** * The attributes of the domain object. */ private HashMap&lt;?, ?&gt; entityAttributes; /** * The default constructor. */ public SerializedCGLibEntity() { SerializedCGLibEntity.LOG .debug("Initializing with default constructor"); } /** * Initialise with the attributes to be serialised. * * @param name * The entity name. * @param id * The domain object identifier. * @param version * The entity version. * @param attributes * The entity attributes. */ public SerializedCGLibEntity(final String name, final IEntityID&lt;S&gt; id, final long version, final HashMap&lt;?, ?&gt; attributes) { SerializedCGLibEntity.LOG .debug("Initializing with parameterized constructor"); this.entityName = name; this.entityId = id; this.entityVersion = version; this.entityAttributes = attributes; } /** * Inject the bean factory. * * @param factory * The bean factory. */ public void setBeanFactory(final BeanFactory factory) { SerializedCGLibEntity.LOG.debug("Injected bean factory"); this.beanFactory = factory; } /** * Called after deserialisation. The corresponding entity factory is * retrieved from the bean application context and BeanUtils methods are * used to initialise the object. * * @return The initialised domain object. * @throws ObjectStreamException * If there was a problem creating or initialising the domain * object. */ public Object readResolve() throws ObjectStreamException { SerializedCGLibEntity.LOG.debug("Transforming deserialized object"); final T entity = this.createEntity(); entity.setId(this.entityId); try { PropertyUtils.setSimpleProperty(entity, "version", this.entityVersion); for (Map.Entry&lt;?, ?&gt; entry : this.entityAttributes.entrySet()) { PropertyUtils.setSimpleProperty(entity, entry.getKey() .toString(), entry.getValue()); } } catch (IllegalAccessException e) { throw new InvalidObjectException(e.getMessage()); } catch (InvocationTargetException e) { throw new InvalidObjectException(e.getMessage()); } catch (NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } return entity; } /** * Lookup the entity factory in the application context and create an * instance of the entity. The entity factory is located by getting the * entity definition bean and using the factory registered with it or * getting the entity factory. The name used for the definition bean lookup * is ${entityName}Definition while ${entityName} is used for the factory * lookup. * * @return The domain object instance. * @throws ObjectStreamException * If the entity definition bean or entity factory were not * available. */ @SuppressWarnings("unchecked") private T createEntity() throws ObjectStreamException { SerializedCGLibEntity.LOG.debug("Getting domain object factory"); // Try to use the entity definition bean final IEntityDefinitionBean&lt;S, T&gt; entityDefinition = (IEntityDefinitionBean&lt;S, T&gt;)this.beanFactory .getBean(StringUtils.uncapitalize(this.entityName) + "Definition", IEntityDefinitionBean.class); if (entityDefinition != null) { final IEntityFactory&lt;S, T&gt; entityFactory = entityDefinition .getFactory(); if (entityFactory != null) { SerializedCGLibEntity.LOG .debug("Domain object factory obtained via enity definition bean"); return entityFactory.create(); } } // Try to use the entity factory final IEntityFactory&lt;S, T&gt; entityFactory = (IEntityFactory&lt;S, T&gt;)this.beanFactory .getBean(StringUtils.uncapitalize(this.entityName) + "Factory", IEntityFactory.class); if (entityFactory != null) { SerializedCGLibEntity.LOG .debug("Domain object factory obtained via direct look-up"); return entityFactory.create(); } // Neither worked! SerializedCGLibEntity.LOG.warn("Cannot find domain object factory"); throw new InvalidObjectException( "No entity definition or factory found for " + this.entityName); } } </code></pre>
[ { "answer_id": 238581, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 1, "selected": false, "text": "ApplicationContext BeanFactory ApplicationContext BeanFactory ApplicationContext" }, { "answer_id": 500568, "author": "krumpi", "author_id": 61162, "author_profile": "https://Stackoverflow.com/users/61162", "pm_score": 0, "selected": false, "text": "<aop:spring-configured /> <bean class=\"package.name.SerializedCGLibEntity\" scope=\"prototype\"> <property name=\"beanFactory\" value=\"whateverValue\"/> </bean>" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1969/" ]
237,977
<p>This is probably one of those easy questions.. I'm trying to redirect the user after they've successfully authenticated, or return them back to the login page. But the Success page is on a different route and I can't get the redirection to work..</p> <p>Here are my routes in Globals.asax:</p> <pre><code>routes.MapRoute( _ "Default", _ "{controller}/{action}/{id}", _ New With {.controller = "Login", .action = "Index", .id = ""} _ ) routes.MapRoute( _ "Stuff", _ "{controller}/{action}/{id}", _ New With {.controller = "Stuff", .action = "Index", .id = ""} _ ) </code></pre> <p>I've got 2 Controllers: <code>LoginController.vb</code> and <code>StuffController.vb</code>. The <code>Views/Login/Index.aspx</code> file contains a simple form with the code:</p> <pre><code>&lt;form method="post" action="/Login/Authenticate"&gt; </code></pre> <p>The <code>LoginController</code> contains the following code:</p> <pre><code>Function Authenticate() As RedirectToRouteResult ' authentication code commented out ;o) Return RedirectToRoute("Stuff") End Function </code></pre> <p>And the StuffController contains the following:</p> <pre><code>Function Index() ' show stuff.. Return View() ' return /Views/Stuff/Index.aspx End Function </code></pre> <p>Here's what I've tried so far:</p> <ul> <li>Function Authenticate()</li> <li>Function Authenticate() As ActionResult()</li> <li>Function Authenticate() As RedirectToRouteResult()</li> </ul> <p>all of which cause a Redirect Loop timeout in the browser. What am I missing?!</p>
[ { "answer_id": 237991, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 4, "selected": true, "text": "Return RedirectToRoute(\"Stuff\");\n RedirectToAction(\"Index\", \"Stuff\");\n" }, { "answer_id": 393672, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "routes.MapRoute( _ \n\"Stuff\", _\n\"\",_ \nNew With {.controller = \"Stuff\", .action = \"Index\", .id = \"\"} _ \n)\n" }, { "answer_id": 4302543, "author": "Tengiz", "author_id": 523720, "author_profile": "https://Stackoverflow.com/users/523720", "pm_score": 4, "selected": false, "text": "return RedirectToRoute(\"Stuff\", (RouteTable.Routes[\"Stuff\"] as Route).Defaults);\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
237,978
<p>An <a href="https://stackoverflow.com/questions/61278/quick-and-dirty-way-to-profile-your-code#231614">answer to one of my questions</a> included the following line of code:</p> <pre><code>label = std::safe_string(name); // label is a std::string </code></pre> <p>The intent seems to be a wrapper around a string literal (so presumably no allocation takes place). I've never heard of <code>safe_string</code> and neither, apparently, has <a href="http://www.google.com/search?q=%22std%3A%3Asafe_string%22" rel="nofollow noreferrer">google</a> (nor could I find it in the 98 standard). </p> <p>Does anyone know what this is about?</p>
[ { "answer_id": 237996, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 2, "selected": false, "text": "std::safe_string" }, { "answer_id": 238032, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 4, "selected": true, "text": "//tools-cgi.cpp\nstring safe_string (const char * s)\n{\n return (s != NULL) ? s : \"\";\n}\n NULL" }, { "answer_id": 238103, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "// defined somewhere else as \"\"\nextern const char * const g_strEmptyString ;\n\ninline const char * safe_string(const char * p)\n{\n return (p) ? (p) : (g_strEmptyString) ;\n}\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
237,987
<p>I'm a recent semi-convert to Eclipse after 20 years of using vi and gvim. One of the things I miss about gvim is that I could cut a bunch of different snippets of code into named buffers, and paste them at will when doing something like repeating a common idiom. For instance I'd have it so <code>"ap</code> would paste</p> <pre><code>DatabaseHandle handle = null; try { handle = DatabaseConnectionPool.newHandle(); </code></pre> <p>and then <code>"bp</code> would paste</p> <pre><code> handle.commit(); } finally { handle.rollback(); DatabaseConnectionPool.returnHandle(handle); } </code></pre> <p>And I could repeat both of them over and over in the course of a day. In an answer to another question, somebody mentioned that you could "manage code snippets" in Eclipse, but didn't mention how. So now I'm asking: how do you manage code snippets in Eclipse? </p>
[ { "answer_id": 238042, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 7, "selected": true, "text": "dbHandle ctrl+space" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/237987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333/" ]
238,002
<p>How can I replace Line Breaks within a string in C#?</p>
[ { "answer_id": 238005, "author": "The.Anti.9", "author_id": 2128, "author_profile": "https://Stackoverflow.com/users/2128", "pm_score": 2, "selected": false, "text": "Line.Replace(\"\\n\", \"whatever you want to replace with\");\n" }, { "answer_id": 238014, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": false, "text": "string ReplaceNewlines(string blockOfText, string replaceWith)\n{\n return blockOfText.Replace(\"\\r\\n\", replaceWith).Replace(\"\\n\", replaceWith).Replace(\"\\r\", replaceWith);\n}\n" }, { "answer_id": 238016, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 8, "selected": false, "text": "string replaceWith = \"\";\nstring removedBreaks = Line.Replace(\"\\r\\n\", replaceWith).Replace(\"\\n\", replaceWith).Replace(\"\\r\", replaceWith);\n" }, { "answer_id": 238020, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 11, "selected": true, "text": "Environment.NewLine myString = myString.Replace(System.Environment.NewLine, \"replacement text\"); //add a line terminating ;\n" }, { "answer_id": 238025, "author": "driis", "author_id": 13627, "author_profile": "https://Stackoverflow.com/users/13627", "pm_score": 4, "selected": false, "text": "Environment.NewLine newline line = line.Replace(Environment.NewLine, \"newLineReplacement\");\n \\n \\r\\n" }, { "answer_id": 238030, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": false, "text": "string line = ...\n\nline = line.Replace( \"\\r\", \"\").Replace( \"\\n\", \"\" );\n public static class StringExtensions\n{\n public static string RemoveLineBreaks( this string lines )\n {\n return lines.Replace( \"\\r\", \"\").Replace( \"\\n\", \"\" );\n }\n\n public static string ReplaceLineBreaks( this string lines, string replacement )\n {\n return lines.Replace( \"\\r\\n\", replacement )\n .Replace( \"\\r\", replacement )\n .Replace( \"\\n\", replacement );\n }\n}\n" }, { "answer_id": 1858752, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "string s = Regex.Replace(source_string, \"\\n\", \"\\r\\n\");\n string s = Regex.Replace(source_string, \"\\r\\n\", \"\\n\");\n" }, { "answer_id": 3666952, "author": "data", "author_id": 221042, "author_profile": "https://Stackoverflow.com/users/221042", "pm_score": 2, "selected": false, "text": "yourString.Replace(\"\\r\\n\",\"\\n\") //handling windows linebreaks\n.Replace(\"\\r\",\"\\n\") //handling mac linebreaks\n" }, { "answer_id": 3915190, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 3, "selected": false, "text": "var answer = Regex.Replace(value, \"(\\n|\\r)+\", replacementString);\n" }, { "answer_id": 7195741, "author": "Zamir", "author_id": 868582, "author_profile": "https://Stackoverflow.com/users/868582", "pm_score": 3, "selected": false, "text": "\\r\\n \\t public string Transform(string data)\n{\n string result = data;\n char cr = (char)13;\n char lf = (char)10;\n char tab = (char)9;\n\n result = result.Replace(\"\\\\r\", cr.ToString());\n result = result.Replace(\"\\\\n\", lf.ToString());\n result = result.Replace(\"\\\\t\", tab.ToString());\n\n return result;\n}\n" }, { "answer_id": 8196219, "author": "Mark Byers", "author_id": 61974, "author_profile": "https://Stackoverflow.com/users/61974", "pm_score": 9, "selected": false, "text": "Environment.NewLine string.Replace string result = Regex.Replace(input, @\"\\r\\n?|\\n\", replacementString);\n" }, { "answer_id": 12569009, "author": "Amrik", "author_id": 1695004, "author_profile": "https://Stackoverflow.com/users/1695004", "pm_score": 2, "selected": false, "text": "\\n \\r \\r\\n \\r \\r\\n \\n parseCSV function parseCSV(data) {\n //alert(data);\n //replace UNIX new lines\n data = data.replace(/\\r\\n/g, \"\\n\");\n //replace MAC new lines\n data = data.replace(/\\r/g, \"\\n\");\n //split into rows\n var rows = data.split(\"\\n\");\n}\n" }, { "answer_id": 35508201, "author": "Dominik Szymański", "author_id": 5951777, "author_profile": "https://Stackoverflow.com/users/5951777", "pm_score": 4, "selected": false, "text": "string.Replace(\"\\r\\n\", \"\\n\").Replace('\\r', '\\n').Replace('\\n', 'replacement');\n" }, { "answer_id": 36323161, "author": "RAY", "author_id": 1914557, "author_profile": "https://Stackoverflow.com/users/1914557", "pm_score": 3, "selected": false, "text": "string ReplacementString = \"\";\n\nRegex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @\"(\\r\\n?|\\n)\", ReplacementString);\n strin" }, { "answer_id": 48881719, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 1, "selected": false, "text": "StringReader .ReadLine() StringBuilder .AppendLine" }, { "answer_id": 52797492, "author": "ewwink", "author_id": 458214, "author_profile": "https://Stackoverflow.com/users/458214", "pm_score": 4, "selected": false, "text": "@\"[\\r\\n]+\" using System;\nusing System.Text.RegularExpressions;\n\nclass MainClass {\n public static void Main (string[] args) {\n string str = \"AAA\\r\\nBBB\\r\\n\\r\\n\\r\\nCCC\\r\\r\\rDDD\\n\\n\\nEEE\";\n\n Console.WriteLine (str.Replace(System.Environment.NewLine, \"-\"));\n /* Result:\n AAA\n -BBB\n -\n -\n -CCC\n\n\n DDD---EEE\n */\n Console.WriteLine (Regex.Replace(str, @\"\\r\\n?|\\n\", \"-\"));\n // Result:\n // AAA-BBB---CCC---DDD---EEE\n\n Console.WriteLine (Regex.Replace(str, @\"[\\r\\n]+\", \"-\"));\n // Result:\n // AAA-BBB-CCC-DDD-EEE\n }\n}\n" }, { "answer_id": 56439378, "author": "Tadej", "author_id": 7199922, "author_profile": "https://Stackoverflow.com/users/7199922", "pm_score": 0, "selected": false, "text": "var input = @\"sdfhlu \\r\\n sdkuidfs\\r\\ndfgdgfd\";\nvar match = @\"[\\\\ ]+\";\nvar replaceWith = \" \";\nConsole.WriteLine(\"input: \" + input);\nvar x = Regex.Replace(input.Replace(@\"\\n\", replaceWith).Replace(@\"\\r\", replaceWith), match, replaceWith);\nConsole.WriteLine(\"output: \" + x);\n var input = @\"sdfhlusdkuidfs\\r\\ndfgdgfd\";\nvar match = @\"[\\\\s]+\";\nvar replaceWith = \"\";\nConsole.WriteLine(\"input: \" + input);\nvar x = Regex.Replace(input, match, replaceWith);\nConsole.WriteLine(\"output: \" + x);\n" }, { "answer_id": 70244795, "author": "MSS", "author_id": 4238323, "author_profile": "https://Stackoverflow.com/users/4238323", "pm_score": -1, "selected": false, "text": "string result = Regex.Replace(ex.Message, @\"(\\r\\n?|\\r?\\n)+\", \"replacement text\");\n \\r\\n \\n \\r" }, { "answer_id": 70737257, "author": "Boris Dligach", "author_id": 7888235, "author_profile": "https://Stackoverflow.com/users/7888235", "pm_score": 4, "selected": false, "text": "myString = myString.ReplaceLineEndings();\n" }, { "answer_id": 74438711, "author": "Pavel Stepanek", "author_id": 20137151, "author_profile": "https://Stackoverflow.com/users/20137151", "pm_score": 0, "selected": false, "text": "\"\\r\" \"\\n\" \\x0d \\u000D System.Environment.NewLine replace() MyStr.replace( System.String.Concat( System.Char.ConvertFromUtf32(13).ToString(), System.Char.ConvertFromUtf32(10).ToString() ), ReplacementString );\n \"\\r\" \"\\n\" \\x0d \\u000D System.Environment.NewLine replace() $([System.IO.File]::ReadAllText('MyFile.txt').replace( $([System.String]::Concat($([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString()))),$([System.String]::Concat('^',$([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString())))))\n" } ]
2008/10/26
[ "https://Stackoverflow.com/questions/238002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3821/" ]