qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
315,340 | <p>Nearly all programming languages used are <a href="http://en.wikipedia.org/wiki/Turing_Complete" rel="noreferrer">Turing Complete</a>, and while this affords the language to represent any <a href="http://en.wikipedia.org/wiki/Computability_theory_(computer_science)" rel="noreferrer">computable</a> algorithm, it also comes with its own set of <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="noreferrer">problems</a>. Seeing as all the algorithms I write are intended to halt, I would like to be able to represent them in a language that guarantees they will halt.</p>
<p><a href="http://en.wikipedia.org/wiki/Regular_Expression" rel="noreferrer">Regular expressions</a> used for matching strings and <a href="http://en.wikipedia.org/wiki/Finite_state_machine" rel="noreferrer">finite state machines</a> are used when <a href="http://en.wikipedia.org/wiki/Lexing" rel="noreferrer">lexing</a>, but I'm wondering if there's a more general, broadly language that's not Turing complete?</p>
<p><strong>edit:</strong> I should clarify, by 'general purpose' I don't necessarily want to be able to write all halting algorithms in the language (I don't think that such a language would exist) but I suspect that there are common threads in halting proofs that can be generalized to produce a language in which all algorithms are guaranteed to halt.</p>
<p>There's also another way to tackle this problem - eliminate the need for theoretically infinite memory. Once you limit the amount of memory the machine is allowed, the number of states the machine is in is finite and countable, and therefore you can determine if the algorithm will halt (by not allowing the machine to move into a state it's been in before).</p>
| [
{
"answer_id": 315401,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 4,
"selected": false,
"text": "function confusion()\n{\n if( halts( confusion ) )\n {\n while True:\n no-op\n }\n else\n return;\n}\n function nonhalting()\n{\n while 1:\n no-op\n}\n function simple_halting_function()\n{\n return 1;\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] |
315,358 | <p>What is the correct syntax for this:</p>
<pre><code>IList<string> names = "Tom,Scott,Bob".Split(',').ToList<string>().Reverse();
</code></pre>
<p>What am I messing up?
What does TSource mean?</p>
| [
{
"answer_id": 315365,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 2,
"selected": false,
"text": "List<string> names = new List<string>(\"Tom,Scott,Bob\".Split(','));\nnames.Reverse();\n"
},
{
"answer_id": 315369,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": true,
"text": "List<T>.Reverse() void List<string> names = \"Tom,Scott,Bob\".Split(',').ToList<string>();\nnames.Reverse();\n IList<string> names = \"Tom,Scott,Bob\".Split(',').Reverse().ToList<string>();\n IEnumerable<T> List<T> Enumerable.Reverse<T>() List<T>.Reverse() string[] namesArray = \"Tom,Scott,Bob\".Split(',');\nList<string> namesList = new List<string>(namesArray.Length);\nnamesList.AddRange(namesArray);\nnamesList.Reverse();\n"
},
{
"answer_id": 315377,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 3,
"selected": false,
"text": "List<string> names = \"Tom,Scott,Bob\".Split(',').Reverse().ToList();\n"
},
{
"answer_id": 315379,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 1,
"selected": false,
"text": "var x = \"Tom,Scott,Bob\".Split(',').Reverse().ToList<string>()\n"
},
{
"answer_id": 11339698,
"author": "Des Horsley",
"author_id": 692328,
"author_profile": "https://Stackoverflow.com/users/692328",
"pm_score": 4,
"selected": false,
"text": "string str = \"Tom, Scott, Bob\";\n IList<string> names = str.Split(new string[] {\",\",\" \"},\n StringSplitOptions.RemoveEmptyEntries);\n"
},
{
"answer_id": 45799171,
"author": "ablaze",
"author_id": 799593,
"author_profile": "https://Stackoverflow.com/users/799593",
"pm_score": 1,
"selected": false,
"text": "string str = \"Tom Cruise, Scott, ,Bob | at\";\nIEnumerable<string> names = str.Split(new char[] {',', '|', ' '}, StringSplitOptions.RemoveEmptyEntries);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36590/"
] |
315,362 | <p>tldr: Can someone show me how to properly format this Python iMAP example so it works?</p>
<p>from
<a href="https://docs.python.org/2.4/lib/imap4-example.html" rel="nofollow noreferrer">https://docs.python.org/2.4/lib/imap4-example.html</a></p>
<blockquote>
<pre><code>import getpass, imaplib
M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()
</code></pre>
</blockquote>
<p>Assuming my email is "email@gmail.com" and the password is "password," how should this look? I tried <code>M.login(getpass.getuser(email@gmail.com), getpass.getpass(password))</code>
and it timed out. Complete newb here, so it's very likely I missed something obvious (like creating an iMAP object first? Not sure).</p>
| [
{
"answer_id": 315387,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 2,
"selected": false,
"text": "M = imaplib.IMAP4_SSL( 'imap.gmail.com' )\n M = imaplib.IMAP4_SSL()\nM.open( 'imap.gmail.com' )\n"
},
{
"answer_id": 315710,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 4,
"selected": false,
"text": "import imaplib\n\n# you want to connect to a server; specify which server\nserver= imaplib.IMAP4_SSL('imap.googlemail.com')\n# after connecting, tell the server who you are\nserver.login('email@gmail.com', 'password')\n# this will show you a list of available folders\n# possibly your Inbox is called INBOX, but check the list of mailboxes\ncode, mailboxen= server.list()\nprint mailboxen\n# if it's called INBOX, then…\nserver.select(\"INBOX\")\n"
},
{
"answer_id": 316457,
"author": "Brian C. Lane",
"author_id": 27461,
"author_profile": "https://Stackoverflow.com/users/27461",
"pm_score": 4,
"selected": false,
"text": "#!/usr/bin/env python\n\n''' Utility to scan my mailbox for new mesages from Logwatch on systems and then\n grab useful info from the message and output a summary page.\n\n by Brian C. Lane <bcl@brianlane.com>\n'''\nimport os, sys, imaplib, rfc822, re, StringIO\n\nserver ='mail.brianlane.com'\nusername='yourusername'\npassword='yourpassword'\n\nM = imaplib.IMAP4_SSL(server)\nM.login(username, password)\nM.select()\ntyp, data = M.search(None, '(UNSEEN SUBJECT \"Logwatch\")')\nfor num in data[0].split():\n typ, data = M.fetch(num, '(RFC822)')\n# print 'Message %s\\n%s\\n' % (num, data[0][1])\n\n match = re.search( \"^(Users logging in.*?)^\\w\",\n data[0][1],\n re.MULTILINE|re.DOTALL )\n if match:\n file = StringIO.StringIO(data[0][1])\n message = rfc822.Message(file)\n print message['from']\n print match.group(1).strip()\n print '----'\n\nM.close()\nM.logout()\n"
},
{
"answer_id": 29733692,
"author": "Tobias Kienzler",
"author_id": 321973,
"author_profile": "https://Stackoverflow.com/users/321973",
"pm_score": 0,
"selected": false,
"text": "M.login(getpass.getuser(email@gmail.com), getpass.getpass(password)) M.login('email@gmail.com', 'password') getpass getuser email@gmail.com"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
315,363 | <p>I have a nice and lovely Django site up and running, but have noticed that my <code>error.log</code> file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like <code>http://mysite.com/ie</code> or <code>http://mysite.com/~admin.php</code> etc. </p>
<p>Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a <code>TemplateDoesNotExist</code> exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.</p>
<p>Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?</p>
| [
{
"answer_id": 315596,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 2,
"selected": false,
"text": "DISALLOWED_USER_AGENT DISALLOWED_USER_AGENTS = (\n re.compile(r'Java'),\n re.compile(r'gigamega'),\n re.compile(r'litefinder'),\n)\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] |
315,378 | <p>When coding, what is a good rule of thumb to keep in mind with respect to performance? There are endless ways to optimize for a specific platform and compiler, but I'm looking for answers that apply equally well (or almost) across compilers and platforms.</p>
| [
{
"answer_id": 315415,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "if switch void doit(int m) { switch(m) { case 1: f1(); break; case 2: f2(); break; } } void doit(void(*m)()) { m(); } ++t t++ const new T t[N] = { }; operator() std::vector std::string boost::array<T, Size>"
},
{
"answer_id": 315451,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "if () template <typename T>\nstruct add {\n operator T ()(T const& a, T const& b) const { return a + b; }\n};\n\nint result = add<int>()(1, 2);\n std::unary_function std::binary_function typedef <int> make pair template <typename T1, typename T2>\npair<T1, T2> make_pair(T1 const& first, T2 const& second) {\n return pair<T1, T2>(first, second);\n}\n\n// Implied types:\npair<int, float> pif = make_pair(1, 1.0f);\n template <typename T, typename R>\nstruct UnaryFunctionoid {\n virtual R invoke(T const& value) const = 0;\n};\n\nstruct IsEvenFunction : UnaryFunctionoid<int, bool> {\n bool invoke(int const& value) const { return value % 2 == 0; }\n};\n\n// call it, somewhat clumsily:\nUnaryFunctionoid const& f = IsEvenFunction();\nf.invoke(4); // true\n"
},
{
"answer_id": 315647,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 1,
"selected": false,
"text": "sizeof(object) sizeof(object) for(int i = 0 ; i < n ; i++){\n for(int j = 0 ; j < m ; j++){\n arr[i,j] = f();\n for(int i = 0 ; i < n ; i++){\n for(int j = 0 ; j < m ; j++){\n arr[j,i] = f();\n GetTickCount"
},
{
"answer_id": 316305,
"author": "Alastair",
"author_id": 31038,
"author_profile": "https://Stackoverflow.com/users/31038",
"pm_score": 1,
"selected": false,
"text": "std::vector"
},
{
"answer_id": 378569,
"author": "Mark Beckwith",
"author_id": 45799,
"author_profile": "https://Stackoverflow.com/users/45799",
"pm_score": 0,
"selected": false,
"text": "new"
},
{
"answer_id": 388593,
"author": "harishvk27",
"author_id": 48606,
"author_profile": "https://Stackoverflow.com/users/48606",
"pm_score": 1,
"selected": false,
"text": "class x {\n\nx::x(char *str):m_x(str) {} // and not as x::x(char *str) { m_str(str); }\n\nprivate:\nstd::string m_x;\n\n};\n"
},
{
"answer_id": 48272289,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "// Stores millions of strings.\nstd::vector<std::string> boatload_of_strings;\n std::string sizeof(std::string) class BoatloadOfStrings\n{\npublic:\n // Returns the nth string.\n const char* operator[](int n) const\n {\n return buffer.data() + string_start[n];\n }\n\n // Inserts a string.\n void insert(const char* str)\n {\n string_start.push_back(buffer.size());\n buffer.insert(buffer.end(), str, str + strlen(str)+1);\n }\n\nprivate:\n // Stores all the characters of all null-terminated\n // strings in one giant buffer.\n std::vector<char> buffer;\n\n // Stores the starting position of each null-terminated\n // string.\n std::vector<size_t> string_start;\n};\n std::vector std::string BoatloadOfStrings class IPixel\n{\npublic:\n virtual ~IPixel() {}\n\n // Abstract pixel operations.\n ...\n};\n class IImage\n{\npublic:\n virtual ~IImage() {}\n\n // Abstract image operations.\n ...\n};\n class Creature\n{\npublic:\n virtual ~Creature() {}\n\n // Abstract creature operations.\n ...\n};\n\nclass Human: public Creature\n{\n ...\n};\n\nclass Orc: public Creature\n{\n ...\n};\n\nclass Undead: public Creature\n{\n ...\n};\n Creature* class CreatureHorde\n{\npublic:\n virtual ~CreatureHorde() {}\n\n // Abstract creature horde operations.\n ...\n};\n\nclass HumanHorde: public CreatureHorde\n{\n ...\n};\n\nclass OrcHorde: public CreatureHorde\n{\n ...\n};\n\nclass UndeadHorde: public CreatureHorde\n{\n ...\n};\n CreatureHorde*"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13760/"
] |
315,381 | <p>I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An example would be very much appreciated. Thanks in advance. </p>
| [
{
"answer_id": 315404,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "match fnmatch fnmatch re.match"
},
{
"answer_id": 315430,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "import re\nimport os\nr = re.compile(r'\\d{2}.+gif$')\nfor root, dirs, files in os.walk('/home/vinko'):\n l = [os.path.join(root,x) for x in files if r.match(x)]\n if l: print l #Or append to a global list, whatever\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37804/"
] |
315,393 | <p>I have a KMainWindow:</p>
<pre><code>//file.h
class MainWindow: public KMainWindow {
public:
MainWindow(QWidget *parent = 0);
...
...
...
private slots:
void removeClick();
//file.cpp
MainWindow::MainWindow(QWidget *parent) :
KMainWindow(parent) {}
void MainWindow::removeClick()
{
std::cout << "Remove" << std::endl;
}
</code></pre>
<p>I can compile it correctly, but when I execute the I get the message</p>
<pre><code>Object::connect: No such slot KMainWindow::removeClick()
</code></pre>
<p>Can anybody help me?</p>
| [
{
"answer_id": 320769,
"author": "mxcl",
"author_id": 6444,
"author_profile": "https://Stackoverflow.com/users/6444",
"pm_score": 3,
"selected": true,
"text": "class MainWindow: public KMainWindow \n{\n Q_OBJECT\n\npublic:\n // [snip]\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39339/"
] |
315,402 | <p>The following exception is thrown:</p>
<p>Error Message: Microsoft.SqlServer.Management.Smo.FailedOperationException: Drop failed for Database '4d982a46-58cb-4ddb-8999-28bd5bb900c7'. ---> Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException: Cannot drop database "4d982a46-58cb-4ddb-8999-28bd5bb900c7" because it is currently in use.</p>
<p>Any idea what caused this?</p>
<p>Is it possible to call a SMO function to finalize any running Transact-SQL statements?</p>
| [
{
"answer_id": 315417,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "SqlConnection using"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11135/"
] |
315,403 | <p>I am using windows authentication within an ASP.NET application. I am wondering how to best get the objectGuid from the currently logged in user?</p>
<p>Regards, Egil.</p>
| [
{
"answer_id": 316721,
"author": "PhilPursglove",
"author_id": 1738,
"author_profile": "https://Stackoverflow.com/users/1738",
"pm_score": 3,
"selected": true,
"text": "Dim entry As DirectoryServices.DirectoryEntry\nDim mySearcher As System.DirectoryServices.DirectorySearcher\nDim result As System.DirectoryServices.SearchResult\nDim myEntry As DirectoryEntry\nDim domainName As String\nDim userId As String\nDim objectGuid As Guid\n\n'Split the username into domain and userid parts\ndomainName = Page.User.Identity.Name.Substring(0, Page.User.Identity.Name.IndexOf(\"\\\"))\nuserId = Page.User.Identity.Name.Substring(Page.User.Identity.Name.IndexOf(\"\\\") + 1)\n\n'Start at the top level domain\nentry = New DirectoryEntry(domainName)\n\nmySearcher = New DirectorySearcher(entry)\n\n'Build a filter for just the user\nmySearcher.Filter = (\"(&(anr=\" & userId & \")(objectClass=user))\")\n\n'Get the search result ...\nresult = mySearcher.FindOne\n\n'... and then get the AD entry that goes with it\nmyEntry = result.GetDirectoryEntry\n\n'The Guid property is the objectGuid\nobjectGuid = myEntry.Guid\n"
},
{
"answer_id": 828211,
"author": "Pavel Chuchuva",
"author_id": 14131,
"author_profile": "https://Stackoverflow.com/users/14131",
"pm_score": 2,
"selected": false,
"text": "string login = HttpContext.Current.User.Identity.Name;\nstring domain = login.Substring(0, login.IndexOf('\\\\'));\nstring userName = login.Substring(login.IndexOf('\\\\') + 1);\nDirectoryEntry domainEntry = new DirectoryEntry(\"LDAP://\" + domain);\nDirectorySearcher searcher = new DirectorySearcher(domainEntry);\nsearcher.Filter = string.Format(\n \"(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))\",\n userName);\nSearchResult searchResult = searcher.FindOne();\nDirectoryEntry entry = searchResult.GetDirectoryEntry();\nGuid objectGuid = new Guid(entry.NativeGuid);\n"
},
{
"answer_id": 2589201,
"author": "Felan",
"author_id": 307105,
"author_profile": "https://Stackoverflow.com/users/307105",
"pm_score": 4,
"selected": false,
"text": "// using System.Security.Principal;\nIPrincipal userPrincipal = HttpContext.Current.User;\nWindowsIdentity windowsId = userPrincipal.Identity as WindowsIdentity;\nif (windowsId != null)\n{\n SecurityIdentifier sid = windowsId.User;\n\n using(DirectoryEntry userDe = new DirectoryEntry(\"LDAP://<SID=\" + sid.Value + \">\"))\n {\n Guid objectGuid = new Guid(userDe.NativeGuid);\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32809/"
] |
315,435 | <p>I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?</p>
<p>I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid in some part that should be fairly simple. So.... </p>
| [
{
"answer_id": 315454,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "gameBoard[10,10]\n enum tile\n{\n none,\n white,\n black\n}\n for (int i = 0; i < 10; i++)\n{\n for (int j = 0; j < 10; j++)\n {\n // The Piece to draw would be at gameBoard[i,j];\n // Pixel locations are calculated by multiplying the array location by an offset.\n DrawPiece(gameBoard[i,j],i * Width of Tile, j * width of tile);\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
315,437 | <p>Is there some way to detect file handle leaks at program termination? </p>
<p>In particular I would like to make sure that all of my handles that get created are being freed in code. </p>
<p>For example, I may have a CreateFile() somewhere, and at program termination I want to detect and ensure that all of them are closed. </p>
| [
{
"answer_id": 442695,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 2,
"selected": false,
"text": "CreateFile CloseHandle // StdAfx.h\n#include <windows.h>\n#undef CreateFile\n#if defined(UNICODE)\n #define CreateFile DbgCreateFileW\n#else\n #define CreateFile DbgCreateFileA\n#endif\n\n// etc.\n DbgCreateFileW DbgCreateFileA CloseHandle"
},
{
"answer_id": 3131331,
"author": "Vivian De Smedt",
"author_id": 329318,
"author_profile": "https://Stackoverflow.com/users/329318",
"pm_score": 4,
"selected": true,
"text": "!htrace -enable\n!htrace -snapshot\n!htrace -diff\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
315,459 | <p>I will have around 200,000 images as part of my website. Each image will be stored 3 times: full size, thumbnail, larger thumbnail. Full size images are around 50Kb to 500Kb.</p>
<p>Normal tech: Linux, Apache, MySQL, PHP on a VPS.</p>
<p>What is the optimum way to store these for fast retrieval and display via a browser??</p>
<p>Should I store everything in a single folder?
Should I store the full size images in 1 folder, the thumbails in another etc?
Should I store the images in folders of 1000, and keep an index to which folder the image is in?</p>
<p>Thanks for any advice.
Albert.</p>
| [
{
"answer_id": 315494,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "/images/I/M/G/8/IMG8993:\nIMG8993_full.jpg\nIMG8993_thumb.jpg\nIMG8993_smallthumb.jpg\n"
},
{
"answer_id": 315524,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 0,
"selected": false,
"text": "ls"
},
{
"answer_id": 315541,
"author": "Jeremy Frey",
"author_id": 13412,
"author_profile": "https://Stackoverflow.com/users/13412",
"pm_score": 1,
"selected": false,
"text": "/imageServer.php?userID=12345imageId=67890&size=full\n /jeremyZX/images/myPhoto.jpg\n/jeremyZX/images/tn/myPhoto.jpg\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
315,464 | <p>Consider the following dialog with the command-line interface to the kernel:</p>
<pre><code>$ math
Mathematica 6.0 for Linux x86 (32-bit)
In[1]:= p = Plot[x^2, {x,-1,1}]
Out[1]= -Graphics-
In[2]:= Export["foo.png", p]
Out[2]= foo.png
</code></pre>
<p>That works fine on a machine with <code>$Version = 6.0 for Linux x86 (32-bit) (June 2, 2008)</code> but fails on a machine with <code>$Version = 7.0 for Linux x86 (64-bit) (November 11, 2008)</code> with the following error:</p>
<pre><code>Export::nofe: A front end is not available; export of PNG
requires a front end.
</code></pre>
<p>With similar errors for any other image format I can think of.</p>
<p>So the question is, how can I get the Mathematica kernel, sans front end, to export images? Why does it work without a hitch in Mathematica 6.0? If the above example works for you in version 7, please let me know!</p>
<p>PS: Version 7 introduced the function <code>UsingFrontEnd</code> but that fails with</p>
<pre><code>Developer`UseFrontEnd::nofestart:
Unable to launch a front end. Proceeding without a front end.
</code></pre>
<p>presumably because X11 is not installed on the machine.</p>
<h3>Addendum</h3>
<p>It turns out there is no difference between version 6 and version 7 in this regard. Rather, on the machine with version 6, the front end was being invoked silently. The problem with the other machine, as the answers to this question make clear, is that there was no X server and so the front end could not be invoked.</p>
| [
{
"answer_id": 1703375,
"author": "trybik",
"author_id": 207241,
"author_profile": "https://Stackoverflow.com/users/207241",
"pm_score": 4,
"selected": true,
"text": "UseFrontEnd[Export[filename,graphics]] export DISPLAY=machine_address:0.0 -display machine_address:0.0 Xvfb :display_nr &"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
] |
315,475 | <p>is there an easy way to solve the following problem.</p>
<p>Let's say I fetch a IList with some books in my controller from my model. Now I want to enrich the output and fetch a preview from Amazon with another model from an outside framework and get another IList.</p>
<p>Now I put both ILists into a property bag.</p>
<p>In NVelocity I use a #foreach for the BookList, but how can I access the amazonbooklist with the right preview?
I cannot use $amazonbook[index], where index would be the isbn.
Do I really need to put both lists in one big list with a simple onject containing only the two other objects?</p>
<p>Remember, both models are from different frameworks and cannot be placed in one framework. Both frameworks have to stay seperated. I try to solve the NVelocity problem and ofcourse, this problem is just an example, we don't sell books ;)</p>
| [
{
"answer_id": 315594,
"author": "Ris Adams",
"author_id": 15683,
"author_profile": "https://Stackoverflow.com/users/15683",
"pm_score": 2,
"selected": true,
"text": "class BookList{\n MyBookObject a;\n AmazonBookObject b;\n}\n"
},
{
"answer_id": 349265,
"author": "MZywitza",
"author_id": 44243,
"author_profile": "https://Stackoverflow.com/users/44243",
"pm_score": 3,
"selected": false,
"text": "$amazonbook.get_Item($index) \n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25233/"
] |
315,485 | <p>Does Visual Studio .NET have a way to toggle word-wrap on and off?</p>
<p>I am used to this feature in Eclipse which allows you to right click and toggle word wrap on and off so that when you have long lines that extend out to the right, you don't have to move the bottom scroll bar right and left to read your code/html:
<a href="http://web.archive.org/web/20131027224437/http://ahtik.com:80/blog/2006/06/18/first-alpha-of-eclipse-word-wrap-released/" rel="noreferrer">http://web.archive.org/web/20131027224437/http://ahtik.com:80/blog/2006/06/18/first-alpha-of-eclipse-word-wrap-released/</a></p>
| [
{
"answer_id": 55887378,
"author": "Judel5",
"author_id": 1236141,
"author_profile": "https://Stackoverflow.com/users/1236141",
"pm_score": 2,
"selected": false,
"text": "Visual Studio 2017"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
315,488 | <p>I have an AVI file, which I want to re-encode to fit on a CD of size 650 MB. How can I encode such that file size does not exceed the given size? Which program can I use ?</p>
| [
{
"answer_id": 315702,
"author": "Klathzazt",
"author_id": 35223,
"author_profile": "https://Stackoverflow.com/users/35223",
"pm_score": 2,
"selected": false,
"text": "C:\\Program Files\\Microsoft SDKs\\Windows\\v6.1\\Samples\\Multimedia\\DirectShow\\BaseClasses\n C:\\Program Files\\Microsoft SDKs\\Windows\\v6.1\\Samples\\Multimedia\\DirectShow\n C:\\Program Files\\Microsoft SDKs\\Windows\\v6.1\\Bin\\graphedt.exe\n"
},
{
"answer_id": 315730,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "target bit-rate = size / seconds\n seconds = (90mins * 60) = 5400\nsize = ((650MB * 1024) * 8) = 5324800\ntarget bit-rate = ~986 kilobytes per second\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37603/"
] |
315,495 | <p>I am currently using SQL Server Management Studio (Ver 9.00.3042.00) and click the "New Query" and wrote the following code:</p>
<pre><code>Select
colA,
colB,
colC
colD
From
table1
</code></pre>
<p>When I click the parse (checkbox) button to validate the SQL statement, it says "Command(s) completed successfully". Isn't the parse button suppose to catch these simple errors...</p>
<p>Has anyone experienced this type of behavior from Management Studio? This just started happening this week....</p>
| [
{
"answer_id": 315510,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 5,
"selected": true,
"text": "colC as colD\n Select \n colA\n , colB\n , colC\n colD\nFrom\n table1\n"
},
{
"answer_id": 315579,
"author": "Michael Kniskern",
"author_id": 26327,
"author_profile": "https://Stackoverflow.com/users/26327",
"pm_score": 0,
"selected": false,
"text": "Select \n colA, \n colB \n colC \n colD\nFrom \n table1\n\nSelect \n colA, \n colB, \n colC, \n colD,\nFrom \n table1\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
315,496 | <p>I have an object that implements <a href="http://www.php.net/~helly/php/ext/spl/interfaceArrayAccess.html" rel="nofollow noreferrer">ArrayAccess</a>, <a href="http://www.php.net/~helly/php/ext/spl/interfaceIterator.html" rel="nofollow noreferrer">Iterator</a> and <a href="http://www.php.net/~helly/php/ext/spl/interfaceCountable.html" rel="nofollow noreferrer">Countable</a>. That produces a nigh-perfect array masking. I can access it with offsets (<code>$object[foo]</code>), I can throw it into a <a href="http://php.net/foreach" rel="nofollow noreferrer"><code>foreach</code></a>-loop, and many other things.</p>
<p>But what I can't do is give it to the native array iterator functions (<code>next()</code>, <code>reset()</code>, <code>current()</code>, <code>key()</code>), even though I have implemented the required methods from Iterator. PHP seems to stubbornly try to iterate through its member variables, and entirely disregards the iterator-methods.</p>
<p>Is there an interface that would hook the object to the remaining array-traversing-functions, or am I stuck with what I have?</p>
<p><strong>Update:</strong> IteratorAggregate doesn't seem to be the answer either. While it is used in <code>foreach</code>-loops, the basic array iterator functions don't call the methods.</p>
| [
{
"answer_id": 315575,
"author": "majelbstoat",
"author_id": 38812,
"author_profile": "https://Stackoverflow.com/users/38812",
"pm_score": 2,
"selected": false,
"text": "class MyIterator implements Iterator {\n public function key() {\n //\n }\n\n public function rewind() {\n //\n }\n\n // etc.\n\n}\n\nclass MyMainClass implements IteratorAggregate {\n private $_data = array();\n\n // getIterator is required for the IteratorAggregate interface.\n public function getIterator() {\n return new MyIterator($this->_data);\n }\n\n // etc.\n\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] |
315,504 | <p>Do you have any tricks for generating SQL statements, mainly INSERTs, in Excel for various data import scenarios?</p>
<p>I'm really getting tired of writing formulas with like </p>
<p><code>="INSERT INTO Table (ID, Name) VALUES (" & C2 & ", '" & D2 & "')"</code></p>
| [
{
"answer_id": 315535,
"author": "Jason V",
"author_id": 27912,
"author_profile": "https://Stackoverflow.com/users/27912",
"pm_score": 6,
"selected": true,
"text": "=CONCATENATE(\"insert into table (id, name) values (\",C2,\",' \",D2,\" ');\") =CONCATENATE(\"insert into table (id, date, price) values (\",C3,\",'\",D3,\"',\",B3,\");\")"
},
{
"answer_id": 315982,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 0,
"selected": false,
"text": "=\"'\""
},
{
"answer_id": 1001355,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO \n [ODBC;Driver={SQL Server};SERVER=MYSERVER;DATABASE=MyDatabase;UID=sa;Pwd=mypassword;].MyTable (ID, Name)\nSELECT F1, F2\n FROM \n [Excel 8.0;HDR=NO;IMEX=1;Database=C:\\db.xls;].[Sheet1$A1:B4];\n"
},
{
"answer_id": 1101386,
"author": "Shannon Severance",
"author_id": 121544,
"author_profile": "https://Stackoverflow.com/users/121544",
"pm_score": 2,
"selected": false,
"text": "insert into table t1 values('<<A>>', '<<B>>')\n =SUBSTITUTE(SUBSTITUTE($C$1, \"<<A>>\", A2), \"<<B>>\", B2)\n $C$1 =concatenate(\"insert into table t1 values '\", A2, \"', '\", B2, \"')\"\n"
},
{
"answer_id": 5637760,
"author": "Peter Carswell",
"author_id": 704397,
"author_profile": "https://Stackoverflow.com/users/704397",
"pm_score": 1,
"selected": false,
"text": "dim SqlString as String\nSqlString = \"SELECT * FROM %1 WHERE (var=%2)\"\nSqlString = Replace(\"%1\", \"Table_Name\")\nSqlString = Replace(\"%2\", \"\"value\"\")\n SUBSTITUTE"
},
{
"answer_id": 28550019,
"author": "RubberDuck",
"author_id": 3198973,
"author_profile": "https://Stackoverflow.com/users/3198973",
"pm_score": 1,
"selected": false,
"text": "INSERT INTO table\nVALUES /*string that we don't want to type by hand*/\n SELECT *\nFROM table\nWHERE foo IN (/*another string I don't want to type out*/)\n Function SQLConcat(rng As Range, Optional quoted As Boolean = False, Optional parenthesis As Boolean = False) As String\n' ***************************************************************\n' * Returns a comma separated list for use in SQL IN statements *\n' * Params *\n' * - rng: Range of cells to concatenate *\n' * - quoted: True/False. If true, values are placed inside *\n' * of single quotes. Default of false *\n' * - parenthesis: Boolean. *\n' * Useful for INSERT INTO tbl VALUES(53),(90),(397) *\n' * *\n' * Author: Christopher J. McClellan *\n' * Published under Creative Commons Attribution-Share Alike *\n' * http://creativecommons.org/licenses/by-sa/3.0/ *\n' * You are free to change, distribute, and pretty much do *\n' * whatever you like with the code, but you must give credit *\n' * to the original author and publish any derivitive of this *\n' * code under the same license. *\n' ***************************************************************\n\nDim tmp As String 'temporary string\nDim row As Long 'first cell is special case\nrow = 0 'initalize row count\nDim c As Object 'cell\nDim txtwrapperLeft As String, txtwrapperRight As String\n\nIf quoted = True And parenthesis = False Then\n txtwrapperLeft = \"'\"\n txtwrapperRight = \"'\"\nElseIf quoted = True And parenthesis = True Then\n txtwrapperLeft = \"('\"\n txtwrapperRight = \"')\"\nElseIf quoted = False And parenthesis = True Then\n txtwrapperLeft = \"(\"\n txtwrapperRight = \")\"\nElse\n'quoted = false and parenthesis = false\n txtwrapperLeft = \"\"\n txtwrapperRight = \"\"\nEnd If\n\nFor Each c In rng.Cells\n If row = 0 Then\n tmp = txtwrapperLeft & c.Value & txtwrapperRight\n Else\n tmp = tmp & \",\" & txtwrapperLeft & c.Value & txtwrapperRight\n End If\n row = row + 1\n Debug.Print tmp\nNext c\n\n'return\nSQLConcat = tmp\nEnd Function\n"
},
{
"answer_id": 54764331,
"author": "Vivek Gajbhiye",
"author_id": 10052086,
"author_profile": "https://Stackoverflow.com/users/10052086",
"pm_score": 0,
"selected": false,
"text": "=CONCATENATE(\"INSERT INTO `database_name`.`table_name`(`Column_Name`,`Column_Name`) VALUES ( '\",A1,\"',\",B1,\"); \")\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11063/"
] |
315,507 | <p>For some reason, I am having trouble thinking of a good way to rewrite this function so it uses constant stack space. Most online discussions of tree recursion cheat by using the Fibonacci function and exploiting the properties of that particular problem. Does anyone have any ideas for this "real-world" (well, more real-world than the Fibonacci series) use of recursion?</p>
<p><a href="http://clojure.org" rel="noreferrer">Clojure</a> is an interesting case since it does not have tail-call optimization, but only tail recursion via the "recur" special form. It also strongly discourages the use of mutable state. It does have many lazy constructs including <a href="http://clojure.org/api#toc489" rel="noreferrer">tree-seq</a>, but I am not able to see how they can help me for this case. Can anyone share some techniques they have picked up from C, Scheme, Haskell, or other programming languages?</p>
<pre><code>(defn flatten [x]
(let [type (:type x)]
(cond (or (= type :NIL) (= type :TEXT))
x
(= type :CONCAT)
(doc-concat (flatten (:doc1 x))
(flatten (:doc2 x)))
(= type :NEST)
(doc-nest (:level x)
(flatten (:doc x)))
(= type :LINE)
(doc-text " ")
(= type :UNION)
(recur (:doc1 x)))))
</code></pre>
<p>edit: By request in the comments...</p>
<p>Restated in general terms and using Scheme -- how do I rewrite the following recursion pattern so it doesn't consume stack space or require tail-call optimization of non-self-calls?</p>
<pre><code>(define (frob x)
(cond ((foo? x)
x)
((bar? x)
(macerate (f x) (frob (g x))))
((thud? x)
(frobnicate (frob (g x))
(frob (h x))))))
</code></pre>
<p>I chose annoying names to drive home the point that I am looking for answers that don't rely on the algebraic properties of x, macerate, frobnicate, f, g, or h. I just want to rewrite the recursion.</p>
<p><strong>UPDATE</strong>:</p>
<p>Rich Hickey has kindly added an explicit <a href="http://lambda-the-ultimate.org/node/3106" rel="noreferrer">trampoline function</a> to Clojure.</p>
| [
{
"answer_id": 315875,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 2,
"selected": false,
"text": "(define (frob0 x k)\n (cond ((foo? x)\n (k x))\n ((bar? x)\n (frob0 (g x) \n (lambda (y) \n (k (macerate (f x) y))))\n ((thud? x)\n (frob0 (g x) \n (lambda (y)\n (frob0 (h x) \n (lambda (z)\n (k (frobnicate y z))))))))\n\n(define (frob x)\n (frob0 x (lambda (y) y))\n"
},
{
"answer_id": 315943,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 0,
"selected": false,
"text": "(define (doaction vars action)\n (cond ((symbol=? action 'frob)\n (cond ((foo? (first vars))\n (first vars))\n ((bar? (first vars))\n (doaction (list (f (first vars)) (doaction (g x) 'frob)) 'macerate)\netc...\n"
},
{
"answer_id": 315994,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 4,
"selected": true,
"text": "push x,1 on homemade stack\nwhile stack length > 1\n n = pop\n if (n==1)\n x = pop\n if (type(x)==NIL || type(x)==TEXT)\n push x // this is the \"return value\"\n else if (type(x)==CONCAT)\n push 2 // say call doc-concat\n push doc2(x), 1 // 2nd recursion\n push doc1(x), 1 // 1st recursion\n else if (type(x)==NEST)\n push 3 // say call doc-nest\n push level(x) // push level argument to doc-nest\n push doc(x), 1 // schedule recursion\n else if (type(x)==LINE)\n push \" \" // return a blank\n else if (type(x)==UNION)\n push doc1(x), 1 // just recur\n else if (n==2)\n push doc-concat(pop, pop) // finish the CONCAT case\n else if (n==3)\n push doc-nest(pop, pop) // finish the NEST case\n endif\nendwhile\n// final value is the only value on the stack\n"
},
{
"answer_id": 319369,
"author": "comingstorm",
"author_id": 210211,
"author_profile": "https://Stackoverflow.com/users/210211",
"pm_score": 0,
"selected": false,
"text": " data Tree = Null | Node Tree Val Tree\n\n-- original, non-tail-recursive function:\nflatten :: Tree -> Result\nflatten Null = nullval\nflatten (Node a v b) = nodefunc (flatten a) v (flatten b)\n\n-- modified, tail-recursive code:\ndata Task = A Val Tree | B Result Val\n\neval :: Tree -> [Task] -> Result\nuse :: Result -> [Task] -> Result\n\neval Null tasks = use nullval tasks\neval (Node a v b) tasks = eval a ((A v b):tasks)\n\nuse aval ((A v b):tasks) = eval b ((B aval v):tasks)\nuse bval ((B aval v):tasks) = use (nodefunc aval v bval) tasks\nuse val [] = val\n\n-- actual substitute function\nflatten2 :: Tree -> Result\nflatten2 tree = eval tree []\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28604/"
] |
315,513 | <p>I want to be able to take still images with a web cam, via .NET 2.0 (or 3.5 if necessary). I know I can use DirectShow but that seems like a very large learning curve.</p>
<p>Is there a simple to use OCX, or library that can work with most standard webcams?</p>
| [
{
"answer_id": 315875,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 2,
"selected": false,
"text": "(define (frob0 x k)\n (cond ((foo? x)\n (k x))\n ((bar? x)\n (frob0 (g x) \n (lambda (y) \n (k (macerate (f x) y))))\n ((thud? x)\n (frob0 (g x) \n (lambda (y)\n (frob0 (h x) \n (lambda (z)\n (k (frobnicate y z))))))))\n\n(define (frob x)\n (frob0 x (lambda (y) y))\n"
},
{
"answer_id": 315943,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 0,
"selected": false,
"text": "(define (doaction vars action)\n (cond ((symbol=? action 'frob)\n (cond ((foo? (first vars))\n (first vars))\n ((bar? (first vars))\n (doaction (list (f (first vars)) (doaction (g x) 'frob)) 'macerate)\netc...\n"
},
{
"answer_id": 315994,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 4,
"selected": true,
"text": "push x,1 on homemade stack\nwhile stack length > 1\n n = pop\n if (n==1)\n x = pop\n if (type(x)==NIL || type(x)==TEXT)\n push x // this is the \"return value\"\n else if (type(x)==CONCAT)\n push 2 // say call doc-concat\n push doc2(x), 1 // 2nd recursion\n push doc1(x), 1 // 1st recursion\n else if (type(x)==NEST)\n push 3 // say call doc-nest\n push level(x) // push level argument to doc-nest\n push doc(x), 1 // schedule recursion\n else if (type(x)==LINE)\n push \" \" // return a blank\n else if (type(x)==UNION)\n push doc1(x), 1 // just recur\n else if (n==2)\n push doc-concat(pop, pop) // finish the CONCAT case\n else if (n==3)\n push doc-nest(pop, pop) // finish the NEST case\n endif\nendwhile\n// final value is the only value on the stack\n"
},
{
"answer_id": 319369,
"author": "comingstorm",
"author_id": 210211,
"author_profile": "https://Stackoverflow.com/users/210211",
"pm_score": 0,
"selected": false,
"text": " data Tree = Null | Node Tree Val Tree\n\n-- original, non-tail-recursive function:\nflatten :: Tree -> Result\nflatten Null = nullval\nflatten (Node a v b) = nodefunc (flatten a) v (flatten b)\n\n-- modified, tail-recursive code:\ndata Task = A Val Tree | B Result Val\n\neval :: Tree -> [Task] -> Result\nuse :: Result -> [Task] -> Result\n\neval Null tasks = use nullval tasks\neval (Node a v b) tasks = eval a ((A v b):tasks)\n\nuse aval ((A v b):tasks) = eval b ((B aval v):tasks)\nuse bval ((B aval v):tasks) = use (nodefunc aval v bval) tasks\nuse val [] = val\n\n-- actual substitute function\nflatten2 :: Tree -> Result\nflatten2 tree = eval tree []\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16794/"
] |
315,517 | <p>Here is the code currently used.</p>
<pre><code>public String getStringFromDoc(org.w3c.dom.Document doc) {
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
writer.flush();
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
</code></pre>
| [
{
"answer_id": 315578,
"author": "digitalsanctum",
"author_id": 22436,
"author_profile": "https://Stackoverflow.com/users/22436",
"pm_score": 4,
"selected": false,
"text": "try {\n Transformer transformer = TransformerFactory.newInstance().newTransformer();\n StreamResult result = new StreamResult(new StringWriter());\n DOMSource source = new DOMSource(doc);\n transformer.transform(source, result);\n return result.getWriter().toString();\n} catch(TransformerException ex) {\n ex.printStackTrace();\n return null;\n}\n //Serialize DOM\nOutputFormat format = new OutputFormat (doc); \n// as a String\nStringWriter stringOut = new StringWriter (); \nXMLSerializer serial = new XMLSerializer (stringOut,format);\nserial.serialize(doc);\n// Display the XML\nSystem.out.println(stringOut.toString());\n"
},
{
"answer_id": 315595,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 3,
"selected": false,
"text": "org.w3c.dom.Document domDocument = ...;\nnu.xom.Document xomDocument = \n nu.xom.converters.DOMConverter.convert(domDocument);\nString xml = xomDocument.toXML();\n org.jsoup.helper.W3CDom converter = new W3CDom();\nString html = converter.asString( domDocument );\n"
},
{
"answer_id": 315663,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 7,
"selected": true,
"text": "public String getStringFromDoc(org.w3c.dom.Document doc) {\n DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();\n LSSerializer lsSerializer = domImplementation.createLSSerializer();\n return lsSerializer.writeToString(doc); \n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700/"
] |
315,519 | <p>Which is better in general in terms of the ordering? Do you put the fault condition at the top or bottom?</p>
<pre><code>if (noProblems == true) {
// do stuff
} else {
// deal with problem
}
</code></pre>
<p>OR</p>
<pre><code>if (noProblems == false) {
// deal with problem
} else {
// do stuff
}
</code></pre>
| [
{
"answer_id": 315523,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 7,
"selected": true,
"text": "if (some error condition)\n{\n //handle it\n return;\n}\n//implicit else for happy path\n...\n"
},
{
"answer_id": 315544,
"author": "John",
"author_id": 13895,
"author_profile": "https://Stackoverflow.com/users/13895",
"pm_score": 0,
"selected": false,
"text": "// do stuff\n // deal with problem\n"
},
{
"answer_id": 315564,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 0,
"selected": false,
"text": "if (foo is null) then\n // bail\nend if\n\nif (bar == foo) then\n // foo hasn't been changed... print the regular report\nelse\n // foo has changed, run the reconciliation report instead.\nend if\n"
},
{
"answer_id": 315622,
"author": "anand",
"author_id": 33411,
"author_profile": "https://Stackoverflow.com/users/33411",
"pm_score": 0,
"selected": false,
"text": "\nDWORD bRetVal= TRUE;\nif(foo is null) \n{\n bRetVal = FALSE;\n goto Error;\n}\nelse\n{\n// do something\n}\n\nExit:\n return bRetVal;\n\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
315,527 | <p>I am trying to use <a href="http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx" rel="nofollow noreferrer">ShellExecute</a> to open a file in Excel. I was reading about the function on MSDN forums, and I found the folowing information about the handle, which is the first parameter: </p>
<p>"hwnd [in] A handle to the owner window used for displaying a user interface (UI) or error messages. This value can be NULL if the operation is not associated with a window."</p>
<p>I have also heard this referred to as the handle to the parent window. What is the parent/owner window? As you see below I am using NULL for the handle, but since the operation is indeed associated with a window, I probably need a handle, but I don't know what to use for the handle.</p>
<pre><code>ShellExecute(NULL, "open" ,"Excel.exe",
"C:\\Documents and Settings\\Lab1\\My Documents\\Test.xls",
NULL, SW_SHOWNORMAL);
</code></pre>
| [
{
"answer_id": 315554,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "\" ' ... ' \" \"'C:\\\\Documents and Settings\\\\Lab1\\\\My Documents\\\\Test.xls'\"\n \" \"\" ... \"\" \" \"\"\"C:\\\\Documents and Settings\\\\Lab1\\\\My Documents\\\\Test.xls\"\"\"\n ShellExecute( NULL, \"open\", \n \"Test.xls\", \"C:\\\\Documents and Settings\\\\Lab1\\\\My Documents\\\\\", \n NULL, SW_SHOWNORMAL);\n"
},
{
"answer_id": 315797,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 2,
"selected": false,
"text": "ShellExecute"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23970/"
] |
315,546 | <p>I like the idea of having only one <code>return</code> statement per method.</p>
<p>What do you do in this situation though?</p>
<pre><code>public static string ChopText(string Text)
{
if (String.IsNullOrEmpty(Text))
{
// return here ?????
}
}
</code></pre>
<p>The only alternative I can think of is setting a flag, and then checking for the flag.</p>
<p><strong>Problem is, I don't like having huge if statements that span more than a page.</strong> I've also seen ugly nested if statements as a result of this.</p>
| [
{
"answer_id": 315562,
"author": "Paul Kapustin",
"author_id": 38325,
"author_profile": "https://Stackoverflow.com/users/38325",
"pm_score": 3,
"selected": false,
"text": "public static string ChopText(string Text))\n{\n if(String.IsNullOrEmpty(Text)\n return Text;\n\n ...\n}\n"
},
{
"answer_id": 315580,
"author": "BacMan",
"author_id": 455213,
"author_profile": "https://Stackoverflow.com/users/455213",
"pm_score": 2,
"selected": false,
"text": "if (Valid) { do lots of stuff}\nelse {return};\n if (invalid) { return; }\nif (invalid2) {return; }\n if (invalid) {\n throws IllegalArgumentException();\n"
},
{
"answer_id": 5581673,
"author": "Louis",
"author_id": 696855,
"author_profile": "https://Stackoverflow.com/users/696855",
"pm_score": 1,
"selected": false,
"text": "\npublic static string ChopText(string Text)\n{\n string returnString = \"\";\n if(String.IsNullOrEmpty(Text))\n {\n returnString = \"return string text\";\n }\n return returnString;\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] |
315,552 | <p>Working on big, high loaded project I got the problem that already described in billion of topics on forums and blog, but there is no solution that will help in my case. Here is the story.</p>
<p>I have the HTML code of banner, I don't know what is the code. Sometimes it's plain HTML, but sometimes it's <code><script></code> tag with document.write inside it with <code><script></code> tag that has src to doubleclick network in it.</p>
<p>So we have: script > document.write > script(doubleclick).</p>
<p>doubleclick network, as you may know, use document.write too and most of the time they give flash banners that need to load one more js file.</p>
<p>So after all we have: script > document.write > script(doubleclick) > document.write > script > ...</p>
<p>This works good when you place it in HTML directly. Page rendering 1 part, load banner1, keep rendering page, load banner2, finalizing page rendering.</p>
<p>But right now I need to render page first and only after that load banners.
As banner use document.write I need to load it before window.onload event (note: after window.onload document.write will rewrite whole document.)</p>
<p>What I've done:</p>
<p>In the head section I have an banners object(real namespace kind of huge :)), with property scope.</p>
<p>When page rendering and banner code is meet I place the code of the banner into the scope and put <code><div id="bannerPlaceHolder"+id></div></code> -- so here I will need to put banner content later on</p>
<p>Page rendered and before <code></body></code> tag I put <code><script>banners.load()</script></code> banners.load method do this for each item in scope array:</p>
<pre><code>document.write('<div id="codeHolder'+id+'">');
document.write(bannerCode);
document.write('</div>');
</code></pre>
<p>And only after this I have <code>window.onload()</code> event that do this:</p>
<p>take all banners codeHolders and node-by-node append it nodes from codeHolder to placeHolder, so in result I have loaded banners after rendering the page and banners are on the right places.</p>
<p>All is perfect except IE, it load any js script that was putted in DOM dynamically in asynchron way, so document.write inside doubleclick scripts append nodes to the end of the document and not in my codeHolder nodes. As usual it's only in IE.</p>
<p>I will be really appreciated to anyone who may know the solution.</p>
| [
{
"answer_id": 1975537,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 2,
"selected": false,
"text": "document.write document.write $('#bannerPlaceHolder').writeCapture().html('<script type=\"text/javascript\" src=\"http://doubleclick.net/bannerCode.js\"></script>');\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15752/"
] |
315,585 | <p>Anyone out there using Fogbugz and Scrum together?</p>
<p>We use Fogbugz extensively, and I'm looking for ideas from anyone who may be using it as part of Scrum. I found these two items, but they are archived and unvailable for further discussion. I'm specifically interested in ideas for mapping Scrum concepts into Fogbugz.</p>
<p>Some things are fairly obvious. Releases and sprints map well to each other. But other parts of Scrum don't really fit. </p>
<p><a href="http://support.fogcreek.com/default.asp?fogbugz.4.12143.4" rel="noreferrer">http://support.fogcreek.com/default.asp?fogbugz.4.12143.4</a><br>
<a href="http://support.fogcreek.com/default.asp?fogbugz.4.19971.3" rel="noreferrer">http://support.fogcreek.com/default.asp?fogbugz.4.19971.3</a> </p>
<p><strike>I'm also thinking it might not be too hard to create some lightweight custom stuff to wrap around Fogbugz so that we don't have to abandon one of our favorite tools in order to improve our software process integration.</strike></p>
<p><strong>Edit:</strong></p>
<p>I'm adding a few more specific questions that have come up. Any suggestions on these items would be helpful:</p>
<ul>
<li><strike>How do we prioritize a large
backlog with only the 7 priority
levels provided by Fogbugz? We can
modify the database tables to add
more levels, but is that an
appropriate in the current/intended
Fogbugz model?</strike></li>
<li>How/where do we
document a sprint goal?</li>
<li>How do we document a canceled sprint?</li>
<li>How do we document sprint review?</li>
<li>How do we track completed or canceled
sprints?</li>
</ul>
<p><strong>Edit #2:</strong></p>
<p>Chris's reply below reminded me that we have indeed upgraded to Fogbugz v7. It has many great features that align it more closely with Agile, Scrum, and Lean including:</p>
<ul>
<li>Project Backlog (via plugin)</li>
<li>Custom Workflow</li>
<li>Burn Down Charts</li>
<li>Kanban Board (via plugin)</li>
</ul>
<p>See the following links for more info:<br>
<a href="http://www.fogcreek.com/FogBugz/WhatsNew.html" rel="noreferrer">http://www.fogcreek.com/FogBugz/WhatsNew.html</a><br>
<a href="http://www.fogcreek.com/FogBugz/Plugins/default.aspx?ixCategory=-3" rel="noreferrer">http://www.fogcreek.com/FogBugz/Plugins/default.aspx?ixCategory=-3</a></p>
<p><strong>Edit #3</strong>
Adding link that Perhentian mentioned in his answer as well as another I found:</p>
<p><a href="http://www.danielroot.info/2009/08/how-to-apply-scrum-using-fogbugz-7.html" rel="noreferrer">http://www.danielroot.info/2009/08/how-to-apply-scrum-using-fogbugz-7.html</a><br>
<a href="http://www.fogcreek.com/FogBugz/blog/post/Scrum-Friendly-Features.aspx" rel="noreferrer">http://www.fogcreek.com/FogBugz/blog/post/Scrum-Friendly-Features.aspx</a></p>
| [
{
"answer_id": 328595,
"author": "Stefan Rusek",
"author_id": 19704,
"author_profile": "https://Stackoverflow.com/users/19704",
"pm_score": 2,
"selected": false,
"text": "priority:7 project:\"project name\"\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5208/"
] |
315,590 | <p>I want to load 52 images (deck of cards) in gif format from my recourse folder into an Image[] in c#. Any ideas?</p>
<p>Thanks,
Jon</p>
| [
{
"answer_id": 315611,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 3,
"selected": true,
"text": " public static Bitmap GetBitmap( string filename )\n {\n Bitmap retBitmap = null;\n string path = String.Concat( BitmapDir, filename );\n if ( File.Exists( path ) )\n {\n try\n {\n retBitmap = new Bitmap( path, true );\n }\n catch { }\n }\n return retBitmap;\n }\n string[] files = Directory.GetFiles( BitmapDir, \"*.gif\" );\n"
},
{
"answer_id": 315633,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 1,
"selected": false,
"text": "Image[] cards = Directory.GetFiles(cardsFolder).Select(f => Image.FromFile(f)).ToArray();\n"
},
{
"answer_id": 315699,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 1,
"selected": false,
"text": " List<System.Drawing.Image> images = new List<System.Drawing.Image>();\n foreach (System.Reflection.MethodInfo t \n in typeof(Resources.Resource).GetMethods())\n {\n if (t.ReturnType.ToString() == \"System.Drawing.Bitmap\")\n {\n images.Add(new System.Drawing.Bitmap((System.Drawing.Image)t.Invoke(null, null)));\n\n }\n }\n"
},
{
"answer_id": 315812,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 1,
"selected": false,
"text": " protected void MethodToBeCalled()\n {\n\n\n System.Drawing.Image[] cards = Directory.GetFiles(cardsFolder).Where(\n f =>\n {\n\n if (IsImage((string)f))\n {\n return true ;\n }\n else { return false; }\n }\n ).Select(f => System.Drawing.Image.FromFile(f)).ToArray();\n\n }\n private bool IsImage(string filename)\n {\n string[] knownPicExtensions = {\".jpg\",\".gif\",\".png\",\".bmp\",\".jpeg\",\".jpe\" };\n\n foreach (string extension in knownPicExtensions)\n {\n if (filename.ToLower().EndsWith(extension))\n return true;\n }\n\n return false;\n }\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40399/"
] |
315,591 | <p>I am working on an object factory to keep track of a small collection of objects. The objects can be of different types, but they will all respond to <code>createInstance</code> and <code>reset</code>. The objects can not be derived from a common base class because some of them will have to derive from built-in cocoa classes like <code>NSView</code> and <code>NSWindowController</code>.</p>
<p>I would like to be able to create instances of any suitable object by simply passing the desired classname to my factory as follows:</p>
<pre><code>myClass * variable = [factory makeObjectOfClass:myClass];</code></pre>
<p>The <code>makeObjectOfClass:</code> method would look something like this:</p>
<pre><code>- (id)makeObjectOfClass:(CLASSNAME)className
{
assert([className instancesRespondToSelector:@selector(reset)]);
id newInstance = [className createInstance];
[managedObjects addObject:newInstance];
return newInstance;
}</code></pre>
<p>Is there a way to pass a class name to a method, as I have done with the <code>(CLASSNAME)className</code> argument to <code>makeObjectOfClass:</code> above?</p>
<p>For the sake of completeness, here is why I want to manage all of the objects. I want to be able to reset the complete set of objects in one shot, by calling <code>[factory reset];</code>.</p>
<pre><code>- (void)reset
{
[managedObjects makeObjectsPerformSelector:@selector(reset)];
}</code></pre>
| [
{
"answer_id": 315641,
"author": "Michael Tsai",
"author_id": 6311,
"author_profile": "https://Stackoverflow.com/users/6311",
"pm_score": 2,
"selected": false,
"text": "- (id)makeObjectOfClassNamed:(NSString *)className\n{\n Class klass = NSClassFromString(className);\n assert([klass instancesRespondToSelector:@selector(reset)]);\n id newInstance = [klass createInstance];\n [managedObjects addObject:newInstance];\n return newInstance;\n}\n +createInstance [[klass alloc] init] MyClass *variable = [factory makeObjectOfClassNamed:@\"MyClass\"];\n MyClass *variable = [factory makeObjectOfClass:[MyClass class]];\n"
},
{
"answer_id": 315651,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 2,
"selected": false,
"text": "id string = [[NSClassFromString(@\"NSString\") alloc] initWithString:@\"Hello!\"];\nNSLog( @\"%@\", string );\n"
},
{
"answer_id": 315662,
"author": "Matt Gallagher",
"author_id": 36103,
"author_profile": "https://Stackoverflow.com/users/36103",
"pm_score": 6,
"selected": true,
"text": "Class classFromString = NSClassFromString(@\"MyClass\");\n MyClass * variable = [factory makeObjectOfClass:[MyClass class]];\n\n- (id)makeObjectOfClass:(Class)aClass\n{\n assert([aClass instancesRespondToSelector:@selector(reset)]);\n id newInstance = [aClass createInstance];\n [managedObjects addObject:newInstance];\n return newInstance;\n}\n"
},
{
"answer_id": 315687,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "@protocol +createInstance +reset"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33686/"
] |
315,608 | <p>I am building a graphic board like project where i am facing a design issue.</p>
<p>Main Class is Board which is a canvas responsible for handling mouse events when drawing shapes. It also has context variables such as currentShape or snapFlag to activate grid magnetism.</p>
<p>To handle the moving / resizing / rotating of the shapes, they inherit from a third party open source tool called ObjectHandles (flex).</p>
<p>I have a baseShape extending ObjectHandles main class to override some of its internal functions, like the onMove function.</p>
<p>When creating a shape (mouse down, move, mouse up) this is handle by the Board and it knows about his own snap flag.</p>
<p>var mouseUpPoint:Point = boardCanvas.globalToLocal(new Point(event.stageX, event.stageY));
var snapMouseUpPoint = snapPoint(mouseUpPoint.x, mouseUpPoint.y); </p>
<p>In my overidden onMove method i would like the shape to be aware of the Board snap flag and when its changing. How do i do this ?</p>
<p><strong>Do i pass the Board as a parameter in my basicShape constructor so that i can check snap ?</strong></p>
<p><strong>Do i pass the flag as a parameter and somehow make all shapes listen for change ?</strong></p>
<p>What is the cleanest solution ?</p>
<p>Thanks a lot. </p>
| [
{
"answer_id": 315653,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 1,
"selected": false,
"text": "Board Shape Board Shape onMove"
},
{
"answer_id": 315769,
"author": "coulix",
"author_id": 32032,
"author_profile": "https://Stackoverflow.com/users/32032",
"pm_score": 0,
"selected": false,
"text": " protected function onMouseMove(event:MouseEvent) : void\n {\n if( ! visible ) { return; }\n\n if( ! event.buttonDown )\n {\n setMouseCursor( event.stageX, event.stageY );\n return;\n }\n\n if(parent == null )\n {\n return;\n }\n\n\n var dest:Point = parent.globalToLocal( new Point(event.stageX, event.stageY) );\n var desiredPos:Point = new Point();\n var desiredSize:Point = new Point();\n var desiredRotation:Number = 0; \n\n... plenty more\nthen \n\n if( wasMoved ) { dispatchMoving() ; }\n if( wasResized ) { dispatchResizing() ; }\n if( wasRotated ) { dispatchRotating(); }\n"
},
{
"answer_id": 316827,
"author": "coulix",
"author_id": 32032,
"author_profile": "https://Stackoverflow.com/users/32032",
"pm_score": 0,
"selected": false,
"text": "// added on override\nvar board:BoardMediator = ApplicationFacade.getInstance().retrieveMediator(BoardMediator.NAME) as BoardMediator;\n desiredPos = board.snapPoint(desiredPos.x, desiredPos.y);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32032/"
] |
315,609 | <p>The application that I'm designing will retrieve and store content from a variety of disparate sources on a schedule. In some cases, the content will be retrieved based on a time interval (think stock quotes), and in other cases the content will be retrieved based on a custom schedule (MWF @ 2pm). Many of the processes lend themselves to MS Workflow. The built-in SQL tracking service will provide a lot of value. The content sources are sufficiently different that each different type of content retrieval will be a custom workflow.</p>
<p>My question is, how should I host, monitor,schedule, and expose the Workflows?</p>
<p>Requirements:</p>
<ul>
<li>Must be able to monitor the health of each content "agent" via admin UI</li>
<li>Must be able to start and stop individual workflows via admin UI</li>
<li>Workflows are recurring based on a schedule, but not necessarily "long-running"</li>
<li>"Service" must have high availability</li>
</ul>
<p>Windows service, Workflow Service, ASP.Net, WCF are all available to me, and I'm open to other suggestions as well.</p>
| [
{
"answer_id": 315653,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 1,
"selected": false,
"text": "Board Shape Board Shape onMove"
},
{
"answer_id": 315769,
"author": "coulix",
"author_id": 32032,
"author_profile": "https://Stackoverflow.com/users/32032",
"pm_score": 0,
"selected": false,
"text": " protected function onMouseMove(event:MouseEvent) : void\n {\n if( ! visible ) { return; }\n\n if( ! event.buttonDown )\n {\n setMouseCursor( event.stageX, event.stageY );\n return;\n }\n\n if(parent == null )\n {\n return;\n }\n\n\n var dest:Point = parent.globalToLocal( new Point(event.stageX, event.stageY) );\n var desiredPos:Point = new Point();\n var desiredSize:Point = new Point();\n var desiredRotation:Number = 0; \n\n... plenty more\nthen \n\n if( wasMoved ) { dispatchMoving() ; }\n if( wasResized ) { dispatchResizing() ; }\n if( wasRotated ) { dispatchRotating(); }\n"
},
{
"answer_id": 316827,
"author": "coulix",
"author_id": 32032,
"author_profile": "https://Stackoverflow.com/users/32032",
"pm_score": 0,
"selected": false,
"text": "// added on override\nvar board:BoardMediator = ApplicationFacade.getInstance().retrieveMediator(BoardMediator.NAME) as BoardMediator;\n desiredPos = board.snapPoint(desiredPos.x, desiredPos.y);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40396/"
] |
315,618 | <p>How do I extract a tar (or tar.gz, or tar.bz2) file in Java?</p>
| [
{
"answer_id": 315668,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": true,
"text": "GZIPInputStream InputStream FileInputStream GZIPInputStream InputStream InputStream is = new GZIPInputStream(new FileInputStream(file));\n FileInputStream BufferedInputStream"
},
{
"answer_id": 4165096,
"author": "Jörg",
"author_id": 472992,
"author_profile": "https://Stackoverflow.com/users/472992",
"pm_score": 4,
"selected": false,
"text": "tar:gz:http://anyhost/dir/mytar.tar.gz!/mytar.tar!/path/in/tar/README.txt"
},
{
"answer_id": 7534962,
"author": "Renaud",
"author_id": 125617,
"author_profile": "https://Stackoverflow.com/users/125617",
"pm_score": 3,
"selected": false,
"text": "FileSystemManager fsManager = VFS.getManager();\nFileObject archive = fsManager.resolveFile(\"tgz:file://\" + fileName);\n\n// List the children of the archive file\nFileObject[] children = archive.getChildren();\nSystem.out.println(\"Children of \" + archive.getName().getURI()+\" are \");\nfor (int i = 0; i < children.length; i++) {\n FileObject fo = children[i];\n System.out.println(fo.getName().getBaseName());\n if (fo.isReadable() && fo.getType() == FileType.FILE\n && fo.getName().getExtension().equals(\"nxml\")) {\n FileContent fc = fo.getContent();\n InputStream is = fc.getInputStream();\n }\n}\n <dependency>\n <groupId>commons-vfs</groupId>\n <artifactId>commons-vfs</artifactId>\n <version>1.0</version>\n </dependency>\n"
},
{
"answer_id": 7556307,
"author": "Dan Borza",
"author_id": 510638,
"author_profile": "https://Stackoverflow.com/users/510638",
"pm_score": 6,
"selected": false,
"text": "/** Untar an input file into an output file.\n\n * The output file is created in the output folder, having the same name\n * as the input file, minus the '.tar' extension. \n * \n * @param inputFile the input .tar file\n * @param outputDir the output directory file. \n * @throws IOException \n * @throws FileNotFoundException\n * \n * @return The {@link List} of {@link File}s with the untared content.\n * @throws ArchiveException \n */\nprivate static List<File> unTar(final File inputFile, final File outputDir) throws FileNotFoundException, IOException, ArchiveException {\n\n LOG.info(String.format(\"Untaring %s to dir %s.\", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));\n\n final List<File> untaredFiles = new LinkedList<File>();\n final InputStream is = new FileInputStream(inputFile); \n final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream(\"tar\", is);\n TarArchiveEntry entry = null; \n while ((entry = (TarArchiveEntry)debInputStream.getNextEntry()) != null) {\n final File outputFile = new File(outputDir, entry.getName());\n if (entry.isDirectory()) {\n LOG.info(String.format(\"Attempting to write output directory %s.\", outputFile.getAbsolutePath()));\n if (!outputFile.exists()) {\n LOG.info(String.format(\"Attempting to create output directory %s.\", outputFile.getAbsolutePath()));\n if (!outputFile.mkdirs()) {\n throw new IllegalStateException(String.format(\"Couldn't create directory %s.\", outputFile.getAbsolutePath()));\n }\n }\n } else {\n LOG.info(String.format(\"Creating output file %s.\", outputFile.getAbsolutePath()));\n final OutputStream outputFileStream = new FileOutputStream(outputFile); \n IOUtils.copy(debInputStream, outputFileStream);\n outputFileStream.close();\n }\n untaredFiles.add(outputFile);\n }\n debInputStream.close(); \n\n return untaredFiles;\n}\n\n/**\n * Ungzip an input file into an output file.\n * <p>\n * The output file is created in the output folder, having the same name\n * as the input file, minus the '.gz' extension. \n * \n * @param inputFile the input .gz file\n * @param outputDir the output directory file. \n * @throws IOException \n * @throws FileNotFoundException\n * \n * @return The {@File} with the ungzipped content.\n */\nprivate static File unGzip(final File inputFile, final File outputDir) throws FileNotFoundException, IOException {\n\n LOG.info(String.format(\"Ungzipping %s to dir %s.\", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));\n\n final File outputFile = new File(outputDir, inputFile.getName().substring(0, inputFile.getName().length() - 3));\n\n final GZIPInputStream in = new GZIPInputStream(new FileInputStream(inputFile));\n final FileOutputStream out = new FileOutputStream(outputFile);\n\n IOUtils.copy(in, out);\n\n in.close();\n out.close();\n\n return outputFile;\n}\n"
},
{
"answer_id": 22481757,
"author": "D3iv",
"author_id": 3433434,
"author_profile": "https://Stackoverflow.com/users/3433434",
"pm_score": 4,
"selected": false,
"text": "Archiver archiver = ArchiverFactory.createArchiver(\"tar\", \"gz\");\narchiver.extract(archiveFile, destDir);\n <dependency>\n <groupId>org.rauschig</groupId>\n <artifactId>jarchivelib</artifactId>\n <version>0.5.0</version>\n</dependency>\n"
},
{
"answer_id": 54830968,
"author": "Wade Walker",
"author_id": 207245,
"author_profile": "https://Stackoverflow.com/users/207245",
"pm_score": 2,
"selected": false,
"text": "public static void unTarGz( Path pathInput, Path pathOutput ) throws IOException {\n TarArchiveInputStream tararchiveinputstream =\n new TarArchiveInputStream(\n new GzipCompressorInputStream(\n new BufferedInputStream( Files.newInputStream( pathInput ) ) ) );\n\n ArchiveEntry archiveentry = null;\n while( (archiveentry = tararchiveinputstream.getNextEntry()) != null ) {\n Path pathEntryOutput = pathOutput.resolve( archiveentry.getName() );\n if( archiveentry.isDirectory() ) {\n if( !Files.exists( pathEntryOutput ) )\n Files.createDirectory( pathEntryOutput );\n }\n else\n Files.copy( tararchiveinputstream, pathEntryOutput );\n }\n\n tararchiveinputstream.close();\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18103/"
] |
315,621 | <p>I have a table with N rows, and I wanna select N-1 rows. </p>
<p>Suggestions on how to do this in one query, if it's possible..?</p>
| [
{
"answer_id": 315631,
"author": "Joshua Carmody",
"author_id": 8409,
"author_profile": "https://Stackoverflow.com/users/8409",
"pm_score": 6,
"selected": true,
"text": "SELECT * FROM TABLE WHERE ID != (SELECT MAX(ID) FROM TABLE)\n"
},
{
"answer_id": 38857293,
"author": "Redithion",
"author_id": 1423901,
"author_profile": "https://Stackoverflow.com/users/1423901",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM table ORDER BY id DESC LIMIT 10000 OFFSET 1;\n"
},
{
"answer_id": 38857476,
"author": "Devansh Modi",
"author_id": 6552041,
"author_profile": "https://Stackoverflow.com/users/6552041",
"pm_score": -1,
"selected": false,
"text": "SELECT * FROM table WHERE ID <> LAST_INSERT_ID()\n"
},
{
"answer_id": 72050382,
"author": "marisxanis",
"author_id": 1249945,
"author_profile": "https://Stackoverflow.com/users/1249945",
"pm_score": 0,
"selected": false,
"text": "DECLARE rowsNr INT DEFAULT 0; \nSET rowsNr = SELECT (count(*) AS 'TOTAL_ROWS' FROM TABLE;\nSET rowsNr = rowsNr -1;\nSELECT * FROM Table WHERE ... LIMIT rowsNr;\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33232/"
] |
315,667 | <p>I'm a non-computer science student doing a history thesis that involves determining the frequency of specific terms in a number of texts and then plotting these frequencies over time to determine changes and trends. While I have figured out how to determine word frequencies for a given text file, I am dealing with a (relatively, for me) large number of files (>100) and for consistencies sake would like to limit the words included in the frequency count to a specific set of terms (sort of like the opposite of a "stop list")</p>
<p>This should be kept very simple. At the end all I need to have is the frequencies for the specific words for each text file I process, preferably in spreadsheet format (tab delineated file) so that I can then create graphs and visualizations using that data.</p>
<p>I use Linux day-to-day, am comfortable using the command line, and would love an open-source solution (or something I could run with WINE). That is not a requirement however:</p>
<p>I see two ways to solve this problem:</p>
<ol>
<li>Find a way strip-out all the words in a text file EXCEPT for the pre-defined list and then do the frequency count from there, or:</li>
<li>Find a way to do a frequency count using just the terms from the pre-defined list.</li>
</ol>
<p>Any ideas?</p>
| [
{
"answer_id": 315707,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nmy $word_list_file = shift;\nmy $process_file = shift;\n\nmy %word_counts;\n\n# Open the word list file, read a line at a time, remove the newline,\n# add it to the hash of words to track, initialize the count to zero\nopen(WORDS, $word_list_file) or die \"Failed to open list file: $!\\n\";\nwhile (<WORDS>) {\n chomp;\n # Store words in lowercase for case-insensitive match\n $word_counts{lc($_)} = 0;\n}\nclose(WORDS);\n\n# Read the text file one line at a time, break the text up into words\n# based on word boundaries (\\b), iterate through each word incrementing\n# the word count in the word hash if the word is in the hash\nopen(FILE, $process_file) or die \"Failed to open process file: $!\\n\";\n\nwhile (<FILE>) {\n chomp;\n while ( /-$/ ) {\n # If the line ends in a hyphen, remove the hyphen and\n # continue reading lines until we find one that doesn't\n chop;\n my $next_line = <FILE>;\n defined($next_line) ? $_ .= $next_line : last;\n }\n\n my @words = split /\\b/, lc; # Split the lower-cased version of the string\n foreach my $word (@words) {\n $word_counts{$word}++ if exists $word_counts{$word};\n }\n}\nclose(FILE);\n\n# Print each word in the hash in alphabetical order along with the\n# number of time encountered, delimited by tabs (\\t)\nforeach my $word (sort keys %word_counts)\n{\n print \"$word\\t$word_counts{$word}\\n\"\n}\n linux\nfrequencies\nscience\nwords\n perl analyze.pl words.txt text.txt\n frequencies 3\nlinux 1\nscience 1\nwords 3\n s/-//g;\n"
},
{
"answer_id": 315779,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "for file in *.txt\ndo \n sed -r 's/([^ ]+) +/\\1\\n/g' \"$file\" \\\n | grep -F -f 'go-words' \\\n | sort | uniq -c > \"${file}.frq\"\ndone\n"
},
{
"answer_id": 316018,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/perl -w\nuse strict;\n\nuse File::Slurp;\nuse Tie::File;\n\n# Usage:\n#\n# $ perl WordCount.pl <Files>\n# \n# Example:\n# \n# $ perl WordCount.pl *.text\n#\n# Counts words in all files given as arguments.\n# The words are taken from the file \"WordList\".\n# The output is appended to the file \"WordCount.out\" in the format implied in the\n# following example:\n#\n# File,Word1,Word2,Word3,...\n# File1,0,5,3,...\n# File2,6,3,4,...\n# .\n# .\n# .\n# \n\n### Configuration\n\nmy $CaseSensitive = 1; # 0 or 1\nmy $OutputSeparator = \",\"; # another option might be \"\\t\" (TAB)\nmy $RemoveHyphenation = 0; # 0 or 1. Careful, may be too greedy.\n\n###\n\nmy @WordList = read_file(\"WordList\");\nchomp @WordList;\n\ntie (my @Output, 'Tie::File', \"WordCount.out\");\npush (@Output, join ($OutputSeparator, \"File\", @WordList));\n\nfor my $InFile (@ARGV)\n { my $Text = read_file($InFile);\n if ($RemoveHyphenation) { $Text =~ s/-\\n//g; };\n my %Count;\n for my $Word (@WordList)\n { if ($CaseSensitive)\n { $Count{$Word} = ($Text =~ s/(\\b$Word\\b)/$1/g); }\n else\n { $Count{$Word} = ($Text =~ s/(\\b$Word\\b)/$1/gi); }; };\n my $OutputLine = \"$InFile\";\n for my $Word (@WordList)\n { if ($Count{$Word})\n { $OutputLine .= $OutputSeparator . $Count{$Word}; }\n else\n { $OutputLine .= $OutputSeparator . \"0\"; }; };\n push (@Output, $OutputLine); };\n\nuntie @Output;\n wc-test wc-ans-test File,linux,frequencies,science,words\nwc-ans-test,2,2,2,12\nwc-test,1,3,1,3\n gnuplot"
},
{
"answer_id": 739323,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 1,
"selected": false,
"text": "cat *.txt | tr A-Z a-z | tr -cs a-z '\\n' | sort | uniq -c | sort -rn | \nsed '/[0-9] /&, /'\n grep -w -F -f stopwords.txt"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40414/"
] |
315,672 | <p>Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.</p>
<p>For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "<code>IN</code>" clause.</p>
<pre><code>import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]
mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()
sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"
mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()
</code></pre>
<p>Any help would be appreciated!</p>
| [
{
"answer_id": 315684,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 5,
"selected": true,
"text": "\",\".join( map(str, record_ids) )\n \",\".join( list_of_strings ) map( str, list )"
},
{
"answer_id": 315786,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "where rec_id in ()"
},
{
"answer_id": 315822,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 2,
"selected": false,
"text": "sqlStmt=(\"UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in (%s)\"\n % ', '.join(['?' for n in record_ids]))\n\nmysql_cursor.execute(sqlStmt, record_ids)\nmysql.commit()\n"
},
{
"answer_id": 318342,
"author": "Dave",
"author_id": 40736,
"author_profile": "https://Stackoverflow.com/users/40736",
"pm_score": 0,
"selected": false,
"text": "sqlStmt=(\"UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in (%s)\"\n % ', '.join(['?'] * len(record_ids)))\n"
},
{
"answer_id": 3146633,
"author": "Joao Coelho",
"author_id": 205075,
"author_profile": "https://Stackoverflow.com/users/205075",
"pm_score": -1,
"selected": false,
"text": "sqlStmt=\"UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in \" +\n record_ids.__str__().replace('[','(').replace(']',')')\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31319/"
] |
315,678 | <p>I have a web application that uses Ext-JS 2.2. In a certain component, we have an empty toolbar that we are trying to add a button to using </p>
<pre><code>myPanel.getTopToolbar().insertButton(0, [...array of buttons...]);
</code></pre>
<p>However, in IE6/7 this fails because of lines 20241-20242 in ext-all-debug.js:</p>
<pre><code>var td = document.createElement("td");
this.tr.insertBefore(td, this.tr.childNodes[index]);
</code></pre>
<p>Since "this.tr.childNodes([0])" does not yet exist in IE, this fails with "Invalid argument".</p>
<p>THE REAL QUESTION:
Can I, using CSS similar to the below add a child to every toolbar <tr> so that this.tr.childNodes[0] is found:</p>
<pre><code>div.x-toolbar tr:after { content: " "; }
</code></pre>
<p>I totally realize this is a hack, but for legal reasons I cannot change any Javascript, not even to add an empty button ({}) to each toolbar. Major kudos to anyone that can figure this out.</p>
| [
{
"answer_id": 316155,
"author": "cwhite",
"author_id": 4923,
"author_profile": "https://Stackoverflow.com/users/4923",
"pm_score": 1,
"selected": false,
"text": " myPanel.getTopToolbar().add(buttons etc);\n myPanel.getTopToolbar().addButton(..);\n"
},
{
"answer_id": 482338,
"author": "Burke",
"author_id": 21980,
"author_profile": "https://Stackoverflow.com/users/21980",
"pm_score": 1,
"selected": false,
"text": "myPanel.on('render', function() {\n this.getTopToolbar().insertButton(0, [...array of buttons...]);\n}, true);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25066/"
] |
315,706 | <p>When reading from a <a href="http://search.cpan.org/dist/IO" rel="nofollow noreferrer">IO::Socket::INET</a> filehandle it can not be assumed that there will always be data available on the stream. What techniques are available to either peek at the stream to check if data is available or when doing the read take no data without a valid line termination and immediately pass through the read?</p>
| [
{
"answer_id": 315751,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "Blocking 0 $sock = IO::Socket::INET->new(Blocking => 0, ...);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12251/"
] |
315,708 | <p>Is there any good way to convert strings like "xlSum", "xlAverage", and "xlCount" into the value they have under Microsoft.Office.Interop.Excel.XlConsolidationFunction?</p>
<p>I guess reflection would be slow (if its possible). There are about 10 of these constant values. I was trying to avoid a large switch statement if possible.</p>
| [
{
"answer_id": 315715,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 0,
"selected": false,
"text": "Dictionary<string, ...>"
},
{
"answer_id": 315721,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "using Microsoft.Office.Interop.Excel;\n\nXlConslidationFunction func = (XlConsolidationFunction)\n Enum.Parse( typeof(XlConsolidationFunction),\n stringVal );\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36590/"
] |
315,712 | <p>I have a three-step process that is entirely reliant upon JavaScript and Ajax to load data and animate the process from one step to the next. To further complicate matters, the transition (forward and backward) between steps is animated :-(. As user's progress through the process anchor's appear showing the current step and previous steps. If they click on a previous step, then it takes them back to the previous step.</p>
<p>Right now, the entire process (forward and backward) works correctly, if you begin at step 1, but if you jump straight to step 3 then the anchors for step 1 and step 2 also perform the same action as step 3. </p>
<p>This is the portion of the code that loops through all of the steps up to the current step that the user would be on and displays each anchor in turn and assigns the appropriate function to the click event:</p>
<pre><code>for (var i = 0; i < profile.current + 1; i++) {
if ($('step_anchor_' + i).innerHTML.empty()) {
var action = profile.steps[i].action;
var dao_id = profile.steps[i].dao_id;
$('step_anchor_' + i).innerHTML = profile.steps[i].anchor;
$('step_anchor_' + i).observe('click', function(){
pm.loadData(action, dao_id, true);
});
Effect.Appear('step_anchor_' + i, {
duration: 1,
delay: (down_delay++)
});
}
}
</code></pre>
<p>I know that problem lies in the way that the action and dao_id parameters are being passed in. I've also tried passing profile.steps[i].action and profile.steps[i].dao_id but in that case both profile and i or at least i are out scope. </p>
<p>How do I make it so that I can assign the parameters for action and dao_id correctly for each step? (If it makes any difference we are using Prototype and Scriptaculous)</p>
| [
{
"answer_id": 315880,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 4,
"selected": true,
"text": "for (var i = 0; i < profile.current + 1; i++) {\n if ($('step_anchor_' + i).innerHTML.empty()) {\n var action = profile.steps[i].action;\n var dao_id = profile.steps[i].dao_id;\n\n $('step_anchor_' + i).innerHTML = profile.steps[i].anchor;\n $('step_anchor_' + i).observe('click', function(a, b){\n return function(){pm.loadData(a, b, true)};\n }(action, dao_id));\n\n Effect.Appear('step_anchor_' + i, {\n duration: 1,\n delay: (down_delay++)\n });\n }\n}\n function createHandler(action, dao_id) {\n return function(){pm.loadData(action, dao_id, true);};\n} \n\n/* snip - inside some other function */\nfor (var i = 0; i < profile.current + 1; i++) {\n if ($('step_anchor_' + i).innerHTML.empty()) {\n var action = profile.steps[i].action;\n var dao_id = profile.steps[i].dao_id;\n\n $('step_anchor_' + i).innerHTML = profile.steps[i].anchor;\n $('step_anchor_' + i).observe('click', createHandler(action, dao_id));\n Effect.Appear('step_anchor_' + i, {\n duration: 1,\n delay: (down_delay++)\n });\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178/"
] |
315,716 | <p>I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reactor as needed. I don't know how to tie it from reactor to all protocol instances...</p>
| [
{
"answer_id": 316559,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 6,
"selected": true,
"text": "from twisted.internet import reactor, protocol, task\n\nclass MyProtocol(protocol.Protocol):\n def connectionMade(self):\n self.factory.clientConnectionMade(self)\n def connectionLost(self, reason):\n self.factory.clientConnectionLost(self)\n\nclass MyFactory(protocol.Factory):\n protocol = MyProtocol\n def __init__(self):\n self.clients = []\n self.lc = task.LoopingCall(self.announce)\n self.lc.start(10)\n\n def announce(self):\n for client in self.clients:\n client.transport.write(\"10 seconds has passed\\n\")\n\n def clientConnectionMade(self, client):\n self.clients.append(client)\n\n def clientConnectionLost(self, client):\n self.clients.remove(client)\n\nmyfactory = MyFactory()\nreactor.listenTCP(9000, myfactory)\nreactor.run()\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29120/"
] |
315,719 | <p>I'm trying to convert a character code to a character with chr(), but VBScript isn't giving me the value I expect. According to VBScript, character code 199 is:</p>
<pre><code>�
</code></pre>
<p>However, when using something like Javascript's String.fromCharCode, 199 is:</p>
<pre><code>Ç
</code></pre>
<p>The second result is what I need to get out of VBScript's chr() function. Any idea what the problem is?</p>
| [
{
"answer_id": 315725,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 4,
"selected": true,
"text": "Chr(199) ChrW(199) Unicode ChrB(199)"
},
{
"answer_id": 315731,
"author": "Daniel Kreiseder",
"author_id": 31406,
"author_profile": "https://Stackoverflow.com/users/31406",
"pm_score": 0,
"selected": false,
"text": "fromCharCode() Unicode Chr() ANSI"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31516/"
] |
315,724 | <p>I have an after_save filter which I dont want to trigger in a specific instance. Is there a way to do this similar to save_without_validation?</p>
<p>Thanks,</p>
| [
{
"answer_id": 316162,
"author": "Michael Sepcot",
"author_id": 6033,
"author_profile": "https://Stackoverflow.com/users/6033",
"pm_score": 0,
"selected": false,
"text": "def self.skip_callback(callback, &block)\n method = instance_method(callback)\n remove_method(callback) if respond_to?(callback)\n define_method(callback){ true }\n begin\n result = yield\n ensure\n remove_method(callback)\n define_method(callback, method)\n end\n result\nend\n"
},
{
"answer_id": 4457316,
"author": "Swanand",
"author_id": 18768,
"author_profile": "https://Stackoverflow.com/users/18768",
"pm_score": 0,
"selected": false,
"text": " Post.after_update.reject! {|callback| callback.method.to_s == 'fancy_callback_on_update' }\n Post.after_create.reject! {|callback| callback.method.to_s == 'fancy_callback_on_create' }\n\n Post.after_create :fancy_callback_on_create\n Post.after_update :fancy_callback_on_update\n save"
},
{
"answer_id": 4480501,
"author": "Garrett Lancaster",
"author_id": 547237,
"author_profile": "https://Stackoverflow.com/users/547237",
"pm_score": 0,
"selected": false,
"text": "create_without_callbacks update_without_callbacks"
},
{
"answer_id": 4480510,
"author": "brad",
"author_id": 74389,
"author_profile": "https://Stackoverflow.com/users/74389",
"pm_score": 1,
"selected": false,
"text": "create_without_callbacks @my_obj.send(:create_without_callbacks)\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
315,729 | <p>I am facing a problem.
I would like to localize my action names in my project so french people can have clean urls with french names.</p>
<p><a href="http://www.test.com/Home" rel="nofollow noreferrer">http://www.test.com/Home</a> should be <a href="http://www.test.com/Accueil" rel="nofollow noreferrer">http://www.test.com/Accueil</a></p>
<p>It is a good thing too for google indexing.
Moreover I would like to be Restful on the application, so I would like too keep english name because developers (even frenchies) prefer to work on english names.</p>
<p>I don't know if it's possible and how.</p>
<p>My first idea should be something like get the browser language, assign it to the CurrentThread.CurrentCulture, so I can select the view name I want.</p>
<p>Thank you very much for your answers.</p>
| [
{
"answer_id": 315737,
"author": "Kyle West",
"author_id": 34133,
"author_profile": "https://Stackoverflow.com/users/34133",
"pm_score": 3,
"selected": true,
"text": "routes.MapRoute(\"Catalog-Brands\", \"catalog/brand/\", new {controller = \"Brand\", action = \"Index\", isActive = true});\n routes.MapRoute(\"Catalog-Brands-French\", \"french-catalog/french-brand/\", new {controller = \"Brand\", action = \"Index\", isActive = true});\n public static void RegisterUsRoutes\n\npublic static void RegisterFrenchRoutes\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1195872/"
] |
315,736 | <p>I have a WCF Service that should not enter the faulted state. If there's an exception, it should be logged and the service should continue uninterrupted. The service has a one-way operation contract and is reading messages from an MSMQ.</p>
<p>My problems are twofold:</p>
<ol>
<li>The service appears to be swallowing
an exception/fault so I am unable to
debug it. How do I get the service
to expose the exception so that I
can log or handle it?</li>
<li>The service is
entering into a faulted state after
this exception is swallowed. How do
I prevent the service from entering
into a faulted state?</li>
</ol>
| [
{
"answer_id": 316560,
"author": "David Vidmar",
"author_id": 11063,
"author_profile": "https://Stackoverflow.com/users/11063",
"pm_score": 3,
"selected": false,
"text": "ServiceHelper<CodeListServiceClient, CodeListService.CodeListService>.Use(\n proxy => seasonCodeBindingSource.DataSource = proxy.GetSeasonCodes(brandID);\n);\n using System;\nusing System.ServiceModel;\n\nnamespace Sportina.EnterpriseSystem.Client.Framework.Helpers\n{\n public delegate void UseServiceDelegate<TServiceProxy>(TServiceProxy proxy);\n\n public static class ServiceHelper<TServiceClient, TServiceInterface> where TServiceClient : ClientBase<TServiceInterface>, new() where TServiceInterface : class\n {\n public static void Use(UseServiceDelegate<TServiceClient> codeBlock)\n {\n TServiceClient proxy = null;\n bool success = false;\n try\n {\n proxy = new TServiceClient(); \n codeBlock(proxy);\n proxy.Close();\n success = true;\n }\n catch (Exception ex)\n {\n Common.Logger.Log.Fatal(\"Service error: \" + ex); \n throw;\n }\n finally\n {\n if (!success && proxy != null)\n proxy.Abort();\n }\n }\n }\n}\n"
},
{
"answer_id": 1479898,
"author": "rjchicago",
"author_id": 179329,
"author_profile": "https://Stackoverflow.com/users/179329",
"pm_score": 3,
"selected": false,
"text": " channelFactory = new ChannelFactory<IService>(endpoint);\n channelFactory.Faulted += OnChannelFaulted;\n var channel = channelFactory.CreateChannel();\n void OnChannelFaulted(object sender, EventArgs e)\n {\n channelFactory.Abort();\n }\n"
},
{
"answer_id": 1833516,
"author": "Rolf Kristensen",
"author_id": 193178,
"author_profile": "https://Stackoverflow.com/users/193178",
"pm_score": 3,
"selected": false,
"text": "ServiceHost host = new ServiceHost(new Service.MyService());\nhost.Faulted += new EventHandler(host_faulted);\nhost.Open();\n public class ErrorHandler : IErrorHandler\n{\n public void ProvideFault(Exception error, MessageVersion version, ref Message fault)\n {\n\n }\n\n public bool HandleError(Exception error)\n {\n Console.WriteLine(\"exception\");\n return false;\n }\n}\n\npublic class ErrorServiceBehavior : IServiceBehavior\n{\n public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)\n {\n\n }\n\n public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)\n {\n\n }\n\n public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)\n {\n ErrorHandler handler = new ErrorHandler();\n foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)\n {\n dispatcher.ErrorHandlers.Add(handler);\n }\n }\n}\n\nServiceHost host = new ServiceHost(new Service.MyService());\nhost.Faulted += new EventHandler(host_faulted);\nhost.Description.Behaviors.Add(new ErrorServiceBehavior());\nhost.Open();\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
315,738 | <p>I have a very simple html. The red div is inside the blue div and has a 10 px top margin. On non-ie browsers, the blue box is 10 px apart from the top of viewport and the red div is at the very top of the blue div. What I expect is the ie behavior: red div must be 10 px apart from the top of the blue div. Why does non-ie browsers render like this? (I suppose the wrong behavior is the IE's but why?)</p>
<p>And, what is the correct way to do this?</p>
<p><a href="http://img92.imageshack.us/img92/7662/blankmr7.jpg">why blank? http://img92.imageshack.us/img92/7662/blankmr7.jpg</a></p>
<pre><code><html>
<head>
<style>
body { margin:0; padding:0; }
.outer
{
background-color: #00f;
height: 50px;
}
.inner
{
height: 20px;
width: 20px;
background-color: #f00;
margin: 10px 0 0 10px;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner">
</div>
</div>
</body>
</html>
</code></pre>
| [
{
"answer_id": 315772,
"author": "Chris Lloyd",
"author_id": 42413,
"author_profile": "https://Stackoverflow.com/users/42413",
"pm_score": 2,
"selected": false,
"text": "overflow: auto; <html>\n<head>\n<style>\nbody { margin:0; padding:0; }\n.outer\n{\n background-color: #00f;\n height: 50px;\n overflow: auto;\n}\n.inner\n{\n height: 20px;\n width: 20px;\n background-color: #f00;\n margin: 10px 0 0 10px;\n}\n</style>\n</head>\n<body>\n<div class=\"outer\">\n <div class=\"inner\">\n </div>\n</div>\n</body>\n</html>\n"
},
{
"answer_id": 315790,
"author": "Chris Lloyd",
"author_id": 42413,
"author_profile": "https://Stackoverflow.com/users/42413",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n<style>\nbody { margin:0; padding:0; }\n.outer\n{\n background-color: #00f;\n height: 50px;\n border: 1px solid transparent;\n}\n.inner\n{\n height: 20px;\n width: 20px;\n background-color: #f00;\n margin: 10px 0 0 10px;\n padding: 0;\n}\n</style>\n</head>\n<body>\n<div class=\"outer\">\n <div class=\"inner\">\n </div>\n</div>\n</body>\n</html>\n"
},
{
"answer_id": 315842,
"author": "mercator",
"author_id": 23263,
"author_profile": "https://Stackoverflow.com/users/23263",
"pm_score": 4,
"selected": true,
"text": "overflow: auto .outer:before {\n content: \".\";\n display: block;\n height: 0;\n clear: both;\n visibility: hidden;\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] |
315,739 | <p>I have a problem when assigning functions to the click event of a button in IE 7 with jQuery. Something like the following works fine in Opera but produces an infinite loop in IE:</p>
<pre><code>function updateIndputFields(index, id) {
$("#reloadBtn").click(function(){ updateIndputFields(index, id) });
}
</code></pre>
<p>As I understand it, an infinite loop would not be the expected behavior in this situation. But I'm new to jQuery so maybe I've missed something. Anyways, what should I do to make the click event of the reloadBtn button be set to 'updateIndputFields(index, id)' in IE?</p>
| [
{
"answer_id": 315789,
"author": "ringmaster",
"author_id": 40413,
"author_profile": "https://Stackoverflow.com/users/40413",
"pm_score": 4,
"selected": true,
"text": "<script type=\"text/javascript\">\nfunction updateIndputFields(index, id) {\n$('#output').append('<p>' + index + ' : ' + id + '</p>');\n$('#reloadBtn').unbind('click');\n$(\"#reloadBtn\").click(function(){ updateIndputFields(index, id) });\n}\n</script>\n<p><a href=\"#\" id=\"reloadBtn\">reload</a></p>\n<p><a href=\"#\" onclick=\"updateIndputFields(1,2);return false;\">start</a></p>\n<div id=\"output\"></div>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055/"
] |
315,745 | <p>I want to use this pure HTML/CSS template for my ASP.NET website:</p>
<p><a href="http://sub3.tanguay.de" rel="nofollow noreferrer">http://sub3.tanguay.de</a></p>
<p>I copy it inside my Default.aspx page, inside the FORM element, but the form messes up the layout:</p>
<p><a href="http://sub2.tanguay.de" rel="nofollow noreferrer">http://sub2.tanguay.de</a>
<br/>
<strong>UPDATE: this now displays correctly, thanks to Devio.</strong></p>
<p>I tried altering the style of the form tag but can't get it to stop affecting the layout, I tried:</p>
<pre><code>style="margin: 0px; padding: 0px; display: inline; background-color: transparent;"
</code></pre>
<ul>
<li>Is this a common issue when copying in layout templates into ASP.NET?</li>
<li>Is there an easy work around, like some margin:-2px fix or something like that?</li>
<li>I need to keep the form tag, of course, for the ASP.NET functionality.</li>
</ul>
| [
{
"answer_id": 315774,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 2,
"selected": true,
"text": "form {\n margin:10px; padding: 0;\n border: 1px solid #f2f2f2; \n background-color: #FAFAFA; /* remove this */\n}\n"
},
{
"answer_id": 1651069,
"author": "Gary Joynes",
"author_id": 17937,
"author_profile": "https://Stackoverflow.com/users/17937",
"pm_score": 2,
"selected": false,
"text": "<form id=\"form1\" runat=\"server\" style=\"display: inline; background-color: transparent;\">\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
315,752 | <p>I need to update a pair of old classic asp pages— a <code>search.asp</code> page that provides a simple form which is then posted to a <code>results.asp</code> page. One of the form options on the search page is a drop down list (<code><select</code>) for the "format". If the user chooses the excel format the results page just sets the Response.ContentType to <code>application/vnd.ms-excel</code> and adds a content-disposition header to set the file name and make it an attachment. That's it: it's up to excel to then correctly render the html, and it generally does a pretty good job.</p>
<p>All that works pretty well, except for one thing. The reason for the Excel option is that in this case the users really do want to see as many as 10,000 items or even more for a single search. They'll use Excel to do some additional analysis on the results. So the search operation typically takes just over a minute and I can't change that. </p>
<p>The user experience during that minute is less than ideal. Not only is the user just sitting there with little to no feedback, but there are often enough results that the page overflows the response buffer. This means the page has to flush periodically, and therefore the file starts downloading right away but the download manager isn't able to provide meaningful feedback by itself. My mission is to improve the situation.</p>
<p>The first step is to just show a simple <code>processing...</code> message on the search page when the form submits, and I can do that easily enough. In fact, it's been doing this already for the "HTML" format option. The problem is that when downloading the Excel file I don't know how to tell anything about the download so I can hide the message again, and the existing implementation doesn't provide any feedback on download progress at all. Any ideas? If I can just get a javascript function to fire when the download completes I can hook just about anything to that, but I can't even do that yet.</p>
<p><strong>Update:</strong><br>
I re-worded the question to try to present the problem more clearly.</p>
| [
{
"answer_id": 315861,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 0,
"selected": false,
"text": "Response.AddHeader \"Content-Disposition\", \"attachment; filename=report.xls\"\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
315,760 | <p>I've been using this function but I'd like to know what's the most efficient and accurate way to get it.</p>
<pre><code>function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
</code></pre>
| [
{
"answer_id": 315767,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 9,
"selected": true,
"text": "function daysInMonth (month, year) { // Use 1 for January, 2 for February, etc.\n return new Date(year, month, 0).getDate();\n}\n\nconsole.log(daysInMonth(2, 1999)); // February in a non-leap year.\nconsole.log(daysInMonth(2, 2000)); // February in a leap year."
},
{
"answer_id": 5471966,
"author": "dolmen",
"author_id": 328115,
"author_profile": "https://Stackoverflow.com/users/328115",
"pm_score": 3,
"selected": false,
"text": "var daysInMonth = (function() {\n var cache = {};\n return function(month, year) {\n var entry = year + '-' + month;\n\n if (cache[entry]) return cache[entry];\n\n return cache[entry] = new Date(year, month, 0).getDate();\n }\n})();\n"
},
{
"answer_id": 22237589,
"author": "Tony Li",
"author_id": 2026978,
"author_profile": "https://Stackoverflow.com/users/2026978",
"pm_score": 1,
"selected": false,
"text": "function numberOfDays(iMonth, iYear) {\n var myDate = new Date(iYear, iMonth + 1, 1); //find the fist day of next month\n var newDate = new Date(myDate - 1); //find the last day\n return newDate.getDate(); //return # of days in this month\n }\n"
},
{
"answer_id": 27810609,
"author": "GitaarLAB",
"author_id": 588079,
"author_profile": "https://Stackoverflow.com/users/588079",
"pm_score": 4,
"selected": false,
"text": "Date object 0 AD/BC 1 BC 1 function daysInMonth(m, y){\n return m===2?y&3||!(y%25)&&y&15?28:29:30+(m+(m>>3)&1);\n} <!-- example for the snippet -->\n<input type=\"text\" value=\"enter year\" onblur=\"\n for( var r='', i=0, y=+this.value\n ; 12>i++\n ; r+= 'Month: ' + i + ' has ' + daysInMonth(i, y) + ' days<br>'\n );\n this.nextSibling.innerHTML=r;\n\" /><div></div>"
},
{
"answer_id": 28096458,
"author": "Yash",
"author_id": 1766033,
"author_profile": "https://Stackoverflow.com/users/1766033",
"pm_score": 1,
"selected": false,
"text": "function (year, month) {\n var isLeapYear = ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);\n\n return [31, (isLeapYear ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];\n}\n"
},
{
"answer_id": 31403697,
"author": "Jaybeecave",
"author_id": 1599441,
"author_profile": "https://Stackoverflow.com/users/1599441",
"pm_score": 2,
"selected": false,
"text": "function daysInMonth(month,year) {\n var monthNum = new Date(Date.parse(month +\" 1,\"+year)).getMonth()+1\n return new Date(year, monthNum, 0).getDate();\n}\n\ndaysInMonth('feb', 2015)\n//28\n\ndaysInMonth('feb', 2008)\n//29\n"
},
{
"answer_id": 36150994,
"author": "artem_p",
"author_id": 2211266,
"author_profile": "https://Stackoverflow.com/users/2211266",
"pm_score": 2,
"selected": false,
"text": "moment().daysInMonth(); // number of days in the current month\nmoment(\"2012-02\", \"YYYY-MM\").daysInMonth() // 29\nmoment(\"2012-01\", \"YYYY-MM\").daysInMonth() // 31\n"
},
{
"answer_id": 39467407,
"author": "Tomas Langkaas",
"author_id": 6738706,
"author_profile": "https://Stackoverflow.com/users/6738706",
"pm_score": 2,
"selected": false,
"text": "//m is 0-based, Jan = 0, Dec = 11\n\nfunction daysInMonth(m,y){\n return 31-(m-1?m%7&1:y&(y%25?3:15)?3:2);\n}\n\nconsole.log(daysInMonth(1, 2003), \"days in February in the non-leap year 2003\");\nconsole.log(daysInMonth(1, 2004), \"days in February in the leap year 2004\");\nconsole.log(daysInMonth(1, 2100), \"days in February in the non-leap year 2100\");\nconsole.log(daysInMonth(1, 2000), \"days in February in the leap year 2000\");\n\nconsole.log(daysInMonth(0, 2022), \"days in January 2022\");\nconsole.log(daysInMonth(1, 2022), \"days in February 2022\");\nconsole.log(daysInMonth(2, 2022), \"days in March 2022\");\nconsole.log(daysInMonth(3, 2022), \"days in April 2022\");\nconsole.log(daysInMonth(4, 2022), \"days in May 2022\");\nconsole.log(daysInMonth(5, 2022), \"days in June 2022\");\nconsole.log(daysInMonth(6, 2022), \"days in July 2022\");\nconsole.log(daysInMonth(7, 2022), \"days in August 2022\");\nconsole.log(daysInMonth(8, 2022), \"days in September 2022\");\nconsole.log(daysInMonth(9, 2022), \"days in October 2022\");\nconsole.log(daysInMonth(10, 2022), \"days in November 2022\");\nconsole.log(daysInMonth(11, 2022), \"days in December 2022\"); (m - 1 ? /* Not February */ : /* February */) m - 1 m % 7 m & 1 y & (y % 25 ? 3 : 15)"
},
{
"answer_id": 42684837,
"author": "mrplants",
"author_id": 2116338,
"author_profile": "https://Stackoverflow.com/users/2116338",
"pm_score": 1,
"selected": false,
"text": "Date.prototype.getNumberOfDaysInMonth = function(monthOffset) {\n if (monthOffset !== undefined) {\n return new Date(this.getFullYear(), this.getMonth()+monthOffset, 0).getDate();\n } else {\n return new Date(this.getFullYear(), this.getMonth(), 0).getDate();\n }\n}\n var myDate = new Date();\nmyDate.getNumberOfDaysInMonth(); // Returns 28, 29, 30, 31, etc. as necessary\nmyDate.getNumberOfDaysInMonth(); // BONUS: This also tells you the number of days in past/future months!\n"
},
{
"answer_id": 46605332,
"author": "Shl",
"author_id": 5538728,
"author_profile": "https://Stackoverflow.com/users/5538728",
"pm_score": 1,
"selected": false,
"text": "// month is 1-12\nfunction getDaysInMonth(year, month){\n return month == 2 ? 28 + (year % 4 == 0 ? (year % 100 == 0 ? (year % 400 == 0 ? 1 : 0) : 1):0) : 31 - (month - 1) % 7 % 2;\n}\n"
},
{
"answer_id": 47188148,
"author": "kmiklas",
"author_id": 1526115,
"author_profile": "https://Stackoverflow.com/users/1526115",
"pm_score": 1,
"selected": false,
"text": "function daysInMonth(month, year) {\n var days;\n switch (month) {\n case 1: // Feb, our problem child\n var leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n days = leapYear ? 29 : 28;\n break;\n case 3: case 5: case 8: case 10: \n days = 30;\n break;\n default: \n days = 31;\n }\n return days;\n},\n"
},
{
"answer_id": 52645845,
"author": "Masum Billah",
"author_id": 1800149,
"author_profile": "https://Stackoverflow.com/users/1800149",
"pm_score": 2,
"selected": false,
"text": "new Date(2019,2,0).getDate(); //28\nnew Date(2020,2,0).getDate(); //29\n"
},
{
"answer_id": 60723867,
"author": "Syed",
"author_id": 1292050,
"author_profile": "https://Stackoverflow.com/users/1292050",
"pm_score": 2,
"selected": false,
"text": "function getDayCountOfMonth(year, month) {\n if (month === 3 || month === 5 || month === 8 || month === 10) {\n return 30;\n }\n\n if (month === 1) {\n if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {\n return 29;\n } else {\n return 28;\n }\n }\n\n return 31;\n};\n\nconsole.log(getDayCountOfMonth(2020, 1)); function isLeapYear(year) { \n return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); \n};\n\nconst getDaysInMonth = function (year, month) {\n return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];\n};\n\nconsole.log(getDaysInMonth(2020, 1));"
},
{
"answer_id": 61575747,
"author": "Sanka Sanjeewa",
"author_id": 10564312,
"author_profile": "https://Stackoverflow.com/users/10564312",
"pm_score": 1,
"selected": false,
"text": "const getDaysInMonth = date =>\n new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();\n\ndaysInThisMonth = getDaysInMonth(new Date());\n\nconsole.log(daysInThisMonth);"
},
{
"answer_id": 62379986,
"author": "RASG",
"author_id": 982924,
"author_profile": "https://Stackoverflow.com/users/982924",
"pm_score": 2,
"selected": false,
"text": "const d = (y, m) => new Date(y, m, 0).getDate();\n console.log( d(2020, 2) );\n// 29\n\nconsole.log( d(2020, 6) );\n// 30\n"
},
{
"answer_id": 65471290,
"author": "Greg Herbowicz",
"author_id": 3603905,
"author_profile": "https://Stackoverflow.com/users/3603905",
"pm_score": 1,
"selected": false,
"text": "const countDays = (month, year) => 30 + (month === 2 ? (year % 4 === 0 && 1) - 2 : (month + Number(month > 7)) % 2);\n countDays(11,2020) // 30\ncountDays(2,2020) // 29\ncountDays(2,2021) // 28\n"
},
{
"answer_id": 69267613,
"author": "crg",
"author_id": 7942242,
"author_profile": "https://Stackoverflow.com/users/7942242",
"pm_score": 1,
"selected": false,
"text": "var nbOfDaysInCurrentMonth = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 0)).getDate()\n\nconsole.log(nbOfDaysInCurrentMonth)"
},
{
"answer_id": 72158620,
"author": "Mehran",
"author_id": 19065551,
"author_profile": "https://Stackoverflow.com/users/19065551",
"pm_score": 1,
"selected": false,
"text": "new Date(year, month, 0).getDate();\n"
},
{
"answer_id": 72322767,
"author": "user3693428",
"author_id": 3693428,
"author_profile": "https://Stackoverflow.com/users/3693428",
"pm_score": 0,
"selected": false,
"text": "numDays=0;\nswitch(month)\n{\n case 1:\n numDays=31;\n break;\n case 2:\n numDays=28;\n break;\n case 3:\n numDays=31;\n break;\n case 4:\n numDays=30;\n break;\n case 5:\n numDays=31;\n break;\n case 6:\n numDays=30;\n break;\n case 7:\n numDays=31;\n break;\n case 8:\n numDays=31;\n break;\n case 9:\n numDays=30;\n break;\n case 10:\n numDays=31;\n break;\n case 11:\n numDays=30;\n break;\n case 12:\n numDays=31;\n break;\n}\n\nif(month==2)\n{\n if( (year % 100) == 0 )\n {\n if( (year % 400) == 0 )\n {\n numDays=29;\n }\n }\n else\n {\n if( (year % 4) == 0 )\n {\n numDays=29;\n }\n }\n}\n\n//\nreturn numDays;\n const years = [2019,2020,2021,2022,2023,2024,2025,2026,2027,2028,2100,2400];\nmonth=2;\nfor (let i = 0; i < years.length; i++) \n{\n let text = \"\";\n text += years[i] + '/' + month.toString() + \": \" + numberOfDays(years[i], month).toString();\n alert(text);\n} \n\nfor (let m = 1; m <= 12; m++) \n{\n let text2 = \"\";\n text2 += \"2022/\" + m.toString() + \": \" + numberOfDays(2022, m).toString();\n alert(text2);\n} \n"
},
{
"answer_id": 73556074,
"author": "Mykyta Halchenko",
"author_id": 17239546,
"author_profile": "https://Stackoverflow.com/users/17239546",
"pm_score": 1,
"selected": false,
"text": "month: days const getMonthsDaysForYear = (year) => {\n let monthDaysDictionary = {};\n\n for(let i = 1; i <= 11; i++) {\n const date = new Date(year, i + 1, 0);\n const monthName = date.toLocaleString('en-GB', { month: 'long' });\n monthDaysDictionary[monthName] = date.getDate();\n }\n\n return monthDaysDictionary;\n}\ngetMonthsDaysForYear(2022);\n 1"
},
{
"answer_id": 74073895,
"author": "RARE Kpop Manifesto",
"author_id": 14672114,
"author_profile": "https://Stackoverflow.com/users/14672114",
"pm_score": 0,
"selected": false,
"text": "awk & POSIX awk mawk gawk nawk 1 - 12 0 - 11 month year February {m,g,n}awk '\n\nfunction _____(_,__) {\n #\n # _| Month mm: [1-12]\n # __| Year yyyy:\n # |---> #-days:\n # in yyyy:mm: combo\n return -(\\\n _^(_<_) != --_ \\\n ? (_ %((_+=_+=_^=_<_) +--_)) %--_\\\n : (_+=_^=_<_) + (__ == \"\" ||\n __ % (_+=_) ||\n __% (_*(_*=_++)+_) == ! (__ % (_*_))\\\n ) ) \\\n -(_^=_<_) -+- ++_^_^_*_ \n}'\n\n\n 2 1600 29\n 2 1700 28\n 2 1800 28\n 2 1868 29\n 2 1900 28\n 2 1912 29\n 2 1956 29\n 2 2000 29\n 2 2012 29\n 2 2016 29\n 2 2018 28\n 2 2020 29\n 2 2022 28\n 2 2024 29\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39203/"
] |
315,778 | <p>I just started using CCNet, and in the process of getting my build projects set up I racked up a lot of build history from trial and error. I really don't want to keep that old stuff around, but I can't seem to see where/how to get rid of it. I'm sure this is a silly question, and I apologize if I'm overlooking something that should be obvious. I did <a href="http://confluence.public.thoughtworks.org/display/CCNET/Documentation" rel="noreferrer">RTM</a> and Google for about a half hour, and poked around my CCNet installation, but it's not jumping out at me. I deleted the state files for the projects (don't know if that has anything to do with it), but the old builds are still there if I drill into a project's stats from the dashboard. Any suggestions? Thanks.</p>
<p><strong>Answered</strong>: I had explicitly set the artifacts directory to a location that was not under the CCNet server directory and consequently never looked in it again... went looking and, disco, there's the build histories.</p>
| [
{
"answer_id": 26930555,
"author": "Dan Malcolm",
"author_id": 146280,
"author_profile": "https://Stackoverflow.com/users/146280",
"pm_score": 0,
"selected": false,
"text": "$limit = (Get-Date).AddDays(-60)\n\nget-childitem -Path D:\\Builds -filter MatchMyProjects.* | %{ \n $projectPath=$_.FullName\n $logsPath=$projectPath + \"\\Logs\" \n write-host Removing logs from folder $logsPath\n Get-ChildItem -Path $logsPath -Force -Filter *.xml | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4296/"
] |
315,780 | <p>I have a small web application which uses themes. The themes work on host, so on preinit, if the host = a, load x theme, if the host = b, load y theme. </p>
<p>In my code this looks like: </p>
<p>If request.url.host.contains("a") Then
Page.Theme = x
Else
request.url.host.contains("b") Then
Page.Theme = y </p>
<p>I have a url which is a.abc.com and another which is b.abc.com (well it is this structure, but the letters are meaningful/company names). Problem is (and I have done host == ""), when I debug my site on localhost (another clause in the above if block where host = localhost), the style renders perfectly. Alignment of elements are perfect as I expect with the numerical values I have provided for width, margins, etc in the css. But when I use the publish tool of VS2008 (with updatable ticked), and upload to a.abc.com, which has the same stylesheet as localhost (a copy in its own folder), there are all sorts of alignment issues as if I have done no work. Why do my styles render incorrectly @ runtime? If it helps, I am using VS2008 Pro Edition, IIS6 and Windows Server 2003.</p>
<p>What is frustrating is that the page source indicates the theme is loading ok, as it is referenced in HTML head. So when I publish, the theme for a.abc.com is loaded and referenced. Other than all this information, there is no obvious sign of what the problem is. I haven't tried to conventionally reference a single CSS file in the ASPX markup, but if I did and this worked, then it doesn't explain the problem either, anyway.</p>
<p>Thanks</p>
| [
{
"answer_id": 61499213,
"author": "Imran Rafique",
"author_id": 1600006,
"author_profile": "https://Stackoverflow.com/users/1600006",
"pm_score": 0,
"selected": false,
"text": "Internet Information Services --> World Wide Web Services --> Common HTTP Features "
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
315,787 | <p>I' trying to use a Linq query to find and set the selected value in a drop down list control.</p>
<pre><code> Dim qry = From i In ddlOutcome.Items _
Where i.Text.Contains(value)
Dim selectedItem As ListItem = qry.First
ddlOutcome.SelectedValue = selectedItem.Value
</code></pre>
<p>Even though the documentation says that the DropDownList.Items collection implements IEnumerable I get an error in the Where clause that Option Strict ON disallows late binding!</p>
| [
{
"answer_id": 315878,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 1,
"selected": false,
"text": "Dim qry = From DirectCast(i, ListItem) In ddlOutcome.Items ...\n"
},
{
"answer_id": 315916,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 3,
"selected": false,
"text": "DropDownList1.SelectedIndex = \n DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(\"2\"));\n var selected=from i in DropDownList1.Items.Cast<ListItem>()\n where ((ListItem)i).Text.Contains(\"2\") select i;\n\nDropDownList1.SelectedValue = selected.ToList()[0].Text;\n"
},
{
"answer_id": 317599,
"author": "TGnat",
"author_id": 25121,
"author_profile": "https://Stackoverflow.com/users/25121",
"pm_score": 3,
"selected": true,
"text": " Dim qry = From i In ddlOutcome.Items.Cast(Of ListItem)() _\n Where i.Text.Contains(value)\n\n qry.First().Selected = True\n"
},
{
"answer_id": 388747,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "foreach (ListItem i in DropDownList1.Items)\n {\n DropDownList1.SelectedValue = i.Value;\n if (DropDownList1.SelectedItem.Text==\"text of your DropDownList\")\n {\n break;\n }\n }\n"
},
{
"answer_id": 12508608,
"author": "matt_lethargic",
"author_id": 314591,
"author_profile": "https://Stackoverflow.com/users/314591",
"pm_score": 3,
"selected": false,
"text": "foreach (ListItem li in drp.Items.Cast<ListItem>().Where(li => li.Value == \"\"))\n{\n li.Selected = true;\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25121/"
] |
315,792 | <p>How can I achieve the following? I have two models (blogs and readers) and a JOIN table that will allow me to have an N:M relationship between them:</p>
<pre><code>class Blog < ActiveRecord::Base
has_many :blogs_readers, :dependent => :destroy
has_many :readers, :through => :blogs_readers
end
class Reader < ActiveRecord::Base
has_many :blogs_readers, :dependent => :destroy
has_many :blogs, :through => :blogs_readers
end
class BlogsReaders < ActiveRecord::Base
belongs_to :blog
belongs_to :reader
end
</code></pre>
<p>What I want to do now, is add readers to different blogs. The condition, though, is that I can only add a reader to a blog ONCE. So there mustn't be any duplicates (same <code>readerID</code>, same <code>blogID</code>) in the <code>BlogsReaders</code> table. How can I achieve this?</p>
<p>The second question is, how do I get a list of blog that the readers isn't subscribed to already (e.g. to fill a drop-down select list, which can then be used to add the reader to another blog)?</p>
| [
{
"answer_id": 315821,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": 5,
"selected": false,
"text": "class BlogsReaders < ActiveRecord::Base\n belongs_to :blog\n belongs_to :reader\n\n validates_uniqueness_of :reader_id, :scope => :blog_id\nend\n"
},
{
"answer_id": 316011,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": 1,
"selected": false,
"text": "the_reader = Reader.find(:first, :include => :blogs)\n\nBlog.find(:all, \n :conditions => ['id NOT IN (?)', the_reader.blogs.map(&:id)])\n"
},
{
"answer_id": 317559,
"author": "Josh Delsman",
"author_id": 40644,
"author_profile": "https://Stackoverflow.com/users/40644",
"pm_score": 4,
"selected": true,
"text": "Blog.find(:all,\n :conditions => ['id NOT IN (?)', the_reader.blog_ids])\n"
},
{
"answer_id": 318146,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 7,
"selected": false,
"text": " class Blog < ActiveRecord::Base\n has_many :blogs_readers, :dependent => :destroy\n has_many :readers, :through => :blogs_readers, :uniq => true\n end\n\n class Reader < ActiveRecord::Base\n has_many :blogs_readers, :dependent => :destroy\n has_many :blogs, :through => :blogs_readers, :uniq => true\n end\n\n class BlogsReaders < ActiveRecord::Base\n belongs_to :blog\n belongs_to :reader\n end\n :uniq => true has_many has_and_belongs_to_many :uniq class Blog < ActiveRecord::Base\n has_many :blogs_readers, dependent: :destroy\n has_many :readers, -> { uniq }, through: :blogs_readers\nend\n\nclass Reader < ActiveRecord::Base\n has_many :blogs_readers, dependent: :destroy\n has_many :blogs, -> { uniq }, through: :blogs_readers\nend\n\nclass BlogsReaders < ActiveRecord::Base\n belongs_to :blog\n belongs_to :reader\nend\n uniq NoMethodError: undefined method 'extensions' for []:Array distinct class Blog < ActiveRecord::Base\n has_many :blogs_readers, dependent: :destroy\n has_many :readers, -> { distinct }, through: :blogs_readers\nend\n\nclass Reader < ActiveRecord::Base\n has_many :blogs_readers, dependent: :destroy\n has_many :blogs, -> { distinct }, through: :blogs_readers\nend\n\nclass BlogsReaders < ActiveRecord::Base\n belongs_to :blog\n belongs_to :reader\nend\n"
},
{
"answer_id": 35165086,
"author": "Christos C",
"author_id": 2898994,
"author_profile": "https://Stackoverflow.com/users/2898994",
"pm_score": -1,
"selected": false,
"text": "class Blog < ActiveRecord::Base\n has_many :blogs_readers, :dependent => :destroy\n has_many :readers, :through => :blogs_readers\n serialize :reader_ids, Array\nend\n blog.reader_ids = [1,2,3,4]\n"
},
{
"answer_id": 38845388,
"author": "pastullo",
"author_id": 1490947,
"author_profile": "https://Stackoverflow.com/users/1490947",
"pm_score": 4,
"selected": false,
"text": "class Blog < ActiveRecord::Base\n has_many :blogs_readers, dependent: :destroy\n has_many :readers, -> { distinct }, through: :blogs_readers\nend\n\nclass Reader < ActiveRecord::Base\n has_many :blogs_readers, dependent: :destroy\n has_many :blogs, -> { distinct }, through: :blogs_readers\nend\n\nclass BlogsReaders < ActiveRecord::Base\n belongs_to :blog\n belongs_to :reader\nend\n"
},
{
"answer_id": 45511163,
"author": "JD Isaacks",
"author_id": 46011,
"author_profile": "https://Stackoverflow.com/users/46011",
"pm_score": 2,
"selected": false,
"text": "uniq class Blog < ActiveRecord::Base\n has_many :blogs_readers, dependent: :destroy\n has_many :readers, -> { uniq }, through: :blogs_readers\nend\n distinct class Blog < ActiveRecord::Base\n has_many :blogs_readers, dependent: :destroy\n has_many :readers, -> { distinct }, through: :blogs_readers\nend\n"
},
{
"answer_id": 68989564,
"author": "kinton",
"author_id": 12004339,
"author_profile": "https://Stackoverflow.com/users/12004339",
"pm_score": 1,
"selected": false,
"text": "class BlogsReaders < ActiveRecord::Base\n belongs_to :blog\n belongs_to :reader\n\n validates :blog_id, uniqueness: { scope: :reader_id }\nend\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29909/"
] |
315,799 | <p>I have some code that reads 10 registry keys, sometimes the values are not present sometimes the keys are not present, sometimes the value isn't boolean etc etc. How should I add error handling to this, currently it is placed in one big try{} catch{} but if the second value I read fails then the rest are not read as the program jumps to catch{}, I could add a try{} catch{} for each but I'm guessing there is a better way. How would you handle this? I'm asking as I regularly come across similar problems and my own solution is to add a try{} catch{}.</p>
<p>Thanks for the help.</p>
| [
{
"answer_id": 315807,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "SomeReturnType foo = HackyMethod(first path);\nSomeReturnType bar = HackyMethod(sedond path);\n\nSomeReturnType HackyMethod(string path)\n{\n try {} catch {} etc\n}\n"
},
{
"answer_id": 315817,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 0,
"selected": false,
"text": "public IEnumerable<string> ReadRegistryKeys()\n{\n IEnumerable<string> resultList = new List<string>();\n if (string.IsNullOrEmpty(read_in_key_#1())\n {\n\n resultList.Add(\"Failed to load key 'blah'..\");\n }\n\n if (.... read in the next key .. etc.... ) ...\n\n return resultList == null || resultList.Count <= 0 ? null : resultList;\n}\n"
},
{
"answer_id": 315844,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "Dictionary<String,String> regKeys = new Dictionary<String,String>()\n{\n { \"Key1\", String.Empty},\n { \"Key2\", String.Empty},\n { \"Key3\", String.Empty}\n};\n\nfor (int i = 0; i < regKeys.Length; i++)\n{\n try\n {\n regKeys[i].Value = ReadFromRegistry(regKeys[i].Key);\n }\n catch (Exception ex)\n {\n Console.WriteLine(\"Unable to read Key: \" + regKeys[i].Key \n + \" Exception: \" + ex.Message);\n } \n}\n"
},
{
"answer_id": 315903,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "object o = Microsoft.Win32.Registry.GetValue(\n @\"HKEY_CURRENT_USER\\Software\\Microsoft\\Calc\", \"layout\", \"\");\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
315,803 | <p>I get the following error while building OpenCV on OS X 10.5 (intel):</p>
<pre><code>ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture
ld: warning in .libs/_cv_la-error.o, file is not of required architecture
ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture
ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture
ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture
ld: warning in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libcxcore.dylib, file is not of required architecture
Undefined symbols for architecture i386:
"_fputs$UNIX2003", referenced from:
_PySwigObject_print in _cv_la-_cv.o
_PySwigPacked_print in _cv_la-_cv.o
_PySwigPacked_print in _cv_la-_cv.o
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status
lipo: can't open input file: /var/folders/Sr/Srq9N4R8Hr82xeFvW3o-uk+++TI/-Tmp-//cchT0WVX.out (No such file or directory)
make[4]: *** [_cv.la] Error 1
make[3]: *** [all-recursive] Error 1
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
</code></pre>
<p>While running ./configure --without-python everything is ok. Another strange thing is that when I used Python 2.4.5 or 2.5.1 everything has built ok, the problem occured after switching to Python Framework 2.5.2</p>
| [
{
"answer_id": 321534,
"author": "Pyetras",
"author_id": 40431,
"author_profile": "https://Stackoverflow.com/users/40431",
"pm_score": 0,
"selected": false,
"text": "ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture\nld: warning in .libs/_cv_la-error.o, file is not of required architecture\nld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture\nld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture\nld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture\nld: warning in /Users/Pietras/opencv/cxcore/src/.libs/libcxcore.dylib, file is not of required architecture\nUndefined symbols for architecture i386: ... `\n /Library/Frameworks/Python.framework/Versions/Current/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/sw/bin:/sw/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/AVRMacPack/bin:/usr/X11R6/bin\n which python\n/Library/Frameworks/Python.framework/Versions/Current/bin/python\n"
},
{
"answer_id": 322059,
"author": "Pyetras",
"author_id": 40431,
"author_profile": "https://Stackoverflow.com/users/40431",
"pm_score": 1,
"selected": true,
"text": "/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40431/"
] |
315,804 | <p>In my JSF/Facelets app, here's a simplified version of part of my form:</p>
<pre><code><h:form id="myform">
<h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
<h:message class="error" for="newPassword1" />
<h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
<h:message class="error" for="newPassword2" />
<h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>
</code></pre>
<p>I'd like to be able to assign an error to a specific h:message tag based on something happening in the continueButton() method. Different errors need to be displayed for newPassword and newPassword2. A validator won't really work, because the method that will deliver results (from the DB) is run in the continueButton() method, and is too expensive to run twice. </p>
<p>I can't use the h:messages tag because the page has multiple places that I need to display different error messages. When I tried this, the page displayed duplicates of every message.</p>
<p>I tried this as a best guess, but no luck:</p>
<pre><code>public Navigation continueButton() {
...
expensiveMethod();
if(...) {
FacesContext.getCurrentInstance().addMessage("newPassword", new FacesMessage("Error: Your password is NOT strong enough."));
}
}
</code></pre>
<p>What am I missing? Any help would be appreciated!</p>
| [
{
"answer_id": 315865,
"author": "Jan Zich",
"author_id": 15716,
"author_profile": "https://Stackoverflow.com/users/15716",
"pm_score": 2,
"selected": false,
"text": "<h:outputText\n value=\"#{CreateNewPasswordBean.errorMessage}\"\n render=\"#{CreateNewPasswordBean.errorMessage != null}\" />\n"
},
{
"answer_id": 316890,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "FacesContext.getCurrentInstance().addMessage(\"newPassword1\", \n new FacesMessage(FacesMessage.SEVERITY_ERROR, \"Error Message\"));\n <h:message for=\"newPassword1\" />"
},
{
"answer_id": 317570,
"author": "huo73",
"author_id": 15657,
"author_profile": "https://Stackoverflow.com/users/15657",
"pm_score": 3,
"selected": false,
"text": " FacesContext.getCurrentInstance().addMessage(\"myform:newPassword1\", new FacesMessage(\"Error: Your password is NOT strong enough.\"));\n"
},
{
"answer_id": 319036,
"author": "Eric Noob",
"author_id": 27515,
"author_profile": "https://Stackoverflow.com/users/27515",
"pm_score": 6,
"selected": true,
"text": "<h:form id=\"myform\">\n <h:inputSecret value=\"#{createNewPassword.newPassword1}\" id=\"newPassword1\" />\n <h:message class=\"error\" for=\"newPassword1\" id=\"newPassword1Error\" />\n <h:inputSecret value=\"#{createNewPassword.newPassword2}\" id=\"newPassword2\" />\n <h:message class=\"error\" for=\"newPassword2\" id=\"newPassword2Error\" />\n <h:commandButton value=\"Continue\" action=\"#{createNewPassword.continueButton}\" />\n</h:form>\n FacesContext.getCurrentInstance().addMessage(\"myForm:newPassword1\", new FacesMessage(PASSWORDS_DONT_MATCH, PASSWORDS_DONT_MATCH));\n"
},
{
"answer_id": 321722,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 6,
"selected": false,
"text": "<f:view>\n <h:form>\n <h:commandButton id=\"mybutton\" value=\"click\"\n binding=\"#{showMessageAction.mybutton}\"\n action=\"#{showMessageAction.validatePassword}\" />\n <h:message for=\"mybutton\" />\n </h:form>\n</f:view>\n /** Must be request scope for binding */\npublic class ShowMessageAction {\n\n private UIComponent mybutton;\n\n private boolean isOK = false;\n\n public String validatePassword() {\n if (isOK) {\n return \"ok\";\n }\n else {\n // invalid\n FacesMessage message = new FacesMessage(\"Invalid password length\");\n FacesContext context = FacesContext.getCurrentInstance();\n context.addMessage(mybutton.getClientId(context), message);\n }\n return null;\n }\n\n public void setMybutton(UIComponent mybutton) {\n this.mybutton = mybutton;\n }\n\n public UIComponent getMybutton() {\n return mybutton;\n }\n}\n"
},
{
"answer_id": 11423446,
"author": "InfZero",
"author_id": 379371,
"author_profile": "https://Stackoverflow.com/users/379371",
"pm_score": 2,
"selected": false,
"text": "FacesContext context = FacesContext.getCurrentInstance();\ncontext.addMessage( null, new FacesMessage( \"The message to display in client\" )); \n"
},
{
"answer_id": 50453353,
"author": "Jose Manuel Gomez Alvarez",
"author_id": 2639772,
"author_profile": "https://Stackoverflow.com/users/2639772",
"pm_score": 0,
"selected": false,
"text": " FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, \"Authentication failed\", null);\n FacesContext context = FacesContext.getCurrentInstance();\n context.addMessage(null, message); \n <h:messages></h:messages>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27515/"
] |
315,829 | <p>Suppose you create a generic Object variable and assign it to a specific instance. If you do GetType(), will it get type Object or the type of the original class?</p>
| [
{
"answer_id": 315835,
"author": "Alan",
"author_id": 37843,
"author_profile": "https://Stackoverflow.com/users/37843",
"pm_score": 3,
"selected": true,
"text": "object c = new FooBar();\nif(c is FooBar)\n Console.WriteLine(\"FOOBAR!!!\");\n"
},
{
"answer_id": 315837,
"author": "Kalid",
"author_id": 109,
"author_profile": "https://Stackoverflow.com/users/109",
"pm_score": 2,
"selected": false,
"text": " Foo f = new Foo();\n Type t = f.GetType();\n\n Object o = (object)f;\n Type t2 = o.GetType();\n\n bool areSame = t.Equals(t2);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109/"
] |
315,845 | <p>Is there any reason to avoid using <code>text-align: justify;</code>? </p>
<p>Does it reduce readability or cause problems?</p>
| [
{
"answer_id": 315876,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 5,
"selected": false,
"text": "hyphens"
},
{
"answer_id": 657528,
"author": "hlfcoding",
"author_id": 65465,
"author_profile": "https://Stackoverflow.com/users/65465",
"pm_score": 7,
"selected": true,
"text": "­"
},
{
"answer_id": 7638846,
"author": "frequent",
"author_id": 536768,
"author_profile": "https://Stackoverflow.com/users/536768",
"pm_score": 0,
"selected": false,
"text": "text-align: justify text-align: center"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12689/"
] |
315,846 | <p>When and why would somebody do the following:</p>
<pre><code>doSomething( (MyClass) null );
</code></pre>
<p>Have you ever done this? Could you please share your experience?</p>
| [
{
"answer_id": 315853,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 8,
"selected": true,
"text": "doSomething MyClass public void doSomething(MyClass c) {\n // ...\n}\n\npublic void doSomething(MyOtherClass c) {\n // ...\n}\n class Example {\n static void test(String code, String... s) {\n System.out.println(\"code: \" + code);\n if(s == null) {\n System.out.println(\"array is null\");\n return;\n }\n for(String str: s) {\n if(str != null) {\n System.out.println(str);\n } else {\n System.out.println(\"element is null\");\n }\n }\n System.out.println(\"---\");\n }\n\n public static void main(String... args) {\n /* the array will contain two elements */\n test(\"numbers\", \"one\", \"two\");\n /* the array will contain zero elements */\n test(\"nothing\");\n /* the array will be null in test */\n test(\"null-array\", (String[])null); \n /* first argument of the array is null */\n test(\"one-null-element\", (String)null); \n /* will produce a warning. passes a null array */\n test(\"warning\", null);\n }\n}\n java.lang.String java.lang.String[]"
},
{
"answer_id": 315867,
"author": "Eren Aygunes",
"author_id": 27980,
"author_profile": "https://Stackoverflow.com/users/27980",
"pm_score": 5,
"selected": false,
"text": "null void ShowMessage(String msg, Control parent); void ShowMessage(String msg, MyDelegate callBack); null null ShowMessage(\"Test\", (Control) null); ShowMessage(\"Test2\", (MyDelegate) null);"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] |
315,850 | <p>I want to create a Rails (2.1 and 2.2) model with ActiveRecord validations, but without a database table. What is the most widely used approach? I've found some plugins that claim to offer this functionality, but many of them don't appear to be widely used or maintained. What does the community recommend I do? Right now I am leaning toward coming up with my own solution based on <a href="http://www.prestonlee.com/2007/12/29/rails-20-validations-without-extending-activerecordbase/" rel="noreferrer">this blog post</a>.</p>
| [
{
"answer_id": 316090,
"author": "tpinto",
"author_id": 40467,
"author_profile": "https://Stackoverflow.com/users/40467",
"pm_score": 3,
"selected": false,
"text": "class Car\n # here goes all your model's stuff\nend\n class Car\n attr_accessor :wheels # this will create for you the reader and writer for this attribute\n attr_accessor :doors # ya, this will do the same\n\n # here goes all your model's stuff\nend\n"
},
{
"answer_id": 316098,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": 2,
"selected": false,
"text": "class Car < ActiveRecord::Base\n self.abstract = true\nend\n my_car = Car.new\n"
},
{
"answer_id": 317958,
"author": "Sarah Vessels",
"author_id": 38743,
"author_profile": "https://Stackoverflow.com/users/38743",
"pm_score": 0,
"selected": false,
"text": "config.frameworks -= [:active_record]\n Rails::Initializer.run do |config|"
},
{
"answer_id": 318919,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 5,
"selected": false,
"text": "class Tableless < ActiveRecord::Base\n def self.columns\n @columns ||= [];\n end\n\n def self.column(name, sql_type = nil, default = nil, null = true)\n columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default,\n sql_type.to_s, null)\n end\n\n # Override the save method to prevent exceptions.\n def save(validate = true)\n validate ? valid? : true\n end\nend\n class Foo < Tableless\n column :bar, :string \n validates_presence_of :bar\nend\n Loading development environment (Rails 2.2.2)\n>> foo = Foo.new\n=> #<Foo bar: nil>\n>> foo.valid?\n=> false\n>> foo.errors\n=> #<ActiveRecord::Errors:0x235b270 @errors={\"bar\"=>[\"can't be blank\"]}, @base=#<Foo bar: nil>>\n"
},
{
"answer_id": 320233,
"author": "Laurent Farcy",
"author_id": 40666,
"author_profile": "https://Stackoverflow.com/users/40666",
"pm_score": 1,
"selected": false,
"text": "ActiveRecord::Validations ActiveRecord::Validations::ClassMethods"
},
{
"answer_id": 34354961,
"author": "Artem P",
"author_id": 712308,
"author_profile": "https://Stackoverflow.com/users/712308",
"pm_score": 5,
"selected": false,
"text": "class Model\n include ActiveModel::Model\n\n attr_accessor :var\n\n validates :var, presence: true\nend\n ActiveModel::Model module ActiveModel\n module Model\n def self.included(base)\n base.class_eval do\n extend ActiveModel::Naming\n extend ActiveModel::Translation\n include ActiveModel::Validations\n include ActiveModel::Conversion\n end\n end\n\n def initialize(params={})\n params.each do |attr, value|\n self.public_send(\"#{attr}=\", value)\n end if params\n end\n\n def persisted?\n false\n end\n end\nend\n"
},
{
"answer_id": 44849221,
"author": "xmjw",
"author_id": 693301,
"author_profile": "https://Stackoverflow.com/users/693301",
"pm_score": 3,
"selected": false,
"text": "include ActiveModel::Model"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19693/"
] |
315,887 | <p>How do I mask the address of another site using HTML?</p>
<p>For example, I'd like:</p>
<p><a href="http://www.example.com/source.html" rel="nofollow noreferrer">http://www.example.com/source.html</a></p>
<p>To point to another page:</p>
<p><a href="http://www.example.com/dest.html" rel="nofollow noreferrer">http://www.example.com/dest.html</a></p>
<p>Note that the destination page could be on another domain.</p>
| [
{
"answer_id": 316424,
"author": "Dar",
"author_id": 428842,
"author_profile": "https://Stackoverflow.com/users/428842",
"pm_score": 0,
"selected": false,
"text": "<script>location.href = 'http://www.example.com/dest.htm'</script>\n"
},
{
"answer_id": 325242,
"author": "ONODEVO",
"author_id": 40440,
"author_profile": "https://Stackoverflow.com/users/40440",
"pm_score": 3,
"selected": true,
"text": "<frameset rows=\"100%\">\n <frame src=\"http://www.example.com/dest.html\"/>\n</frameset>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40440/"
] |
315,891 | <p>Can the name and icon of an Eclipse view be programmatically changed? I am referring to the name and icon that appear in the tab for the view - which are specified as XML attributes "name" and "icon" in the <view> element in plugin.xml.</p>
| [
{
"answer_id": 316871,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 3,
"selected": false,
"text": "setPartName(String) setTitleImage(Image) WorkbenchPart EditorPart ViewPart WorkbenchPart protected"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
315,893 | <p>Writing a ton of web applications leveraging JSON/AJAX, I find myself returning tons literal javascript objects (JSON). For example, I may be request all the Cats from GetCats.asp. It would return:</p>
<pre>
[
{ 'id': 0, 'name': 'Persian' },
{ 'id': 1, 'name': 'Calico' },
{ 'id': 2, 'name': 'Tabby' }
]
</pre>
<p>Now, these are all Cat objects with behaviors. However, if I define a Cat object, function Cat() { }, I know of no EFFICIENT way to coax these literal objects into the behaviors of a user defined object. </p>
<p>I can do this by brute force of iterating through them and assigning functions, but it's not going to be pretty. Is there a nice, one line(or few), way of somehow "casting" this behavior onto these literal objects?</p>
| [
{
"answer_id": 315927,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 2,
"selected": false,
"text": "function Cat(c) {\n this.id = c.id;\n this.name = c.name;\n}\nCat.prototype.meow = function() {alert('meow');}\nCat.prototype.displayName= function() {alert(this.name);}\n\nvar cats = [\n { 'id': 0, 'name': 'Persian' },\n { 'id': 1, 'name': 'Calico' },\n { 'id': 2, 'name': 'Tabby' }\n];\n\nfor (i=0,len=cats.length; i<len; i++) {\n cats[i] = new Cat(cats[i]);\n}\n\ncats[0].meow(); // displays \"meow\"\ncats[0].displayName(); // display \"Persian\"\n"
},
{
"answer_id": 315931,
"author": "JSBձոգչ",
"author_id": 8078,
"author_profile": "https://Stackoverflow.com/users/8078",
"pm_score": -1,
"selected": false,
"text": "var list = [\n { 'id': 0, 'name': 'Persian' },\n { 'id': 1, 'name': 'Calico' },\n { 'id': 2, 'name': 'Tabby' }\n];\n\n\nfor (obj in list)\n{\n obj.prototype = new Cat();\n}\n"
},
{
"answer_id": 315983,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 0,
"selected": false,
"text": "var catSource = '[ { \"id\": 0, \"name\": \"Persian\" }, { \"id\": 1, \"name\": \"Calico\" }, { \"id\": 2, \"name\": \"Tabby\" } ]';\n\nfunction Cat(id, name)\n{\n this.id = id;\n this.name = name;\n}\nCat.prototype = \n{\n toString: function()\n {\n return this.name;\n }\n};\n\nfunction doStuff()\n{\n var cats = JSON.parse(catSource, function(key, val)\n {\n // some expression to detect the type of val \n if ( val.id !== undefined && val.name !== undefined )\n return new Cat(val.id, val.name);\n return val;\n });\n alert(cats);\n}\n"
},
{
"answer_id": 316067,
"author": "small_jam",
"author_id": 15752,
"author_profile": "https://Stackoverflow.com/users/15752",
"pm_score": 0,
"selected": false,
"text": "\nvar cats = [\n {id: 15, name: 'Tables', count:45 },\n {id: 23, name: 'Chairs', count:34 }\n];\nvar catsObjects = [];\ncats.each(function(item){\n var newObject = new Cat();\n Object.extend(newObject, item);\n catsObjects.push(newObject);\n});\n"
},
{
"answer_id": 317627,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 0,
"selected": false,
"text": "Object.extend() Object.extend = function ( take, give ) {\n for (var k in give) {\n if (give.hasOwnProperty(k)) {\n take[k] = give[k];\n }\n }\n return take;\n}\n function Cat (c) {\n Object.extend( this, ( c || this.defaults ) );\n}\n\nObject.extend(Cat.prototype, {\n\n meow : function() {\n alert( 'Meow, my name is ' + this.name );\n },\n\n defaults : {\n name : 'I have no name', \n id : null\n }\n\n});\n var cats = [\n { 'id': 0, 'name': 'Persian' },\n { 'id': 1, 'name': 'Calico' },\n { 'id': 2, 'name': 'Tabby' }\n];\n\nfor (i=0,len=cats.length; i<len; i++) {\n cats[i] = new Cat( cats[i] );\n}\n\ncats[0].meow(); // displays \"meow, my name is Persian\"\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
315,911 | <p>Ok, after seeing <a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/2678236#2678236">this post by PJ Hyett</a>, I have decided to skip to the end and go with <a href="http://en.wikipedia.org/wiki/Git_(software)" rel="nofollow noreferrer">Git</a>.</p>
<p>So what I need is a beginner's <strong>practical</strong> guide to Git. "Beginner" being defined as someone who knows how to handle their compiler, understands to some level what a <a href="http://en.wikipedia.org/wiki/Make_%28software%29" rel="nofollow noreferrer">Makefile</a> is, and has touched source control without understanding it very well.</p>
<p>"Practical" being defined as this person doesn't want to get into great detail regarding what Git is doing in the background, and doesn't even care (or know) that it's distributed. Your answers might hint at the possibilities, but try to aim for the beginner that wants to keep a 'main' repository on a 'server' which is backed up and secure, and treat their local repository as merely a 'client' resource.</p>
<p>So:</p>
<h2>Installation/Setup</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#323764">How to install Git</a></li>
<li>How do you set up Git? Try to cover Linux, Windows, Mac, think 'client/server' mindset.
<ul>
<li><a href="https://stackoverflow.com/questions/1482824/setup-git-server-with-msysgit-on-windows">Setup GIT Server with Msysgit on Windows</a></li>
</ul></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#320140">How do you create a new project/repository?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#316062">How do you configure it to ignore files (.obj, .user, etc) that are not really part of the codebase?</a></li>
</ul>
<h2>Working with the code</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/1350157#1350157">How do you get the latest code?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#323906">How do you check out code?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#316055">How do you commit changes?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#319465">How do you see what's uncommitted, or the status of your current codebase?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#323898">How do you destroy unwanted commits?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/1762631#1762631">How do you compare two revisions of a file, or your current file and a previous revision?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/2114836#2114836">How do you see the history of revisions to a file?</a></li>
<li>How do you handle binary files (visio docs, for instance, or compiler environments)?</li>
<li>How do you merge files changed at the "same time"?</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/323898#323898">How do you undo (revert or reset) a commit?</a></li>
</ul>
<h2>Tagging, branching, releases, baselines</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#322967">How do you 'mark' 'tag' or 'release' a particular set of revisions for a particular set of files so you can always pull that one later?</a></li>
<li>How do you pull a particular 'release'?</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/816614#816614">How do you branch?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/816636#816636">How do you merge branches?</a></li>
<li>How do you resolve conflicts and complete the merge?</li>
<li>How do you merge parts of one branch into another branch?</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/5985070#5985070">What is rebasing?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/1590791#1590791">How do I track remote branches?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/1590803#1590803">How can I create a branch on a remote repository?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/5977604#5977604">How do I delete a branch on a remote repository?</a></li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/5968622#5968622">Git workflow examples</a></li>
</ul>
<h2>Other</h2>
<ul>
<li>Describe and link to a good GUI, IDE plugin, etc. that makes Git a non-command line resource, but please list its limitations as well as its good.
<ul>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#323559">msysgit</a> - Cross platform, included with Git</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#323559">gitk</a> - Cross platform history viewer, included with Git</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#323559">gitnub</a> - Mac OS X</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#323559">gitx</a> - Mac OS X history viewer</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#323559">smartgit</a> - Cross platform, commercial, beta</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/322989#322989">tig</a> - console GUI for Linux</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/644129#644129">qgit</a> - GUI for Windows, Linux</li>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide#323559">Git Extensions</a> - package for Windows, includes friendly GUI</li>
</ul></li>
<li>Any other common tasks a beginner should know?
<ul>
<li><a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/319465#319465">Git Status tells you what you just did, what branch you have, and other useful information</a></li>
</ul></li>
<li>How do I work effectively with a subversion repository set as my source control source?</li>
</ul>
<h2>Other Git beginner's references</h2>
<ul>
<li><a href="http://www.sourcemage.org/Git_Guide" rel="nofollow noreferrer">Git guide</a></li>
<li><a href="http://book.git-scm.com/" rel="nofollow noreferrer">Git book</a></li>
<li><a href="http://www-cs-students.stanford.edu/~blynn/gitmagic/" rel="nofollow noreferrer">Git magic</a></li>
<li><a href="http://www.gitcasts.com/" rel="nofollow noreferrer">gitcasts</a></li>
<li><a href="http://github.com/guides/home" rel="nofollow noreferrer">GitHub guides</a></li>
<li><a href="http://www.kernel.org/pub/software/scm/git/docs/gittutorial.html" rel="nofollow noreferrer">Git tutorial</a></li>
<li><a href="http://progit.org/book" rel="nofollow noreferrer">Progit - book by Scott Chacon</a></li>
<li><a href="http://git.or.cz/course/svn.html" rel="nofollow noreferrer" title="Git - SVN Crash Course">Git - SVN Crash Course</a></li>
<li><a href="http://www.newartisans.com/2008/04/git-from-the-bottom-up.html" rel="nofollow noreferrer">Git from the bottom up</a></li>
<li><a href="http://www.gitready.com" rel="nofollow noreferrer">Git ready</a></li>
<li><a href="http://gitref.org/" rel="nofollow noreferrer">gitref.org</a></li>
<li><a href="http://www.ndpsoftware.com/git-cheatsheet.html" rel="nofollow noreferrer">Git visual cheatsheet</a></li>
</ul>
<h2>Delving into Git</h2>
<ul>
<li><a href="http://www.eecs.harvard.edu/~cduan/technical/git/" rel="nofollow noreferrer">Understanding Git conceptually</a></li>
<li><a href="http://eagain.net/articles/git-for-computer-scientists/" rel="nofollow noreferrer">Git for computer scientists</a> (and <a href="http://sitaramc.github.com/gcs/" rel="nofollow noreferrer">another version</a>) </li>
</ul>
<p>I will go through the entries from time to time and 'tidy' them up so they have a consistent look/feel and it's easy to scan the list - feel free to follow a simple "header - brief explanation - list of instructions - gotchas and extra info" template. I'll also link to the entries from the bullet list above so it's easy to find them later.</p>
| [
{
"answer_id": 316039,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 3,
"selected": false,
"text": "git stash"
},
{
"answer_id": 316055,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 5,
"selected": false,
"text": "$ git commit source/main.c\n $ git commit -a # the -a flag pulls in all modified files\n $ git push <remote> <branch> # push new commits to the <branch> on the <remote> repository\n"
},
{
"answer_id": 316062,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 6,
"selected": false,
"text": "$ git status\n[...]\n# Untracked files:\n[...]\n# Documentation/foo.html\n# Documentation/gitignore.html\n# file.o\n# lib.a\n# src/internal.o\n[...]\n$ cat .git/info/exclude\n # ignore objects and archives, anywhere in the tree.\n *.[oa]\n$ cat Documentation/.gitignore\n# ignore generated html files,\n*.html\n# except foo.html which is maintained by hand\n!foo.html\n$ git status\n[...]\n# Untracked files:\n[...]\n# Documentation/foo.html\n[...]\n git add .gitignore \n core.excludesfile = ~/.gitglobalignore\n"
},
{
"answer_id": 319465,
"author": "Peter Burns",
"author_id": 101,
"author_profile": "https://Stackoverflow.com/users/101",
"pm_score": 5,
"selected": false,
"text": "git status svn status git status"
},
{
"answer_id": 320140,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 7,
"selected": false,
"text": ".git checkout git init cd ~/code/project001/\ngit init\n .git git init git init project002\n\n(This is equivalent to: mkdir project002 && cd project002 && git init)\n git status .git $ ls .git\nHEAD config hooks/ objects/\nbranches/ description info/ refs/\n .git cd ~/code/project001/\nrm -rf .git/\n"
},
{
"answer_id": 322967,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 6,
"selected": false,
"text": "git tag git tag -a thetagname\ngit tag -a 0.1\ngit tag -a 2.6.1-rc1 -m 'Released on 01/02/03'\n git tag -l $ git tag -a thetagname # and enter a message, or use -m 'My tag annotation'\n$ git tag -l\nthetagname\n -d $ git tag -d thetagname \nDeleted tag 'thetagname'\n$ git tag\n[no output]\n git tag [tag name] [revision SHA1 hash]\n git tag 1.1.1 81b15a68c6c3e71f72e766931df4e6499990385b\n -a -m -s git tag mytagwithmsg -a -m 'This is a tag, with message'\n -n1 -n245 $ git tag -l -n1\nmytagwithmsg This is a tag, with message\n"
},
{
"answer_id": 322989,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 3,
"selected": false,
"text": "apt-get install tig\n"
},
{
"answer_id": 323559,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 7,
"selected": false,
"text": "git gui git add -i git log git-gui gitk"
},
{
"answer_id": 323748,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 3,
"selected": false,
"text": "git push git pull git push origin master git push git push --tags"
},
{
"answer_id": 323764,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 5,
"selected": false,
"text": "git git gui Start > All Programs > Git git apt-get install git-core\n sudo port install git-core+bash_completion+doc\n fink install git\n brew install git\n yum install git\n .tar.bz .tar.gz build-essential apt cd cd ~/Downloads/git*/ ./configure && make && sudo make install\n /usr/local git /usr/local/bin/git sudo /usr/local/ --prefix ./configure --prefix=/usr/local/gitpath\nmake\nsudo make install\n git /usr/local/bin/gitpath/bin/git $PATH ~/.profile export PATH=\"${PATH}:/usr/local/bin/gitpath/bin/\"\n --prefix=/Users/myusername/bin ~/bin/ $PATH ~/work/track/git /usr/local/git git describe /usr/local/git /usr/local/git/bin PATH MANPATH /usr/local/git/share/man"
},
{
"answer_id": 323898,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 5,
"selected": false,
"text": "# Revert to a previous commit by hash:\ngit-reset --hard <hash>\n # Revert to previous commit:\ngit-reset --hard HEAD^\n"
},
{
"answer_id": 323906,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 3,
"selected": false,
"text": "git clone user@host.com:/dir/to/repo\n"
},
{
"answer_id": 816614,
"author": "Markus Dulghier",
"author_id": 830,
"author_profile": "https://Stackoverflow.com/users/830",
"pm_score": 5,
"selected": false,
"text": "master git branch <branch-name>\n git branch\n git checkout <branch-name>\n git checkout -b <branch-name>\n git branch -d <branch-name>\n git stash\ngit stash branch <branch-name>\n"
},
{
"answer_id": 816636,
"author": "Markus Dulghier",
"author_id": 830,
"author_profile": "https://Stackoverflow.com/users/830",
"pm_score": 4,
"selected": false,
"text": "master release git branch git status git merge master\n master git diff\n"
},
{
"answer_id": 1350157,
"author": "Jeremy Wall",
"author_id": 51233,
"author_profile": "https://Stackoverflow.com/users/51233",
"pm_score": 4,
"selected": false,
"text": "$ git pull <remote> <branch> # fetches the code and merges it into \n # your working directory\n$ git fetch <remote> <branch> # fetches the code but does not merge\n # it into your working directory\n\n$ git pull --tag <remote> <branch> # same as above but fetch tags as well\n$ git fetch --tag <remote> <branch> # you get the idea\n"
},
{
"answer_id": 1590791,
"author": "innaM",
"author_id": 7498,
"author_profile": "https://Stackoverflow.com/users/7498",
"pm_score": 4,
"selected": false,
"text": "# list remote branches\ngit branch -r\n\n# start tracking one remote branch\ngit branch --track some_branch origin/some_branch\n\n# change to the branch locally\ngit checkout some_branch\n\n# make changes and commit them locally\n....\n\n# push your changes to the remote repository:\ngit push\n"
},
{
"answer_id": 1590803,
"author": "innaM",
"author_id": 7498,
"author_profile": "https://Stackoverflow.com/users/7498",
"pm_score": 3,
"selected": false,
"text": "# create a new branch locally\ngit branch name_of_branch\ngit checkout name_of_branch\n# edit/add/remove files \n# ... \n# Commit your changes locally\ngit add fileName\ngit commit -m Message\n# push changes and new branch to remote repository:\ngit push origin name_of_branch:name_of_branch\n"
},
{
"answer_id": 1762631,
"author": "Andrzej Undzillo",
"author_id": 52907,
"author_profile": "https://Stackoverflow.com/users/52907",
"pm_score": 3,
"selected": false,
"text": "git diff $ git diff <commit1> <commit2> <file_name>\n $ git diff --staged <file_name>\n $ git diff <file_name>\n"
},
{
"answer_id": 2114836,
"author": "Pierre-Antoine LaFayette",
"author_id": 135360,
"author_profile": "https://Stackoverflow.com/users/135360",
"pm_score": 4,
"selected": false,
"text": "git log -- filename"
},
{
"answer_id": 2678236,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 5,
"selected": false,
"text": "$ svn checkout svn://foo.googlecode.com/svn/trunk foo # make your changes $ svn commit -m \"my first commit\" $ git clone git@github.com:pjhyett/foo.git # make your changes $ git commit -a -m \"my first commit\" $ git push svn update git pull"
},
{
"answer_id": 2964397,
"author": "Asgeir S. Nilsen",
"author_id": 16023,
"author_profile": "https://Stackoverflow.com/users/16023",
"pm_score": 5,
"selected": false,
"text": "mkdir /your/share/folder/project.git\ncd /your/share/folder/project.git\nnewgrp yourteamgroup # if necessary\ngit init --bare --shared\n cd your/local/workspace/project\ngit remote add origin /your/share/folder/project.git\ngit push origin master\n cd your/local/workspace\ngit clone /your/share/folder/project.git\n authorized_keys --shared cd your/local/workspace/project\ngit remote add origin user@server:/path/to/project.git\ngit push origin master\n PermitEmptyPasswords cd your/local/workspace\ngit clone user@server:/path/to/project.git\n"
},
{
"answer_id": 5977604,
"author": "Felipe Sabino",
"author_id": 429521,
"author_profile": "https://Stackoverflow.com/users/429521",
"pm_score": 3,
"selected": false,
"text": ": git push origin :mybranchname\n origin mybranchname"
},
{
"answer_id": 5985070,
"author": "Felipe Sabino",
"author_id": 429521,
"author_profile": "https://Stackoverflow.com/users/429521",
"pm_score": 3,
"selected": false,
"text": "rebase"
},
{
"answer_id": 9835758,
"author": "torek",
"author_id": 1256452,
"author_profile": "https://Stackoverflow.com/users/1256452",
"pm_score": 2,
"selected": false,
"text": "git rebase --abort filter-branch git gc git commit 7cc5272 git filter-branch fix-nasty-bug git rebase fix-nasty-bug ORIG_HEAD filter-branch git reflog show git log <commit-ID> # ORIG_HEAD after a bad rebase, for instance\ngit show <commit-ID> # or some long SHA1 value you can still see in a window\n git branch recover-my-stuff ORIG_HEAD\n git branch"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] |
315,915 | <p>I have a SUM array formula that has multiple nested IF statements, making it very inefficient. My formula spans over 500 rows, but here is a simple version of it:</p>
<pre><code>{=SUM(IF(IF(A1:A5>A7:A11,A1:A5,A7:A11)-A13:A17>0,
IF(A1:A5>A7:A11,A1:A5,A7:A11)-A13:A17,0))}
</code></pre>
<p>As you can see, the first half of the formula checks where the array is greater than zero, and if they are, it sums those in the second part of the formula.</p>
<p>You will notice that the same IF statement is repeated in there twice, which to me is inefficient, but is the only way I could get the correct answer. </p>
<p>The example data I have is as follows:</p>
<p><a href="http://clients.estatemaster.net/SecureClientSite/Download/TempFiles/example.jpg" rel="nofollow noreferrer">Sample Data in spreadsheet http://clients.estatemaster.net/SecureClientSite/Download/TempFiles/example.jpg</a>
The answer should be 350 in this instance using the formula I mentioned above.</p>
<p>If I tried to put in a MAX statement within the array, therefore removing the test to find where it was greater than zero, so it was like this: </p>
<pre><code>{=SUM(MAX(IF(B2:B6>B8:B12,B2:B6,B8:B12)-B14:B18,0))}
</code></pre>
<p>However, it seems like it only calculates the first row of data in each range, and it gave me the wrong answer of 70.</p>
<p>Does anyone know a away that I can reduce the size of the formula or make it more efficient by not needing to repeat an IF statement in there?</p>
<hr>
<p><strong>UPDATE</strong> </p>
<p>Jimmy</p>
<p>The MAX formula you suggested didnt actually work for all scenarios.</p>
<p>If i changed my sample data in rows 1 to 5 as below (showing that some of the numbers are greater than their respective cells in rows 7 to 11, while some of the numbers are lower)</p>
<p><a href="http://clients.estatemaster.net/SecureClientSite/Download/TempFiles/example2.jpg" rel="nofollow noreferrer">Sample Data in spreadsheet http://clients.estatemaster.net/SecureClientSite/Download/TempFiles/example2.jpg</a></p>
<p>The correct answer im trying to achive is 310, however you suggested MAX formula gives an incorrect answer of 275.</p>
<p>Im guessing the formula needs to be an array function to give the correct answer. </p>
<p>Any other suggestions?</p>
| [
{
"answer_id": 316024,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 2,
"selected": false,
"text": "=MAX( MAX( sum(A1:A5), sum(A7:A11) ) - sum(A13:A17), 0)\n"
},
{
"answer_id": 318478,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 0,
"selected": false,
"text": "{=SUM(IF(A1:A5>A7:A11,A1:A5-A13:A17,A7:A11-A13:A17))}\n {=SUM(IF(IF(A1:A5>A7:A11,A1:A5,A7:A11)>A13:A17,IF(A1:A5>A7:A11,A1:A5,A7:A11)-A13:A17,0))}\n"
},
{
"answer_id": 322577,
"author": "Nathaniel Reinhart",
"author_id": 41122,
"author_profile": "https://Stackoverflow.com/users/41122",
"pm_score": 0,
"selected": false,
"text": "=MAX(SUM(IF(A1:A5>A7:A11, A1:A5, A7:A11))-SUM(A13:A17), 0)\n =SUM((IF(A1:A5>A7:A11,IF(A1:A5>A13:A17,A1:A5,A13:A17),IF(A7:A11>A13:A17,A7:A11,A13:A17))-A13:A17))\n =SUM((((A1:A5>A13:A17)+(A7:A11>A13:A17))>0)*(IF(A1:A5>A7:A11,A1:A5,A7:A11)-A13:A17))\n"
},
{
"answer_id": 334574,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "=MAX(A1,A7)-A13 =IF(C1>0,C1,0) =SUM(D1:D5)"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/315915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40432/"
] |
315,946 | <p>I have a table User which has an identity column <code>UserID</code>, now what is the correct Linq to Entity line of code that would return me the max <code>UserID</code>?</p>
<p>I've tried:</p>
<pre><code>using (MyDBEntities db = new MyDBEntities())
{
var User = db.Users.Last();
// or
var User = db.Users.Max();
return user.UserID;
}
</code></pre>
<p>but <code>Last</code> and <code>Max</code> don't seem to be supported.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 315950,
"author": "Jonas Kongslund",
"author_id": 37548,
"author_profile": "https://Stackoverflow.com/users/37548",
"pm_score": 8,
"selected": true,
"text": "db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();\n"
},
{
"answer_id": 689887,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "int intIdt = db.Users.Max(u => u.UserId);\n int? intIdt = db.Users.Max(u => (int?)u.UserId);\n"
},
{
"answer_id": 3514414,
"author": "Minyie Diaz",
"author_id": 424274,
"author_profile": "https://Stackoverflow.com/users/424274",
"pm_score": 4,
"selected": false,
"text": "Users user = bd.Users.Where(u=> u.UserAge > 21).Max(u => u.UserID); \n"
},
{
"answer_id": 30257987,
"author": "Vihana Kewalramani",
"author_id": 2082715,
"author_profile": "https://Stackoverflow.com/users/2082715",
"pm_score": 4,
"selected": false,
"text": "var max = db.Users.DefaultIfEmpty().Max(r => r == null ? 0 : r.ModelID);\n"
},
{
"answer_id": 41098476,
"author": "Psi-Ed",
"author_id": 1384547,
"author_profile": "https://Stackoverflow.com/users/1384547",
"pm_score": 2,
"selected": false,
"text": "async await User currentUser = await db.Users.OrderByDescending(u => u.UserId).FirstOrDefaultAsync();\n"
},
{
"answer_id": 43331678,
"author": "Michel Lozada",
"author_id": 7703015,
"author_profile": "https://Stackoverflow.com/users/7703015",
"pm_score": -1,
"selected": false,
"text": "public int InsertEntity(Entity factor)\n{\n Db.Entities.Add(factor);\n Db.SaveChanges();\n var id = factor.id;\n return id;\n}\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/315946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32240/"
] |
315,948 | <p>Is there a c++ equivalent of Java's</p>
<pre><code>try {
...
}
catch (Throwable t) {
...
}
</code></pre>
<p>I am trying to debug Java/jni code that calls native windows functions and the virtual machine keeps crashing. The native code appears fine in unit testing and only seems to crash when called through jni. A generic exception catching mechanism would prove extremely useful.</p>
| [
{
"answer_id": 315957,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": false,
"text": "try {\n // ...\n} catch (...) {\n // ...\n}\n ... catch Exception"
},
{
"answer_id": 315960,
"author": "John D. Cook",
"author_id": 25188,
"author_profile": "https://Stackoverflow.com/users/25188",
"pm_score": 4,
"selected": false,
"text": "catch(...)\n"
},
{
"answer_id": 315967,
"author": "Greg D",
"author_id": 6932,
"author_profile": "https://Stackoverflow.com/users/6932",
"pm_score": 9,
"selected": false,
"text": "try{\n // ...\n} catch (...) {\n // ...\n}\n try{\n // ...\n} catch (const std::exception& ex) {\n // ...\n} catch (const std::string& ex) {\n // ...\n} catch (...) {\n // ...\n}\n"
},
{
"answer_id": 315988,
"author": "Paul Sonier",
"author_id": 28053,
"author_profile": "https://Stackoverflow.com/users/28053",
"pm_score": 4,
"selected": false,
"text": "try \n{\n...\n}\ncatch (Exception e)\n{\n...\n}\n"
},
{
"answer_id": 316070,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": false,
"text": "std::null_pointer_exception"
},
{
"answer_id": 1551014,
"author": "Clearer",
"author_id": 187998,
"author_profile": "https://Stackoverflow.com/users/187998",
"pm_score": 6,
"selected": false,
"text": "try { ... } catch( const std::exception &e) { ... }\n e.what() const char* std::exception"
},
{
"answer_id": 18919054,
"author": "Infintyyy",
"author_id": 2580505,
"author_profile": "https://Stackoverflow.com/users/2580505",
"pm_score": 5,
"selected": false,
"text": "try\n{\n //.......\n}\ncatch(...) // <<- catch all\n{\n //.......\n}\n try catch catch"
},
{
"answer_id": 22268788,
"author": "Mellester",
"author_id": 1943599,
"author_profile": "https://Stackoverflow.com/users/1943599",
"pm_score": 5,
"selected": false,
"text": "catch(...) catch(...) throw; try{\n foo = new Foo;\n bar = new Bar;\n}\ncatch(...) // will catch all possible errors thrown. \n{ \n delete foo;\n delete bar;\n throw; // throw the same error again to be handled somewhere else\n}\n catch(...)"
},
{
"answer_id": 24142104,
"author": "bobah",
"author_id": 267482,
"author_profile": "https://Stackoverflow.com/users/267482",
"pm_score": 7,
"selected": false,
"text": "catch(...) #include <iostream>\n\n#include <exception>\n#include <typeinfo>\n#include <stdexcept>\n\nint main()\n{\n try {\n throw ...; // throw something\n }\n catch(...)\n {\n std::exception_ptr p = std::current_exception();\n std::clog <<(p ? p.__cxa_exception_type()->name() : \"null\") << std::endl;\n }\n return 1;\n}\n catch (...)\n{\n std::clog << boost::current_exception_diagnostic_information() << std::endl;\n}\n"
},
{
"answer_id": 29829777,
"author": "Aftershock",
"author_id": 135807,
"author_profile": "https://Stackoverflow.com/users/135807",
"pm_score": 4,
"selected": false,
"text": " SEH exception\n terminate\n unexpected\n pure virtual method call\n invalid parameter\n new operator fault \n SIGABR\n SIGFPE\n SIGILL\n SIGINT\n SIGSEGV\n SIGTERM\n Raised exception\nC++ typed exception\n"
},
{
"answer_id": 60850065,
"author": "muaz",
"author_id": 1149948,
"author_profile": "https://Stackoverflow.com/users/1149948",
"pm_score": 3,
"selected": false,
"text": "try{\n// ...\n} catch (...) {\n// ...\n}\n Access Violation Segmentation Fault"
},
{
"answer_id": 67956416,
"author": "Fedor",
"author_id": 7325599,
"author_profile": "https://Stackoverflow.com/users/7325599",
"pm_score": 1,
"selected": false,
"text": "__try\n{\n // code here may throw or make access violation\n}\n__except( EXCEPTION_EXECUTE_HANDLER )\n{\n // after exception code here, e.g. log the error\n}\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/315948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23120/"
] |
315,963 | <p>I am currently working in C#, and I need to insert a new record into one table, get the new primary key value, and then use that as a foreign key reference in inserting several more records. The Database is MS SQL Server 2003. All help is appreciated!</p>
| [
{
"answer_id": 315974,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 2,
"selected": false,
"text": "SqlCommand cmd = new SqlCommand(@\"\n INSERT INTO T (Name) VALUES(@Name)\n SELECT SCOPE_IDENTITY() As TheId\", conn);\ncmd.AddParameter(\"@Name\", SqlDbType.VarChar, 50).Value = \"Test\";\nint tId = (int)cmd.ExecuteScalar();\n DECLARE @T1 int\n\nINSERT INTO T (Name) VALUES('Test')\n\nSELECT @T1 = SCOPE_IDENTITY() \n\nINSERT INTO T2 (Name, TId) VALUES('Test', @T1)\n"
},
{
"answer_id": 315980,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": true,
"text": "SCOPE_IDENTITY() CREATE PROCEDURE dbo.MyProcedure\n(\n @RowId INT = NULL OUTPUT\n)\nAS\n\nINSERT INTO MyTable\n(\n Column1\n ,Column2\n ,...\n)\nVALUES\n(\n @Param1\n ,@Param2\n ,...\n);\n\nSET @RowId = SCOPE_IDENTITY();\n ; var sql = \"INSERT INTO MyTable (Column1, Column2, ...) VALUES (@P1, @P2, ...);\" +\n \"SELECT SCOPE_IDENTITY();\";\n ExecuteScalar var sql = \"DECLARE @RowId INT;\" + \n \"INSERT INTO MyTable (Column1, Column2, ...) VALUES (@P1, @P2, ...);\" +\n \"SET @RowId = SCOPE_IDENTITY();\" +\n \"INSERT INTO MyOtherTable (Column1, ...) VALUES (@P3, @P4, ...);\";\n SET NOCOUNT ON;"
},
{
"answer_id": 315989,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 2,
"selected": false,
"text": "using(var db = new DataContext()) {\n var user = new User { Name = \"Jhon\" };\n db.Users.InsertOnSubmit(user);\n db.SubmitChanges();\n /* At this point the user.ID field will have the primary key from the database */\n}\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/315963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40459/"
] |
315,964 | <p>I'm relatively familiar with the concepts of DI/IOC containers having worked on projects previously where their use were already in place. However, for this new project, there is no existing framework and I'm having to pick one.</p>
<p>Long story short, there are some scenarios where we'll be configuring several implementations for a given interface. Glancing around the web, it seems like using any of the mainstream frameworks to selectively bind to one of the implementations is quite simple.</p>
<p>There are however contexts where we'll need to run <em>ALL</em> the configured implementations. I've scoured all the IOC tagged posts here and I'm trying to pour through documentation of the major frameworks (so far looking at Unity, Ninject, and Windsor), but docs are often sparse and I've not the time to inspect source for all the packages.</p>
<p>So, are there any mainstream IOC containers that will allow me to bind to all the configured concrete types for one of my services?</p>
| [
{
"answer_id": 316337,
"author": "Jeremy Wiebe",
"author_id": 11807,
"author_profile": "https://Stackoverflow.com/users/11807",
"pm_score": 3,
"selected": true,
"text": "IUnityContainer container = new UnityContainer();\ncontainer.RegisterType<IMyInterface, MyFirstClass>();\ncontainer.RegisterType<IMyInterface, MySecondClass>(\"Two\");\ncontainer.RegisterType<IMyInterface, MyThirdClass>(\"Three\");\n\nvar instances = container.ResolveAll<IMyInterface>();\n\nAssert.AreEqual(2, instances.Count, \"MyFirstClass doesn't get constructed\");\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/315964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2228/"
] |
315,965 | <p>In have a many-to-many linking table and I'm trying to set up two foreign keys on it. I run these two statements:</p>
<pre><code>ALTER TABLE address_list_memberships
ADD CONSTRAINT fk_address_list_memberships_address_id
FOREIGN KEY index_address_id (address_id)
REFERENCES addresses (id);
ALTER TABLE address_list_memberships
ADD CONSTRAINT fk_address_list_memberships_list_id
FOREIGN KEY index_list_id (list_id)
REFERENCES lists (id);
</code></pre>
<p>I would expect that when I run <code>SHOW CREATE TABLE address_list_memberships</code> I'd see this:</p>
<pre><code>[...]
KEY `index_address_id` (`address_id`),
KEY `index_list_id` (`list_id`),
CONSTRAINT `fk_address_list_memberships_list_id` FOREIGN KEY (`list_id`)
REFERENCES `lists` (`id`),
CONSTRAINT `fk_address_list_memberships_address_id` FOREIGN KEY (`address_id`)
REFERENCES `addresses` (`id`)
</code></pre>
<p>But instead I get this:</p>
<pre><code>[...]
KEY `index_list_id` (`list_id`),
CONSTRAINT `fk_address_list_memberships_list_id` FOREIGN KEY (`list_id`)
REFERENCES `lists` (`id`),
CONSTRAINT `fk_address_list_memberships_address_id` FOREIGN KEY (`address_id`)
REFERENCES `addresses` (`id`)
</code></pre>
<p>It looks as though only one index is there. Seems to contradict the <a href="http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html" rel="nofollow noreferrer">MySQL docs</a> which say MySQL automatically creates an index on the referencing column whenever you create a foreign key.</p>
<p>I've noticed this only-one-index thing every time I create two FKs on a table whether I use a GUI tool such as CocoaMySQL or SQLyog, or whether I do it on the command line.</p>
<p>Any illumination of this mystery would be very much appreciated.</p>
| [
{
"answer_id": 316054,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "ALTER mysql> show create table address_list_memberships;\n\nCREATE TABLE `address_list_memberships` (\n `address_id` bigint(20) unsigned NOT NULL,\n `list_id` bigint(20) unsigned NOT NULL,\n KEY `index_address_id` (`address_id`),\n KEY `index_list_id` (`list_id`),\n CONSTRAINT `fk_address_list_memberships_list_id` \n FOREIGN KEY (`list_id`) REFERENCES `lists` (`id`),\n CONSTRAINT `fk_address_list_memberships_address_id` \n FOREIGN KEY (`address_id`) REFERENCES `addresses` (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1\n SELECT * FROM information_schema.key_column_usage \nWHERE table_schema = 'test' AND table_name = 'address_list_memberships'\\G\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/315965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
315,966 | <p>I'm new to using LINQ to Entities (or Entity Framework whatever they're calling it) and I'm writing a lot of code like this:</p>
<pre><code>var item = (from InventoryItem item in db.Inventory
where item.ID == id
select item).First<InventoryItem>();
</code></pre>
<p>and then calling methods on that object like this:</p>
<pre><code>var type = item.ItemTypeReference;
</code></pre>
<p>or</p>
<pre><code>var orders = item.OrderLineItems.Load();
</code></pre>
<p>to retrieve child or related objects.</p>
<p>I haven't profiled the DB or dug too deeply but my guess is that when I call a .Load() or a *Reference property I'm actually making another call to the DB. If this is the case, is there any way to get those objects in my initial LINQ expression?</p>
| [
{
"answer_id": 315985,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 7,
"selected": true,
"text": "var item = from InventoryItem item in\n db.Inventory.Include(\"ItemTypeReference\").Include(\"OrderLineItems\")\n where item.ID == id\n select item;\n using (DataContext db = new DataContext())\n{\n DataLoadOptions options = new DataLoadOptions();\n options.LoadWith<InventoryItem>(ii => ii.ItemTypeReference);\n options.LoadWith<InventoryItem>(ii => ii.OrderLineItems);\n db.LoadOptions = options;\n\n var item = from InventoryItem item in db.Inventory\n where item.ID == id\n select item;\n}\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/315966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
315,968 | <p>I have a Gridview boundfield where i set ReadOnly to true because i don't want user to change its value. However on the objectdatasource control's update method that boundfield became null when i try to use it as parameter in update method. Is there a way to set that value during updating?</p>
| [
{
"answer_id": 316138,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "<asp:TemplateField>\n <InsertItemTemplate>\n <asp:TextBox runat=\"server\" ID=\"itemTextBox\" />\n </InsertItemTemplate>\n <EditItemTemplate>\n <asp:HiddenField runat=\"server\" ID=\"itemHF\" Value='<% Bind(\"Item\") %>' />\n <asp:Label runat=\"server\" ID=\"itemLabel\" Text='<% Eval(\"Item\") %>' />\n </EditItemTemplate>\n <ItemTemplate>\n <asp:Label runat=\"server\" ID=\"itemLabel\" Text='<% Bind(\"Item\") %>' />\n </ItemTemplate>\n</asp:TemplateField>\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/315968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
315,987 | <p>There are a few things that I almost always do when I put a class together in C++.</p>
<p>1) Virtual Destructor
2) Copy constructor and assignment operator (I either implement them in terms of a private function called Copy(), or declare them private and thus explicitly disallow the compiler to auto generate them).</p>
<p>What things do you find are almost always useful?</p>
| [
{
"answer_id": 315999,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "operator string () const;\n friend ostream& operator << (ostream&, const MyClass&);\n"
},
{
"answer_id": 316038,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "-Wall -Werror -Weffc++ -Weffc++ (C++ only)\n Warn about violations of the following style guidelines from Scott\n Meyers’ Effective C++ book:\n\n · Item 11: Define a copy constructor and an assignment operator\n for classes with dynamically allocated memory.\n\n · Item 12: Prefer initialization to assignment in constructors.\n\n · Item 14: Make destructors virtual in base classes.\n\n · Item 15: Have \"operator=\" return a reference to *this.\n\n · Item 23: Don’t try to return a reference when you must return\n an object.\n\n and about violations of the following style guidelines from Scott\n Meyers’ More Effective C++ book:\n\n · Item 6: Distinguish between prefix and postfix forms of incre-\n ment and decrement operators.\n\n · Item 7: Never overload \"&&\", \"││\", or \",\".\n\n If you use this option, you should be aware that the standard\n library headers do not obey all of these guidelines; you can use\n grep -v to filter out those warnings.\n"
},
{
"answer_id": 316040,
"author": "Alan",
"author_id": 37843,
"author_profile": "https://Stackoverflow.com/users/37843",
"pm_score": 1,
"selected": false,
"text": "#ifndef __SOMEDEFINE__\n#define __SOMEDEFINE__\n\n#endif\n #pragma warning(disable: 4786)\n #include <inttypes.h>\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/315987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3886/"
] |
315,991 | <p>I need a command to replace the hosts file on my machine. Seems pretty straight forward but I cannot get the command to work with xcopy. Any obvious flaws in the command?</p>
<p>luaexec -w -f "XCOPY" "%ScriptPath%/ModifiedHosts/vista/hosts"
"%windir%/system32/drivers/etc/hosts" /H</p>
<p>The /R flag does not seem to help and the error I get is "Error: ShellExecuteEx failed 0x2" if I remove all quotes but the beginning and end quotes</p>
| [
{
"answer_id": 316004,
"author": "FerranB",
"author_id": 40441,
"author_profile": "https://Stackoverflow.com/users/40441",
"pm_score": 2,
"selected": true,
"text": "luaexec -w -f \"XCOPY %ScriptPath%/ModifiedHosts/vista/hosts %windir%/system32/drivers/etc/hosts\" /H\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/315991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15059/"
] |
316,007 | <p>I'm wondering if there is a better/inbuilt way, other than using a byte buffer and looping, to read from one stream and write it to another (in .NET). Generally this is done to apply a transform to a stream and move it on.</p>
<p>In this instance, what I am loading a file, putting it through a deflate stream and writing it out to a file (Error handling removed for simplicity):</p>
<pre><code>byte[] buffer = new byte[10000000];
using (FileStream fsin = new FileStream(filename, FileMode.Open))
{
using (FileStream fsout = new FileStream(zipfilename, FileMode.CreateNew))
{
using (DeflateStream ds = new DeflateStream(fsout, CompressionMode.Compress))
{
int read = 0;
do
{
read = fsin.Read(buffer, 0, buffer.Length);
ds.Write(buffer, 0, read);
}
while (read > 0);
}
}
}
buffer = null;
</code></pre>
<p><strong>Edit:</strong></p>
<p>.NET 4.0 now has a Stream.CopyTo function, Hallelujah</p>
| [
{
"answer_id": 316031,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": true,
"text": "CopyTo public static void CopyTo(this Stream source, Stream destination)\n{\n var buffer = new byte[0x1000];\n int bytesInBuffer;\n while ((bytesInBuffer = source.Read(buffer, 0, buffer.Length)) > 0)\n {\n destination.Write(buffer, 0, bytesInBuffer);\n }\n}\n fsin.CopyTo(ds);\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10784/"
] |
316,008 | <p>I'm trying to import some data from Excel to SQL Server, I have a TEXT column with some numbers in it, some of the numbers go over just fine, and some turn into scientific form.</p>
<p>Column in Excel is "text" type, column in the target sql table is varchar(255)</p>
<p>Here are some examples: </p>
<p>Excel [text] -> SQL Server [varchar(255)]<br>
0313852230 -> 0313852230<br>
1024869004 -> 1024869004<br>
1022868890 -> 1.02287e+009<br>
1022868899 -> 1.02287e+009<br>
1022868907 -> 1022868907<br>
1030869319 -> 1030869319<br>
1106869726 -> 1106869726<br>
SomeText -> SomeText </p>
<p>Please help!</p>
<p><strong>SOLUTION: Formatting the column as [Number] with 10 leading zeros worked for me, since all my numbers are 10-digit numbers</strong></p>
| [
{
"answer_id": 316031,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": true,
"text": "CopyTo public static void CopyTo(this Stream source, Stream destination)\n{\n var buffer = new byte[0x1000];\n int bytesInBuffer;\n while ((bytesInBuffer = source.Read(buffer, 0, buffer.Length)) > 0)\n {\n destination.Write(buffer, 0, bytesInBuffer);\n }\n}\n fsin.CopyTo(ds);\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] |
316,009 | <p>I'm working on something that requires traversing through the file system and for any given path, I need to know how 'deep' I am in the folder structure. Here's what I'm currently using:</p>
<pre><code>int folderDepth = 0;
string tmpPath = startPath;
while (Directory.GetParent(tmpPath) != null)
{
folderDepth++;
tmpPath = Directory.GetParent(tmpPath).FullName;
}
return folderDepth;
</code></pre>
<p>This works but I suspect there's a better/faster way? Much obliged for any feedback.</p>
| [
{
"answer_id": 316016,
"author": "Paul Sonier",
"author_id": 28053,
"author_profile": "https://Stackoverflow.com/users/28053",
"pm_score": 5,
"selected": true,
"text": "Directory.GetFullPath().Split(\"\\\\\").Length;\n"
},
{
"answer_id": 316330,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 2,
"selected": false,
"text": "Path int depth = 0;\ndo\n{\n path = Path.GetDirectoryName(path);\n Console.WriteLine(path);\n ++depth;\n} while (!string.IsNullOrEmpty(path));\n\nConsole.WriteLine(\"Depth = \" + depth.ToString());\n"
},
{
"answer_id": 316452,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "public static int FolderDepth(string path)\n{\n if (string.IsNullOrEmpty(path))\n return 0;\n DirectoryInfo parent = Directory.GetParent(path);\n if (parent == null)\n return 1;\n return FolderDepth(parent.FullName) + 1;\n}\n public static int FolderDepth(string path)\n{\n if (string.IsNullOrEmpty(path))\n return 0;\n return FolderDepth(new DirectoryInfo(path));\n}\n\npublic static int FolderDepth(DirectoryInfo directory)\n{\n if (directory == null)\n return 0;\n return FolderDepth(directory.Parent) + 1;\n}\n"
},
{
"answer_id": 33675131,
"author": "GôTô",
"author_id": 456167,
"author_profile": "https://Stackoverflow.com/users/456167",
"pm_score": 3,
"selected": false,
"text": " Path.GetFullPath(tmpPath).Split(Path.DirectorySeparatorChar).Length;\n"
},
{
"answer_id": 51772249,
"author": "HappyDude",
"author_id": 5899555,
"author_profile": "https://Stackoverflow.com/users/5899555",
"pm_score": 0,
"selected": false,
"text": "string pathString = \"C:\\\\temp\\\\\"\nvar rootFolderDepth = pathString.Split(Path.DirectorySeparatorChar).Where(i => i.Length > 0).Count();\n"
},
{
"answer_id": 60928288,
"author": "Ioan G",
"author_id": 13151873,
"author_profile": "https://Stackoverflow.com/users/13151873",
"pm_score": -1,
"selected": false,
"text": " double linqCountTime = 0;\n double stringSplitTime = 0;\n double stringSplitRemEmptyTime = 0;\n int linqCountFind = 0;\n int stringSplitFind = 0;\n int stringSplitRemEmptyFind = 0;\n\n string pth = @\"D:\\dir 1\\complicated dir 2\\more complicated dir 3\\much more complicated dir 4\\only dir\\another complicated dir\\dummy\\dummy.dummy.45682\\\";\n\n //Heat Up\n DateTime dt = DateTime.Now;\n for (int i = 0; i < 10000; i++)\n {\n linqCountFind = pth.Count(c => c == '\\\\');\n }\n _= DateTime.Now.Subtract(dt).TotalMilliseconds;\n dt = DateTime.Now;\n for (int i = 0; i < 10000; i++)\n {\n stringSplitFind = pth.Split('\\\\').Length;\n }\n _ = DateTime.Now.Subtract(dt).TotalMilliseconds;\n dt = DateTime.Now;\n for (int i = 0; i < 10000; i++)\n {\n stringSplitRemEmptyFind = pth.Split(new char[] { '\\\\' }, StringSplitOptions.RemoveEmptyEntries).Length;\n }\n _ = DateTime.Now.Subtract(dt).TotalMilliseconds;\n dt = DateTime.Now;\n\n //Testing\n dt = DateTime.Now;\n for (int i = 0; i < 1000000; i++)\n {\n linqCountFind = pth.Count(c => c == '\\\\');\n }\n linqCountTime = DateTime.Now.Subtract(dt).TotalMilliseconds; //linq.Count: 1390 ms\n\n dt = DateTime.Now;\n for (int i = 0; i < 1000000; i++)\n {\n stringSplitFind = pth.Split('\\\\').Length-1;\n }\n stringSplitTime = DateTime.Now.Subtract(dt).TotalMilliseconds; //string.Split: 715 ms\n\n dt = DateTime.Now;\n for (int i = 0; i < 1000000; i++)\n {\n stringSplitRemEmptyFind = pth.Split(new char[] { '\\\\' }, StringSplitOptions.RemoveEmptyEntries).Length;\n }\n stringSplitRemEmptyTime = DateTime.Now.Subtract(dt).TotalMilliseconds; // string.Split with RemoveEmptyEntries option: 720 ms\n\n string linqCount = \"linqCount - Find: \"+ linqCountFind + \"; Time: \"+ linqCountTime.ToString(\"F0\") +\" ms\"+ Environment.NewLine;\n string stringSplit = \"stringSplit - Find: \" + stringSplitFind + \"; Time: \" + stringSplitTime.ToString(\"F0\") + \" ms\" + Environment.NewLine;\n string stringSplitRemEmpty = \"stringSplitRemEmpty - Find: \" + stringSplitRemEmptyFind + \"; Time: \" + stringSplitRemEmptyTime.ToString(\"F0\") + \" ms\" + Environment.NewLine;\n\n MessageBox.Show(linqCount + stringSplit + stringSplitRemEmpty);\n\n // Results:\n // linqCount - Find: 9; Time: 1390 ms\n // stringSplit - Find: 9; Time: 715 ms\n // stringSplitRemEmpty - Find: 9; Time: 720 ms\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1354/"
] |
316,017 | <p>Here's the code I have in the html file to "include" the file "vmenu.php"</p>
<pre><code> <div id="apDivVistaMenus">
<?php
include 'vmenu.php';
?>
<!-- Begin Vista-Buttons.com -->
<!-- End Vista-Buttons.com -->
</div>
</code></pre>
<p>The menus used to be between the comments below the php include request. But I save that code into the vmenu.php file, which looks like this:</p>
<pre><code><link href="../menu-files/peaceland_styles_zkkus.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript"> var vbImgPath="../menu-files/"</script>
<script type="text/javascript" src="../menu-files/sczkkus.js"></script>
<noscript><a href="http://vista-buttons.com">Xp Style Menu by Vista-Buttons.com v2.73</a></noscript>
</code></pre>
<p>What's the problem?
They are both in the same directory.
If I put the code from the vmenu.php back into the html file, it will load fine.</p>
<p>Thank you!</p>
| [
{
"answer_id": 1738861,
"author": "mattbasta",
"author_id": 205229,
"author_profile": "https://Stackoverflow.com/users/205229",
"pm_score": 0,
"selected": false,
"text": "<div id=\"apDivVistaMenus\">\n<!-- Begin Vista-Buttons.com -->\n<?php include 'vmenu.php'; ?>\n<!-- End Vista-Buttons.com -->\n</div>\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40091/"
] |
316,057 | <p><strong>Duplicate of:</strong> <a href="https://stackoverflow.com/questions/203113/use-javascript-to-inject-script-references-as-needed">Use javascript to inject script references as needed?</a></p>
<p>Javascript doesn't have any directive to "include" or "import" another js file.
This means that if <code>script1.js</code> uses functions/objects defined in <code>script2.js</code>, then every html page that includes script1.js must include script2.js before it.</p>
<p>This shouldn't be a big problem if you only have 2 js files in like 10 html pages. I mean, it's manageable then!</p>
<p>But say suddenly you change <code>script1.js</code> and improve it by using functions/objects defined in a new file, <code>script3.js</code> <br>
The problem is, you can't just tell <code>script1.js</code> to include <code>script3.js</code>, instead, you have to remember every html file that included <code>script1.js</code> and update it to include <code>script3.js</code> as well!</p>
<p>This seems like rather stupid way of organizing code.</p>
<p>Are there recommended strategies or practices to deal with this issue?</p>
<p>Would it be acceptable to have a gigantic js file that holds all the functionality that you use across the website?</p>
| [
{
"answer_id": 316077,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": " var Scriptaculous = {\n Version: '1.8.2',\n require: function(libraryName) {\n // inserting via DOM fails in Safari 2.0, so brute force approach\n document.write('<script type=\"text/javascript\" src=\"'+libraryName+'\"><\\/script>');\n },\n ...\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35364/"
] |
316,078 | <p>I saw the following interesting usage of tar in a co-worker's Bash scripts:</p>
<pre><code>`tar cf - * | (cd <dest> ; tar xf - )`
</code></pre>
<p>Apparently it works much like rsync -av does, but faster. The question arises, how?</p>
<p>-m</p>
<hr>
<p><strong>EDIT</strong>: Can anyone explain <em>why</em> should this solution be preferable over the following? </p>
<pre><code>cp -rfp * dest
</code></pre>
<p>Is the former faster?</p>
| [
{
"answer_id": 316083,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": false,
"text": "f"
},
{
"answer_id": 316085,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 1,
"selected": false,
"text": "tar cf - * | (cd <dest> ; tar xf - )\n <dest>"
},
{
"answer_id": 316093,
"author": "Sparr",
"author_id": 13675,
"author_profile": "https://Stackoverflow.com/users/13675",
"pm_score": 0,
"selected": false,
"text": "tar cf - *\n |\n (cd <dest> ; tar xf - )\n"
},
{
"answer_id": 316346,
"author": "Alastair",
"author_id": 31038,
"author_profile": "https://Stackoverflow.com/users/31038",
"pm_score": 4,
"selected": true,
"text": "alastair box:~/hack/cptest [1134]% mkdir src\nalastair box:~/hack/cptest [1135]% cd src\nalastair box:~/hack/cptest/src [1136]% touch foo\nalastair box:~/hack/cptest/src [1137]% ln -s foo foo-s\nalastair box:~/hack/cptest/src [1138]% ln foo foo-h\nalastair box:~/hack/cptest/src [1139]% ls -a\ntotal 0\n-rw-r--r-- 2 alastair alastair 0 Nov 25 14:59 foo\n-rw-r--r-- 2 alastair alastair 0 Nov 25 14:59 foo-h\nlrwxrwxrwx 1 alastair alastair 3 Nov 25 14:59 foo-s -> foo\nalastair box:~/hack/cptest/src [1142]% mkdir ../cpdest\nalastair box:~/hack/cptest/src [1143]% cp -rfp * ../cpdest\nalastair box:~/hack/cptest/src [1144]% mkdir ../tardest\nalastair box:~/hack/cptest/src [1145]% tar cf - * | (cd ../tardest ; tar xf - )\nalastair box:~/hack/cptest/src [1146]% cd ..\nalastair box:~/hack/cptest [1147]% ls -l cpdest\ntotal 0\n-rw-r--r-- 1 alastair alastair 0 Nov 25 14:59 foo\n-rw-r--r-- 1 alastair alastair 0 Nov 25 14:59 foo-h\nlrwxrwxrwx 1 alastair alastair 3 Nov 25 15:00 foo-s -> foo\nalastair box:~/hack/cptest [1148]% ls -l tardest\ntotal 0\n-rw-r--r-- 2 alastair alastair 0 Nov 25 14:59 foo\n-rw-r--r-- 2 alastair alastair 0 Nov 25 14:59 foo-h\nlrwxrwxrwx 1 alastair alastair 3 Nov 25 15:00 foo-s -> foo\n cp tar alastair box:~/hack/cptest [1149]% ls -i cpdest\n24690722 foo 24690723 foo-h 24690724 foo-s\nalastair box:~/hack/cptest [1150]% ls -i tardest\n24690801 foo 24690801 foo-h 24690802 foo-s\n"
},
{
"answer_id": 442665,
"author": "Teddy",
"author_id": 54435,
"author_profile": "https://Stackoverflow.com/users/54435",
"pm_score": 0,
"selected": false,
"text": "cp cp --archive"
},
{
"answer_id": 584353,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "cp cp tar tar cp cp tar cp"
},
{
"answer_id": 1364221,
"author": "Singletoned",
"author_id": 46715,
"author_profile": "https://Stackoverflow.com/users/46715",
"pm_score": 1,
"selected": false,
"text": "dir/subdir/file1\n dir/subdir/file2\n dir/subdir/file1\n dir/subdir/file1\ndir/subdir/file2\n"
},
{
"answer_id": 4981749,
"author": "William Martin",
"author_id": 614694,
"author_profile": "https://Stackoverflow.com/users/614694",
"pm_score": 2,
"selected": false,
"text": "tar cf - * | (cd <dest> && tar xvBf - )"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31295/"
] |
316,099 | <p>I have a site that connects using cURL (latest version) to a secure gateway for payment.</p>
<p>The problem is cURL always returns 0 length content. I get headers only. And only when I set cURL to return headers. I have the following flags in place.</p>
<pre><code>curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_URL, $gatewayURI);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
</code></pre>
<p>The header returned is</p>
<pre><code>HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Tue, 25 Nov 2008 01:08:34 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Content-Length: 0
Content-Type: text/html
Set-Cookie: ASPSESSIONIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; path=/
Cache-control: private
</code></pre>
<p>I have also tried cURL'ing different sites and they return content fine. I think the problem might have something to do with the https connection.</p>
<p>I have spoken with the company and they are unhelpful.</p>
<p>Has anyone else experienced this error and know a work around? Should I ditch cURL and try and use <code>fsockopen()</code> ?</p>
<p>Thank you. :)</p>
| [
{
"answer_id": 316185,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": -1,
"selected": false,
"text": "curl_setopt($ch, CURLOPT_POST, 1);\ncurl_setopt($ch, CURLOPT_POSTFIELDS, $data);\n"
},
{
"answer_id": 316732,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 7,
"selected": false,
"text": "curl_setopt ($curl_ch, CURLOPT_CAINFO, dirname(__FILE__).\"/cacert.pem\"); \n curl.cainfo=/etc/ssl/certs/ca-certificates.crt composer require paragonie/certainty:dev-master"
},
{
"answer_id": 823832,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "file_get_contents stream_create_context $postdataStr = http_build_query($postdataArr);\n\n$context_options = array (\n 'http' => array ( <blink> // this will allways be http!!!</blink>\n 'method' => 'POST',\n 'header'=> \"Content-type: application/x-www-form-urlencoded\\r\\n\"\n . \"Content-Length: \" . strlen($postdataArr) . \"\\r\\n\"\n . \"Cookie: \" . $cookies.\"\\r\\n\"\n 'content' => $postdataStr\n )\n );\n\n$context = stream_context_create($context_options);\n$HTTPSReq = file_get_contents('https://www.example.com/', false, $context);\n"
},
{
"answer_id": 3304467,
"author": "mixdev",
"author_id": 6109,
"author_profile": "https://Stackoverflow.com/users/6109",
"pm_score": 5,
"selected": false,
"text": "curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); \ncurl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); \n"
},
{
"answer_id": 12981784,
"author": "Cobra_Fast",
"author_id": 522479,
"author_profile": "https://Stackoverflow.com/users/522479",
"pm_score": 3,
"selected": false,
"text": "curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);\n"
},
{
"answer_id": 17055807,
"author": "user203319",
"author_id": 203319,
"author_profile": "https://Stackoverflow.com/users/203319",
"pm_score": 2,
"selected": false,
"text": "curl_setopt($ch, CURLOPT_SSLVERSION, 3);\n"
},
{
"answer_id": 46138906,
"author": "Heitor",
"author_id": 3063226,
"author_profile": "https://Stackoverflow.com/users/3063226",
"pm_score": 0,
"selected": false,
"text": "padlock more information Details Certificate hierarchy curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);\ncurl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); \ncurl_setopt($ch, CURLOPT_CAINFO, [PATH_TO_CRT_FILE]);\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
316,131 | <p>Given a linux kernel oops, how do you go about diagnosing the problem? In the output I can see a stack trace which seems to give some clues. Are there any tools that would help find the problem? What basic procedures do you follow to track it down?</p>
<pre><code>
Unable to handle kernel paging request for data at address 0x33343a31
Faulting instruction address: 0xc50659ec
Oops: Kernel access of bad area, sig: 11 [#1]
tpsslr3
Modules linked in: datalog(P) manet(P) vnet wlan_wep wlan_scan_sta ath_rate_sample ath_pci wlan ath_hal(P)
NIP: c50659ec LR: c5065f04 CTR: c00192e8
REGS: c2aff920 TRAP: 0300 Tainted: P (2.6.25.16-dirty)
MSR: 00009032 CR: 22082444 XER: 20000000
DAR: 33343a31, DSISR: 20000000
TASK = c2e6e3f0[1486] 'datalogd' THREAD: c2afe000
GPR00: c5065f04 c2aff9d0 c2e6e3f0 00000000 00000001 00000001 00000000 0000b3f9
GPR08: 3a33340a c5069624 c5068d14 33343a31 82082482 1001f2b4 c1228000 c1230000
GPR16: c60f0000 000004a8 c59abbe6 0000002f c1228360 c340d6b0 c5070000 00000001
GPR24: c2aff9e0 c5070000 00000000 00000000 00000003 c2cc2780 c2affae8 0000000f
NIP [c50659ec] mesh_packet_in+0x3d8/0xdac [manet]
LR [c5065f04] mesh_packet_in+0x8f0/0xdac [manet]
Call Trace:
[c2aff9d0] [c5065f04] mesh_packet_in+0x8f0/0xdac [manet] (unreliable)
[c2affad0] [c5061ff8] IF_netif_rx+0xa0/0xb0 [manet]
[c2affae0] [c01925e4] netif_receive_skb+0x34/0x3c4
[c2affb10] [c60b5f74] netif_receive_skb_debug+0x2c/0x3c [wlan]
[c2affb20] [c60bc7a4] ieee80211_deliver_data+0x1b4/0x380 [wlan]
[c2affb60] [c60bd420] ieee80211_input+0xab0/0x1bec [wlan]
[c2affbf0] [c6105b04] ath_rx_poll+0x884/0xab8 [ath_pci]
[c2affc90] [c018ec20] net_rx_action+0xd8/0x1ac
[c2affcb0] [c00260b4] __do_softirq+0x7c/0xf4
[c2affce0] [c0005754] do_softirq+0x58/0x5c
[c2affcf0] [c0025eb4] irq_exit+0x48/0x58
[c2affd00] [c000627c] do_IRQ+0xa4/0xc4
[c2affd10] [c00106f8] ret_from_except+0x0/0x14
--- Exception: 501 at __delay+0x78/0x98
LR = cfi_amdstd_write_buffers+0x618/0x7ac
[c2affdd0] [c0163670] cfi_amdstd_write_buffers+0x504/0x7ac (unreliable)
[c2affe50] [c015a2d0] concat_write+0xe4/0x140
[c2affe80] [c0158ff4] part_write+0xd0/0xf0
[c2affe90] [c015bdf0] mtd_write+0x170/0x2a8
[c2affef0] [c0073898] vfs_write+0xcc/0x16c
[c2afff10] [c0073f2c] sys_write+0x4c/0x90
[c2afff40] [c0010060] ret_from_syscall+0x0/0x38
--- Exception: c01 at 0xfd98a50
LR = 0x10003840
Instruction dump:
419d02a0 98010009 800100a4 2f800003 419e0508 2f170000 419a0098 3d20c507
a0e1002e 81699624 39299624 7f8b4800 419e007c a0610016 7d264b78
Kernel panic - not syncing: Fatal exception in interrupt
Rebooting in 1 seconds..
</code></pre>
| [
{
"answer_id": 316504,
"author": "ctuffli",
"author_id": 26683,
"author_profile": "https://Stackoverflow.com/users/26683",
"pm_score": 5,
"selected": true,
"text": "do_IRQ ath_rx_poll ieee80211_input netif_receive_skb gdb /usr/src/linux/vmlinux\n mesh_packet_in() mesh_packet_in() (gdb) info line 0xc50659ec\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20889/"
] |
316,147 | <p>How do I hide the <strong>prev/today/next</strong> navigation in jQuery DatePicker?</p>
<p>I'm happy with just the Month and Year drop down boxes.</p>
<p>Also how do I disable the animations?</p>
<p><a href="https://stackoverflow.com/questions/316147/how-do-i-hide-the-nexttodayprevious-navigation-in-jquery-datepicker-and-turn-of#316153">@tvanfosson</a> - I already tried <code>hideIfNoPrevNext</code> but that only works if you don't have a date range that spans two months. </p>
<p>The duration option did the trick at turning off the animations though. </p>
<p>Cheers.</p>
| [
{
"answer_id": 316153,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": " $('#cal').datepicker( { hideIfNoPrevNext: true, duration: '' } );\n"
},
{
"answer_id": 1037741,
"author": "ukko",
"author_id": 75307,
"author_profile": "https://Stackoverflow.com/users/75307",
"pm_score": 3,
"selected": false,
"text": "$(\"div.ui-datepicker-header a.ui-datepicker-prev,div.ui-datepicker-header a.ui-datepicker-next\").hide();\n"
},
{
"answer_id": 15255932,
"author": "Chris",
"author_id": 2141400,
"author_profile": "https://Stackoverflow.com/users/2141400",
"pm_score": 2,
"selected": false,
"text": "div.ui-datepicker-header \na.ui-datepicker-prev,div.ui-datepicker-header \na.ui-datepicker-next\n{\n display: none; \n}\n"
},
{
"answer_id": 40582095,
"author": "ankit jain",
"author_id": 5945909,
"author_profile": "https://Stackoverflow.com/users/5945909",
"pm_score": -1,
"selected": false,
"text": "$(\"#cal\").datepicker({\nstepMonths: 0\n)};\n"
},
{
"answer_id": 48111867,
"author": "Jerry Joe Desamito",
"author_id": 5211586,
"author_profile": "https://Stackoverflow.com/users/5211586",
"pm_score": 1,
"selected": false,
"text": ".focus(function () {\n $(\".ui-datepicker-next\").hide();\n $(\".ui-datepicker-prev\").hide();\n});\n $('#TextDateId').datepicker({\n dateFormat: \"MM dd yyyy\",\n changeMonth: true,\n }).focus(function () {\n $(\".ui-datepicker-next\").hide();\n $(\".ui-datepicker-prev\").hide();\n });\n"
},
{
"answer_id": 61494343,
"author": "Diggetydog",
"author_id": 3333829,
"author_profile": "https://Stackoverflow.com/users/3333829",
"pm_score": 0,
"selected": false,
"text": ".datepicker().focus(function () {\n $(\".ui-datepicker-next\").hide();\n $(\".ui-datepicker-prev\").hide();\n});\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
] |
316,157 | <p>I have an nmake-based project which in turn calls the asp compiler, which can throw an error, which nmake seems to recognize:</p>
<pre><code>NMAKE : fatal error U1077: 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe' : return code '0x1'
</code></pre>
<p>However, when I call nmake from within a batch file, the environment variable %ERRORLEVEL% remains set at zero:</p>
<pre><code>nmake /NOLOGO
echo BUILD RETURNING: %ERRORLEVEL%
</code></pre>
<p>If I control-c the nmake task, I do end up getting a non-zero ERRORLEVEL (it's set to 2) so my assumption is that I'm able to catch errors okay, but nmake isn't bubbling up the non-zero exit code from it's task. Or, at least, I'm mis-trapping it. Any help would be appreciated.</p>
| [
{
"answer_id": 1327920,
"author": "Jay",
"author_id": 151152,
"author_profile": "https://Stackoverflow.com/users/151152",
"pm_score": 1,
"selected": false,
"text": "@echo off\nrem Args[x]: nmake arguments\necho.>> %~n0.log\necho %date% %time%>> %~n0.log\necho nmake /NOLOGO %*>> %~n0.log\nnmake /NOLOGO %*\necho %errorlevel%>> %~n0.log\n"
},
{
"answer_id": 1765978,
"author": "Jeremy E",
"author_id": 117527,
"author_profile": "https://Stackoverflow.com/users/117527",
"pm_score": 0,
"selected": false,
"text": "exit /b %errorlevel%"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26624/"
] |
316,166 | <p>VBScript doesn't appear to have a way to include a common file of functions.</p>
<p>Is there a way to achieve this?</p>
| [
{
"answer_id": 316169,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 6,
"selected": false,
"text": "sub includeFile (fSpec)\n dim fileSys, file, fileData\n set fileSys = createObject (\"Scripting.FileSystemObject\")\n set file = fileSys.openTextFile (fSpec)\n fileData = file.readAll ()\n file.close\n executeGlobal fileData\n set file = nothing\n set fileSys = nothing\nend sub\n includeFile \"commonapi.vbi\"\nincludeFile \"dbcalls.vbi\"\n includeFile Sub includeFile(fSpec)\n With CreateObject(\"Scripting.FileSystemObject\")\n executeGlobal .openTextFile(fSpec).readAll()\n End With\nEnd Sub\n Sub includeFile(fSpec)\n executeGlobal CreateObject(\"Scripting.FileSystemObject\").openTextFile(fSpec).readAll()\nEnd Sub\n"
},
{
"answer_id": 316192,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<!-- #include virtual=\"/PathTo/MyFile.vbs\" -->\n"
},
{
"answer_id": 316491,
"author": "Richard B",
"author_id": 30214,
"author_profile": "https://Stackoverflow.com/users/30214",
"pm_score": 7,
"selected": true,
"text": "<job id=\"IncludeExample\">\n <script language=\"JavaScript\" src=\"sprintf.js\"/>\n <script language=\"VBScript\" src=\"logging.vbs\"/>\n <script language=\"VBScript\" src=\"iis-queryScriptMaps.vbs\"/>\n</job>\n cscript.exe iis-scriptmaps.wsf\n"
},
{
"answer_id": 319816,
"author": "Mike Henry",
"author_id": 14934,
"author_profile": "https://Stackoverflow.com/users/14934",
"pm_score": 0,
"selected": false,
"text": "script <script language=\"VBScript\" runat=\"server\" src=\"include.asp\"></script>\n"
},
{
"answer_id": 2322285,
"author": "LKlein",
"author_id": 279905,
"author_profile": "https://Stackoverflow.com/users/279905",
"pm_score": 0,
"selected": false,
"text": "<script language=\"VBScript\" src=\"ADOVBS.INC\"/>\n <% %>\n"
},
{
"answer_id": 12374208,
"author": "Etalon",
"author_id": 1663505,
"author_profile": "https://Stackoverflow.com/users/1663505",
"pm_score": 4,
"selected": false,
"text": "<job id=\"MainProg\">\n <script language=\"VBScript\" src=\"Constants.vbs\"/>\n <script language=\"VBScript\" src=\"FileFunctions.vbs\"/>\n <script language=\"VBScript\" src=\"SendMail.vbs\"/>\n <script language=\"VBScript\" src=\"LoggingFunctions.vbs\"/>\n <script language=\"VBScript\" src=\"MainProgram.vbs\"/> \n <script language=\"VBScript\">\n ' Here we call the main program\n MainProgram()\n </script>\n</job>\n Constants.vbs MainProgram.vbs sub MainProgram() sub MainProgram()\n ' Local variables\n Dim strMessage, strSendTo, strSubject\n ' OpenFile is a function from FileFunctions.vbs\n strMessage = OpenFile(\"C:\\Msg\\message.html\")\n strSendTo = \"email.address@yourdomain.com\"\n strSubject = \"Daily report - \" & date\n ' SendMessage is a function from SendMail.vbs\n ' cFrom and cServer are constants from Constants.vbs\n SendMessage(cFrom, strSendTo, strSubject, strMessage, cServer)\n ' Logger is a function from LoggingFunctions.vbs\n Logger(\"Daily report sent - \" & now())\nend sub\n"
},
{
"answer_id": 43957897,
"author": "BuvinJ",
"author_id": 3220983,
"author_profile": "https://Stackoverflow.com/users/3220983",
"pm_score": 3,
"selected": false,
"text": "Sub include( relativeFilePath ) \n Set fso = CreateObject(\"Scripting.FileSystemObject\")\n thisFolder = fso.GetParentFolderName( WScript.ScriptFullName ) \n absFilePath = fso.BuildPath( thisFolder, relativeFilePath )\n executeGlobal fso.openTextFile( absFilePath ).readAll()\nEnd Sub\n . .. include \"..\\Lib\\StringUtilities.vbs\"\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14860/"
] |
316,172 | <p>I'm trying to increase the timeout on all sessions. The site is hosted with Godaddy, and it is written in Flash (client side of course) and asp.net on the backend. I've added this to my web.config, </p>
<pre><code><sessionState timeout="720">
</sessionState>
</code></pre>
<p>Is that really all that I need to do? I'd prefer to not let sessions expire ever, but I'm sure that the server needs to reclaim that memory at some point...I'm not storing anything in the session, really, just using it to track users' progress through the site, and if a user is logged in or not.</p>
<p>Thanks for any pointers...all the documentation seems deceptively simple, and it kind of makes me nervous...</p>
| [
{
"answer_id": 316392,
"author": "Steven Quick",
"author_id": 37493,
"author_profile": "https://Stackoverflow.com/users/37493",
"pm_score": 3,
"selected": false,
"text": "<authentication mode=\"Forms\">\n <forms\n name=\".ASPXAUTH\"\n loginUrl=\"/Home/Default.aspx\"\n defaultUrl=\"/Dashboard/Default.aspx\"\n protection=\"All\"\n timeout=\"30\"\n slidingExpiration=\"true\"\n />\n</authentication>\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] |
316,178 | <p>Profiling LINQ queries and their execution plans is especially important due to the crazy SQL that can sometimes be created. </p>
<p>I often find that I need to track a specific query and have a hard time finding in query analyzer. I often do this on a database which has a lot of running transactions (sometimes production server) - so just opening Profiler is no good.</p>
<p>I've also found tryin to use the DataContext to trace inadequate, since it doesnt give me SQL I can actually execute myself.</p>
<p>My best strategy so far is to add in a 'random' number to my query, and filter for it in the trace.</p>
<p>LINQ:</p>
<pre><code>where o.CompletedOrderID != "59872547981"
</code></pre>
<p>Profiler filter:</p>
<pre><code>'TextData' like '%59872547981'
</code></pre>
<p>This works fine with a couple caveats :</p>
<ul>
<li>I have to be careful to remember to remove the criteria, or pick something that wont affect the query plan too much. Yes I know leaving it in is asking for trouble.</li>
<li>As far as I can tell though, even with this approach I need to start a new trace for every LINQ query I need to track. If I go to 'File > Properties' for an existing trace I cannot change the filter criteria.</li>
</ul>
<p>You cant beat running a query in your app and seeing it pop up in the Profiler without any extra effort. Was just hoping someone else had come up with a better way than this, or at least suggest a less 'dangerous' token to search for than a query on a column.</p>
| [
{
"answer_id": 316207,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "using System.Diagnostics.Debugger;\n\nyourDataContext.Log = new DebuggerWriter();\n"
},
{
"answer_id": 316232,
"author": "KristoferA",
"author_id": 11241,
"author_profile": "https://Stackoverflow.com/users/11241",
"pm_score": 4,
"selected": true,
"text": "from someobject in dc.SomeTable\nwhere someobject.xyz = 123\nselect new { MyObject = someobject, QueryTraceID1234132412='boo' }\n"
},
{
"answer_id": 316304,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "DataContext.GetCommand(); DataContext.GetChangeSet()"
},
{
"answer_id": 60088137,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 2,
"selected": false,
"text": "TagWith() var nearestFriends =\n (from f in context.Friends.TagWith(\"This is my spatial query!\")\n orderby f.Location.Distance(myLocation) descending\n select f).Take(5).ToList();\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
316,181 | <p>Having recently introduced an overload of a method the application started to fail.
Finally tracking it down, the new method is being called where I did not expect it to be.</p>
<p>We had</p>
<pre><code>setValue( const std::wstring& name, const std::wstring& value );
std::wstring avalue( func() );
setValue( L"string", avalue );
std::wstring bvalue( func2() ? L"true", L"false" );
setValue( L"bool", bvalue );
setValue( L"empty", L"" );
</code></pre>
<p>It was changed so that when a bool value is stored we use the same strings (internal data storage of strings)</p>
<pre><code>setValue( const std::wstring& name, const std::wstring& value );
setValue( const std::wstring& name, const bool& value );
std::wstring avalue( func() );
setValue( L"string", avalue );
setValue( L"bool", func2() );
setValue( L"empty", L"" ); << --- this FAILS!?!
</code></pre>
<p>The problem with L"" is that it is implicitly casting and previously it was happy to be a std::wstring, but not it prefers to be a bool.
The MSVC compiler does not complain, or raise warning, so I'm worried that even if I "fix" the setValue( L"empty", L"" ); to be</p>
<pre><code>setValue( L"empty", std::wstring() );
</code></pre>
<p>somebody else may come later and simply use setValue( L"empty", L"" ); and have to track down this issue again.</p>
<p>We thought to use explicit on the method but it is not a valid keyword for this usage.
Is there some way to get the compiler to complain about this, or otherwise prevent the issue? Otherwise I'm thinking to change the name of the method which takes a bool to ensure it can't make an incorrect guess.</p>
| [
{
"answer_id": 316202,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "[over.ics.rank]/2.1 4.12 std::wstring wchar_t const* [over.best.ics]"
},
{
"answer_id": 316224,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\nusing namespace std;\n\nvoid f(const string &s)\n{ cout << \"string version called\" << endl; }\n\nvoid f(const bool &b)\n{ cout << \"bool version called\" << endl; }\n\nint main()\n{ f(\"Hello World\"); }\n"
},
{
"answer_id": 316249,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": false,
"text": "void setValue(std::wstring const& name, const wchar_t * value);\n"
},
{
"answer_id": 316268,
"author": "zdan",
"author_id": 4304,
"author_profile": "https://Stackoverflow.com/users/4304",
"pm_score": 2,
"selected": false,
"text": "setValue( const std::wstring& name, const wchar_t s[] )\n{\n setValue(name, wstring(s));\n}\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37558/"
] |
316,193 | <p>I have <strong>CustomForm</strong> inherited from <strong>Form</strong> which implements a boolean property named <strong>Prop</strong>. The forms I'll be using will inherit from <strong>CustomForm</strong>. This property will do some painting and changes (if it's enabled) to the form. However, this is not working as it should, the VS IDE designed is not being refresh to show the changes. But if I press Ctrl+Shift+B (Menu: Build » Build Solution) the VS IDE will refresh, the form designer will even disappear for a split second and will redraw itself with the new changes applied.</p>
<p>So, is there a way, by code, to force the VS IDE designer to refresh itself just like it happens when I build the solution? If so, I could add that code to the <strong>Prop</strong> set accessor and my problem was gone.</p>
<p>Note that I've tried to call Invalidate(), Refresh() and Update. But none of them seemed to fix the problem...</p>
<hr>
<p>Here's a little insight on my real problem. My code goes something like this:</p>
<pre><code>internal class MyForm : Form {
private FormBorderStyle formBorderStyle;
private bool enableSkin;
[DefaultValue(false)]
public bool EnableSkin {
get {
return enableSkin;
} set {
enableSkin = value;
if(enableSkin) {
BackColor = Color.Lime;
MaximizedBounds = Screen.GetWorkingArea(this);
TransparencyKey = Color.Lime;
base.FormBorderStyle = FormBorderStyle.None;
} else {
BackColor = SystemColors.Control;
MaximizedBounds = Rectangle.Empty;
TransparencyKey = Color.Empty;
base.FormBorderStyle = FormBorderStyle;
}
}
}
[DefaultValue(FormBorderStyle.Sizable)]
public new FormBorderStyle FormBorderStyle {
get {
return formBorderStyle;
} set {
formBorderStyle = value;
if(EnableSkin) {
base.FormBorderStyle = FormBorderStyle.None;
} else {
base.FormBorderStyle = formBorderStyle;
}
}
}
internal MyForm() {
EnableSkin = false;
FormBorderStyle = FormBorderStyle.Sizable;
}
}
</code></pre>
<p>And the problem I'm having is something like this: <a href="http://blogs.msdn.com/calvin_hsia/archive/2007/05/01/windows-vista-aero-borderstyle-paint-problem-as-non-administrator.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/calvin_hsia/archive/2007/05/01/windows-vista-aero-borderstyle-paint-problem-as-non-administrator.aspx</a></p>
<p>In my case, that happens when you set the EnableSkin to True, change it back to False and then, changing the FormBorderStyle will cause the issue you can see on the link above. As stated in the article, the problem doesn't happen when running VS as administrator.</p>
<p>That's why I'm looking for a way to refresh the VS IDE designer. In other words, now that I've found that article, I need to recreate the window just like it happens when the solution is rebuilt.</p>
<hr>
<p>How do I declare a property in the base form?</p>
<p>I currently have:</p>
<pre><code>public class MyForm : Form { }
</code></pre>
<p>And I can only declare properties inside that class, not inside the Form one... I also have used Invalidate() as I said in the first post, but it doesn't fix my problem.</p>
| [
{
"answer_id": 316428,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 2,
"selected": false,
"text": " [Description(\"Description of your property.\"), NotifyParentProperty(true),\n RefreshProperties(RefreshProperties.Repaint)]\n"
},
{
"answer_id": 317319,
"author": "Romias",
"author_id": 7720,
"author_profile": "https://Stackoverflow.com/users/7720",
"pm_score": 0,
"selected": false,
"text": "this.Invalidate()"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40480/"
] |
316,194 | <p>I am trying to understand the process of declaration and assignment of a primitive type at the back stage.</p>
<ol>
<li><code>int i;</code></li>
<li><code>i = 3;</code></li>
</ol>
<p>For 1), on the memory stack, it assigns a space for storing an int type value named i
For 2), it assigns the value 3 to the space preserved above</p>
<p>Is there a memory address there?
From my impression, memory address is always associated with the objects on the heap?</p>
<p><strong>Update:</strong></p>
<p>Regarding the replies: </p>
<p>So, for every variable on the stack, they are all assigned a memory address as well just like the objects on the heap. Am I correct?</p>
<p>But for Java, this is not the case?</p>
| [
{
"answer_id": 316201,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "int i = 3;\n\nint *k = &i; // k now is a pointer to i\n\n*k = 4; // assigns the value k points to (i) to 4, i is now 4\n"
},
{
"answer_id": 316310,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "add $2, $0, 3\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36064/"
] |
316,204 | <p>There's an executable file generated from my program in MFC and I want to use it as the default program to open the <code>.jpg</code> files. That is to say, each time I double click a <code>.jpg</code> file, my program will run. </p>
<p>I tried to add some registry entries linking <code>.jpg</code> files with my program, such as <code>HKEY_CLASSES_ROOT\.jpg\shell\open\command</code> (set its value to <code>"myProgram.exe" "%1"</code>), and <code>HKEY_CLASSES_ROOT\myProgram</code>.</p>
<p>The method works just fine except when some other applications register themselves to open the <code>.jpg</code> files. For example, I have installed acdSee on my computer, so each time I doule click a <code>.jpg</code> file, it always start acdSee instead of my own program. But when I register a completely new type of file with my program, it can be open in the program. I don't know how to set my program as the default opening program of an already registered file programmatically. Can anyone help me solve this problem? Thank you very much!</p>
| [
{
"answer_id": 316279,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 2,
"selected": false,
"text": "HKCR\\.jpg\n @default = MyApp.JpegImage\nHKCR\\MyApp.JpegImage\\shell\\open\\command\n @default = \"myApp.exe \"%1\"\"\n HKCR\\ExistingApp.JpegImage\\shell\\myopen\\\n @default = \"Open with MyApp\"\nHKCR\\ExistingApp.JpegImage\\shell\\myopen\\command\\\n @default = \"myApp.exe \"%1\"\"\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26404/"
] |
316,210 | <p>I'm kind of new to ASP.NET MVC and to the MVC pattern in general but I'm really digging the concept and the rapidity with which I can compose an app. One thing that I'm struggling with is how to expose more than one object to a view. I use a lot of strongly typed views, which works well but what if my view relies on more than one object? Right now I'm doing something pretty hacky and passing a Dictionary to the view and then just keying the different objects. Is there a better pattern for this?</p>
| [
{
"answer_id": 316216,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": " ViewData[\"ObjectA\"] = objectA;\n ViewData[\"ObjectB\"] = objectB;\n <%= ((ObjectA)ViewData[\"ObjectA\"]).PropertyA %>\n <%= ((ObjectB)ViewData[\"ObjectB\")).PropertyB %>\n <% \n var objectA = (ObjectA)ViewData[\"ObjectA\"];\n var objectB = (ObjectB)ViewData[\"ObjectB\"];\n %>\n\n <%= objectA.PropertyA %>\n <%= objectB.PropertyB %>\n"
},
{
"answer_id": 316269,
"author": "Kyle West",
"author_id": 34133,
"author_profile": "https://Stackoverflow.com/users/34133",
"pm_score": 2,
"selected": false,
"text": "public class WhateverControllerViewData\n{\n public ObjectA ObjectA {get;set;}\n public ObjectB ObjectB {get;set;}\n}\n {\n var wcvd = new WahteverControllerViewData;\n wcvd.ObjectA = whatever;\n ..\n\n Return View(wcvd);\n}\n <%= ViewData.Model.ObjectA.Whatever %>\n"
},
{
"answer_id": 317203,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 2,
"selected": false,
"text": "public class TheModel {\n\n public DataClassA DataTypeA { get; set; }\n\n public DataClassB DataTypeB { get; set; }\n\n}\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
316,211 | <p>I have a query that selects all appropriate record in a table 'hotels' and then for each hotel looks for booked room of certain type in table 'booked_rooms' and all of that for certain period.
So first I'm taking out all hotel_ids from 'hotel_table', based on the location provided from the search form, and for each hotel_id i loop through the 'booked_rooms' table.</p>
<p>Here's the code:</p>
<pre><code>if(isset($_GET['book'])){
$sql=mysql_query("SELECT hotel_id FROM 'hotels' WHERE city='$city") or die(mysql_error());
while($row=mysql_fetch_array($sql)){
$sql_2=mysql_query("SELECT * FROM `booked_rooms` WHERE hotel_id='$hotel_id'
AND arrival_date BETWEEN '$arrival_date' AND '$departure_date'
OR departure_date BETWEEN '$arrival_date' AND '$departure_date'")
or die(mysql_error());
}
while($row_2=mysql_fetch_array($sql_2)){
print_r($row_2);
}
}
// $city, $arrival_date and $departure date are values retrieved from the search form
</code></pre>
<p>The problem is that I get a loop through 'hotel' table and get all the hotel_ids appropriate to the location, but got nothing with printing the $row_2 array.
I tried using JOINS in the SQL, 'foreach' loop, but no luck as well.</p>
| [
{
"answer_id": 316235,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 3,
"selected": false,
"text": "SELECT booked_rooms.*, hotels.* FROM 'hotels' \nJOIN 'booked_rooms' ON hotels.hotel_id = booked_rooms.hotel_id\nWHERE \n hotels.city='$city\" AND\n (\n booked_rooms.arrival_date BETWEEN '$arrival_date' AND '$departure_date' OR \n booked_rooms.departure_date BETWEEN '$arrival_date' AND '$departure_date')\n"
},
{
"answer_id": 316271,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 1,
"selected": false,
"text": "hotel_id if( isset($_GET['book']) ) {\n $sql = mysql_query(\"SELECT hotel_id FROM 'hotels' WHERE city='\".mysql_real_escape_string($city).\"'\") or die(mysql_error());\n\n $arrival_date = mysql_real_escape_string($arrival_date);\n $departure_date = mysql_real_escape_string($departure_date);\n while( $row = mysql_fetch_assoc($sql) ) {\n $hotel_id = $row['hotel_id'];\n $sql_2 = mysql_query(\"SELECT *\n FROM `booked_rooms`\n WHERE hotel_id = \".$hotel_id.\"\n AND (\n arrival_date BETWEEN '\".$arrival_date.\"' AND '\".$departure_date.\"'\n OR departure_date BETWEEN '\".$arrival_date.\"' AND '\".$departure_date.\"'\n )\")\n or die(mysql_error());\n\n while( $row_2 = mysql_fetch_assoc($sql_2) ) {\n print_r($row_2);\n }\n }\n\n}\n\n// $city, $arrival_date and $departure date are values retrieved from the search form\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432217/"
] |
316,222 | <p>How can I use a database and PHP sessions to store a user's shopping cart? I am using CodeIgniter, if that helps.</p>
<p>Example code would also be nice.</p>
| [
{
"answer_id": 317357,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "function AddToBasket(){\n if(is_numeric($_GET[\"ID\"])){\n $ProductID=(int)$_GET[\"ID\"];\n $_SESSION[\"Basket\"][]=$ProductID;\n $sOut.=ShowBasketDetail();\n return $sOut; \n }\n}\n function ShowBasket(){\n foreach($_SESSION[Basket] as $ProductID){\n $sql=\"select * from products where ProductID=$ProductID\";\n $result=mysql_query($sql);\n $row=mysql_fetch_row($result);\n echo \"Product: \".$row[0];\n }\n}\n function ClearBasket(){\n unset($_SESSION[Basket]);\n}\n session_start(); mysql_connect();"
},
{
"answer_id": 385631,
"author": "racbear",
"author_id": 45356,
"author_profile": "https://Stackoverflow.com/users/45356",
"pm_score": 1,
"selected": false,
"text": " function addCartItem($item_id, $qty)\n {\n $basket = $this->session->userdata('basket');\n if(!$basket)\n {\n $this->session->set_userdata('basket', array($item_id => $qty));\n }\n else\n {\n ## get array from $basket and *merge some new value from input\n }\n }\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
316,236 | <p>I want to load some images into my application from the file system. There's 2 easy ways to do this:</p>
<pre><code>[UIImage imageNamed:fullFileName]
</code></pre>
<p>or:</p>
<pre><code>NSString *fileLocation = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSData *imageData = [NSData dataWithContentsOfFile:fileLocation];
[UIImage imageWithData:imageData];
</code></pre>
<p>I prefer the first one because it's a lot less code, but I have seen some people saying that the image is cached and that this method uses more memory? Since I don't trust people on most other forums, I thought I'd ask the question here, is there any practical difference, and if so which one is 'better'?</p>
<p>I have tried profiling my app using the Object Allocation instrument, and I can't see any practical difference, though I have only tried in the simulator, and not on an iPhone itself.</p>
| [
{
"answer_id": 316258,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 8,
"selected": true,
"text": "imageNamed:"
},
{
"answer_id": 316266,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 3,
"selected": false,
"text": "[UIImage imageNamed:]"
},
{
"answer_id": 316387,
"author": "Hunter",
"author_id": 555,
"author_profile": "https://Stackoverflow.com/users/555",
"pm_score": 3,
"selected": false,
"text": "[UIImage imageNamed:] UITableViews image"
},
{
"answer_id": 7144922,
"author": "CedricSoubrie",
"author_id": 391796,
"author_profile": "https://Stackoverflow.com/users/391796",
"pm_score": 3,
"selected": false,
"text": "NSString *fileLocation = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];\nUIImage* yourImage = [[[UIImage alloc] initWithContentsOfFile:imagePath] autorelease];\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
] |
316,238 | <p>Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first.</p>
<p>This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as <code>Decimal("%.15f" % my_float)</code>, which will give you garbage at the 15th decimal place if you also have any significant digits before decimal (<code>Decimal("%.15f" % 100000.3) == Decimal('100000.300000000002910')</code>).</p>
<p>Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?</p>
| [
{
"answer_id": 316248,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": ">>> repr(1.5)\n'1.5'\n>>> repr(12345.678901234567890123456789)\n'12345.678901234567'\n"
},
{
"answer_id": 316253,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 7,
"selected": true,
"text": "\"%.15g\" % f\n format(f, \".15g\")\n Decimal from decimal import Decimal\nDecimal(f)\n"
},
{
"answer_id": 8413753,
"author": "vincent wen",
"author_id": 554625,
"author_profile": "https://Stackoverflow.com/users/554625",
"pm_score": 5,
"selected": false,
"text": ">>> a = 2.111111\n>>> a\n2.1111110000000002\n>>> str(a)\n'2.111111'\n>>> decimal.Decimal(str(a))\nDecimal('2.111111')\n"
},
{
"answer_id": 59491357,
"author": "Deep Patel",
"author_id": 11804423,
"author_profile": "https://Stackoverflow.com/users/11804423",
"pm_score": 0,
"selected": false,
"text": "import json\nfrom decimal import Decimal\n\nfloat_value = 123456.2365\ndecimal_value = json.loads(json.dumps(float_value), parse_float=Decimal)\n"
},
{
"answer_id": 62046166,
"author": "Chris",
"author_id": 1308967,
"author_profile": "https://Stackoverflow.com/users/1308967",
"pm_score": 2,
"selected": false,
"text": "g format(0.012345, \".2g\") f format(0.012345, \".2f\") == 0.01"
},
{
"answer_id": 66245400,
"author": "mmj",
"author_id": 694360,
"author_profile": "https://Stackoverflow.com/users/694360",
"pm_score": 0,
"selected": false,
"text": "import decimal\nclass DecimalBuilder(float):\n def __or__(self, a):\n return decimal.Decimal(str(a))\n\n>>> d = DecimalBuilder()\n>>> x = d|0.1\n>>> y = d|0.2\n>>> x + y # works as desired\nDecimal('0.3')\n>>> d|0.1 + d|0.2 # does not work as desired, needs parenthesis\nTypeError: unsupported operand type(s) for |: 'decimal.Decimal' and 'float'\n>>> (d|0.1) + (d|0.2) # works as desired\nDecimal('0.3')\n"
},
{
"answer_id": 69361544,
"author": "Ryabchenko Alexander",
"author_id": 6515755,
"author_profile": "https://Stackoverflow.com/users/6515755",
"pm_score": 3,
"selected": false,
"text": "Decimal(float).quantize(Decimal(\"1.00000\"))\n"
},
{
"answer_id": 72716255,
"author": "ChristophK",
"author_id": 2936442,
"author_profile": "https://Stackoverflow.com/users/2936442",
"pm_score": 2,
"selected": false,
"text": "def ftod(val, prec = 15):\n return Decimal(val).quantize(Decimal(10)**-prec)\n >>> 0.1 + 0.2 == 0.3\nFalse\n >>> from decimal import Decimal\n>>> def ftod(val, prec = 15): # float to Decimal\n... return Decimal(val).quantize(Decimal(10)**-prec)\n... \n>>> ftod(0.1) + ftod(0.2) == ftod(0.3)\nTrue\n >>> Decimal(10)**-4\nDecimal('0.0001')\n >>> for x in [0.1, 0.2, 0.3, ftod(0.1), ftod(0.2), ftod(0.3)]:\n... print(\"{:8} {:.18f}\".format(type(x).__name__+\":\", x))\n... \nfloat: 0.100000000000000006\nfloat: 0.200000000000000011\nfloat: 0.299999999999999989\nDecimal: 0.100000000000000000\nDecimal: 0.200000000000000000\nDecimal: 0.300000000000000000\n >>> for p in [15, 16, 17]:\n... print(\"Rounding precision: {}. Check 0.1 + 0.2 == 0.3 is {}\".format(p,\n... ftod(0.1, p) + ftod(0.2, p) == ftod(0.3, p)))\n... \nRounding precision: 15. Check 0.1 + 0.2 == 0.3 is True\nRounding precision: 16. Check 0.1 + 0.2 == 0.3 is True\nRounding precision: 17. Check 0.1 + 0.2 == 0.3 is False\n >>> import sys\n>>> sys.float_info\nsys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)\n >>> import math\n>>> math.log10(2**53)\n15.954589770191003\n"
},
{
"answer_id": 74502334,
"author": "giocip",
"author_id": 20156393,
"author_profile": "https://Stackoverflow.com/users/20156393",
"pm_score": 0,
"selected": false,
"text": "from decimal import *\ngetcontext().prec = 128 #high precision set\nprint(Decimal(100000.3))\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/52490/"
] |
316,265 | <p><strong>How can you make the experience with Eclipse faster?</strong> </p>
<p>For instance: <em>I disable all the plugins I don't need (Mylyn, Subclipse, …).</em></p>
<p>Instead of using a plugin for <a href="http://en.wikipedia.org/wiki/Mercurial" rel="noreferrer">Mercurial</a>, I configure <a href="https://en.wikipedia.org/wiki/TortoiseHg" rel="noreferrer">TortoiseHG</a> as an external tool.</p>
| [
{
"answer_id": 316270,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 5,
"selected": false,
"text": "-Xmx"
},
{
"answer_id": 316435,
"author": "chromakode",
"author_id": 40508,
"author_profile": "https://Stackoverflow.com/users/40508",
"pm_score": 6,
"selected": false,
"text": "update-alternatives --config java"
},
{
"answer_id": 316535,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 10,
"selected": true,
"text": " -vm jdk1.6.0_10\\jre\\bin\\client\\jvm.dll\n -Xms512m\n -Xmx4096m\n [...]\n Xmx -Xmx4g"
},
{
"answer_id": 1340105,
"author": "ILX",
"author_id": 122674,
"author_profile": "https://Stackoverflow.com/users/122674",
"pm_score": 6,
"selected": false,
"text": "Windows -> Preferences; General -> Appearance -> Label Decorations Windows -> Preferences; General -> Startup and Shutdown"
},
{
"answer_id": 3395162,
"author": "Mateng",
"author_id": 283854,
"author_profile": "https://Stackoverflow.com/users/283854",
"pm_score": 6,
"selected": false,
"text": "-Dosgi.requiredJavaVersion=1.6\n-Xms512m\n-Xmx512m\n-XX:PermSize=512m\n-XX:MaxPermSize=512M\n-Xverify:none\n -Xms -Xmx update-alternatives --config java\n"
},
{
"answer_id": 3555578,
"author": "Colm Ryan",
"author_id": 268754,
"author_profile": "https://Stackoverflow.com/users/268754",
"pm_score": 7,
"selected": false,
"text": "validators"
},
{
"answer_id": 7652543,
"author": "Assem",
"author_id": 790189,
"author_profile": "https://Stackoverflow.com/users/790189",
"pm_score": 8,
"selected": false,
"text": "-Xverify:none"
},
{
"answer_id": 21922284,
"author": "pauluss86",
"author_id": 1631883,
"author_profile": "https://Stackoverflow.com/users/1631883",
"pm_score": 1,
"selected": false,
"text": "tmpfs tmpfs tmpfs rsync tmpfs"
},
{
"answer_id": 25620147,
"author": "Saikat",
"author_id": 1808990,
"author_profile": "https://Stackoverflow.com/users/1808990",
"pm_score": 2,
"selected": false,
"text": "-vm\n--C:\\JAVA\\jre\\bin\\server\\jvm.dll\nC:\\JAVA8x64\\jre\\bin\\server\\jvm.dll\n-vmargs\n-Xnoclassgc\n-Dosgi.requiredJavaVersion=1.6\n-Xms256m\n-Xmx1024m\n"
},
{
"answer_id": 25912761,
"author": "Sudhakar",
"author_id": 2935802,
"author_profile": "https://Stackoverflow.com/users/2935802",
"pm_score": 3,
"selected": false,
"text": " **Tips for making Eclipse IDE Faster**\n Configuring eclipse.ini should be based on your RAM\n -Xms256m\n -Xmx512m\n -XX:PermSize=512m\n -XX:MaxPermSize=512M\n"
},
{
"answer_id": 27242223,
"author": "Du-Lacoste",
"author_id": 3600553,
"author_profile": "https://Stackoverflow.com/users/3600553",
"pm_score": 2,
"selected": false,
"text": "ramdisk\n /dev/shm\n"
},
{
"answer_id": 32875192,
"author": "Rxp",
"author_id": 5393722,
"author_profile": "https://Stackoverflow.com/users/5393722",
"pm_score": 2,
"selected": false,
"text": "C/C++ Window->Preferences C/C++"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356709/"
] |
316,267 | <p>I'm storing a tree in a DB using nested sets. The table's fields are id, lft, rgt, and name. </p>
<p>Given a node ID, I need to find all of its direct children(not grandchildren) that are themselves leaf nodes.</p>
| [
{
"answer_id": 316280,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth\nFROM nested_category AS node,\n nested_category AS parent,\n nested_category AS sub_parent,\n (\n SELECT node.name, (COUNT(parent.name) - 1) AS depth\n FROM nested_category AS node,\n nested_category AS parent\n WHERE node.lft BETWEEN parent.lft AND parent.rgt\n AND node.name = '**[[MY NODE]]**'\n GROUP BY node.name\n ORDER BY node.lft\n )AS sub_tree\nWHERE node.lft BETWEEN parent.lft AND parent.rgt\n AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt\n AND sub_parent.name = sub_tree.name\nGROUP BY node.name\nHAVING depth = 1\nORDER BY node.lft;\n rgt lft + 1"
},
{
"answer_id": 5035332,
"author": "rshaffaf",
"author_id": 610643,
"author_profile": "https://Stackoverflow.com/users/610643",
"pm_score": 1,
"selected": false,
"text": "select \n child.id, \n child.lft, \n child.rgt \nfrom \n nodes child, \n nodes parent \nwhere \n child.lft between parent.lft and parent.rgt \n and parent.id != child.id\n and parent.id = [ID];\n parent.id != child.id"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
316,278 | <p>I am trying to have an element fade in, then in 5000 ms fade back out again. I know I can do something like:</p>
<pre><code>setTimeout(function () { $(".notice").fadeOut(); }, 5000);
</code></pre>
<p>But that will only control the fade out, would I add the above on the callback?</p>
| [
{
"answer_id": 316281,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "$(\".notice\")\n .fadeIn( function() \n {\n setTimeout( function()\n {\n $(\".notice\").fadeOut(\"fast\");\n }, 2000);\n });\n"
},
{
"answer_id": 316298,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 4,
"selected": false,
"text": "$('.notice')\n .fadeIn()\n .animate({opacity: '+=0'}, 2000) // Does nothing for 2000ms\n .fadeOut('fast');\n"
},
{
"answer_id": 316510,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 9,
"selected": true,
"text": ".delay( n ) $('.notice').fadeIn().delay(2000).fadeOut('slow'); \n $.show() $.hide() $.delay() $('.notice')\n .show({duration: 0, queue: true})\n .delay(2000)\n .hide({duration: 0, queue: true});\n jQuery(function($){ \n\nvar e = $('.notice'); \ne.fadeIn(); \ne.queue(function(){ \n setTimeout(function(){ \n e.dequeue(); \n }, 2000 ); \n}); \ne.fadeOut('fast'); \n\n}); \n (function($){ \n\n jQuery.fn.idle = function(time)\n { \n var o = $(this); \n o.queue(function()\n { \n setTimeout(function()\n { \n o.dequeue(); \n }, time);\n });\n };\n})(jQuery);\n $('.notice').fadeIn().idle(2000).fadeOut('slow'); \n"
},
{
"answer_id": 1110527,
"author": "user128026",
"author_id": 128026,
"author_profile": "https://Stackoverflow.com/users/128026",
"pm_score": 3,
"selected": false,
"text": "this $.fn.idle = function(time)\n {\n var o = $(this);\n o.queue(function()\n {\n setTimeout(function()\n {\n o.dequeue();\n }, time);\n });\n return this; //****\n }\n $('.notice').fadeIn().idle(2000).fadeOut('slow');\n"
},
{
"answer_id": 4348420,
"author": "Arash Milani",
"author_id": 205997,
"author_profile": "https://Stackoverflow.com/users/205997",
"pm_score": 4,
"selected": false,
"text": "jQuery.fn.wait = function (MiliSeconds) {\n $(this).animate({ opacity: '+=0' }, MiliSeconds);\n return this;\n}\n $('.notice').fadeIn().wait(2000).fadeOut('slow');\n"
},
{
"answer_id": 10837984,
"author": "DaveAlger",
"author_id": 1336975,
"author_profile": "https://Stackoverflow.com/users/1336975",
"pm_score": 1,
"selected": false,
"text": "$(function(){\n // make sure img is hidden - fade in\n $('img').hide().fadeIn(2000);\n\n // after 5 second timeout - fade out\n setTimeout(function(){$('img').fadeOut(2000);}, 5000);\n});\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
316,294 | <pre><code>class A
def initialize
@x = do_something
end
def do_something
42
end
end
</code></pre>
<p>How can I stub <code>do_something</code> in rspec, before the original implementation is called (thus assigning 42 to <code>@x</code>)? And without changing the implementation, of course.</p>
| [
{
"answer_id": 316318,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 4,
"selected": false,
"text": "# should probably be in spec/spec_helper.rb\nSpec::Runner.configure do |config|\n config.mock_with :mocha\nend\n\ndescribe A, \" when initialized\" do\n it \"should set x to 42\" do\n A.new.x.should == 42\n end\nend\n\ndescribe A, \" when do_something is mocked\" do\n it \"should set x to 23\" do\n A.any_instance.expects(:do_something).returns(23)\n A.new.x.should == 23\n end\nend\n"
},
{
"answer_id": 316353,
"author": "Chris Lloyd",
"author_id": 42413,
"author_profile": "https://Stackoverflow.com/users/42413",
"pm_score": 3,
"selected": false,
"text": "stub.any_instance_of(A).do_something { 23 }\n"
},
{
"answer_id": 318985,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 6,
"selected": true,
"text": "A.any_instance.stub(do_something: 23)\n"
},
{
"answer_id": 1316488,
"author": "phss",
"author_id": 135051,
"author_profile": "https://Stackoverflow.com/users/135051",
"pm_score": -1,
"selected": false,
"text": "A.should_receive(:new).and_return(42)\n"
},
{
"answer_id": 1549926,
"author": "jmhmccr",
"author_id": 48098,
"author_profile": "https://Stackoverflow.com/users/48098",
"pm_score": 0,
"selected": false,
"text": "before :each do\n @my_stub = stub(\"A\")\n @my_stub.should_receive(:do_something).with(no_args()).and_return(42)\n @my_stub.should_receive(:do_something_else).with(any_args()).and_return(true)\n A.stub(:new).and_return(my_stub)\nend\n A.stub(:new).and_return(42)"
},
{
"answer_id": 1961042,
"author": "Denis Barushev",
"author_id": 124384,
"author_profile": "https://Stackoverflow.com/users/124384",
"pm_score": 4,
"selected": false,
"text": "new_method = A.method(:new)\n\nA.stub!(:new).and_return do |*args|\n a = new_method.call(*args)\n a.should_receive(:do_something).and_return(23)\n a\nend\n"
},
{
"answer_id": 2690826,
"author": "Serge Balyuk",
"author_id": 323021,
"author_profile": "https://Stackoverflow.com/users/323021",
"pm_score": 2,
"selected": false,
"text": "new_method proxied_by_rspec__ \nA.stub!(:new).and_return do |*args|\n a = A.proxied_by_rspec__new(*args)\n a.should_receive(:do_something).and_return(23)\n a\nend\n"
},
{
"answer_id": 10402265,
"author": "AdrienE",
"author_id": 223111,
"author_profile": "https://Stackoverflow.com/users/223111",
"pm_score": 0,
"selected": false,
"text": "super it \"should call during_init in initialize\" do\n class TestClass < TheClassToTest\n def initialize\n should_receive(:during_init)\n super\n end\n end\n TestClass.new\nend\n"
},
{
"answer_id": 10967439,
"author": "triskweline",
"author_id": 340168,
"author_profile": "https://Stackoverflow.com/users/340168",
"pm_score": 0,
"selected": false,
"text": "stub_any_instance"
},
{
"answer_id": 12054895,
"author": "David Waller",
"author_id": 23267,
"author_profile": "https://Stackoverflow.com/users/23267",
"pm_score": 2,
"selected": false,
"text": "A.any_instance.stub(do_something: 23)\n"
},
{
"answer_id": 38370743,
"author": "Lukasz Muzyka",
"author_id": 1540290,
"author_profile": "https://Stackoverflow.com/users/1540290",
"pm_score": 2,
"selected": false,
"text": "allow_any_instance_of(Widget).to receive(:name).and_return(\"Wibble\")\n"
}
] | 2008/11/25 | [
"https://Stackoverflow.com/questions/316294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16882/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.