qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
309,506 | <p>I want to reveal a div with an input inside when you click a button, and set its focus.</p>
<p>If I use show(), it works, but if I use slideDown() <strong>the focus is lost after the animation completes</strong>. How can I prevent this from happening?</p>
<p>Sample code:</p>
<pre><code>$("document").ready(function(){
$("#MyButton").click(function(e){
e.preventDefault();
$(".SlidingDiv").slideDown();
$("#MyInput").focus();
});
});
<input type="button" value="Click Me" id="MyButton" />
<div class="SlidingDiv" style="display:none;"><input type="text" id="MyInput" /></div>
</code></pre>
| [
{
"answer_id": 309562,
"author": "James",
"author_id": 21677,
"author_profile": "https://Stackoverflow.com/users/21677",
"pm_score": 4,
"selected": true,
"text": "$(function(){\n $(\"#MyButton\").click(function(e){\n e.preventDefault();\n $(\".SlidingDiv\").slideDown(function(){\n // Callback function - will occur when sliding is complete.\n $(\"#MyInput\").focus();\n });\n });\n});\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842/"
] |
309,522 | <p>(This is related to <a href="https://stackoverflow.com/questions/85373/floor-a-date-in-sql-server">Floor a date in SQL server</a>.)</p>
<p>Does a deterministic expression exist to floor a DATETIME? When I use this as a computed column formula:</p>
<pre><code>DATEADD(dd, DATEDIFF(dd, 0, [datetime_column]), 0)
</code></pre>
<p>the I get an error when I place an index on that column:</p>
<blockquote>
<p>Cannot create index because the key column 'EffectiveDate' is non-deterministic or imprecise.</p>
</blockquote>
<p>But both DATEDIFF and DATEADD are deterministic functions by definition. Where is the catch? Is it possible?</p>
| [
{
"answer_id": 309559,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "CAST(FLOOR(CAST([datetime_column] as FLOAT)) AS DateTime)\n"
},
{
"answer_id": 309642,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": " cast(cast([datetime_column] as int) as datetime)\n cast([datetime_column] as int)"
},
{
"answer_id": 309964,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 3,
"selected": true,
"text": "CONVERT(CHAR(8), datetime_column, 112)\n CREATE TABLE dbo.Test_Determinism (\n datetime_column DATETIME NOT NULL DEFAULT GETDATE())\nGO\n\nCREATE VIEW dbo.Test_Determinism_View\nWITH SCHEMABINDING\nAS\n SELECT\n DATEADD(dd, DATEDIFF(dd, 0, [datetime_column]), 0) AS EffectiveDate\n FROM\n dbo.Test_Determinism\nGO\n\nCREATE UNIQUE CLUSTERED INDEX IDX_Test_Determinism_View ON dbo.Test_Determinism_View (EffectiveDate)\nGO\n"
},
{
"answer_id": 17832037,
"author": "dunxz",
"author_id": 2011398,
"author_profile": "https://Stackoverflow.com/users/2011398",
"pm_score": 1,
"selected": false,
"text": "/* create a deterministic schema bound function */\nCREATE FUNCTION FloorDate(@dt datetime)\nRETURNS datetime\nWITH SCHEMABINDING\nAS\nBEGIN \n RETURN CONVERT(datetime, FLOOR(CONVERT(float, @dt)))\nEND\nGO\n /*create a test table */\nCREATE TABLE [dbo].[TableTestFloorDate](\n [Id] [int] IDENTITY(1,1) NOT NULL,\n [TestDate] [datetime] NOT NULL,\n [TestFloorDate] AS ([dbo].[FloorDate]([TestDate])) PERSISTED,\n CONSTRAINT [PK_TableTestFloorDate] PRIMARY KEY CLUSTERED \n(\n [Id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) \n) \n CREATE INDEX IX_TestFloorDate ON [dbo].[TableTestFloorDate](TestFloorDate)\n INSERT INTO TableTestFloorDate (TestDate) VALUES( convert(datetime, RAND()*50000))\n SELECT * FROM TableTestFloorDate WHERE TestFloorDate='2013-2-2'\n CREATE INDEX IX_TestFloorDate ON [dbo].[TableTestFloorDate](TestDate)\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18771/"
] |
309,533 | <p>I have a webservice @ <a href="http://recpushdata.cyndigo.com/Jobs.asmx" rel="nofollow noreferrer">http://recpushdata.cyndigo.com/Jobs.asmx</a> but I'm not able to access it though I am adding it as a WebReference properly.</p>
<p>Any Help would be great.</p>
| [
{
"answer_id": 309559,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "CAST(FLOOR(CAST([datetime_column] as FLOAT)) AS DateTime)\n"
},
{
"answer_id": 309642,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": " cast(cast([datetime_column] as int) as datetime)\n cast([datetime_column] as int)"
},
{
"answer_id": 309964,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 3,
"selected": true,
"text": "CONVERT(CHAR(8), datetime_column, 112)\n CREATE TABLE dbo.Test_Determinism (\n datetime_column DATETIME NOT NULL DEFAULT GETDATE())\nGO\n\nCREATE VIEW dbo.Test_Determinism_View\nWITH SCHEMABINDING\nAS\n SELECT\n DATEADD(dd, DATEDIFF(dd, 0, [datetime_column]), 0) AS EffectiveDate\n FROM\n dbo.Test_Determinism\nGO\n\nCREATE UNIQUE CLUSTERED INDEX IDX_Test_Determinism_View ON dbo.Test_Determinism_View (EffectiveDate)\nGO\n"
},
{
"answer_id": 17832037,
"author": "dunxz",
"author_id": 2011398,
"author_profile": "https://Stackoverflow.com/users/2011398",
"pm_score": 1,
"selected": false,
"text": "/* create a deterministic schema bound function */\nCREATE FUNCTION FloorDate(@dt datetime)\nRETURNS datetime\nWITH SCHEMABINDING\nAS\nBEGIN \n RETURN CONVERT(datetime, FLOOR(CONVERT(float, @dt)))\nEND\nGO\n /*create a test table */\nCREATE TABLE [dbo].[TableTestFloorDate](\n [Id] [int] IDENTITY(1,1) NOT NULL,\n [TestDate] [datetime] NOT NULL,\n [TestFloorDate] AS ([dbo].[FloorDate]([TestDate])) PERSISTED,\n CONSTRAINT [PK_TableTestFloorDate] PRIMARY KEY CLUSTERED \n(\n [Id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) \n) \n CREATE INDEX IX_TestFloorDate ON [dbo].[TableTestFloorDate](TestFloorDate)\n INSERT INTO TableTestFloorDate (TestDate) VALUES( convert(datetime, RAND()*50000))\n SELECT * FROM TableTestFloorDate WHERE TestFloorDate='2013-2-2'\n CREATE INDEX IX_TestFloorDate ON [dbo].[TableTestFloorDate](TestDate)\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
309,539 | <p>I would like to generate a list of files within a directory. Some of the filenames contain Chinese characters.</p>
<p>eg: [试验].Test.txt</p>
<p>I am using the following code:</p>
<pre><code>require 'find'
dirs = ["TestDir"]
for dir in dirs
Find.find(dir) do |path|
if FileTest.directory?(path)
else
p path
end
end
end
</code></pre>
<p>Running the script produces a list of files but the Chinese characters are escaped (replaced with backslashes followed by numbers). Using the example filename above would produce:</p>
<p>"TestDir/[\312\324\321\351]Test.txt" instead of "TestDir/[试验].Test.txt".</p>
<p>How can the script be altered to output the Chinese characters?</p>
| [
{
"answer_id": 309707,
"author": "rpattabi",
"author_id": 15139,
"author_profile": "https://Stackoverflow.com/users/15139",
"pm_score": 3,
"selected": true,
"text": "$KCODE = 'utf-8'\n"
},
{
"answer_id": 10933975,
"author": "David",
"author_id": 1442494,
"author_profile": "https://Stackoverflow.com/users/1442494",
"pm_score": 1,
"selected": false,
"text": "Dir.entries(Dir.pwd).each do |x|\n p x.encode('UTF-8') unless FileTest.directory?(x) \nend \n Dir.glob('*/*').each do |x|\n p x.encode('UTF-8') unless FileTest.directory?(x) \nend\n Dir.glob('**/*')"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39731/"
] |
309,553 | <p>I commonly find myself extracting common behavior out of classes into helper/utility classes that contain nothing but a set of static methods. I've often wondered if I should be declaring these classes as abstract, since I can't really think of a valid reason to ever instantiate these? </p>
<p>What would the Pros and Cons be to declaring such a class as abstract.</p>
<pre><code>public [abstract] class Utilities{
public static String getSomeData(){
return "someData";
}
public static void doSomethingToObject(Object arg0){
}
}
</code></pre>
| [
{
"answer_id": 311474,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 0,
"selected": false,
"text": "import static Utilities.getSomeData;\n\npublic class Consumer {\n\n public void doSomething(){\n\n String data = getSomeData();\n }\n\n}\n"
},
{
"answer_id": 311518,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "struct Utility { \n static void doSomething() { /* ... */ } \n Utility() = delete; \n};\n"
},
{
"answer_id": 311571,
"author": "user38051",
"author_id": 38051,
"author_profile": "https://Stackoverflow.com/users/38051",
"pm_score": 4,
"selected": false,
"text": "\n\npublic final class Utility\n{\n private Utility(){}\n\n public static void doSomethingUseful()\n {\n ...\n }\n}\n"
},
{
"answer_id": 493297,
"author": "les2",
"author_id": 39489,
"author_profile": "https://Stackoverflow.com/users/39489",
"pm_score": 2,
"selected": false,
"text": "public class Foo {\n // non-instantiable class\n private Foo() { throw new AssertionError(); }\n}\n AssertionError public class CoreUtils { ... }\npublic class WebUtils extends CoreUtils { ... }\n\npublic class Foo { ... WebUtils.someMethodInCoreUtils() ... }\n"
},
{
"answer_id": 57593289,
"author": "Stefan Endrullis",
"author_id": 411766,
"author_profile": "https://Stackoverflow.com/users/411766",
"pm_score": 2,
"selected": false,
"text": "@UtilityClass @UtilityClass\npublic class Utilities{\n\n public String getSomeData() {\n return \"someData\";\n }\n\n public void doSomethingToObject(Object arg0) {\n }\n}\n @UtilityClass"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] |
309,565 | <p>I'm using the StAX event based API's to modify an XML stream. The stream represents an HTML document, complete with DTD declaration. I would like to copy this DTD declaration into the output document (written using an <code>XMLEventWriter</code>). When I ask the factory to disregard DTD's it will not download the DTD, but remove the whole statement and only leave a "<code><!DOCUMENTTYPE</code>" string. When not disregarding, the whole DTD gets downloaded, and included when verbatim outputting the DTD event. I don't want to use the time to download this DTD, but include the complete DTD specification (resolving entities is already disabled and I don't need that). Does anyone know how to disable the fetching of external DTD's.</p>
| [
{
"answer_id": 309643,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": true,
"text": "class CustomResolver implements javax.xml.stream.XMLResolver {\n\n public Object resolveEntity(String publicID,\n String systemID,\n String baseURI,\n String namespace)\n throws XMLStreamException \n {\n if (\"The public ID you expect\".equals(publicID)) {\n return getClass().getResourceAsStream(\"doc.dtd\");\n } else {\n return null;\n }\n }\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4100/"
] |
309,574 | <p>I want my errors to float above, left-justified, the input field that doesn't validate. How can I do this?</p>
<p>If I can't, how can I turn the errors off? I still want the fields to validate (and highlight on error), but not for the actual error messages to display. I couldn't seem to find anything in the jQuery docs that would let me turn them on/off... ??</p>
| [
{
"answer_id": 312102,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 4,
"selected": false,
"text": "$(...).validate({\n errorPlacement: function(error, element) {\n error.insertBefore(element);\n }\n});\n label.error {\n /* Move the error above the input element. */\n position: absolute;\n line-height: 1.5em;\n margin-top: -1.5em;\n\n background-color: red;\n color: white;\n padding: 0 2px;\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32154/"
] |
309,581 | <p>What is the difference between a <code>const_iterator</code> and an <code>iterator</code> and where would you use one over the other?</p>
| [
{
"answer_id": 309589,
"author": "Dominic Rodger",
"author_id": 20972,
"author_profile": "https://Stackoverflow.com/users/20972",
"pm_score": 8,
"selected": true,
"text": "const_iterator iterator const const"
},
{
"answer_id": 309610,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 6,
"selected": false,
"text": "T* // A non-const iterator to a non-const element. Corresponds to std::vector<T>::iterator\nT* const // A const iterator to a non-const element. Corresponds to const std::vector<T>::iterator\nconst T* // A non-const iterator to a const element. Corresponds to std::vector<T>::const_iterator\n"
},
{
"answer_id": 4710559,
"author": "Mr Coder",
"author_id": 197992,
"author_profile": "https://Stackoverflow.com/users/197992",
"pm_score": 0,
"selected": false,
"text": " for(vector<int>::iterator i = randomData.begin() ; i != randomData.end() ; ++i)*i = 0;\nfor(vector<int>::const_iterator i = randomData.begin() ; i!= randomData.end() ; ++i)cout << *i;\n"
},
{
"answer_id": 41275112,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 3,
"selected": false,
"text": "std::vector<int> v{0};\nstd::vector<int>::iterator it = v.begin();\n*it = 1;\nassert(v[0] == 1);\n const std::vector<int> v{0};\nstd::vector<int>::const_iterator cit = v.begin();\n// Compile time error: cannot modify container with const_iterator.\n//*cit = 1;\n v.begin() const iterator const_iterator const_iterator this const class C {\n public:\n std::vector<int> v;\n void f() const {\n std::vector<int>::const_iterator it = this->v.begin();\n }\n void g(std::vector<int>::const_iterator& it) {}\n};\n const this this->v auto std::vector<int> v{0};\nstd::vector<int>::iterator it = v.begin();\n\n// non-const to const.\nstd::vector<int>::const_iterator cit = it;\n\n// Compile time error: cannot modify container with const_iterator.\n//*cit = 1;\n\n// Compile time error: no conversion from const to no-const.\n//it = ci1;\n const int int"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
309,604 | <p>I need to do the following for hundreds of files:
Append the name of the file (which may contain spaces) to the end of each line in the file.</p>
<p>It seems to me there should be some way to do this:</p>
<pre><code>sed -e 's/$/FILENAME/' *
</code></pre>
<p>where <code>FILENAME</code> represents the name of the current file. Is there a sed variable representing the current filename? Or does anyone have a different solution using bash, awk, etc.?</p>
| [
{
"answer_id": 309616,
"author": "Tyler McHenry",
"author_id": 39375,
"author_profile": "https://Stackoverflow.com/users/39375",
"pm_score": 2,
"selected": false,
"text": "for i in * \ndo\n sed -e \"s/\\$/$i/\" \"$i\" \ndone\n for i in * ; do sed -e \"s/\\$/$i/\" \"$i\" ; done\n TFILE=`mktemp`\nfor i in * \ndo\n sed -e \"s/\\$/$i/\" \"$i\" > $TFILE\n cp -f $TFILE \"$i\"\ndone\nrm -f $TFILE\n"
},
{
"answer_id": 309621,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 0,
"selected": false,
"text": "for f in *; do echo $f >> $f; done\n"
},
{
"answer_id": 309635,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "for i in * ; do \n sed -e \"s/\\$/$i/\" --in-place \"$i\" \ndone\n"
},
{
"answer_id": 309644,
"author": "shmuelp",
"author_id": 4673,
"author_profile": "https://Stackoverflow.com/users/4673",
"pm_score": 4,
"selected": true,
"text": "perl -p -i -e 's/$/$ARGV/;' *\n"
},
{
"answer_id": 309655,
"author": "MCS",
"author_id": 1094969,
"author_profile": "https://Stackoverflow.com/users/1094969",
"pm_score": 0,
"selected": false,
"text": "(\n OLDIFS=$IFS\n IFS=$'\\n'\n for f in *\n do\n IFS=OLDIFS\n sed -e \"s/\\$/$f/\" $f > tmpfile\n mv tmpfile $f\n IFS=$'\\n'\n done\n)\n"
},
{
"answer_id": 309661,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "awk '{print $0,FILENAME}' > tmpfile\n"
},
{
"answer_id": 9760464,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "printf \"%s\\n\" * | sed 's/.*/sed -i \"s|$| &|\" &/' | bash\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1094969/"
] |
309,615 | <p>I'd like to establish an ssh tunnel over ssh to my mysql server.</p>
<p>Ideally I'd return a mysqli db pointer just like I was connecting directly.</p>
<p>I'm on a shared host that doesn't have the <a href="http://ca.php.net/ssh2" rel="noreferrer">SSH2</a> libraries but I might be able to get them installed locally using PECL.</p>
<p>If there's a way that uses native commands that would be great.</p>
<p>I was thinking something like this, but without those libraries it won't work.</p>
<pre><code>$connection = ssh2_connect('SERVER IP', 22);
ssh2_auth_password($connection, 'username', 'password');
$tunnel = ssh2_tunnel($connection, 'DESTINATION IP', 3307);
$db = new mysqli_connect('127.0.0.1', 'DB_USERNAME', 'DB_PASSWORD',
'dbname', 3307, $tunnel)
or die ('Fail: ' . mysql_error());
</code></pre>
<p>Anyone have any ideas? I'm running a shared CentOS linux host at liquidweb.</p>
<p>Any thoughts on making the tunnel persistent? Is it possible to establish it with another script and just take advantage of it in <code>PHP</code>?</p>
<p>Thanks.</p>
| [
{
"answer_id": 310932,
"author": "Brian C. Lane",
"author_id": 27461,
"author_profile": "https://Stackoverflow.com/users/27461",
"pm_score": 4,
"selected": false,
"text": "ssh -L 3306:localhost:3306 user@domain.com\n"
},
{
"answer_id": 472586,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "system exec $connection = ssh2_connect($remotehost, '22');\nif (ssh2_auth_password($connection, $user,$pass)) {\n echo \"Authentication Successful!\\n\";\n} else {\n die('Authentication Failed...');\n}\n\n\n$stream=ssh2_exec($connection,'echo \"select * from zingaya.users where id=\\\"1606\\\";\" | mysql');\nstream_set_blocking($stream, true);\nwhile($line = fgets($stream)) {\n flush();\n echo $line.\"\\n\";\n}\n"
},
{
"answer_id": 12660234,
"author": "Sosy",
"author_id": 208943,
"author_profile": "https://Stackoverflow.com/users/208943",
"pm_score": 4,
"selected": false,
"text": "ssh -f -L bind-ip-address:bind-port:remote-ip-address:remote-port \\\nusername@remote-server [command] >> /path/to/logfile\n shell_exec(\"ssh -f -L 127.0.0.1:3307:127.0.0.1:3306 user@remote.rjmetrics.com sleep 60 >> logfile\"); \n$db = mysqli_connect(\"127.0.0.1\", \"sqluser\", \"sqlpassword\", \"rjmadmin\", 3307);\n shell_exec() mysqli_connect() mysql_connect() mysql_* sleep 60 -N -N sleep 60"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430/"
] |
309,631 | <p>In what cases is it necessary to synchronize access to instance members?
I understand that access to static members of a class always needs to be synchronized- because they are shared across all object instances of the class.</p>
<p>My question is when would I be incorrect if I do not synchronize instance members? </p>
<p>for example if my class is</p>
<pre><code>public class MyClass {
private int instanceVar = 0;
public setInstanceVar()
{
instanceVar++;
}
public getInstanceVar()
{
return instanceVar;
}
}
</code></pre>
<p>in what cases (of usage of the class <code>MyClass</code>) would I <em>need</em> to have methods:
<code>public synchronized setInstanceVar()</code> and
<code>public synchronized getInstanceVar()</code> ?</p>
<p>Thanks in advance for your answers.</p>
| [
{
"answer_id": 309652,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": "instanceVar volatile setInstanceVar() synchronized private volatile int instanceVar =0;\n\npublic synchronized setInstanceVar() { instanceVar++;\n\n}\n"
},
{
"answer_id": 309670,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 1,
"selected": false,
"text": " synchronized increment()\n { \n i++\n }\n\n synchronized get()\n {\n return i;\n }\n synchronized int {\n increment\n return get()\n }\n"
},
{
"answer_id": 309677,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 5,
"selected": false,
"text": "synchronized synchronized synchronized this public synchronized void setInstanceVar() public void setInstanceVar() {\n synchronized(this) {\n instanceVar++;\n }\n}\n synchronized MyClass c = new MyClass();\nsynchronized(c) {\n ...\n}\n synchronized synchronized MyClass lock synchronized(...) public class MyClass {\n private int instanceVar;\n private final Object lock = new Object(); // must be final!\n\n public void setInstanceVar() {\n synchronized(lock) {\n instanceVar++;\n }\n }\n}\n java.util.concurrent.Lock java.util.concurrent.locks.ReentrantLock"
},
{
"answer_id": 309755,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "public class MyClass{\n private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();\n private int myValue = 0;\n\n public void setValue(){\n rwl.writeLock().lock();\n myValue++;\n rwl.writeLock().unlock();\n }\n\n public int getValue(){\n rwl.readLock.lock();\n int result = myValue;\n rwl.readLock.unlock();\n return result;\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39732/"
] |
309,638 | <p>How can I prevent the pocket PC device from shutting down from my application when the power button pressed? I am using C#.</p>
| [
{
"answer_id": 311892,
"author": "Jérôme Laban",
"author_id": 26346,
"author_profile": "https://Stackoverflow.com/users/26346",
"pm_score": 0,
"selected": false,
"text": " [DllImport(\"coredll\")]\n private extern static IntPtr SetPowerRequirement(string pvDevice, int deviceState, \n int deviceFlags, IntPtr pvSystemState, int stateFlags);\n\n [DllImport(\"coredll\")]\n private extern static int ReleasePowerRequirement(IntPtr handle);\n IntPtr handle = SetPowerRequirement(\"BLK1:\", 0 /* D0, Full On */, 1, IntPtr.Zero, 0);\n // Do something that requires the device to stay on ...\n ReleasePowerRequirement(handle);\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
309,639 | <p>The following questions are about XML serialization/deserialization and schema validation for a .net library of types which are to be used for data exchange.</p>
<hr>
<p>First question, if I have a custom xml namespace say "<a href="http://mydomain/mynamespace" rel="nofollow noreferrer">http://mydomain/mynamespace</a>" do I have to add a</p>
<pre><code>[XmlRoot(Namespace = "http://mydomain/mynamespace")]
</code></pre>
<p>to every class in my library. Or is there a way to define this namespace as default for the whole assembly?</p>
<hr>
<p>Second question, is there a reason behind the always added namespaces</p>
<pre><code>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
</code></pre>
<p>even if there is no actual reference to any of the namespaces? I just feel they add noise to the resulting xml. Is there a way to remove them an only have the custom namespace in the resulting xml?</p>
<hr>
<p>Third question, are there tools to support the generation of schema definitions (e.g. for all public [Serializable] classes of an assembly) and the validation of xml against specific schemas available?</p>
<p>If there are, would you recommend XML Schema from W3C or RELAX NG?</p>
| [
{
"answer_id": 310150,
"author": "david valentine",
"author_id": 36627,
"author_profile": "https://Stackoverflow.com/users/36627",
"pm_score": 0,
"selected": false,
"text": "xsd /c /n:myNamespace.Schema.v2_0 myschema_v2_0.xsd\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21566/"
] |
309,651 | <p>I'm new to development on the iPhone. Just about every sample project (as well as the default project templates) have one or more delegates and controllers. Can someone give me a breakdown of what the delegates are responsible for vs. what the controllers are supposed to do?</p>
| [
{
"answer_id": 310250,
"author": "wisequark",
"author_id": 33159,
"author_profile": "https://Stackoverflow.com/users/33159",
"pm_score": 2,
"selected": false,
"text": "UIApplication"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678/"
] |
309,668 | <p>Our web team has been asked to build some user interfaces in Sharepoint. The UI's would primarily be forms that would need to write to a SQL Server database.</p>
<p>Is ASP.NET the best way to do this? If so what's the best way to integrate the ASP.NET application into Sharepoint?</p>
| [
{
"answer_id": 309684,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 3,
"selected": true,
"text": "1. Build web parts \n2. build user controls , and use smart part to display them.\n3. use infopath \n4. host the asp.net in an iframe (page viewer web part).\n"
},
{
"answer_id": 317239,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 0,
"selected": false,
"text": "public class MyWebPart : WebPart\n{\n protected override OnInit(EventArgs e)\n {\n EnsureChildControls();\n base.OnInit(e);\n }\n\n override void CreateChildControls()\n {\n LoadControl(\"SomeUserControlAtSomePath.ascx\");\n base.CreateChildControls();\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67719/"
] |
309,674 | <p>I am looking for a good menu to use in an ASP.NET. I am currently using the asp menu. I need
it to work in IE 6,7,8, Firefox and Safari. I also need it to not add a lot of overhead to the page client-side. I need to be able to load it from the database.</p>
| [
{
"answer_id": 1010268,
"author": "CRice",
"author_id": 55693,
"author_profile": "https://Stackoverflow.com/users/55693",
"pm_score": 0,
"selected": false,
"text": " .HorizontalMenu_DynamicMenuStyle\n{\n font-family: Verdana;\n font-size: medium;\n background-color: #FCFCFC;\n border: solid 1px green;\n z-index: 100;\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5633/"
] |
309,675 | <p>I am creating an touch screen application using Swing and have a request to change one of buttons so that it will behave like a keyboard when the button is held down.<br>
(First of all, I am not sure that the touch screen will allow the user to "hold down" the button, but pretend that they can for now)</p>
<p>I was going to go down the path of starting a loop when <code>mousePressed</code> was called and then ending the loop when <code>mouseReleased</code> was called. This will involve starting a thread and having to deal with synchronization as well as <code>invokeLater()</code> to get events back on the <code>EventQueue</code>.</p>
<p>Is there a very simple way to do what I want? I hope I am just not seeing the API to do it.</p>
| [
{
"answer_id": 37165865,
"author": "Mike Lima",
"author_id": 6320298,
"author_profile": "https://Stackoverflow.com/users/6320298",
"pm_score": 0,
"selected": false,
"text": "import java.awt.Font;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\n\nimport javax.swing.Action;\nimport javax.swing.BorderFactory;\nimport javax.swing.JButton;\nimport javax.swing.SwingUtilities;\n\npublic class TypomaticButton extends JButton implements MouseListener {\n private boolean autotype = false;\n private static Thread theThread = null;\n private String myName = \"unknown\";\n private int \n speed = 150, \n wait = 300,\n decrement = (wait - speed) / 10; \n\n TypomaticButton(Action action){\n super(action);\n myName = action.getValue(Action.NAME).toString();\n addMouseListener(this);\n }\n\n TypomaticButton(String text){\n super(text);\n setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));\n\n myName = text;\n addMouseListener(this);\n }\n\n @Override\n public void mouseClicked(MouseEvent arg0) {}\n\n @Override\n public void mouseEntered(MouseEvent arg0) { }\n\n @Override\n public void mouseExited(MouseEvent arg0) { }\n\n @Override\n public void mousePressed(MouseEvent arg0) {\n autotype = true;\n theThread = new Thread(new Runnable() { // do it on a new thread so we don't block the UI thread\n @Override\n public void run() {\n for (int i = 10000; i > 0 && autotype; i--) { // don't go on for ever\n try {\n Thread.sleep(wait); // wait awhile\n } catch (InterruptedException e) {\n break;\n }\n if(wait != speed){\n wait = wait - decrement; // gradually accelerate to top speed\n if(wait < speed)\n wait = speed;\n }\n SwingUtilities.invokeLater(new Runnable() { // run this bit on the UI thread\n public void run() {\n if(!autotype) // it may have been stopped meanwhile\n return;\n ActionListener[] als = getActionListeners();\n for(ActionListener al : als){ // distribute to all listeners\n ActionEvent aevent = new ActionEvent(getClass(), 0, myName);\n al.actionPerformed(aevent);\n }\n }\n });\n }\n autotype = false;\n }\n });\n theThread.start();\n }\n\n @Override\n public void mouseReleased(MouseEvent arg0) {\n autotype = false;\n wait = 300;\n }\n\n void speed(int millisecs){\n speed = millisecs;\n decrement = (wait - speed) / 10; \n }\n\n void stop(){\n autotype = false;\n if(theThread != null){\n theThread.interrupt();\n }\n }\n\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8517/"
] |
309,680 | <p>I have the following code that creates two objects (ProfileManager and EmployerManager) where the object EmployerManager is supposed to inherit from the object ProfileManager.
However, when I do alert(pm instanceof ProfileManager); it returns false.</p>
<pre><code>function ProfileFactory(profileType) {
switch(profileType)
{
case 'employer':
return new EmployerManager();
break;
}
}
function ProfileManager() {
this.headerHTML = null;
this.contentHTML = null;
this.importantHTML = null;
this.controller = null;
this.actions = new Array();
this.anchors = new Array();
}
ProfileManager.prototype.loadData = function(action, dao_id, toggleBack) {
var step = this.actions.indexOf(action);
var prv_div = $('div_' + step - 1);
var nxt_div = $('div_' + step);
new Ajax.Request(this.controller, {
method: 'get',
parameters: {action : this.actions[step], dao_id : dao_id},
onSuccess: function(data) {
nxt_div.innerHTML = data.responseText;
if(step != 1 && !prv_div.empty()) {
prv_div.SlideUp();
}
nxt_div.SlideDown();
for(i = 1; i <= step; i++)
{
if($('step_anchor_' + i).innerHTML.empty())
{
$('step_anchor_' + i).innerHTML = this.anchors[i];
}
}
}
}
)
}
EmployerManager.prototype.superclass = ProfileManager;
function EmployerManager() {
this.superclass();
this.controller = 'eprofile.php';
this.anchors[1] = 'Industries';
this.anchors[2] = 'Employer Profiles';
this.anchors[3] = 'Employer Profile';
this.actions[1] = 'index';
this.actions[2] = 'employer_list';
this.actions[3] = 'employer_display';
}
var pm = new ProfileFactory('employer');
alert(pm instanceof ProfileManager);
</code></pre>
<p>BTW, this is my very first attempt at Object-Oriented JavaScript, so if you feel compelled to comment on the stupidity of my approach please feel free to do so, but offer suggestions on how to approach the problem better.</p>
| [
{
"answer_id": 311331,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 2,
"selected": true,
"text": "function EmployerManager() {\n\n this.controller = 'eprofile.php';\n this.anchors = new Array('Industries', 'Employer Profiles', 'Employer Profile');\n this.actions = new Array('index', 'employer_list', 'employer_display'); \n}\n\nEmployerManager.prototype = new ProfileManager;\n"
},
{
"answer_id": 29527542,
"author": "cuixiping",
"author_id": 988089,
"author_profile": "https://Stackoverflow.com/users/988089",
"pm_score": 0,
"selected": false,
"text": "function A(){\n B.call(this);\n}\nfunction B(){\n}\n\n//there are 2 ways to make instanceof works\n//1. use Object.create\nA.prototype = Object.create(B.prototype);\n//2. use new\n//A.prototype = new B();\n\nconsole.log(new A() instanceof B); //true\n\n//make instanceof works\nEmployerManager.prototype = Object.create(ProfileManager.prototype);\n//add other prototype memebers\nEmployerManager.prototype.superclass = ProfileManager;\n\nconsole.log(new EmployerManager() instanceof ProfileManager); //true\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178/"
] |
309,682 | <p>I'm writing a HTML form that's divided in fieldsets, and I need to get the form fields from a specific fiedset in a function.<br>
Currently it's like this: </p>
<pre><code>function conta(Fieldset){
var Inputs = Fieldset.getElementsByTagName("input");
var Selects = Fieldset.getElementsByTagName("select");
/* Doing the stuff I need to do in two iterations, one for each field type */
}
</code></pre>
<p>But who knows what the future may hold, and if the form gets some new field types (radios, checkboxes) this could become awful to mantain.<br>
I know that <code>form</code> elements have the <code>elements</code> attribute that returns all the form fields and I was hoping I could use something like that.<br>
(I know I still gotta discriminate the field type in a bunch of conditionals inside the iteration, but I think it would be faster and easier to keep. Unless it isn't and I should not be doing it)</p>
| [
{
"answer_id": 309691,
"author": "Ryan Eastabrook",
"author_id": 105,
"author_profile": "https://Stackoverflow.com/users/105",
"pm_score": 0,
"selected": false,
"text": "//$(\"input select textarea\").each(function() {\n$(\":input\").each(function() { //even better\n // do stuff here\n});\n"
},
{
"answer_id": 309702,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "$('fieldset#fieldset1 > input[type=text]').each( function() {\n ... do something for text inputs }\n );\n\n$('fieldset#fieldset1 > input[type=radio]').each( function() {\n ... do something for radios }\n );\n\n$('fieldset#fieldset1 > select').each( function() {\n ... do something for selects }\n );\n\n$('fieldset#fieldset1 > textarea').each( function() {\n ... do something for textareas }\n );\n"
},
{
"answer_id": 1327122,
"author": "Filip Dupanović",
"author_id": 44041,
"author_profile": "https://Stackoverflow.com/users/44041",
"pm_score": 1,
"selected": false,
"text": "function condat(fieldset) {\n var tagNames = ['input', 'select', 'textarea']; // Insert other tag names here\n var elements = [];\n\n for (var i in tagNames)\n elements.concat(fieldset.getElementsByTagName(tagNames[i]);\n\n for (var i in elements) {\n // Do what you want\n }\n}\n"
},
{
"answer_id": 47070013,
"author": "N. Maks",
"author_id": 6912069,
"author_profile": "https://Stackoverflow.com/users/6912069",
"pm_score": 1,
"selected": false,
"text": "function condat(fieldset) {\n var tagNames = ['input', 'select', 'textarea']; // Insert other tag names here\n var elements = [];\n\n for (var i in tagNames) {\n elements = elements.concat([].slice.call(fieldset.getElementsByTagName(tagNames[i])));\n }\n for (var i in elements) {\n // Do what you want.\n // Attributes of the selected tag's can be referenced for example as \n // elements[i].value = ...;\n }\n}\n elements[i].value = elements[i].defaultValue; //do what you want"
},
{
"answer_id": 47070193,
"author": "segu",
"author_id": 4937433,
"author_profile": "https://Stackoverflow.com/users/4937433",
"pm_score": 0,
"selected": false,
"text": "function condat(fieldset) {\n var elements = fieldset.querySelectorAll('input, select, textarea');\n elements.forEach(function(element){\n // Do what you want with every element\n });\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9835/"
] |
309,683 | <p>I have a page with a few fields and a runtime-generated image on it. The contents of this page are inside an UpdatePanel. There is a button to take the user to a secondary page, which has a button that calls javascript:history.go(-1) when clicked.</p>
<p>The problem is, the first page does a full request instead of a postback or just using the state it was in before navigating away from it. That is, the fields are all reset to their default values, thereby confusing the user. I'd like their values to be retained regardless of navigation. I do not want to create a new history state for every field change.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 309691,
"author": "Ryan Eastabrook",
"author_id": 105,
"author_profile": "https://Stackoverflow.com/users/105",
"pm_score": 0,
"selected": false,
"text": "//$(\"input select textarea\").each(function() {\n$(\":input\").each(function() { //even better\n // do stuff here\n});\n"
},
{
"answer_id": 309702,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "$('fieldset#fieldset1 > input[type=text]').each( function() {\n ... do something for text inputs }\n );\n\n$('fieldset#fieldset1 > input[type=radio]').each( function() {\n ... do something for radios }\n );\n\n$('fieldset#fieldset1 > select').each( function() {\n ... do something for selects }\n );\n\n$('fieldset#fieldset1 > textarea').each( function() {\n ... do something for textareas }\n );\n"
},
{
"answer_id": 1327122,
"author": "Filip Dupanović",
"author_id": 44041,
"author_profile": "https://Stackoverflow.com/users/44041",
"pm_score": 1,
"selected": false,
"text": "function condat(fieldset) {\n var tagNames = ['input', 'select', 'textarea']; // Insert other tag names here\n var elements = [];\n\n for (var i in tagNames)\n elements.concat(fieldset.getElementsByTagName(tagNames[i]);\n\n for (var i in elements) {\n // Do what you want\n }\n}\n"
},
{
"answer_id": 47070013,
"author": "N. Maks",
"author_id": 6912069,
"author_profile": "https://Stackoverflow.com/users/6912069",
"pm_score": 1,
"selected": false,
"text": "function condat(fieldset) {\n var tagNames = ['input', 'select', 'textarea']; // Insert other tag names here\n var elements = [];\n\n for (var i in tagNames) {\n elements = elements.concat([].slice.call(fieldset.getElementsByTagName(tagNames[i])));\n }\n for (var i in elements) {\n // Do what you want.\n // Attributes of the selected tag's can be referenced for example as \n // elements[i].value = ...;\n }\n}\n elements[i].value = elements[i].defaultValue; //do what you want"
},
{
"answer_id": 47070193,
"author": "segu",
"author_id": 4937433,
"author_profile": "https://Stackoverflow.com/users/4937433",
"pm_score": 0,
"selected": false,
"text": "function condat(fieldset) {\n var elements = fieldset.querySelectorAll('input, select, textarea');\n elements.forEach(function(element){\n // Do what you want with every element\n });\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
309,706 | <p>So i'm not really sure why this is happening but I'm running through some DataRows where I have the control name, property, and value that I want to set. Everything works fine except when I set the TEXT property of a button. For some reason, the click event is called...</p>
<p>Here's some of the code I've got:</p>
<pre><code>string controlName, value, property;
Control currentControl = null;
System.Reflection.PropertyInfo propertyInfo = null;
// run through all rows in the table and set the property
foreach (DataRow r in languageDataset.Tables[_parentForm.Name].Rows)
{
controlName = r["ControlName"].ToString().ToUpper();
value = r["Value"].ToString();
property = r["Property"].ToString();
// check all controls on the form
foreach (Control c in formControls)
{
// only change it if its the right control
if (c.Name.ToUpper() == controlName)
{
propertyInfo = c.GetType().GetProperty(property);
if (propertyInfo != null)
propertyInfo.SetValue(c, value, null); ******Calls Event Handler?!?!******
//
currentControl = c;
break;
}
}
}
</code></pre>
<p>So why in the world would it call the event handler when setting the value? Here's what I'm setting it with that's causing this:</p>
<pre><code><SnappletChangePassword>
<ControlName>buttonAcceptPassword</ControlName>
<Property>Text</Property>
<Value>Accept</Value>
</SnappletChangePassword>
</code></pre>
| [
{
"answer_id": 309766,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "using System;\nusing System.Drawing;\nusing System.Reflection;\nusing System.Windows.Forms;\n\nclass Test\n{\n static void Main()\n {\n Button goButton = new Button { \n Text = \"Go!\",\n Location = new Point(5, 5)\n };\n\n Button targetButton = new Button {\n Text = \"Target\",\n Location = new Point(5, 50)\n };\n goButton.Click += (sender, args) => SetProperty(targetButton, \"Text\", \"Changed\");\n targetButton.Click += (sender, args) => MessageBox.Show(\"Target clicked!\");\n\n Form f = new Form { Width = 200, Height = 120,\n Controls = { goButton, targetButton }\n };\n Application.Run(f);\n }\n\n private static void SetProperty(object target, string propertyName, object value)\n {\n PropertyInfo property = target.GetType().GetProperty(propertyName);\n property.SetValue(target, value, null);\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21828/"
] |
309,713 | <p>I'm using a Flash TextField control to display some HTML content inside a Flash presentation to be shown on a large touch-screen kiosk. Unfortunately, if any image tag in the displayed HTML content points to a non-existent image, a dialogue is shown with the error message </p>
<pre><code>Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
</code></pre>
<p>I am trying to avoid having that dialogue pop up. The <a href="http://www.kirupa.com/forum/showthread.php?t=287501" rel="nofollow noreferrer">solution</a> for loading content through a loader class is to catch <code>IOErrorEvent.IO_ERROR</code>, but I've tried listening for that on the TextField, on stage, Main and loaderInfo to no avail. I've tried wrapping the whole thing in a try-catch, and that also doesn't work.</p>
<p>Here's the simplified code I'm using to find solutions:</p>
<pre><code>package {
import flash.display.Sprite;
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
public class Main extends Sprite {
public function Main():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
var html:TextField = new TextField();
html.type = TextFieldType.DYNAMIC;
html.multiline = true;
html.htmlText = "Bogus image: <img src=\"foo.jpg\" />";
addChild(html);
}
}
}
</code></pre>
<p><strong>Edit: And here's the entire working code.</strong></p>
<p>For dynamic content and so forth, of course, you would need a list of images and a function to generate handlers, etc.</p>
<pre><code>package {
import flash.display.Loader;
import flash.display.Sprite;
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
public class Main extends Sprite {
public function Main():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
var html:TextField = new TextField();
html.type = TextFieldType.DYNAMIC;
html.multiline = true;
html.htmlText = "Bogus image: <img id=\"image\" src=\"foo.jpg\" />";
var loader:Loader = html.getImageReference("image") as Loader;
if(loader){
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:Event):void {
trace("Error loading foo.jpg!");
});
}
addChild(html);
}
}
}
</code></pre>
| [
{
"answer_id": 329881,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": -1,
"selected": false,
"text": "stage.addEventListener(IOError.IO_ERROR, myErrorHandler);\n"
},
{
"answer_id": 917971,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "html.htmlText = \"Bogus image: <img src=\\\"foo.jpg\\\" id=\"image\" />\"; \n var loader:Loader = html.getImageReference(\"image\") as Loader;\nif(loader){\n loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:Event):void{});\n}\n"
},
{
"answer_id": 7854328,
"author": "ganesh",
"author_id": 1007741,
"author_profile": "https://Stackoverflow.com/users/1007741",
"pm_score": 1,
"selected": false,
"text": " var html:TextField = new TextField();\n html.width=388.95;\n html.height=400;\n html.type = TextFieldType.DYNAMIC;\n html.multiline = true;\n html.htmlText = \"Bogus image: <img id='image' src='foo.jpg'/>\"; \n var loader:Loader = html.getImageReference(\"image\") as Loader;\nloader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHan);\nfunction completeHan(e:Event){\n addChild(html);\n}\n\nThis will work..\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7526/"
] |
309,723 | <p>Is there a way to view the list of <em>recent documents</em> you've opened in Vim?</p>
<p>I realize I could view the cursor <em>jump list</em>, <code>:ju</code>, and then go to a cursor position in the list but this is not ideal because there will be multiple listings of the same document in the list.</p>
<p>Is there another command which would do what I'm looking for?</p>
| [
{
"answer_id": 4633847,
"author": "Alex Bolotov",
"author_id": 66473,
"author_profile": "https://Stackoverflow.com/users/66473",
"pm_score": 9,
"selected": true,
"text": ":help old :ol[dfiles]\n '0 '1 '2 '9 viminfo :bro[wse] ol[dfiles][!]\n :oldfiles !"
},
{
"answer_id": 47565251,
"author": "ZHOU Ling",
"author_id": 4505813,
"author_profile": "https://Stackoverflow.com/users/4505813",
"pm_score": 2,
"selected": false,
"text": "\" ------------------------------- minibufexpl mappings -----------------------------------\n\"let g:miniBufExplSplitBelow=1\nnnoremap <silent> <leader>bn :bn<cr>\nnnoremap <silent> <leader>bp :bp<cr>\nnnoremap <silent> <leader>bf :bf<cr>\nnnoremap <silent> <leader>bl :bl<cr>\nnnoremap <silent> <leader>bt :TMiniBufExplorer<cr>\n"
},
{
"answer_id": 48198198,
"author": "shmup",
"author_id": 463678,
"author_profile": "https://Stackoverflow.com/users/463678",
"pm_score": 2,
"selected": false,
"text": "oldfiles"
},
{
"answer_id": 50344355,
"author": "Hope",
"author_id": 4600536,
"author_profile": "https://Stackoverflow.com/users/4600536",
"pm_score": 2,
"selected": false,
"text": ":Denite file_old Enter nnoremap <leader>o :Denite<space>file_old<CR>\n :browse oldfiles q 1 Enter"
},
{
"answer_id": 50558960,
"author": "user1338062",
"author_id": 1338062,
"author_profile": "https://Stackoverflow.com/users/1338062",
"pm_score": 5,
"selected": false,
"text": ":oldfiles :History"
},
{
"answer_id": 53569017,
"author": "Edman",
"author_id": 9506867,
"author_profile": "https://Stackoverflow.com/users/9506867",
"pm_score": 0,
"selected": false,
"text": "let g:netrw_sort_by = 'time'\n\nlet g:netrw_sort_direction = 'r'\n cd ~/vim\n"
},
{
"answer_id": 67217747,
"author": "Ahmad",
"author_id": 2651073,
"author_profile": "https://Stackoverflow.com/users/2651073",
"pm_score": 0,
"selected": false,
"text": "aliases alias vil='vim -c \"normal! '\\''0\"' # open the last file\nalias vil1='vim -c \"normal! '\\''1\"' # open the second last file ...\nalias vil2='vim -c \"normal! '\\''2\"'\n"
},
{
"answer_id": 70445176,
"author": "ken",
"author_id": 2701130,
"author_profile": "https://Stackoverflow.com/users/2701130",
"pm_score": 0,
"selected": false,
"text": ":ol :CtrlPMRU"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16973/"
] |
309,734 | <p>I need to be able to take an arbitrary text input that may have a byte order marker (BOM) on it to mark its encoding, and output it as ASCII. We have some old tools that don't understand BOM's and I need to send them ASCII-only data.</p>
<p>Now, I just got done writing this code and I just can't quite believe the inefficiency here. Four copies of the data, not to mention any intermediate buffers internally in StreamReader. Is there a better way to do this?</p>
<pre><code>// i_fileBytes is an incoming byte[]
string unicodeString = new StreamReader(new MemoryStream(i_fileBytes)).ReadToEnd();
byte[] unicodeBytes = Encoding.Unicode.GetBytes(unicodeString.ToCharArray());
byte[] ansiBytes = Encoding.Convert(Encoding.Unicode, Encoding.ASCII, unicodeBytes);
string ansiString = Encoding.ASCII.GetString(ansiBytes);
</code></pre>
<p>I need the StreamReader() because it has an internal BOM detector to choose the encoding to read the rest of the file. Then the rest is just to make it convert into the final ASCII string.</p>
<p>Is there a better way to do this?</p>
| [
{
"answer_id": 309791,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": true,
"text": "Encoding.Unicode.GetString int start = (i_fileBytes[0] == 0xff && i_fileBytes[1] == 0xfe) ? 2 : 0;\nstring text = Encoding.Unicode.GetString(i_fileBytes, start, i_fileBytes.Length-start);\n Read() ReadToEnd()"
},
{
"answer_id": 3347509,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 0,
"selected": false,
"text": "System.Text.Encoding.ASCII.GetBytes(new StreamReader(new MemoryStream(i_fileBytes)).ReadToEnd())\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14582/"
] |
309,737 | <p>I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:</p>
<pre><code>import org.apache.commons.lang.builder.EqualsBuilder;
public class Foo {
public class Bar {
private Bar() {}
public Foo getMyFoo() {
return Foo.this
}
private int myInt = 0;
public boolean equals(Object o) {
if (o == null || o.getClass() != getClass) return false;
Bar other = (Bar) o;
return new EqualsBuilder()
.append(getMyFoo(), other.getMyFoo())
.append(myInt, other.myInt)
.isEquals();
}
}
public Bar createBar(...) {
//sensible implementation
}
public Bar createOtherBar(...) {
//another implementation
}
public boolean equals(Object o) {
//sensible equals implementation
}
}
</code></pre>
<p>Is there syntax by which I can refer to <code>other</code>'s <code>Foo</code> reference apart from declaring the <code>getMyFoo()</code> method? Something like <code>other.Foo.this</code> (which doesn't work)?</p>
| [
{
"answer_id": 309891,
"author": "p3t0r",
"author_id": 16685,
"author_profile": "https://Stackoverflow.com/users/16685",
"pm_score": 2,
"selected": false,
"text": "public class Foo {\n\n public Bar createBar(){\n Bar bar = new Bar(this)\n return bar;\n }\n}\n\npublic class Bar {\n Foo foo;\n public Bar(Foo foo){\n this.foo = foo;\n }\n\n public boolean equals(Object other) {\n return foo.equals(other.foo);\n }\n}\n"
},
{
"answer_id": 309896,
"author": "Ray Tayek",
"author_id": 51292,
"author_profile": "https://Stackoverflow.com/users/51292",
"pm_score": -1,
"selected": false,
"text": "public class Foo {\n public class Bar {\n public Foo getMyFoo() {\n return Foo.this;\n }\n }\n public Foo foo(Bar bar) {\n return bar.getMyFoo();\n }\n public static void main(String[] arguments) {\n Foo foo1=new Foo();\n Bar bar1=foo1.new Bar();\n Foo foo=(new Foo()).foo(bar1);\n System.out.println(foo==foo1);\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/390636/"
] |
309,740 | <p>I read about this ages ago but never tried it now I can't remember if this is possible or not. Is it possible to extend a class from two parents on php5 e.g.</p>
<p>class_d extends class_c and class_b</p>
<p>moreover can you do this if class_c and class_b are themselves extended from class_a ... so you get something like this</p>
<pre><code> class_a
class_b class_c
class_d
</code></pre>
| [
{
"answer_id": 309891,
"author": "p3t0r",
"author_id": 16685,
"author_profile": "https://Stackoverflow.com/users/16685",
"pm_score": 2,
"selected": false,
"text": "public class Foo {\n\n public Bar createBar(){\n Bar bar = new Bar(this)\n return bar;\n }\n}\n\npublic class Bar {\n Foo foo;\n public Bar(Foo foo){\n this.foo = foo;\n }\n\n public boolean equals(Object other) {\n return foo.equals(other.foo);\n }\n}\n"
},
{
"answer_id": 309896,
"author": "Ray Tayek",
"author_id": 51292,
"author_profile": "https://Stackoverflow.com/users/51292",
"pm_score": -1,
"selected": false,
"text": "public class Foo {\n public class Bar {\n public Foo getMyFoo() {\n return Foo.this;\n }\n }\n public Foo foo(Bar bar) {\n return bar.getMyFoo();\n }\n public static void main(String[] arguments) {\n Foo foo1=new Foo();\n Bar bar1=foo1.new Bar();\n Foo foo=(new Foo()).foo(bar1);\n System.out.println(foo==foo1);\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
309,744 | <p>Is there a basic php method that accepts a URL and retrieves the date last modified from the header? </p>
<p>It would seem like something php can do, but I'm not sure which object to check.</p>
<p>Thanks</p>
| [
{
"answer_id": 309770,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "$c = curl_init('http://...');\ncurl_setopt($c, CURLOPT_HEADER, 1); // Include the header\ncurl_setopt($c, CURLOPT_RETURNTRANSFER, 1); // Return the result instead of printing it\n$result = curl_exec($c);\n\nif (curl_errno($c))\n die(curl_error($c));\n\n// $result now contains the response, including the headers\n\nif (preg_match('/Last-Modified:(.*?)/i', $result, $matches))\n var_dump($matches[1]);\n"
},
{
"answer_id": 309914,
"author": "AndreLiem",
"author_id": 26577,
"author_profile": "https://Stackoverflow.com/users/26577",
"pm_score": 1,
"selected": false,
"text": "$c = curl_init('http://...'); \ncurl_setopt($c, CURLOPT_HEADER, 1); // Include the header \ncurl_setopt($c, CURLOPT_RETURNTRANSFER, 1);\ncurl_setopt($c, CURLOPT_FILETIME, 1); \ncurl_exec($c);\n$result = curl_getinfo($c); \n\nif (curl_errno($c))\n die(curl_error($c));\n\necho date('G:i M jS \\'y',(int)$result['filetime']);\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26577/"
] |
309,745 | <p>How do I check to see if a variable is a number, or contains a number, in UNIX shell?</p>
| [
{
"answer_id": 309789,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 4,
"selected": false,
"text": "test if [ $var -eq $var 2> /dev/null ]; then ...\n"
},
{
"answer_id": 309804,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": false,
"text": "if echo $var | egrep -q '^[0-9]+$'; then\n # $var is a number\nelse\n # $var is not a number\nfi\n"
},
{
"answer_id": 309822,
"author": "Darron",
"author_id": 22704,
"author_profile": "https://Stackoverflow.com/users/22704",
"pm_score": 3,
"selected": false,
"text": "if [[ $var == +([0-9]) ]]; then ...\n"
},
{
"answer_id": 16440294,
"author": "Wasim",
"author_id": 2362237,
"author_profile": "https://Stackoverflow.com/users/2362237",
"pm_score": 2,
"selected": false,
"text": " ### \n echo $var|egrep '^[0-9]+$'\n if [ $? -eq 0 ]; then\n echo \"$var is a number\"\n else\n echo \"$var is not a number\"\n fi\n"
},
{
"answer_id": 16443779,
"author": "Norman Gray",
"author_id": 375147,
"author_profile": "https://Stackoverflow.com/users/375147",
"pm_score": 2,
"selected": false,
"text": "sh grep if expr \"$var\" : '[0-9][0-9]*$'>/dev/null; then\n echo yes\nelse\n echo no\nfi\n $var expr"
},
{
"answer_id": 16444570,
"author": "Jens",
"author_id": 648658,
"author_profile": "https://Stackoverflow.com/users/648658",
"pm_score": 4,
"selected": false,
"text": "case $var in\n (*[!0-9]*|'') echo not a number;;\n (*) echo a number;;\nesac\n - + case ${var#[-+]} in\n (*[!0-9]*|'') echo not a number;;\n (*) echo a number;;\nesac\n"
},
{
"answer_id": 19140349,
"author": "petie",
"author_id": 2839229,
"author_profile": "https://Stackoverflow.com/users/2839229",
"pm_score": -1,
"selected": false,
"text": "a=123\nif [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ]\nthen\n echo numeric\nelse\n echo ng\nfi\n a=12s3\nif [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ]\nthen\n echo numeric\nelse\n echo ng\nfi\n"
},
{
"answer_id": 21899585,
"author": "Johnney Jung",
"author_id": 3331315,
"author_profile": "https://Stackoverflow.com/users/3331315",
"pm_score": 2,
"selected": false,
"text": "if [ $var -ge 0 2>/dev/null ] ; then ...\n"
},
{
"answer_id": 23673539,
"author": "Vouze",
"author_id": 2165806,
"author_profile": "https://Stackoverflow.com/users/2165806",
"pm_score": 0,
"selected": false,
"text": "if echo $var | egrep -q '^[0-9]+$'\n var=\"123\nqwer\"\n var=`cat var.txt`\n if [ \"$var\" -eq \"$var\" ] 2> /dev/null\nthen echo yes\nelse echo no\nfi\n"
},
{
"answer_id": 23679244,
"author": "Sriharsha Kalluru",
"author_id": 1005707,
"author_profile": "https://Stackoverflow.com/users/1005707",
"pm_score": -1,
"selected": false,
"text": "$ test ab -eq 1 >/dev/null 2>&1\n$ echo $?\n2\n\n$ test 21 -eq 1 >/dev/null 2>&1\n$ echo $?\n1\n\n$ test 1 -eq 1 >/dev/null 2>&1\n$ echo $?\n0\n"
},
{
"answer_id": 24459805,
"author": "khitron",
"author_id": 3784510,
"author_profile": "https://Stackoverflow.com/users/3784510",
"pm_score": 0,
"selected": false,
"text": "if ( \"$*\" == \"0\" ) then\n exit 0 # number\nelse\n ((echo \"$*\" | bc) > /tmp/tmp.txt) >& /dev/null\n set tmp = `cat /tmp/tmp.txt`\n rm -f /tmp/tmp/txt\n if ( \"$tmp\" == \"\" || $tmp == 0 ) then\n exit 1 # not a number\n else\n exit 0 # number\n endif\n\nendif\n chmod +x checknumber\n checknumber -3.45\n"
},
{
"answer_id": 32886426,
"author": "Oguz",
"author_id": 5260150,
"author_profile": "https://Stackoverflow.com/users/5260150",
"pm_score": 1,
"selected": false,
"text": "if echo \"$var\" | egrep -q '^\\-?[0-9]+$'; then \n echo \"$var is an integer\"\nelse \n echo \"$var is not an integer\"\nfi\n 2 is an integer\n-2 is an integer\n2.5 is not an integer \n2b is not an integer\n if echo \"$var\" | egrep -q '^\\-?[0-9]*\\.?[0-9]+$'; then \n echo \"$var is a number\"\nelse \n echo \"$var is not a number\"\nfi\n 2 is a number\n-2 is a number\n-2.6 is a number\n-2.c6 is not a number\n2. is not a number\n2.0 is a number\n"
},
{
"answer_id": 34891288,
"author": "Pritam Chatterjee",
"author_id": 5813754,
"author_profile": "https://Stackoverflow.com/users/5813754",
"pm_score": -1,
"selected": false,
"text": "NUMBER=$1\n\n IsDecimal=`echo \"$NUMBER\" | grep \"\\.\"`\n\nif [ -n \"$IsDecimal\" ]\nthen\n echo \"$NUMBER is Decimal\"\n var1=`echo \"$NUMBER\" | cut -d\".\" -f1`\n var2=`echo \"$NUMBER\" | cut -d\".\" -f2`\n\n Digit1=`echo \"$var1\" | egrep '^-[0-9]+$'`\n Digit2=`echo \"$var1\" | egrep '^[0-9]+$'`\n Digit3=`echo \"$var2\" | egrep '^[0-9]+$'`\n\n\n if [ -n \"$Digit1\" ] && [ -n \"$Digit3\" ]\n then\n echo \"$NUMBER is a number\"\n elif [ -n \"$Digit2\" ] && [ -n \"$Digit3\" ]\n then\n echo \"$NUMBER is a number\"\n\n else\n echo \"$NUMBER is not a number\"\n fi\nelse\n echo \"$NUMBER is not Decimal\"\n\n Digit1=`echo \"$NUMBER\" | egrep '^-[0-9]+$'`\n Digit2=`echo \"$NUMBER\" | egrep '^[0-9]+$'`\n\n if [ -n \"$Digit1\" ] || [ -n \"$Digit2\" ]; then\n echo \"$NUMBER is a number\"\n else\n echo \"$NUMBER is not a number\"\n fi\nfi\n"
},
{
"answer_id": 47684324,
"author": "cab404",
"author_id": 4444055,
"author_profile": "https://Stackoverflow.com/users/4444055",
"pm_score": 0,
"selected": false,
"text": "( test ! -z \"$num\" && test \"$num\" -eq \"$num\" 2> /dev/null ) && {\n # $num is a number\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
309,769 | <p>What's the most common way to deal with a series of block elements that need to be on a line (if javascript needs to be able to modify their widths, for example)? What are the pros and cons to applying float:left to each of them vs. using positioning to place them?</p>
| [
{
"answer_id": 310435,
"author": "Darko",
"author_id": 32943,
"author_profile": "https://Stackoverflow.com/users/32943",
"pm_score": 3,
"selected": true,
"text": "<div id=\"con\">\n <div class=\"float\"></div>\n <div class=\"float\"></div>\n</div>\n #con { background:#f0f; }\n.float { float:left; width:100px; height:100px; background:#0ff; }\n #con { background:#f0f; overflow:hidden; }\n"
},
{
"answer_id": 310484,
"author": "Gabe",
"author_id": 9835,
"author_profile": "https://Stackoverflow.com/users/9835",
"pm_score": 3,
"selected": false,
"text": "display:inline-block;\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32771/"
] |
309,775 | <p>I want to design a class that will parse a string into tokens that are meaningful to my application.</p>
<p>How do I design it?</p>
<ol>
<li>Provide a ctor that accepts a string, provide a Parse method and provide methods (let's call them "minor") that return individual tokens, count of tokens etc. OR</li>
<li>Provide a ctor that accepts nothing, provide a Parse method that accepts a string and minor methods as above. OR</li>
<li>Provide a ctor that accepts a string and provide only minor methods but no parse method. The parsing is done by the ctor.</li>
</ol>
<p>1 and 2 have the disadvantage that the user may call minor methods without calling the Parse method. I'll have to check in every minor method that the Parse method was called.</p>
<p>The problem I see in 3 is that the parse method may potentially do a lot of things. It just doesn't seem right to put it in the ctor.</p>
<p>2 is convenient in that the user may parse any number of strings without instantiating the class again and again.</p>
<p>What's a good approach? What are some of the considerations?</p>
<p>(the language is c#, if someone cares).</p>
<p>Thanks</p>
| [
{
"answer_id": 309806,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 2,
"selected": false,
"text": "ValueObject values = parsingClass.Parse(theString);\n"
},
{
"answer_id": 309937,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 0,
"selected": false,
"text": "// Using option 3\nParsingClass myClass = new ParsingClass(inputString);\n\n// Parse a new string.\nmyClass = new ParsingClass(anotherInputString);\n\n// Using option 2\nParsingClass myClass = new ParsingClass();\nmyClass.Parse(inputString);\n\n// Parse a new string.\nmyClass.Parse(anotherInputString);\n // Option 4\nParsingClass myClass = ParsingClass.Parse(inputString);\n\n// Parse a new string.\nmyClass = ParsingClass.Parse(anotherInputString);\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
309,786 | <p>How do I force Postgres to use an index when it would otherwise insist on doing a sequential scan?</p>
| [
{
"answer_id": 309814,
"author": "Patryk Kordylewski",
"author_id": 30927,
"author_profile": "https://Stackoverflow.com/users/30927",
"pm_score": 7,
"selected": false,
"text": "enable_seqscan enable_indexscan enable_ enable_"
},
{
"answer_id": 13409114,
"author": "Niraj Bhawnani",
"author_id": 1810915,
"author_profile": "https://Stackoverflow.com/users/1810915",
"pm_score": 7,
"selected": false,
"text": "set enable_seqscan=false\n"
},
{
"answer_id": 30859337,
"author": "Ezequiel Tolnay",
"author_id": 3886053,
"author_profile": "https://Stackoverflow.com/users/3886053",
"pm_score": 5,
"selected": false,
"text": "SELECT client_id, SUM(amount)\nFROM transactions\nWHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND\n description = 'Refund'\nGROUP BY client_id\n SELECT client_id, SUM(amount)\nFROM transactions\nWHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND\n description||'' = 'Refund'\nGROUP BY client_id\n"
},
{
"answer_id": 46964102,
"author": "Antony Gibbs",
"author_id": 2250843,
"author_profile": "https://Stackoverflow.com/users/2250843",
"pm_score": 2,
"selected": false,
"text": "OFFSET 0"
},
{
"answer_id": 52833441,
"author": "emkey08",
"author_id": 1070129,
"author_profile": "https://Stackoverflow.com/users/1070129",
"pm_score": 5,
"selected": false,
"text": "ANALYZE;\nSET random_page_cost = 1.0;\nSET effective_cache_size = 'X GB'; # replace X with total RAM size minus 2 GB\n ANALYZE; random_page_cost 4.0 random_page_cost 1.1 random_page_cost 1.1 random_page_cost 1.0 1.0 random_page_cost SET random_page_cost = 1.0;\n effective_cache_size 4 GB effective_cache_size SET effective_cache_size = '14 GB'; # e.g. on a dedicated server with 16 GB RAM\n ALTER SYSTEM SET ... ALTER DATABASE db_name SET ..."
},
{
"answer_id": 66444534,
"author": "emu",
"author_id": 797845,
"author_profile": "https://Stackoverflow.com/users/797845",
"pm_score": 0,
"selected": false,
"text": "gin select *\nfrom address\nnatural join city\nnatural join restaurant\nwhere st_within(address.location, restaurant.delivery_area)\nand restaurant.delivery_area ~ address.location\n st_within(address.location, restaurant.delivery_area) (restaurant.delivery_area ~ address.location) AND _st_contains(restaurant.delivery_area, address.location) restaurant.delivery_area ~ address.location address.location"
},
{
"answer_id": 67882997,
"author": "Hasan Tuncay",
"author_id": 1033919,
"author_profile": "https://Stackoverflow.com/users/1033919",
"pm_score": 1,
"selected": false,
"text": "create table customer(id numeric(10), age int, phone varchar(200))\n select * from customer where phone = '1235' and age+1 = 24 \n select * from customer where phone = '1235' and age::varchar = '23'\n select * from customer (index idx_phone) where phone = '1235' and age = 23.\n"
},
{
"answer_id": 68306041,
"author": "Vesanto",
"author_id": 2816941,
"author_profile": "https://Stackoverflow.com/users/2816941",
"pm_score": 3,
"selected": false,
"text": "VACUUM ANALYZE schema.table;\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91385/"
] |
309,790 | <p>In Java, what is the difference between the twin methods?</p>
<pre><code>public void methodA() throws AnException {
//do something
throw new AnException();
}
public void methodA() {
//do the same thing
throw new AnException();
}
</code></pre>
<p>I have a intuition that it has something to do with being a well-designed method (because I put methodA in an interface, declared it the way methodA* does in its implementation and received a warning from Java that "A* cannot override A because A* doesn't throw AnException"). </p>
<p>Is this speculation correct? </p>
<p>Is there any other subtle connotations in the two ways of doing things?</p>
| [
{
"answer_id": 671252,
"author": "Yuval",
"author_id": 2819,
"author_profile": "https://Stackoverflow.com/users/2819",
"pm_score": 2,
"selected": false,
"text": "public abstract class AbstractBox {\n public abstract void addItem(Item newItem);\n public abstract void removeItem(Item oldItem);\n}\n public class MyBox extends AbstractBox {\n public void addItem(Item newItem) throws ItemAlreadyPresentException {...}\n public void removeItem(Item oldItem) throws NoSuchItemException {...}\n}\n public void boxHandler(AbstractBox box) {\n Item item = new Item();\n box.removeItem(item);\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8203/"
] |
309,802 | <p>Is there any way to set an event handler without doing it manually in the classname.designer.cs file other than double clicking the UI element?</p>
| [
{
"answer_id": 309807,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 2,
"selected": false,
"text": "myButton.Click += myHandler;\n myButton.Click += delegate\n{\n MessageBox.Show(\"Clicked!\");\n};\n"
},
{
"answer_id": 309810,
"author": "Dan C.",
"author_id": 26391,
"author_profile": "https://Stackoverflow.com/users/26391",
"pm_score": 1,
"selected": false,
"text": "myControl.Event += new EventHandler(SomeHandlerMethodInYourClass)"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2184/"
] |
309,815 | <p>How do you control the column width in a gridview control in ASP.NET 2.0?</p>
| [
{
"answer_id": 309863,
"author": "DCNYAM",
"author_id": 30419,
"author_profile": "https://Stackoverflow.com/users/30419",
"pm_score": 2,
"selected": false,
"text": "<asp:BoundField HeaderText=\"Name\" DataField=\"LastName\">\n <HeaderStyle Width=\"20em\" />\n</asp:BoundField>\n"
},
{
"answer_id": 546134,
"author": "achinda99",
"author_id": 60824,
"author_profile": "https://Stackoverflow.com/users/60824",
"pm_score": 3,
"selected": false,
"text": " <asp:GridView ID=\"GridView1\" runat=\"server\">\n <HeaderStyle Width=\"10%\" />\n <RowStyle Width=\"10%\" />\n <FooterStyle Width=\"10%\" />\n <Columns>\n <asp:BoundField HeaderText=\"Name\" DataField=\"LastName\" \n HeaderStyle-Width=\"10%\" ItemStyle-Width=\"10%\"\n FooterStyle-Width=\"10%\" />\n </Columns>\n </asp:GridView>\n"
},
{
"answer_id": 9215193,
"author": "dProvencher",
"author_id": 1200192,
"author_profile": "https://Stackoverflow.com/users/1200192",
"pm_score": 2,
"selected": false,
"text": "columnName.ItemStyle.Width = Unit.Percentage(someDouble);\n"
},
{
"answer_id": 18145958,
"author": "Microsoft Developer",
"author_id": 662320,
"author_profile": "https://Stackoverflow.com/users/662320",
"pm_score": 0,
"selected": false,
"text": "Gridview.Columns[1].ItemStyle.Width = 100;\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
309,818 | <p>I'm try to extract info from a MySQL DB into a MS SQL DB. The DB is a mess and the developer is no longer available.</p>
<p>All dates are in char fields, and I use </p>
<pre><code>SELECT concat( mid(DueDate, 7, 4), mid(DueDate, 4, 2), mid(DueDate, 1, 2)) as DueDate FROM TableName
</code></pre>
<p>to get the date field in a format so MS sql server can import them.</p>
<p>Now, I want to export only the record with the date greater than today, so the questions are:</p>
<ul>
<li>What is the equivalent of GetDate() in MySQL?</li>
<li>Is there a better way to cast the date to make the comparison?</li>
</ul>
| [
{
"answer_id": 309823,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 5,
"selected": true,
"text": "mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');\n -> '2004-04-31'\n WHERE STR_TO_DATE('04/31/2009', '%m/%d/%Y') > NOW()\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
] |
309,819 | <p>Has there been any attempt and creating a formalized method for organizing CSS code? Before I go and make up my own strategy for keeping things readable, I'm wondering what else is out there. Google hasn't been very helpful, as I'm not entirely sure what terms to search for.</p>
<p>I'm thinking more along the lines of indenting/spacing, when to use new lines, naming conventions, etc.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 310072,
"author": "cowgod",
"author_id": 6406,
"author_profile": "https://Stackoverflow.com/users/6406",
"pm_score": 2,
"selected": false,
"text": "#page_container html body ul #slogan #red_bold body { background-color: #fff; color: #999; font-family: verdana, arial, helvetica, sans-serif; font-size: 76%; padding: 0; margin: 0; }\na { color: #2c5eb4; text-decoration: none; }\na:hover { text-decoration: underline; }\nh1, h2, h3, h4, h5, h6 { color: #f70; font-family: helvetica, verdana, arial, serif; font-weight: bold; margin: 1.2em 0; }\nh1 { font-size: 2.4em; line-height: 1.2em; margin-bottom: 0em; margin-top: 0em; }\nh2 { font-size: 1.7em; }\nh3 { font-size: 1.4em; }\nh4 { font-size: 1.2em; font-weight: bold; }\nh5 { font-size: 1.0em; font-weight: bold; }\nh6 { font-size: 0.8em; font-weight: bold; }\nimg { border: 0; }\nli, ol, ul { font-size: 1.0em; line-height: 1.8em; list-style-position: inside; margin-bottom: 0.1em; margin-left: 0; margin-top: 0.2em; }\n#content { clear: both; margin: 0; margin-top: -4em; }\n#columns { height: 36em; }\n#column1, #column2, #column3, #column4 { border-right: 1px solid #dbdbdb; float: left; width: 18%; margin: 0 0.5em; padding: 0 1em; height: 100%; }\n#column1 { width: 28%; }\n#column1 input { float: right; }\n#column1 label { color: #999; float: left; }\n#column2 a, #column3 a { font-weight: bold; }\n#column4 { border-right: 0; }\n#form { margin: 0 2em; }\n.help_button { float: right; text-align: right; width: 30px; }\n"
},
{
"answer_id": 310104,
"author": "Andy Ford",
"author_id": 17252,
"author_profile": "https://Stackoverflow.com/users/17252",
"pm_score": 2,
"selected": false,
"text": "el {\n display:;\n float:;\n clear:;\n visibility:;\n position:;\n top:;\n right:;\n bottom:;\n left:;\n z-index:;\n width:;\n min-width:;\n height:;\n min-height:;\n overflow:;\n margin:;\n padding:;\n border:;\n border-top:;\n border-right:;\n border-bottom:;\n border-left:;\n border-width:;\n border-top-width:;\n border-right-width:;\n border-bottom-width:;\n border-left-width:;\n border-color:;\n border-top-color:;\n border-right-color:;\n border-bottom-color:;\n border-left-color:;\n border-style:;\n border-top-style:;\n border-right-style:;\n border-bottom-style:;\n border-left-style:;\n border-collapse:;\n border-spacing:;\n outline:;\n list-style:;\n font:;\n font-family:;\n font-size:;\n line-height:;\n font-weight:;\n text-align:;\n text-indent:;\n text-transform:;\n text-decoration:;\n white-space:;\n vertical-align:;\n color:;\n opacity:;\n background:;\n background-color:;\n background-image:;\n background-position:;\n background-repeat:;\n cursor:;\n }\n"
},
{
"answer_id": 3842154,
"author": "David Rivers",
"author_id": 224192,
"author_profile": "https://Stackoverflow.com/users/224192",
"pm_score": 0,
"selected": false,
"text": "@import .warn {color:red;} p.warn {font-style:italic;} h1.warn {border:5px solid red;} @import url('/css/base.css');\n\na {\n color:#369;\n font-family: Helvetica, sans-serif;\n font-weight: bold;\n text-decoration: underscore; }\n a img {\n border: 0; }\n\nblockquote, .nav, p {\n margin-bottom: 10px; }\nblockquote {\n background: #eee;\n padding: 10px; }\n\nh1, h2, h3, h4 {\n font-family: Georgia, serif; }\nh1.warning {\n border: 5px solid red; }\n\n.nav a {\n font-size: 150%;\n padding: 10px; }\n.nav li {\n display: inline-block; }\n\np.warning {\n font-style: italic; }\n p.warning a {\n background: #fff;\n border-bottom: 2px solid #000;\n padding: 5px; }\n p.warning .keyword {\n text-decoration: underline; }\n p blockquote, .nav, p"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
309,834 | <p>I have a read query that I execute within a transaction so that I can specify the isolation level. Once the query is complete, what should I do?</p>
<ul>
<li>Commit the transaction </li>
<li>Rollback the transaction</li>
<li>Do nothing (which will cause the transaction to be rolled back at the end of the using block)</li>
</ul>
<p>What are the implications of doing each?</p>
<pre><code>using (IDbConnection connection = ConnectionFactory.CreateConnection())
{
using (IDbTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadUncommitted))
{
using (IDbCommand command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = "SELECT * FROM SomeTable";
using (IDataReader reader = command.ExecuteReader())
{
// Read the results
}
}
// To commit, or not to commit?
}
}
</code></pre>
<p>EDIT: The question is not if a transaction should be used or if there are other ways to set the transaction level. The question is if it makes any difference that a transaction that does not modify anything is committed or rolled back. Is there a performance difference? Does it affect other connections? Any other differences?</p>
| [
{
"answer_id": 309848,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": -1,
"selected": false,
"text": "SELECT * FROM SomeTable WITH (NOLOCK)\n"
},
{
"answer_id": 309849,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "using (IDbConnection connection = ConnectionFactory.CreateConnection())\nusing (IDbTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadUncommitted))\nusing (IDbCommand command = connection.CreateCommand())\n{\n command.Transaction = transaction;\n command.CommandText = \"SELECT * FROM SomeTable\";\n using (IDataReader reader = command.ExecuteReader())\n {\n // Do something useful\n }\n // To commit, or not to commit?\n}\n"
},
{
"answer_id": 310312,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "set transaction isolation level read uncommitted\n"
},
{
"answer_id": 680856,
"author": "Oliver Drotbohm",
"author_id": 18122,
"author_profile": "https://Stackoverflow.com/users/18122",
"pm_score": 2,
"selected": false,
"text": "INSERT"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8739/"
] |
309,880 | <p>I'm trying to create a custom transition, to serve as a replacement for a default transition you would get here, for example:</p>
<pre><code>[self.navigationController pushViewController:someController animated:YES];
</code></pre>
<p>I have prepared an OpenGL-based view that performs an effect on some static texture mapped to a plane (let's say it's a copy of the flip effect in Core Animation). What I don't know how to do is:</p>
<ul>
<li>grab current view content and make a texture out of it (I remember seeing a function that does just that, but can't find it)</li>
<li>how to do the same for the view that is currently offscreen and is going to replace current view </li>
<li>are there some APIs I can hook to in order to make my transition class as native as possible (make it a kind of Core Animation effect)?</li>
</ul>
<p>Any thoughts or links are greatly appreciated!</p>
<p><strong>UPDATE</strong></p>
<p>Jeffrey Forbes's answer works great as a solution to capture the content of a view. </p>
<p>What I haven't figured out yet is how to capture the content of the view I want to transition to, which should be invisible until the transition is done.</p>
<p>Also, which method should I use to present the OpenGL view?
For demonstration purposes I used pushViewController. That affects the navbar, though, which I actually want to go one item back, with animation, check this vid for explanation:</p>
<p><a href="http://vimeo.com/4649397" rel="noreferrer">http://vimeo.com/4649397</a>.</p>
<p>Another option would be to go with presentViewController, but that shows fullscreen.
Do you think maybe creating another window (or view?) could be useful?</p>
| [
{
"answer_id": 312112,
"author": "Jeffrey Forbes",
"author_id": 28019,
"author_profile": "https://Stackoverflow.com/users/28019",
"pm_score": 3,
"selected": true,
"text": "UIGraphicsBeginImageContext(self.view.frame.size);\n[[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];\nUIImage* test = UIGraphicsGetImageFromCurrentImageContext();\nUIImageView* view = [[UIImageView alloc] initWithImage:test];\nUIGraphicsEndImageContext();\n"
},
{
"answer_id": 27885257,
"author": "wenhuan chen",
"author_id": 4087573,
"author_profile": "https://Stackoverflow.com/users/4087573",
"pm_score": 0,
"selected": false,
"text": "- (void)animationFromModalView:(UIView *)modalView toMasterView:(UIView *)masterView\n{\n\n[masterView setNeedsLayout];\n[masterView layoutIfNeeded];\n\n[self performSelector:@selector(delayAnimationFromModalViewToMasterView) withObject:nil afterDelay:.1f];\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9804/"
] |
309,884 | <p>The code golf series seem to be fairly popular. I ran across some code that converts a number to its word representation. Some examples would be (powers of 2 for programming fun):</p>
<ul>
<li>2 -> Two</li>
<li>1024 -> One Thousand Twenty Four</li>
<li>1048576 -> One Million Forty Eight Thousand Five Hundred Seventy Six</li>
</ul>
<p>The algorithm my co-worker came up was almost two hundred lines long. Seems like there would be a more concise way to do it.</p>
<p>Current guidelines:</p>
<ul>
<li>Submissions in any <strong>programming</strong> language welcome (I apologize to
PhiLho for the initial lack of clarity on this one)</li>
<li>Max input of 2^64 (see following link for words, thanks mmeyers)</li>
<li><a href="http://en.wikipedia.org/wiki/Long_and_short_scales" rel="nofollow noreferrer">Short scale</a> with English output preferred, but any algorithm is welcome. Just comment along with the programming language as to the method used.</li>
</ul>
| [
{
"answer_id": 309962,
"author": "gpojd",
"author_id": 28071,
"author_profile": "https://Stackoverflow.com/users/28071",
"pm_score": 5,
"selected": false,
"text": "perl -MNumber::Spell -e 'print spell_number(2);'\n"
},
{
"answer_id": 309982,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 6,
"selected": true,
"text": "(format nil \"~r\" 1234) ==> \"one thousand two hundred thirty-four\"\n (format nil \"~@r\" 1234) ==> \"MCCXXXIV\"\n"
},
{
"answer_id": 309996,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "#include <stdio.h>\n#include <string.h>\n\nconst char *zero_to_nineteen[20] = {\"\", \"One \", \"Two \", \"Three \", \"Four \", \"Five \", \"Six \", \"Seven \", \"Eight \", \"Nine \", \"Ten \", \"Eleven \", \"Twelve \", \"Thirteen \", \"Fourteen \", \"Fifteen \", \"Sixteen \", \"Seventeen \", \"Eighteen \", \"Nineteen \"};\n\nconst char *twenty_to_ninety[8] = {\"Twenty \", \"Thirty \", \"Forty \", \"Fifty \", \"Sixty \", \"Seventy \", \"Eighty \", \"Ninety \"};\n\nconst char *big_numbers[7] = {\"\", \"Thousand \", \"Million \", \"Billion \", \"Trillion \", \"Quadrillion \", \"Quintillion \"};\n\nvoid num_to_word(char *buf, unsigned long long num)\n{\n unsigned long long power_of_1000 = 1000000000000000000ull;\n int power_index = 6;\n\n if(num == 0)\n {\n strcpy(buf, \"Zero\");\n return;\n }\n\n buf[0] = 0;\n\n while(power_of_1000 > 0)\n {\n int group = num / power_of_1000;\n if(group >= 100)\n {\n strcat(buf, zero_to_nineteen[group / 100]);\n strcat(buf, \"Hundred \");\n group %= 100;\n }\n\n if(group >= 20)\n {\n strcat(buf, twenty_to_ninety[group / 10 - 2]);\n group %= 10;\n }\n\n if(group > 0)\n strcat(buf, zero_to_nineteen[group]);\n\n if(num >= power_of_1000)\n strcat(buf, big_numbers[power_index]);\n\n num %= power_of_1000;\n power_of_1000 /= 1000;\n power_index--;\n }\n\n buf[strlen(buf) - 1] = 0;\n}\n #include <string.h>\n#define C strcat(b,\n#define U unsigned long long\nchar*z[]={\"\",\"One\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Ten\",\"Eleven\",\"Twelve\",\"Thirteen\",\"Fourteen\",\"Fifteen\",\"Sixteen\",\"Seventeen\",\"Eighteen\",\"Nineteen\"},*t[]={\"Twenty \",\"Thirty \",\"Forty \",\"Fifty \",\"Sixty \",\"Seventy \",\"Eighty \",\"Ninety \"},*q[]={\"\",\"Thousand \",\"Million \",\"Billion \",\"Trillion \",\"Quadrillion \",\"Quintillion \"};\nvoid W(char*b,U n){U p=1000000000000000000ull;int i=6;*b=0;if(!n)strcpy(b,\"Zero \");else while(p){int g=n/p;if(g>99){C z[g/100]);C \" \");C \"Hundred \");g%=100;}if(g>19){C t[g/10-2]);g%=10;}if(g)C z[g]),C \" \");if(n>=p)C q[i]);n%=p;p/=1000;i--;}b[strlen(b)-1]=0;}\n"
},
{
"answer_id": 310006,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 5,
"selected": false,
"text": "#include <string>\nusing namespace std;\n\nstring Thousands[] = { \"zero\", \"thousand\", \"million\", \"billion\", \"trillion\", \"quadrillion\", \"quintillion\", \"sexillion\", \"septillion\", \"octillion\", \"nonillion\", \"decillion\" };\nstring Ones[] = { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nstring Tens[] = { \"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nstring concat(bool cond1, string first, bool cond2, string second) { return (cond1 ? first : \"\") + (cond1 && cond2 ? \" \" : \"\") + (cond2 ? second : \"\"); }\n\nstring toStringBelowThousand(unsigned long long n) {\n return concat(n >= 100, Ones[n / 100] + \" hundred\", n % 100 != 0, (n % 100 < 20 ? Ones[n % 100] : Tens[(n % 100) / 10] + (n % 10 > 0 ? \" \" + Ones[n % 10] : \"\")));\n}\n\nstring toString(unsigned long long n, int push = 0) {\n return n == 0 ? \"zero\" : concat(n >= 1000, toString(n / 1000, push + 1), n % 1000 != 0, concat(true, toStringBelowThousand(n % 1000), push > 0, Thousands[push]));\n}\n cout << toString(51351); // => fifty one thousand three hundred fifty one\n"
},
{
"answer_id": 310098,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 3,
"selected": false,
"text": "g=lambda n:[\"zero\",\" \".join(w(n,0))][n>0]\nw=lambda n,l:w(n//m,l+1)+[e,z[n%m//100]+[\"hundred\"]][n%m//100>0]+\\\n(p(\"twen thir fo\"+r,\"ty\")[n%100//10-2]+z[n%10]if n%100>19 else z[n%100])+\\\n[e,k[l]][n%m>0]if n else e\np=lambda a,b:[[i+b]for i in a.split()]\ne=[];r=\"r fif six seven eigh nine\";m=1000\nk=[e,[\"thousand\"]]+p(\"m b tr quadr quint\",\"illion\")\nz=[e]+p(\"one two three four five six seven eight nine ten eleven twelve\",\"\")+\\\np(\"thir fou\"+r,\"teen\")\n >>> n2w(2**20)\n'one million forty-eight thousand five hundred seventy-six'\n\ndef n2w(n):\n if n < 0: return 'minus ' + n2w(-n)\n if n < 10: return W('zero one two three four five six seven eight nine')[n]\n if n < 20: return W('ten eleven twelve',\n 'thir four fif six seven eigh nine',\n 'teen')[n-10]\n if n < 100: \n tens = W('', 'twen thir for fif six seven eigh nine', 'ty')[n//10-2]\n return abut(tens, '-', n2w(n % 10))\n if n < 1000:\n return combine(n, 100, 'hundred')\n for i, word in enumerate(W('thousand', 'm b tr quadr quint', 'illion')):\n if n < 10**(3*(i+2)):\n return combine(n, 10**(3*(i+1)), word)\n assert False\n\ndef W(b, s='', suff=''): return b.split() + [s1 + suff for s1 in s.split()]\ndef combine(n, m, term): return abut(n2w(n // m) + ' ' + term, ' ', n2w(n % m))\ndef abut(w10, sep, w1): return w10 if w1 == 'zero' else w10 + sep + w1\n"
},
{
"answer_id": 310470,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 3,
"selected": false,
"text": "if exists (select 1 from sys.objects where object_id = object_id(N'dbo.fnGetNumberString'))\n drop function fnGetNumberString\ngo\n\n/*\nTests:\ndeclare @tests table ( testValue bigint )\ninsert into @tests select -43213 union select -5 union select 0 union select 2 union select 15 union select 33 union select 100 union select 456 union select 1024 union select 10343 union select 12345678901234 union select -3434343434343\n\nselect testValue, dbo.fnGetNumberString(testValue) as textValue\nfrom @tests\n*/\n\ncreate function dbo.fnGetNumberString\n(\n @value bigint\n)\nreturns nvarchar(1024)\nas\nbegin\n if @value = 0 return 'zero' -- lets me avoid special-casing this later\n\n declare @isNegative bit\n set @isNegative = 0\n\n if @value < 0\n select @isNegative = 1, @value = @value * -1\n\n declare @groupNames table ( groupOrder int, groupName nvarchar(15) )\n insert into @groupNames select 1, '' union select 2, 'thousand' union select 3, 'million' union select 4, 'billion' union select 5, 'trillion' union select 6, 'quadrillion' union select 7, 'quintillion' union select 8, 'sextillion'\n\n declare @digitNames table ( digit tinyint, digitName nvarchar(10) )\n insert into @digitNames select 0, '' union select 1, 'one' union select 2, 'two' union select 3, 'three' union select 4, 'four' union select 5, 'five' union select 6, 'six' union select 7, 'seven' union select 8, 'eight' union select 9, 'nine' union select 10, 'ten' union select 11, 'eleven' union select 12, 'twelve' union select 13, 'thirteen' union select 14, 'fourteen' union select 15, 'fifteen' union select 16, 'sixteen' union select 17, 'seventeen' union select 18, 'eighteen' union select 19, 'nineteen'\n\n declare @tensGroups table ( digit tinyint, groupName nvarchar(10) )\n insert into @tensGroups select 2, 'twenty' union select 3, 'thirty' union select 4, 'forty' union select 5, 'fifty' union select 6, 'sixty' union select 7, 'seventy' union select 8, 'eighty' union select 9, 'ninety'\n\n declare @groups table ( groupOrder int identity, groupValue int )\n\n declare @convertedValue varchar(50)\n\n while @value > 0\n begin\n insert into @groups (groupValue) select @value % 1000\n\n set @value = @value / 1000\n end\n\n declare @returnValue nvarchar(1024)\n set @returnValue = ''\n\n if @isNegative = 1 set @returnValue = 'negative'\n\n select @returnValue = @returnValue +\n case when len(h.digitName) > 0 then ' ' + h.digitName + ' hundred' else '' end +\n case when len(isnull(t.groupName, '')) > 0 then ' ' + t.groupName + case when len(isnull(o.digitName, '')) > 0 then '-' else '' end + isnull(o.digitName, '') else case when len(isnull(o.digitName, '')) > 0 then ' ' + o.digitName else '' end end +\n case when len(n.groupName) > 0 then ' ' + n.groupName else '' end\n from @groups g\n join @groupNames n on n.groupOrder = g.groupOrder\n join @digitNames h on h.digit = (g.groupValue / 100)\n left join @tensGroups t on t.digit = ((g.groupValue % 100) / 10)\n left join @digitNames o on o.digit = case when (g.groupValue % 100) < 20 then g.groupValue % 100 else g.groupValue % 10 end\n order by g.groupOrder desc\n\n return @returnValue\nend\ngo\n"
},
{
"answer_id": 310829,
"author": "Paul Fisher",
"author_id": 39808,
"author_profile": "https://Stackoverflow.com/users/39808",
"pm_score": 4,
"selected": false,
"text": "W p w=lambda n:[\"zero\",\" \".join(_(n,0))][n>0]\n_=lambda n,l:_(n//M,l+1)+[E,Z[n%M//C]+[\"hundred\"]][n%M//C>0]+\\\n(p(\"twen thir fo\"+R,\"ty\")[n%C//10-2]+Z[n%10]if n%C>19 else Z[n%C])+\\\n[E,([E,[\"thousand\"]]+p(\"m b tr quadr quint\",\"illion\"))[l]][n%M>0]if n else E\np=lambda a,b:[[i+b]for i in a.split()]\nE=[];R=\"r fif six seven eigh nine\";M=1000;C=100\nZ=[E]+p(\"one two three four five six seven eight nine ten eleven twelve\",\"\")+\\\np(\"thir fou\"+R,\"teen\")\n if __name__ == \"__main__\":\n import sys\n print w(int(sys.argv[1]))\n assert(w(100)==\"one hundred\")\n assert(w(1000000)==\"one million\")\n assert(w(1024)==\"one thousand twenty four\")\n assert(w(1048576)==\"one million forty eight thousand five hundred seventy six\")\n R E Z P M j _ a y [['bar'],['gubhfnaq'],['gjragl'],['sbhe']] c n o c(\"z o ge\",\"vyyvba\") == [['zvyyvba'],['ovyyvba'],['gevyyvba']]"
},
{
"answer_id": 311078,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 3,
"selected": false,
"text": "#light\nlet thou=[|\"\";\"thousand\";\"million\";\"billion\";\"trillion\";\"quadrillion\";\"quintillion\"|]\nlet ones=[|\"\";\"one\";\"two\";\"three\";\"four\";\"five\";\"six\";\"seven\";\"eight\";\"nine\";\"ten\";\"eleven\";\n \"twelve\";\"thirteen\";\"fourteen\";\"fifteen\";\"sixteen\";\"seventeen\";\"eighteen\";\"nineteen\"|]\nlet tens=[|\"\";\"\";\"twenty\";\"thirty\";\"forty\";\"fifty\";\"sixty\";\"seventy\";\"eighty\";\"ninety\"|]\nlet (^-) x y = if y=\"\" then x else x^\"-\"^y\nlet (^+) x y = if y=\"\" then x else x^\" \"^y\nlet (^?) x y = if x=\"\" then x else x^+y\nlet (+^+) x y = if x=\"\" then y else x^+y\nlet Tiny n = if n < 20 then ones.[n] else tens.[n/10] ^- ones.[n%10]\nlet Small n = (ones.[n/100] ^? \"hundred\") +^+ Tiny(n%100)\nlet rec Big n t = if n = 0UL then \"\" else\n (Big (n/1000UL) (t+1)) +^+ (Small(n%1000UL|>int) ^? thou.[t])\nlet Convert n = if n = 0UL then \"zero\" else Big n 0\n let Show n = \n printfn \"%20u -> \\\"%s\\\"\" n (Convert n)\n\nlet tinyTests = [0; 1; 10; 11; 19; 20; 21; 30; 99] |> List.map uint64\nlet smallTests = tinyTests @ (tinyTests |> List.map (fun n -> n + 200UL))\nlet MakeTests t1 t2 = \n List.map (fun n -> n * (pown 1000UL t1)) smallTests\n |> List.map_concat (fun n -> List.map (fun x -> x * (pown 1000UL t2) + n) smallTests)\nfor n in smallTests do\n Show n\nfor n in MakeTests 1 0 do\n Show n\nfor n in MakeTests 5 2 do\n Show n \nShow 1000001000678000001UL\nShow 17999999999999999999UL\n"
},
{
"answer_id": 311436,
"author": "Paulius",
"author_id": 1353085,
"author_profile": "https://Stackoverflow.com/users/1353085",
"pm_score": 6,
"selected": false,
"text": "@echo off\n\nset zero_to_nineteen=Zero One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen\nset twenty_to_ninety=ignore ignore Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety\nset big_numbers=ignore Thousand Million Billion Trillion Quadrillion Quintillion Sextillion Septillion Octillion Nonillion Decillion Undecillion Duodecillion Tredecillion Quattuordecillion Quindecillion Sexdecillion Septendecillion Octodecillion Novemdecillion Vigintillion\nrem 10^0 10^3 10^6 10^9 10^12 10^15 10^18 10^21 10^24 10^27 10^30 10^33 10^36 10^39 10^42 10^45 10^48 10^51 10^54 10^57 10^60 10^63\n\ncall :parse_numbers %*\n\nexit /B 0\n\n:parse_numbers\n :parse_numbers_loop\n if \"$%~1\" == \"$\" goto parse_numbers_end\n call :parse_number %~1\n echo %~1 -^> %parse_number_result%\n shift\n goto parse_numbers_loop\n :parse_numbers_end\n exit /B 0\n\n:parse_number\n call :get_sign %~1\n set number_sign=%get_sign_result%\n call :remove_groups %get_sign_result_number%\n call :trim_leading_zeros %remove_groups_result%\n set number=%trim_leading_zeros_result%\n if \"$%number%\" == \"$0\" (\n set parse_number_result=Zero\n exit /B 0\n )\n set counter=0\n set parse_number_result=\n :parse_number_loop\n set last_three=%number:~-3%\n set number=%number:~0,-3%\n call :parse_three %last_three%\n call :get_from %counter% %big_numbers%\n if \"$%get_from_result%\" == \"$\" (\n set parse_number_result=* ERR: the number is too big! Even wikipedia doesn't know how it's called!\n exit /B 0\n )\n if not \"$%parse_three_result%\" == \"$Zero\" (\n if %counter% == 0 (\n set parse_number_result=%parse_three_result%\n ) else (\n if not \"$%parse_number_result%\" == \"$\" (\n set parse_number_result=%parse_three_result% %get_from_result% %parse_number_result%\n ) else (\n set parse_number_result=%parse_three_result% %get_from_result%\n )\n )\n )\n set /A counter+=1\n if not \"$%number%\" == \"$\" goto parse_number_loop\n if \"$%parse_number_result%\" == \"$\" (\n set parse_number_result=Zero\n exit /B 0\n ) else if not \"$%number_sign%\" == \"$\" (\n set parse_number_result=%number_sign% %parse_number_result%\n )\n exit /B 0\n\n:parse_three\n call :trim_leading_zeros %~1\n set three=%trim_leading_zeros_result%\n set /A three=%three% %% 1000\n set /A two=%three% %% 100\n call :parse_two %two%\n set parse_three_result=\n set /A digit=%three% / 100\n if not \"$%digit%\" == \"$0\" (\n call :get_from %digit% %zero_to_nineteen%\n )\n if not \"$%digit%\" == \"$0\" (\n if not \"$%get_from_result%\" == \"$Zero\" (\n set parse_three_result=%get_from_result% Hundred\n )\n )\n if \"$%parse_two_result%\" == \"$Zero\" (\n if \"$%parse_three_result%\" == \"$\" (\n set parse_three_result=Zero\n )\n ) else (\n if \"$%parse_three_result%\" == \"$\" (\n set parse_three_result=%parse_two_result%\n ) else (\n set parse_three_result=%parse_three_result% %parse_two_result%\n )\n )\n exit /B 0\n\n:parse_two\n call :trim_leading_zeros %~1\n set two=%trim_leading_zeros_result%\n set /A two=%two% %% 100\n call :get_from %two% %zero_to_nineteen%\n if not \"$%get_from_result%\" == \"$\" (\n set parse_two_result=%get_from_result%\n goto parse_two_20_end\n )\n set /A digit=%two% %% 10\n call :get_from %digit% %zero_to_nineteen%\n set parse_two_result=%get_from_result%\n set /A digit=%two% / 10\n call :get_from %digit% %twenty_to_ninety%\n if not \"$%parse_two_result%\" == \"$Zero\" (\n set parse_two_result=%get_from_result% %parse_two_result%\n ) else (\n set parse_two_result=%get_from_result%\n )\n goto parse_two_20_end\n :parse_two_20_end\n exit /B 0\n\n:get_from\n call :trim_leading_zeros %~1\n set idx=%trim_leading_zeros_result%\n set /A idx=0+%~1\n shift\n :get_from_loop\n if \"$%idx%\" == \"$0\" goto get_from_loop_end\n set /A idx-=1\n shift\n goto get_from_loop\n :get_from_loop_end\n set get_from_result=%~1\n exit /B 0\n\n:trim_leading_zeros\n set str=%~1\n set trim_leading_zeros_result=\n :trim_leading_zeros_loop\n if not \"$%str:~0,1%\" == \"$0\" (\n set trim_leading_zeros_result=%trim_leading_zeros_result%%str%\n exit /B 0\n )\n set str=%str:~1%\n if not \"$%str%\" == \"$\" goto trim_leading_zeros_loop\n if \"$%trim_leading_zeros_result%\" == \"$\" set trim_leading_zeros_result=0\n exit /B 0\n\n:get_sign\n set str=%~1\n set sign=%str:~0,1%\n set get_sign_result=\n if \"$%sign%\" == \"$-\" (\n set get_sign_result=Minus\n set get_sign_result_number=%str:~1%\n ) else if \"$%sign%\" == \"$+\" (\n set get_sign_result_number=%str:~1%\n ) else (\n set get_sign_result_number=%str%\n )\n exit /B 0\n\n:remove_groups\n set str=%~1\n set remove_groups_result=%str:'=%\n exit /B 0\n @echo off\nrem 10^x:x= 66 63 60 57 54 51 48 45 42 39 36 33 30 27 24 21 18 15 12 9 6 3 0\ncall number 0\ncall number 2\ncall number -17\ncall number 30\ncall number 48\ncall number -256\ncall number 500\ncall number 874\ncall number 1'024\ncall number -17'001\ncall number 999'999\ncall number 1'048'576\ncall number -1'000'001'000'000\ncall number 912'345'014'587'957'003\ncall number -999'912'345'014'587'124'337'999'999\ncall number 111'222'333'444'555'666'777'888'999'000'000'000'001\ncall number -912'345'014'587'912'345'014'587'124'912'345'014'587'124'337\ncall number 999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999\ncall number 1'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000\nrem 10^x:x= 66 63 60 57 54 51 48 45 42 39 36 33 30 27 24 21 18 15 12 9 6 3 0\n 0 -> Zero\n2 -> Two\n-17 -> Minus Seventeen\n30 -> Thirty\n48 -> Forty Eight\n-256 -> Minus Two Hundred Fifty Six\n500 -> Five Hundred\n874 -> Eight Hundred Seventy Four\n1'024 -> One Thousand Twenty Four\n-17'001 -> Minus Seventeen Thousand One\n999'999 -> Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine\n1'048'576 -> One Million Forty Eight Thousand Five Hundred Seventy Six\n-1'000'001'000'000 -> Minus One Trillion One Million\n912'345'014'587'957'003 -> Nine Hundred Twelve Quadrillion Three Hundred Forty Five Trillion Fourteen Billion Five Hundred Eighty Seven Million Nine Hundred Fifty Seven Thousand Three\n-999'912'345'014'587'124'337'999'999 -> Minus Nine Hundred Ninety Nine Septillion Nine Hundred Twelve Sextillion Three Hundred Forty Five Quintillion Fourteen Quadrillion Five Hundred Eighty Seven Trillion One Hundred Twenty Four Billion Three Hundred Thirty Seven Million Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine\n111'222'333'444'555'666'777'888'999'000'000'000'001 -> One Hundred Eleven Undecillion Two Hundred Twenty Two Decillion Three Hundred Thirty Three Nonillion Four Hundred Forty Four Octillion Five Hundred Fifty Five Septillion Six Hundred Sixty Six Sextillion Seven Hundred Seventy Seven Quintillion Eight Hundred Eighty Eight Quadrillion Nine Hundred Ninety Nine Trillion One\n-912'345'014'587'912'345'014'587'124'912'345'014'587'124'337 -> Minus Nine Hundred Twelve Tredecillion Three Hundred Forty Five Duodecillion Fourteen Undecillion Five Hundred Eighty Seven Decillion Nine Hundred Twelve Nonillion Three Hundred Forty Five Octillion Fourteen Septillion Five Hundred Eighty Seven Sextillion One Hundred Twenty Four Quintillion Nine Hundred Twelve Quadrillion Three Hundred Forty Five Trillion Fourteen Billion Five Hundred Eighty Seven Million One Hundred Twenty Four Thousand Three Hundred Thirty Seven\n999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999'999 -> Nine Hundred Ninety Nine Vigintillion Nine Hundred Ninety Nine Novemdecillion Nine Hundred Ninety Nine Octodecillion Nine Hundred Ninety Nine Septendecillion Nine Hundred Ninety Nine Sexdecillion Nine Hundred Ninety Nine Quindecillion Nine Hundred Ninety Nine Quattuordecillion Nine Hundred Ninety Nine Tredecillion Nine Hundred Ninety Nine Duodecillion Nine Hundred Ninety Nine Undecillion Nine Hundred Ninety Nine Decillion Nine Hundred Ninety Nine Nonillion Nine Hundred Ninety Nine Octillion Nine Hundred Ninety Nine Septillion Nine Hundred Ninety Nine Sextillion Nine Hundred Ninety Nine Quintillion Nine Hundred Ninety Nine Quadrillion Nine Hundred Ninety Nine Trillion Nine Hundred Ninety Nine Billion Nine Hundred Ninety Nine Million Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine\n1'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000'000 -> * ERR: the number is too big! Even wikipedia doesn't know how it's called!\n"
},
{
"answer_id": 312092,
"author": "Germán",
"author_id": 17138,
"author_profile": "https://Stackoverflow.com/users/17138",
"pm_score": 3,
"selected": false,
"text": "NumSpeller.spell(458582)\n"
},
{
"answer_id": 396103,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 2,
"selected": false,
"text": "Perl 5.10 my %expo=(0,'',\n qw'1 thousand 2 million 3 billion 4 trillion 5 quadrillion 6 quintillion\n 7 sextillion 8 septillion 9 octillion 10 nonillion 11 decillion 12 undecillion\n 13 duodecillion 14 tredecillion 15 quattuordecillion 16 quindecillion\n 17 sexdecillion 18 septendecillion 19 octodecillion 20 novemdecillion\n 21 vigintillion'\n);\n\nmy %digit=(0,'',\n qw'1 one 2 two 3 three 4 four 5 five 6 six 7 seven 8 eight 9 nine 10 ten\n 11 eleven 12 twelve 13 thirteen 14 fourteen 15 fifteen 16 sixteen 17 seventeen\n 18 eighteen 19 nineteen 2* twenty 3* thirty 4* forty 5* fifty 6* sixty\n 7* seventy 8* eighty 9* ninety'\n);\n\nsub spell_number(_){\n local($_)=@_;\n ($_,@_)=split/(?=(?:.{3})*+$)/;\n $_=0 x(3-length).$_;\n unshift@_,$_;\n my @o;\n my $c=@_;\n for(@_){\n my $o='';\n /(.)(.)(.)/;\n $o.=$1?$digit{$1}.' hundred':'';\n $o.=$2==1?\n ' '.$digit{$2.$3}\n :\n ($2?' '.$digit{\"$2*\"}:'').\n ($2&&$3?' ':'').\n $digit{$3}\n ;\n $o.=--$c?($o?' '.$expo{$c}.', ':''):'';\n push@o,$o;\n }\n my $o;\n $o.=$_ for@o;\n $o=~/^\\s*+(.*?)(, )?$/;\n $o?$1:'zero';\n}\n split() my local strict warnings"
},
{
"answer_id": 402103,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env perl\nmy %symbols = (\n1 => \"One\", 2 => \"Two\", 3 => \"Three\", 4 => \"Four\", 5 => \"Five\",\n6 => \"Six\", 7 => \"Seven\", 8 => \"Eight\", 9 => \"Nine\", 10 => \"Ten\",\n11 => \"Eleven\", 12 => \"Twelve\", 13 => \"Thirteen\", 14 => \"Fourteen\",\n15 => \"Fifteen\", 16 => \"Sixteen\", 17 => \"Seventeen\", 18 => \"Eighteen\",\n19 => \"Nineteen\", 20 => \"Twenty\", 30 => \"Thirty\", 40 => \"Forty\",\n50 => \"Fifty\", 60 => \"Sixty\", 70 => \"Seventy\", 80 => \"Eighty\",\n90 => \"Ninety\", 100 => \"Hundred\");\n\nmy %three_symbols = (1 => \"Thousand\", 2 => \"Million\", 3 => \"Billion\" );\n\nsub babo {\nmy ($input) = @_;\nmy @threes = split(undef, $input);\nmy $counter = ($#threes + 1);\nmy $remainder = $counter % 3;\nmy @result;\n\nwhile ($counter > 0){\n my $digits = \"\";\n my $three;\n my $full_match = 0;\n\n if ($remainder > 0){\n while ($remainder > 0) {\n $digits .= shift(@threes);\n $remainder--;\n $counter--;\n }\n }\n else {\n $digits = join('',@threes[0,1,2]);\n splice(@threes, 0, 3);\n $counter -= 3;\n }\n if (exists($symbols{$digits})){\n $three = $symbols{$digits};\n $full_match = 1;\n }\n elsif (length($digits) == 3) {\n $three = $symbols{substr($digits,0,1)};\n $three .= \" Hundred\";\n $digits = substr($digits,1,2);\n if (exists($symbols{$digits})){\n $three .= \" \" . $symbols{$digits};\n $full_match = 1;\n }\n }\n if ($full_match == 0){\n $three .= \" \" . $symbols{substr($digits,0,1).\"0\"};\n $three .= \" \" . $symbols{substr($digits,1,1)};\n }\n push(@result, $three);\n if ($counter > 0){\n push(@result, \"Thousand\");\n }\n}\nmy $three_counter = 0;\nmy @r = map {$_ eq \"Thousand\" ? $three_symbols{++$three_counter}:$_ }\n reverse @result;\nreturn join(\" \", reverse @r);\n}\nprint babo(1) . \"\\n\";\nprint babo(12) . \"\\n\";\nprint babo(120) . \"\\n\";\nprint babo(1234) . \"\\n\";\nprint babo(12345) . \"\\n\";\nprint babo(123456) . \"\\n\";\nprint babo(1234567) . \"\\n\";\nprint babo(1234567890) . \"\\n\";\n"
},
{
"answer_id": 408776,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 6,
"selected": false,
"text": " static string wordify(decimal v)\n {\n if (v == 0) return \"zero\";\n var units = \" one two three four five six seven eight nine\".Split();\n var teens = \" eleven twelve thir# four# fif# six# seven# eigh# nine#\".Replace(\"#\", \"teen\").Split();\n var tens = \" ten twenty thirty forty fifty sixty seventy eighty ninety\".Split();\n var thou = \" thousand m# b# tr# quadr# quint# sext# sept# oct#\".Replace(\"#\", \"illion\").Split();\n var g = (v < 0) ? \"minus \" : \"\";\n var w = \"\";\n var p = 0;\n v = Math.Abs(v);\n while (v > 0)\n {\n int b = (int)(v % 1000);\n if (b > 0)\n {\n var h = (b / 100);\n var t = (b - h * 100) / 10;\n var u = (b - h * 100 - t * 10);\n var s = ((h > 0) ? units[h] + \" hundred\" + ((t > 0 | u > 0) ? \" and \" : \"\") : \"\")\n + ((t > 0) ? (t == 1 && u > 0) ? teens[u] : tens[t] + ((u > 0) ? \"-\" : \"\") : \"\")\n + ((t != 1) ? units[u] : \"\");\n s = (((v > 1000) && (h == 0) && (p == 0)) ? \" and \" : (v > 1000) ? \", \" : \"\") + s;\n w = s + \" \" + thou[p] + w;\n }\n v = v / 1000;\n p++;\n }\n return g + w;\n }\n static void Main(string[] args)\n{\n Console.WriteLine(wordify(decimal.MaxValue));\n}\n"
},
{
"answer_id": 409411,
"author": "recursive",
"author_id": 44743,
"author_profile": "https://Stackoverflow.com/users/44743",
"pm_score": 4,
"selected": false,
"text": "w=lambda n:_(n,[\"\",\"thousand \"]+p(\"m b tr quadr quint\",\"illion\"))[:-1]or\"zero\"\n_=lambda n,S:n*\"x\"and _(n//M,S[1:])+(Z[n%M//C]+\"hundred \")*(n%M//C>0)+(n%C>19\nand p(\"twen thir fo\"+R,\"ty\")[n%C//10-2]+Z[n%10]or Z[n%C])+S[0]*(n%M>0)\np=lambda a,b=\"\":[i+b+\" \"for i in a.split()]\nR=\"r fif six seven eigh nine\"\nM=1000\nC=100\nZ=[\"\"]+p(\"one two three four five%st nine ten eleven twelve\"%R[5:20])+p(\n\"thir fou\"+R,\"teen\")\n if __name__ == \"__main__\":\n import sys\n assert(w(0)==\"zero\")\n assert(w(100)==\"one hundred\")\n assert(w(1000000)==\"one million\")\n assert(w(1024)==\"one thousand twenty four\")\n assert(w(1048576)==\"one million forty eight thousand five hundred seventy six\")\n"
},
{
"answer_id": 852172,
"author": "Tolgahan Albayrak",
"author_id": 104468,
"author_profile": "https://Stackoverflow.com/users/104468",
"pm_score": 0,
"selected": false,
"text": "public abstract class ValueSource\n{\n public abstract object Value { get; }\n}\n public abstract class NumberTextValueSource:ValueSource\n{\n public abstract decimal Number { get; }\n public abstract string Format { get; }\n public abstract string Negative { get; }\n public abstract bool UseValueIfZero { get; }\n public abstract string N0 { get; }\n public abstract string N1 { get; }\n public abstract string N2 { get; }\n public abstract string N3 { get; }\n public abstract string N4 { get; }\n public abstract string N5 { get; }\n public abstract string N6 { get; }\n public abstract string N7 { get; }\n public abstract string N8 { get; }\n public abstract string N9 { get; }\n public abstract string N10 { get; }\n public abstract string N11 { get; }\n public abstract string N12 { get; }\n public abstract string N13 { get; }\n public abstract string N14 { get; }\n public abstract string N15 { get; }\n public abstract string N16 { get; }\n public abstract string N17 { get; }\n public abstract string N18 { get; }\n public abstract string N19 { get; }\n public abstract string N20 { get; }\n public abstract string N30 { get; }\n public abstract string N40 { get; }\n public abstract string N50 { get; }\n public abstract string N60 { get; }\n public abstract string N70 { get; }\n public abstract string N80 { get; }\n public abstract string N90 { get; }\n public abstract string N100 { get; }\n public abstract string NHundred { get; }\n public abstract string N1000 { get; }\n public abstract string NThousand { get; }\n public abstract string NMillion { get; }\n public abstract string NBillion { get; }\n public abstract string NTrillion { get; }\n public abstract string NQuadrillion { get; }\n\n\n string getOne(Type t, string v)\n {\n if (v[0] == '0' && !UseValueIfZero)\n return \"\";\n return (string)t.GetProperty(\"N\" + v[0].ToString()).GetValue(this, null);\n }\n\n\n string getTwo(Type t, string v)\n {\n if (v[0] == '0')\n if (v[1] != '0')\n return getOne(t, v.Substring(1));\n else\n return \"\";\n\n if (v[1] == '0' || v[0] == '1')\n return (string)t.GetProperty(\"N\" + v).GetValue(this, null);\n\n return (string)t.GetProperty(\"N\" + v[0].ToString() + \"0\").GetValue(this, null) +\n getOne(t, v.Substring(1));\n }\n\n\n string getThree(Type t, string v)\n {\n if(v[0] == '0')\n return getTwo(t,v.Substring(1));\n\n if (v[0] == '1')\n return\n N100 +\n getTwo(t, v.Substring(1));\n return\n getOne(t, v[0].ToString()) +\n NHundred +\n getTwo(t, v.Substring(1));\n }\n\n\n string getFour(Type t, string v)\n {\n if (v[0] == '0')\n return getThree(t, v.Substring(1));\n if (v[0] == '1')\n return\n N1000 +\n getThree(t, v.Substring(1));\n return\n getOne(t, v[0].ToString()) +\n NThousand +\n getThree(t, v.Substring(1));\n }\n\n\n string getFive(Type t, string v)\n {\n if (v[0] == '0')\n return getFour(t, v.Substring(1));\n return\n getTwo(t, v.Substring(0, 2)) +\n NThousand +\n getThree(t, v.Substring(2));\n }\n\n\n string getSix(Type t, string v)\n {\n if (v[0] == '0')\n return getFive(t, v.Substring(1));\n return\n getThree(t, v.Substring(0, 3)) +\n NThousand +\n getThree(t, v.Substring(3));\n }\n\n\n string getSeven(Type t, string v)\n {\n if (v[0] == '0')\n return getSix(t, v.Substring(1));\n return\n getOne(t, v[0].ToString()) +\n NMillion +\n getSix(t, v.Substring(3));\n }\n\n\n string getEight(Type t, string v)\n {\n if (v[0] == '0')\n return getSeven(t, v.Substring(1));\n return\n getTwo(t, v.Substring(0, 2)) +\n NMillion +\n getSix(t, v.Substring(2));\n }\n\n\n string getNine(Type t, string v)\n {\n if (v[0] == '0')\n return getEight(t, v.Substring(1));\n return\n getThree(t, v.Substring(0, 3)) +\n NMillion +\n getSix(t, v.Substring(3));\n }\n\n\n string getTen(Type t, string v)\n {\n if (v[0] == '0')\n return getNine(t, v.Substring(1));\n return\n getOne(t, v.Substring(0, 1)) +\n NBillion +\n getNine(t, v.Substring(1));\n }\n\n\n string getEleven(Type t, string v)\n {\n if (v[0] == '0')\n return getTen(t, v.Substring(1));\n return\n getTwo(t, v.Substring(0, 2)) +\n NBillion +\n getNine(t, v.Substring(2));\n }\n\n\n string getTwelve(Type t, string v)\n {\n if (v[0] == '0')\n return getEleven(t, v.Substring(1));\n return\n getThree(t, v.Substring(0, 3)) +\n NBillion +\n getNine(t, v.Substring(3));\n }\n\n\n string getThirteen(Type t, string v)\n {\n if (v[0] == '0')\n return getTwelve(t, v.Substring(1));\n return\n getOne(t, v.Substring(0, 1)) +\n NTrillion +\n getTwelve(t, v.Substring(1));\n }\n\n\n string getForteen(Type t, string v)\n {\n if (v[0] == '0')\n return getThirteen(t, v.Substring(1));\n return\n getTwo(t, v.Substring(0, 2)) +\n NTrillion +\n getTwelve(t, v.Substring(2));\n }\n\n\n string getFifteen(Type t, string v)\n {\n if (v[0] == '0')\n return getForteen(t, v.Substring(1));\n return\n getThree(t, v.Substring(0, 3)) +\n NTrillion +\n getTwelve(t, v.Substring(3));\n }\n\n\n string getSixteen(Type t, string v)\n {\n if (v[0] == '0')\n return getFifteen(t, v.Substring(1));\n return\n getOne(t, v.Substring(0, 1)) +\n NQuadrillion +\n getFifteen(t, v.Substring(1));\n }\n\n\n string getSeventeen(Type t, string v)\n {\n if (v[0] == '0')\n return getSixteen(t, v.Substring(1));\n return\n getTwo(t, v.Substring(0, 2)) +\n NQuadrillion +\n getFifteen(t, v.Substring(2));\n }\n\n\n string getEighteen(Type t, string v)\n {\n if (v[0] == '0')\n return getSeventeen(t, v.Substring(1));\n return\n getThree(t, v.Substring(0, 3)) +\n NQuadrillion +\n getFifteen(t, v.Substring(3));\n }\n\n\n string convert(Type t, string hp)\n {\n switch (hp.Length)\n {\n case 1:\n return getOne(t, hp);\n case 2:\n return getTwo(t, hp);\n case 3:\n return getThree(t, hp);\n case 4:\n return getFour(t, hp);\n case 5:\n return getFive(t, hp);\n case 6:\n return getSix(t, hp);\n case 7:\n return getSeven(t, hp);\n case 8:\n return getEight(t, hp);\n case 9:\n return getNine(t, hp);\n case 10:\n return getTen(t, hp);\n case 11:\n return getEleven(t, hp);\n case 12:\n return getTwelve(t, hp);\n case 13:\n return getThirteen(t, hp);\n case 14:\n return getForteen(t, hp);\n case 15:\n return getFifteen(t, hp);\n case 16:\n return getSixteen(t, hp);\n case 17:\n return getSeventeen(t, hp);\n case 18:\n return getEighteen(t, hp);\n }\n return \"\";\n }\n\n\n public override object Value\n {\n get\n {\n decimal d = Number;\n decimal highPoint, lowPoint;\n bool isNeg = d < 0;\n d = Math.Abs(d);\n highPoint = Math.Floor(d);\n lowPoint = d - highPoint;\n Type t = this.GetType();\n\n string strHigh = convert(t, highPoint.ToString()),\n strLow =\n lowPoint > 0 ?\n convert(t, lowPoint.ToString().Substring(2)) :\n UseValueIfZero ? N0 : \"\";\n if (isNeg) strHigh = Negative + \" \" + strHigh;\n return string.Format(Format, strHigh, strLow);\n }\n }\n}\n public class TRYNumberTextValueSource:NumberTextValueSource\n{\n decimal num;\n public TRYNumberTextValueSource(decimal value)\n {\n num = Math.Round(value, 2);\n }\n public override decimal Number\n {\n get { return num; }\n }\n\n public override string Format\n {\n get\n {\n if (num == 0)\n return N0 + \" YTL\";\n if (num > -1 && num < 1)\n return \"{0}{1} Kurus\";\n return \"{0} YTL {1} Kurus\";\n }\n }\n\n public override string Negative\n {\n get { return \"-\"; }\n }\n\n public override bool UseValueIfZero\n {\n get { return false; }\n }\n\n public override string N0\n {\n get { return \"sifir\"; }\n }\n\n public override string N1\n {\n get { return \"bir\"; }\n }\n\n public override string N2\n {\n get { return \"iki\"; }\n }\n\n public override string N3\n {\n get { return \"üç\"; }\n }\n\n public override string N4\n {\n get { return \"dört\"; }\n }\n\n public override string N5\n {\n get { return \"bes\"; }\n }\n\n public override string N6\n {\n get { return \"alti\"; }\n }\n\n public override string N7\n {\n get { return \"yedi\"; }\n }\n\n public override string N8\n {\n get { return \"sekiz\"; }\n }\n\n public override string N9\n {\n get { return \"dokuz\"; }\n }\n\n public override string N10\n {\n get { return \"on\"; }\n }\n\n public override string N11\n {\n get { return \"onbir\"; }\n }\n\n public override string N12\n {\n get { return \"oniki\"; }\n }\n\n public override string N13\n {\n get { return \"onüç\"; }\n }\n\n public override string N14\n {\n get { return \"ondört\"; }\n }\n\n public override string N15\n {\n get { return \"onbes\"; }\n }\n\n public override string N16\n {\n get { return \"onalti\"; }\n }\n\n public override string N17\n {\n get { return \"onyedi\"; }\n }\n\n public override string N18\n {\n get { return \"onsekiz\"; }\n }\n\n public override string N19\n {\n get { return \"ondokuz\"; }\n }\n\n public override string N20\n {\n get { return \"yirmi\"; }\n }\n\n public override string N30\n {\n get { return \"otuz\"; }\n }\n\n public override string N40\n {\n get { return \"kirk\"; }\n }\n\n public override string N50\n {\n get { return \"elli\"; }\n }\n\n public override string N60\n {\n get { return \"altmis\"; }\n }\n\n public override string N70\n {\n get { return \"yetmis\"; }\n }\n\n public override string N80\n {\n get { return \"seksen\"; }\n }\n\n public override string N90\n {\n get { return \"doksan\"; }\n }\n\n public override string N100\n {\n get { return \"yüz\"; }\n }\n\n public override string NHundred\n {\n get { return \"yüz\"; }\n }\n\n public override string N1000\n {\n get { return \"bin\"; }\n }\n\n public override string NThousand\n {\n get { return \"bin\"; }\n }\n\n public override string NMillion\n {\n get { return \"milyon\"; }\n }\n\n public override string NBillion\n {\n get { return \"milyar\"; }\n }\n\n public override string NTrillion\n {\n get { return \"trilyon\"; }\n }\n\n public override string NQuadrillion\n {\n get { return \"trilyar\"; }\n }\n}\n MessageBox.show((string)(new TRYNumberTextValueSource(12345)).Value);\n"
},
{
"answer_id": 859758,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 2,
"selected": false,
"text": "string Number(ulong i)\n{\n static string[] names = [\n \"\"[],\n \" thousand\",\n \" million\",\n \" billion\",\n \" trillion\",\n \" quadrillion\",\n ];\n string ret = null;\n foreach(mult; names)\n {\n if(i%1000 != 0)\n {\n if(ret != null) ret = ret ~ \", \"\n ret = Cent(i%1000) ~ mult ~ ret;\n }\n i /= 1000;\n }\n return ret;\n}\n\nstring Cent(int i)\n{\n static string[] v = \n [\"\"[], \"one\", \"two\", \"three\", \"four\", \n \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n\n static string[] tens = \n [\"!\"[], \"!\", \"twenty\", \"thirty\", \"forty\", \n \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n\n string p1, p2, p3 = \"\";\n\n\n if(i >= 100)\n {\n p1 = v[i/100] ~ \" hundred\";\n p3 = (i % 100 != 0) ? \" and \" : \"\"; //optional\n }\n else\n p1 = \"\";\n\n i %= 100;\n switch(i)\n {\n case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9:\n p2 = v[i];\n break;\n\n case 10: p2 = \"ten\"; break;\n case 11: p2 = \"eleven\"; break;\n case 12: p2 = \"twelve\"; break;\n case 13: p2 = \"thirteen\"; break;\n case 14: p2 = \"fourteen\"; break;\n case 15: p2 = \"fifteen\"; break;\n case 16: p2 = \"sixteen\"; break;\n case 17: p2 = \"seventeen\"; break;\n case 18: p2 = \"eighteen\"; break;\n case 19: p2 = \"nineteen\"; break;\n\n default:\n p2 = tens[i/10] ~ \"-\" ~ v[i%10];\n break;\n\n }\n\n return p1 ~ p3 ~ p2;\n}\n\nimport std.stdio;\nvoid main()\n{\n writef(\"%s\\n\", Number(8_000_400_213));\n}\n"
},
{
"answer_id": 862625,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 5,
"selected": false,
"text": "dd 0ba02c6bfh, 0b8bd10c1h, 0e808b512h, 0ea870100h, 08700e9e8h, 010273eah\ndd 0e0e8c2h, 06b51872h, 0c000ebe8h, 0b3c02e8h, 03368067dh, 0b2e901h\ndd 0baaa5004h, 0fd8110c1h, 0cd7c1630h, 0bf3031bbh, 0a0571000h, 0ec880080h\ndd 0c581c589h, 023c0081h, 0e7f087ch, 0823e38h, 027b00875h, 0e901d068h\ndd 0b6400080h, 04f6f603h, 080d08a1ch, 0b60f80c4h, 07f06c7f4h, 088303000h\ndd 0ac00813eh, 087ef828h, 0b00056e8h, 051e81dh, 0d83850adh, 0e7f157ch\ndd 0a74fc38h, 0262ce088h, 0e901a368h, 01d2c003bh, 0580036e8h, 0b7efc38h\ndd 0774d838h, 0f828e088h, 0800026e8h, 0127e1dfah, 0afd448ah, 0440afe44h\ndd 074f838ffh, 0e8c28a05h, 0cafe000fh, 0ab7cee39h, 05a2405c6h, 021cd09b4h\ndd 05e856c3h, 020b05e00h, 0c5bec3aah, 074c00a02h, 03c80460ah, 0fefa755bh\ndd 046f675c8h, 0745b3cach, 0f8ebaae8h, 0eec1d689h, 08a3c8a03h, 07e180cah\ndd 0cfd2c1feh, 0ebe8c342h, 0fed8d0ffh, 0c3f775cdh, 01e581e8fh, 0303c5ea8h\ndd 0df6f652ah, 078bde03ch, 05e027500h, 01ec1603ch, 07d40793dh, 0603c8080h\ndd 09f6f2838h, 040f17a3dh, 080f17a22h, 0403d7264h, 0793cdee1h, 0140740f1h\ndd 01e2f7d32h, 02f488948h, 0a7c43b05h, 0a257af9bh, 0be297b6ch, 04609e30ah\ndd 0b8f902abh, 07c21e13eh, 09a077d9eh, 054f82ab5h, 0fabe2af3h, 08a6534cdh\ndd 0d32b4c97h, 035c7c8ceh, 082bcc833h, 0f87f154fh, 0650ff7eah, 02f143fdfh\ndd 0a1fd687fh, 0c3e687fdh, 0c6d50fe0h, 075f13574h, 0898c335bh, 0e748ce85h\ndd 08769676fh, 0ad2cedd3h, 0928c77c7h, 077e2d18eh, 01a77e8f6h\ndb 0bah, 01bh\n mov di,strings\n mov dx,tree_data * 8 + 1\n mov bp,code_data * 8\nl1:\n mov ch,8\n call extract_bits\n xchg dx,bp\n call extract_bit\n xchg dx,bp\n jnc l2\n add dx,ax\nl2:\n call extract_bit\n jc l3\n mov ch,6\n call extract_bits\n shr al,2\n cmp al,11\n push l27\n jl get_string\nl25:\n add al,48+32\n stosb\nl27:\n mov dx,tree_data * 8 + 1\nl3:\n cmp bp,end_data * 8\n jl l1\n\nconvert:\n mov bx,'01'\n mov di,01000h\n push di\n\n mov al,[80h]\n mov ah,ch\n mov bp,ax\n add bp,81h\n cmp al,2\n jl zero\n jg l90\n cmp byte ptr [82h],bh\n jne l90\nzero: \n mov al,39\n push done\n\nget_string:\n mov si,strings-1\n or al,al\n je l36\nl35:\n inc si\n cmp byte ptr [si],';'+32\n jne l35\n dec al\n jnz l35\nl36:\n inc si\nl37:\n lodsb\n cmp al,';'+32\n je ret\n stosb\n jmp l37\n\n\nl90:\n inc ax\n mov dh,3\n div dh\n add al,28\n mov dl,al\n add ah,80h\n db 0fh, 0b6h, 0f4h ; movzx si,ah\n mov word ptr [80h],'00'\n\nl95: \n lodsb\n\n sub al,bh\n jle l100\n call get_string2\n mov al,29\n call get_string2\n\nl100:\n lodsw\n push ax\n cmp al,bl\n jl l150\n jg l140\n cmp ah,bh\n je l140\n\n mov al,ah\n sub al,'0'-10\n push l150\n\nget_string2:\n push si\n call get_string\n pop si\n mov al,' '\n stosb\n ret\n\nl140:\n sub al,'0'-19\n call get_string2\n\nl150:\n pop ax\n cmp ah,bh\n jle l200\n cmp al,bl\n je l200\n mov al,ah\n sub al,bh\n call get_string2\n\nl200:\n cmp dl,29\n jle l300\n\n mov al,[si-3]\n or al,[si-2]\n or al,[si-1]\n cmp al,bh\n je l300\n\n mov al,dl\n call get_string2\n\nl300:\n dec dl\n cmp si,bp\n jl l95\n\ndone: \n mov byte ptr [di],'$'\n pop dx\n mov ah,9\n int 21h \n int 20h\n\nl41:\n rcr al,1\n dec ch\n jz ret\n\nextract_bits:\n push l41\nextract_bit:\n mov si,dx\n shr si,3\n mov bh,[si]\n mov cl,dl\n and cl,7\n inc cl\n ror bh,cl\n inc dx\n ret\n\ntree_data:\n dw 01e8fh, 01e58h, 05ea8h, 0303ch, 0652ah, 0df6fh, 0e03ch, 078bdh\n dw 07500h, 05e02h, 0603ch, 01ec1h, 0793dh, 07d40h, 08080h, 0603ch\n dw 02838h, 09f6fh, 07a3dh, 040f1h, 07a22h, 080f1h, 07264h, 0403dh\n dw 0dee1h, 0793ch, 040f1h, 01407h, 07d32h, 01e2fh, 08948h\n db 048h\ncode_data:\n dw 052fh, 0c43bh, 09ba7h, 057afh, 06ca2h, 0297bh, 0abeh, 09e3h\n dw 0ab46h, 0f902h, 03eb8h, 021e1h, 09e7ch, 077dh, 0b59ah, 0f82ah\n dw 0f354h, 0be2ah, 0cdfah, 06534h, 0978ah, 02b4ch, 0ced3h, 0c7c8h\n dw 03335h, 0bcc8h, 04f82h, 07f15h, 0eaf8h, 0ff7h, 0df65h, 0143fh\n dw 07f2fh, 0fd68h, 0fda1h, 0e687h, 0e0c3h, 0d50fh, 074c6h, 0f135h\n dw 05b75h, 08c33h, 08589h, 048ceh, 06fe7h, 06967h, 0d387h, 02cedh\n dw 0c7adh, 08c77h, 08e92h, 0e2d1h, 0f677h, 077e8h, 0ba1ah\n db 01bh\nend_data:\n\nstrings:\n"
},
{
"answer_id": 1176105,
"author": "Gary Benade",
"author_id": 95326,
"author_profile": "https://Stackoverflow.com/users/95326",
"pm_score": 1,
"selected": false,
"text": "convert_number(2850)\n function convert_number($number)\n{\n if (($number < 0) || ($number > 999999999))\n {\n throw new Exception(\"Number is out of range\");\n }\n\n $Gn = floor($number / 1000000); /* Millions (giga) */\n $number -= $Gn * 1000000;\n $kn = floor($number / 1000); /* Thousands (kilo) */\n $number -= $kn * 1000;\n $Hn = floor($number / 100); /* Hundreds (hecto) */\n $number -= $Hn * 100;\n $Dn = floor($number / 10); /* Tens (deca) */\n $n = $number % 10; /* Ones */\n\n $res = \"\";\n\n if ($Gn)\n {\n $res .= convert_number($Gn) . \" Million\";\n }\n\n if ($kn)\n {\n $res .= (empty($res) ? \"\" : \" \") .\n convert_number($kn) . \" Thousand\";\n }\n\n if ($Hn)\n {\n $res .= (empty($res) ? \"\" : \" \") .\n convert_number($Hn) . \" Hundred\";\n }\n\n $ones = array(\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\",\n \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eightteen\",\n \"Nineteen\");\n $tens = array(\"\", \"\", \"Twenty\", \"Thirty\", \"Fourty\", \"Fifty\", \"Sixty\",\n \"Seventy\", \"Eigthy\", \"Ninety\");\n\n if ($Dn || $n)\n {\n if (!empty($res))\n {\n $res .= \" and \";\n }\n\n if ($Dn < 2)\n {\n $res .= $ones[$Dn * 10 + $n];\n }\n else\n {\n $res .= $tens[$Dn];\n\n if ($n)\n {\n $res .= \"-\" . $ones[$n];\n }\n }\n }\n\n if (empty($res))\n {\n $res = \"zero\";\n }\n\n return $res;\n}\n"
},
{
"answer_id": 1179116,
"author": "Sinan Ünür",
"author_id": 100754,
"author_profile": "https://Stackoverflow.com/users/100754",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse Lingua::EN::Numbers qw(num2en);\n\nprint num2en($_), \"\\n\" for 2, 1024, 1024*1024;\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] |
309,892 | <p>I ran into an interesting behavior recently. It seems that if I override .equals() to take a parameter other than Object, it doesn't get called. Can anyone explain to me why this is happening? It seems to violate my understanding of polymorphism in OOP, but maybe I'm missing something.</p>
<p>Here's much simpler code that shows what I'm seeing:</p>
<pre><code>public class MyClass {
private int x;
public MyClass(int n) { x = n; }
public boolean equals(Object o) { return false; }
public boolean equals(MyClass mc) { return x == mc.x; }
public static void main(String[] args) {
List<MyClass> list = new ArrayList<MyClass>();
list.add(new MyClass(3));
System.out.println("Contains 3? " + list.contains(new MyClass(3)));
}
}
</code></pre>
<p>When this is run, it prints "<code>Contains 3? false</code>". It looks like the equals(Object) function is called, even though there is another that would work. By contrast, if I write equals like this the code works as expected:</p>
<pre><code>public boolean equals(Object o) {
if(!(o instanceof MyClass))
return false;
MyClass mc = (MyClass)o;
return x == mc.x;
}
</code></pre>
<p>Why isn't it figuring out which version of the function to call based on the type of the parameter?</p>
| [
{
"answer_id": 309974,
"author": "InverseFalcon",
"author_id": 39455,
"author_profile": "https://Stackoverflow.com/users/39455",
"pm_score": -1,
"selected": false,
"text": "contains() List List<MyClass> List contains() Object equals() MyClass"
},
{
"answer_id": 310165,
"author": "blizpasta",
"author_id": 20646,
"author_profile": "https://Stackoverflow.com/users/20646",
"pm_score": 3,
"selected": false,
"text": "<E boolean contains(Object o)\n Returns true if this list contains the specified element. \n boolean contains(E o)\n Returns true if this list contains the specified element. \n private transient Object elementData[];\n\npublic boolean contains(Object elem) {\n return indexOf(elem) >= 0;\n}\n\npublic int indexOf(Object elem) {\n if (elem == null) {\n for (int i = 0; i < size; i++)\n if (elementData[i]==null)\n return i;\n } else {\n for (int i = 0; i < size; i++)\n if (elem.equals(elementData[i]))\n return i;\n }\n return -1;\n}\n <E class A{ \n public int content; \n A(){\n this(0);\n } \n A(int value){\n content = value;\n } \n public boolean equals(Object obj){\n System.out.println(\"overriding equals method\");\n return this.content == ((A) obj).content;\n } \n public boolean equals(A a){\n System.out.println(\"overloading equals method\");\n return this.content == a.content;\n } \n public static void main(String[] args){\n A x = new A(1);\n A y = new A(2);\n Object z = new A(1);\n System.out.println(x.equals(y));\n System.out.println(x.equals(x));\n System.out.println(x.equals(z));\n //override as z is declared as Object at compile time\n //so it will use methods in class Object instead of class A\n System.out.println(x.equals((Object) y));\n System.out.println(x.equals((Object) x)); \n } \n}\n//rant: they didn't teach me these in javaschool and I had to learn it the hard way.\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
309,921 | <p>Wondering how to open many new windows with Javascript. I have found plenty of places on the internet that show you how to open a new browser window with Javascript, but I want to open a new UNIQUE window. For Example.</p>
<p>I have two links on a page. the user clicks on both links and they are both opened in the same window. I want each link to open a new window WITH JAVASCRIPT.</p>
<p>Another Example.
<strong>I just opened a window with javascript and I have a link inside my newly opened window. I click on the link and it opens in the same window. I want to pop it out of that window WITH JAVASCRIPT, NOT use the same window.</strong></p>
<p>Help?</p>
| [
{
"answer_id": 309926,
"author": "Gavin Miller",
"author_id": 33226,
"author_profile": "https://Stackoverflow.com/users/33226",
"pm_score": 3,
"selected": true,
"text": "window.open('page.html','WindowTitle','width=400,height=200')\n"
},
{
"answer_id": 310129,
"author": "ibsteveog408",
"author_id": 32199,
"author_profile": "https://Stackoverflow.com/users/32199",
"pm_score": 1,
"selected": false,
"text": "window.open(...) var WindowObjectReference = window.open(strUrl, strWindowName [, strWindowFeatures]); \n strWindowName"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
] |
309,922 | <p>Is it only to allow logical grouping?</p>
| [
{
"answer_id": 310030,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 0,
"selected": false,
"text": "PROPERTY(int, MyVal);\n private:\n int fMyVal;\npublic:\n void setMyVal(const int f) { fMyVal = f; };\n int getMyVal() { return fMyVal; };\n protected:\n int v1;\n PROPERTY (int, v2) // fv2 is private with public accessors\n int v3; // whoops. f3 is public,\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37952/"
] |
309,930 | <p>I've got a database with three tables: Books (with book details, PK is CopyID), Keywords (list of keywords, PK is ID) and KeywordsLink which is the many-many link table between Books and Keywords with the fields ID, BookID and KeywordID.</p>
<p>I'm trying to make an advanced search form in my app where you can search on various criteria. At the moment I have it working with Title, Author and Publisher (all from the Book table). It produces SQL like:</p>
<pre><code>SELECT * FROM Books WHERE Title Like '%Software%' OR Author LIKE '%Spolsky%';
</code></pre>
<p>I want to extend this search to also search using tags - basically to add another OR clause to search the tags. I've tried to do this by doing the following</p>
<pre><code>SELECT *
FROM Books, Keywords, Keywordslink
WHERE Title LIKE '%Joel%'
OR (Name LIKE '%good%' AND BookID=Books.CopyID AND KeywordID=Keywords.ID)
</code></pre>
<p>I thought using the brackets might separate the 2nd part into its own kinda clause, so the join was only evaluated in that part - but it doesn't seem to be so. All it gives me is a long list of multiple copies of the one book that satisfies the <code>Title LIKE '%Joel%'</code> bit.</p>
<p>Is there a way of doing this using pure SQL, or would I have to use two SQL statements and combine them in my app (removing duplicates in the process).</p>
<p>I'm using MySQL at the moment if that matters, but the app uses ODBC and I'm hoping to make it DB agnostic (might even use SQLite eventually or have it so the user can choose what DB to use).</p>
| [
{
"answer_id": 309942,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM books WHERE title LIKE'%Joel%' OR bookid IN \n (SELECT bookid FROM keywordslink WHERE keywordid IN\n (SELECT id FROM keywords WHERE name LIKE '%good%'))\n"
},
{
"answer_id": 309948,
"author": "Neil Barnwell",
"author_id": 26414,
"author_profile": "https://Stackoverflow.com/users/26414",
"pm_score": 3,
"selected": false,
"text": "select distinct b.*\nfrom books b\nleft join keywordslink kl on kl.bookid = b.bookid\nleft join keywords k on kl.keywordid = k.keywordid\nwhere b.title like '%assd%'\nor k.keyword like '%asdsad%'\n"
},
{
"answer_id": 309950,
"author": "scwagner",
"author_id": 3981,
"author_profile": "https://Stackoverflow.com/users/3981",
"pm_score": 3,
"selected": true,
"text": "SELECT \n * \nFROM \n Books \n LEFT OUTER JOIN KeywordsLink ON KeywordsLink.BookID = Books.CopyID \n LEFT OUTER JOIN Keywords ON Keywords.ID = KeywordsLink.KeywordID \nWHERE Books.Title LIKE '%JOEL%' \n OR Keywords.Name LIKE '%GOOD%'\n"
},
{
"answer_id": 309954,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 2,
"selected": false,
"text": "UNION (SELECT Books.* FROM <first kind of search>)\nUNION\n(SELECT Books.* FROM <second kind of search>)\n UNION UNION ALL"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912/"
] |
309,939 | <p>I have a class library with all my database logic. My DAL/BLL. </p>
<p>I have a few web projects which will use the same database and classes, so I thought it was a good idea to abstract the data layer into its own project.</p>
<p>However, when it comes to adding functionality to classes for certain projects I want to add methods to certain classes.</p>
<p>For example, my data layer has Product and SomeItem objects:</p>
<pre><code>// Data Access Layer project
namespace DAL {
public class Product {
//implementation here
}
public class SomeItem {
//implementation here
}
}
</code></pre>
<p>In one project I want to add an interface that is used by different content items, so I have a class called:</p>
<pre><code>// This is in Web Project
namespace DAL {
public partial class Product : ICustomBehaviour {
#region ICustomBehaviour Implementation
TheSharedMethod();
#endregion
}
}
</code></pre>
<p><strong>Is it a good idea to write a partial class in a separate project (creating a dependency) using the <em>same</em> namespace? If it's a bad idea, how can I get this type of functionality to work?</strong></p>
<p>It doesn't seem to want to merge them at compile time, so I'm not sure what I'm doing wrong.</p>
| [
{
"answer_id": 383654,
"author": "user47460",
"author_id": 47460,
"author_profile": "https://Stackoverflow.com/users/47460",
"pm_score": 0,
"selected": false,
"text": "Northind.DAL (prj)\n-NorthindDataContext (EntityNamespace set to \"Northwind.BLL\")\n--Product() (Entity, partial class auto-generated)\n--Category() (Entity, partial class auto-generated)\n--Supplier() (Entity, partial class auto-generated)\n\nNorthind.BLL (prj)\n-Product() : IMyCustomEnityInterface, BaseEntity (override OnValidate(), etc)\n-Category() : IMyCustomEnityInterface, BaseEntity (override OnValidate(), etc)\n-Supplier() : IMyCustomEnityInterface, BaseEntity (override OnValidate(), etc)\n"
},
{
"answer_id": 48277694,
"author": "Kasper van den Berg",
"author_id": 814206,
"author_profile": "https://Stackoverflow.com/users/814206",
"pm_score": 4,
"selected": false,
"text": "namespace SharedPartialCodeTryout.DataTypes\n{\n public partial class Address\n {\n public Address(string name, int number, Direction dir)\n {\n this.Name = name;\n this.Number = number;\n this.Dir = dir;\n }\n\n public string Name { get; }\n public int Number { get; }\n public Direction Dir { get; }\n }\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n <PropertyGroup>\n<!-- standard Visual Studio stuff removed -->\n <OutputType>Library</OutputType>\n<!-- standard Visual Studio stuff removed -->\n </PropertyGroup>\n<!-- standard Visual Studio stuff removed -->\n <ItemGroup>\n <Reference Include=\"System\" />\n </ItemGroup>\n <ItemGroup>\n <Compile Include=\"Address.cs\" />\n <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n </ItemGroup>\n <Import Project=\"..\\SharedProject\\SharedProject.projitems\" Label=\"Shared\" />\n <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>\n Address.Direction namespace SharedPartialCodeTryout.DataTypes\n{\n public partial class Address\n {\n public enum Direction\n {\n NORTH,\n EAST,\n SOUTH,\n WEST\n }\n }\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <PropertyGroup Label=\"Globals\">\n <ProjectGuid>33b08987-4e14-48cb-ac3a-dacbb7814b0f</ProjectGuid>\n <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>\n </PropertyGroup>\n <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\\CodeSharing\\Microsoft.CodeSharing.Common.Default.props\" />\n <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\\CodeSharing\\Microsoft.CodeSharing.Common.props\" />\n <PropertyGroup />\n <Import Project=\"SharedProject.projitems\" Label=\"Shared\" />\n <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\\CodeSharing\\Microsoft.CodeSharing.CSharp.targets\" />\n</Project>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <PropertyGroup>\n <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>\n <HasSharedItems>true</HasSharedItems>\n <SharedGUID>33b08987-4e14-48cb-ac3a-dacbb7814b0f</SharedGUID>\n </PropertyGroup>\n <PropertyGroup Label=\"Configuration\">\n <Import_RootNamespace>SharedProject</Import_RootNamespace>\n </PropertyGroup>\n <ItemGroup>\n <Compile Include=\"$(MSBuildThisFileDirectory)Address.Direction.cs\" />\n </ItemGroup>\n</Project>\n Address Address.Direction using SharedPartialCodeTryout.DataTypes;\nusing System;\n\nnamespace SharedPartialCodeTryout.Client\n{\n class Program\n {\n static void Main(string[] args)\n {\n // Create an Address\n Address op = new Address(\"Kasper\", 5297879, Address.Direction.NORTH);\n // Use it\n Console.WriteLine($\"Addr: ({op.Name}, {op.Number}, {op.Dir}\");\n }\n }\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n <PropertyGroup>\n<!-- Removed standard Visual Studio Exe project stuff -->\n <OutputType>Exe</OutputType>\n<!-- Removed standard Visual Studio Exe project stuff -->\n </PropertyGroup>\n<!-- Removed standard Visual Studio Exe project stuff -->\n <ItemGroup>\n <Reference Include=\"System\" />\n </ItemGroup>\n <ItemGroup>\n <Compile Include=\"Program.cs\" />\n <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n </ItemGroup>\n <ItemGroup>\n <None Include=\"App.config\" />\n </ItemGroup>\n <ItemGroup>\n <ProjectReference Include=\"..\\SharedPartialCodeTryout.DataTypes\\SharedPartialCodeTryout.DataTypes.csproj\">\n <Project>{7383254d-bd80-4552-81f8-a723ce384198}</Project>\n <Name>SharedPartialCodeTryout.DataTypes</Name>\n </ProjectReference>\n </ItemGroup>\n <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n <PropertyGroup>\n<!-- Removed standard Visual Studio Exe project stuff -->\n <OutputType>Exe</OutputType>\n<!-- Removed standard Visual Studio Exe project stuff -->\n <?PropertyGroup>\n<!-- Removed standard Visual Studio Exe project stuff -->\n <ItemGroup>\n <Reference Include=\"System\" />\n <Reference Include=\"Microsoft.CSharp\" />\n </ItemGroup>\n <ItemGroup>\n <Compile Include=\"Program.cs\" />\n <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n </ItemGroup>\n <ItemGroup>\n <None Include=\"App.config\" />\n </ItemGroup>\n <Import Project=\"..\\SharedProject\\SharedProject.projitems\" Label=\"Shared\" />\n <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26931/"
] |
309,943 | <p>Need to an expression that returns only things with an "I" followed by either a "J" or a "V" (No Quotes) and then a minimum of 1 number up to 3 numbers.</p>
<p>I J### <br />
I V### <br />
I J## <br />
I V## <br />
I J# <br />
I v# <br /></p>
| [
{
"answer_id": 309952,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": true,
"text": "I(J|V)[0-9]{1,3}\n I (J|V)[0-9]{1,3}\n"
},
{
"answer_id": 309955,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "I [JV]\\d{1,3}\n"
},
{
"answer_id": 310543,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 0,
"selected": false,
"text": "v# I[JVv]\\d{1,3}\n v"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38349/"
] |
309,945 | <p>For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by <code>cursor.execute</code> method on contents of its second parameter.</p>
<p>By "implicit quotation" I mean:</p>
<pre><code>value = "Unsafe string"
query = "SELECT * FROM some_table WHERE some_char_field = %s;"
cursor.execute( query, (value,) ) # value will be correctly quoted
</code></pre>
<p>I would prefer something like that:</p>
<pre><code>value = "Unsafe string"
query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \
READY_TO_USE_QUOTING_FUNCTION(value)
cursor.execute( query ) # value will be correctly quoted, too
</code></pre>
<p>Is such low level <code>READY_TO_USE_QUOTING_FUNCTION</code> expected by Python DB API specification (I couldn't find such functionality in <a href="http://www.python.org/dev/peps/pep-0249/" rel="noreferrer">PEP 249</a> document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...</p>
| [
{
"answer_id": 310011,
"author": "davidavr",
"author_id": 8247,
"author_profile": "https://Stackoverflow.com/users/8247",
"pm_score": 0,
"selected": false,
"text": "connection literal cursor.execute"
},
{
"answer_id": 310078,
"author": "Richard Levasseur",
"author_id": 36805,
"author_profile": "https://Stackoverflow.com/users/36805",
"pm_score": 1,
"selected": false,
"text": "\\ 'my '' quoted string'"
},
{
"answer_id": 310591,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 2,
"selected": false,
"text": "def make_my_query():\n # ...\n return sql, (value1, value2)\n\ndef do_it():\n query = make_my_query()\n cursor.execute(*query)\n"
},
{
"answer_id": 312423,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 6,
"selected": true,
"text": "from psycopg2.extensions import adapt\n\nprint adapt(\"Hello World'; DROP DATABASE World;\")\n from psycopg2.extensions import register_adapter\n\nregister_adapter(mytype, myadapter)\n"
},
{
"answer_id": 312577,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": -1,
"selected": false,
"text": "from django.db import backend\nmy_quoted_variable = backend.DatabaseOperations().quote_name(myvar)\n"
},
{
"answer_id": 13848683,
"author": "Roberto",
"author_id": 446717,
"author_profile": "https://Stackoverflow.com/users/446717",
"pm_score": 0,
"selected": false,
"text": "from psycopg2.extensions import adapt\n\nvalue = \"Unsafe string\"\nquery = \"SELECT * FROM some_table WHERE some_char_field = %s;\" % \\\n adapt(value).getquoted()\ncursor.execute( query ) # value will be correctly quoted, too\n getquoted value \"SELECT * FROM some_table WHERE some_char_field = \" + adapt(value).getquoted()"
},
{
"answer_id": 14763136,
"author": "Sasha Pachev",
"author_id": 2052730,
"author_profile": "https://Stackoverflow.com/users/2052730",
"pm_score": -1,
"selected": false,
"text": "import re\n\ndef db_quote(s):\n return \"\\\"\" + re.escape(s) + \"\\\"\"\n"
},
{
"answer_id": 24590439,
"author": "Beli",
"author_id": 1925300,
"author_profile": "https://Stackoverflow.com/users/1925300",
"pm_score": 4,
"selected": false,
"text": ">>> cur.mogrify(\"INSERT INTO test (num, data) VALUES (%s, %s)\", (42, 'bar'))\n\"INSERT INTO test (num, data) VALUES (42, E'bar')\"\n"
},
{
"answer_id": 54427664,
"author": "asherbret",
"author_id": 2016436,
"author_profile": "https://Stackoverflow.com/users/2016436",
"pm_score": 0,
"selected": false,
"text": ">>> from pypika import Order, Query\n>>> Query.from_('customers').select('id', 'fname', 'lname', 'phone').orderby('id', order=Order.desc)\nSELECT \"id\",\"fname\",\"lname\",\"phone\" FROM \"customers\" ORDER BY \"id\" DESC\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26141/"
] |
309,953 | <p>Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):</p>
<pre><code>jQuery.ajax({
type: "GET",
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
</code></pre>
<p>And also:</p>
<pre><code>jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
});
</code></pre>
<p>I've also tried adding the $.ajaxError but that didn't work either:</p>
<pre><code>jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
</code></pre>
<p>Thanks in advance for any replies!</p>
| [
{
"answer_id": 2085814,
"author": "Fhansen",
"author_id": 253158,
"author_profile": "https://Stackoverflow.com/users/253158",
"pm_score": 2,
"selected": false,
"text": "jQuery(document).ajaxError(function(event, request, settings){\n alert(\"Error\");\n});\n"
},
{
"answer_id": 11159357,
"author": "tomjshore",
"author_id": 1475274,
"author_profile": "https://Stackoverflow.com/users/1475274",
"pm_score": 1,
"selected": false,
"text": "try {\n $.getJSON(ajaxURL,callback).ajaxError();\n} catch(err) {\n alert(\"wow\");\n alert(\"Error : \"+ err);\n}\n alert(\"Error : \" + err);\n"
},
{
"answer_id": 11799589,
"author": "Matt",
"author_id": 1048862,
"author_profile": "https://Stackoverflow.com/users/1048862",
"pm_score": 4,
"selected": false,
"text": "success var success = false;\n\n$.getJSON(url, function(json) {\n success = true;\n // ... whatever else your callback needs to do ...\n});\n\n// Set a 5-second (or however long you want) timeout to check for errors\nsetTimeout(function() {\n if (!success)\n {\n // Handle error accordingly\n alert(\"Houston, we have a problem.\");\n }\n}, 5000);\n var errorTimeout = setTimeout(function() {\n if (!success)\n {\n // Handle error accordingly\n alert(\"Houston, we have a problem.\");\n }\n}, 5000);\n\n$.getJSON(url, function(json) {\n clearTimeout(errorTimeout);\n // ... whatever else your callback needs to do ...\n});\n <script> https://api.site.com/endpoint?this=that&callback=myFunc <script src=\"https://api.site.com/endpoint?this=that&callback=myFunc\"></script>\n <script> {\"answer\":42}\n <script>{\"answer\":42}</script>\n callback myFunc({\"answer\":42})\n <script>myFunc({\"answer\":42})</script>\n myFunc myFunc(data)\n{\n alert(\"The answer to life, the universe, and everything is: \" + data.answer);\n}\n"
},
{
"answer_id": 12407125,
"author": "Marcel",
"author_id": 1668675,
"author_profile": "https://Stackoverflow.com/users/1668675",
"pm_score": 0,
"selected": false,
"text": ".complete(function(response, status) {\n if (response.status == \"404\")\n alert(\"404 Error\");\n else{\n //Do something\n } \n if(status == \"error\")\n alert(\"Error\");\n else{\n //Do something\n }\n});\n"
},
{
"answer_id": 18018822,
"author": "ghost rider3",
"author_id": 1263588,
"author_profile": "https://Stackoverflow.com/users/1263588",
"pm_score": 0,
"selected": false,
"text": "statusCode: {\n 404: function() {\n alert(\"page not found\");\n }\n }\n jQuery.ajax({\ntype: \"GET\",\nstatusCode: {\n 404: function() {\n alert(\"page not found\");\n }\n},\nurl: handlerURL,\ndataType: \"jsonp\",\nsuccess: function(results){\n alert(\"Success!\");\n},\nerror: function(XMLHttpRequest, textStatus, errorThrown){\n alert(\"Error\");\n}\n});\n"
},
{
"answer_id": 18640728,
"author": "Farhan Ahmad",
"author_id": 973155,
"author_profile": "https://Stackoverflow.com/users/973155",
"pm_score": 4,
"selected": false,
"text": "$.getJSON(\"example.json\", function() {\n console.log( \"success\" );\n}).fail(function() { \n console.log( \"error\" ); \n}); \n .fail()"
},
{
"answer_id": 19075701,
"author": "user2314737",
"author_id": 2314737,
"author_profile": "https://Stackoverflow.com/users/2314737",
"pm_score": 6,
"selected": false,
"text": "jQuery.getJSON(handlerURL + \"&callback=?\", \n function(jsonResult){\n alert(\"Success!\");\n })\n.done(function() { alert('getJSON request succeeded!'); })\n.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })\n.always(function() { alert('getJSON request ended!'); });\n"
},
{
"answer_id": 20256923,
"author": "Tom Groentjes",
"author_id": 1369006,
"author_profile": "https://Stackoverflow.com/users/1369006",
"pm_score": 0,
"selected": false,
"text": "$(selector).getJSON(url,data,success(data,status,xhr))\n $.getJSON(url, datatosend, function(data){\n //do something with the data\n});\n \"?callback=?\" $.getJSON(url, datatosend, function(data, status, xhr){\n if (status == \"success\"){\n //do something with the data\n }else if (status == \"timeout\"){\n alert(\"Something is wrong with the connection\");\n }else if (status == \"error\" || status == \"parsererror\" ){\n alert(\"An error occured\");\n }else{\n alert(\"datatosend did not change\");\n } \n});\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12367/"
] |
309,979 | <p>I have a LinkButton that has to postback to perform some logic.</p>
<p>Once it is finished, instead of loading the page back up in the browser, I want to leave it alone and pop open a new window.</p>
<p>So far, the best idea I've had is to put the LinkButton in an UpdatePanel, and have it render some JavaScript out when it reloads, yet I think that is totally hacky. Also, if I recall right, JavaScript within a update panel won't run anyways.</p>
<p>Any other ideas?</p>
| [
{
"answer_id": 310231,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 2,
"selected": false,
"text": "protected void Button1_Click(object sender, EventArgs e)\n\n{\n\n// Do some server side work\n\nstring script = \"window.open('http://www.yahoo.com','Yahoo')\";\n\nif (!ClientScript.IsClientScriptBlockRegistered(\"NewWindow\"))\n\n{\n\nClientScript.RegisterClientScriptBlock(this.GetType(),\"NewWindow\",script, true);\n\n}\n\n}\n"
},
{
"answer_id": 310346,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": true,
"text": "<script runat=\"server\">\n void lnk_Click(object sender, EventArgs e) {\n // Do work\n }\n</script>\n\n<script type=\"text/javascript\">\n var oldTarget, oldAction;\n function newWindowClick(target) {\n var form = document.forms[0];\n oldTarget = form.target;\n oldAction = form.action;\n form.target = target;\n\n window.setTimeout(\n \"document.forms[0].target=oldTarget;\"\n + \"document.forms[0].action=oldAction;\", \n 200\n );\n }\n</script>\n\n<asp:LinkButton runat=\"server\" PostBackUrl=\"Details.aspx\" Text=\"Click Me\"\n OnClick=\"lnk_Click\"\n OnClientClick=\"newWindowClick('details');\" />\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
309,991 | <p>I have a just one table mapped in a datacontext. Here's the property and attribute on the column of interest:</p>
<pre><code>[Column(Storage="_CustomerNumber", DbType="VarChar(25)")]
public string CustomerNumber
{
</code></pre>
<p>This column is, in fact, a varchar(25) and has an index.</p>
<p>I've got some simple code:</p>
<pre><code>DataClasses1DataContext myDC = new DataClasses1DataContext();
myDC.Log = Console.Out;
List<string> myList = new List<string>() { "111", "222", "333" };
myDC.Customers
.Where(c => myList.Contains(c.CustomerNumber))
.ToList();
</code></pre>
<p>Which generates this SQL text:</p>
<pre><code>SELECT [t0].[CustomerNumber], [t0].[CustomerName]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[CustomerNumber] IN (@p0, @p1, @p2)
-- @p0: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [111]
-- @p1: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [222]
-- @p2: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [333]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>
<p>Notice that the paramaters are nvarchar!</p>
<p>When this query hits the database, it generates a horrible plan which involves <strong>converting the multi-million row index on CustomerNumber to nvarchar</strong> before seeking within it.</p>
<p>I'm not allowed to change the table, but I can change the query and the dbml. What can I do to get the data out without getting this index conversion?</p>
| [
{
"answer_id": 310024,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "List<IQueryable<Customer>> myQueries = \n myList.Select(s => myDC.Customers.Where(c => c.CustomerNumber == s)).ToList();\nIQueryable<Customers> myQuery = myQueries.First();\nforeach(IQueryable<Customer> someQuery in myQueries.Skip(1))\n{\n myQuery = myQuery.Concat(someQuery);\n}\nmyQuery.ToList();\n SELECT [t4].[CustomerNumber], [t4].[CustomerName]\nFROM (\n SELECT [t2].[CustomerNumber], [t2].[CustomerName]\n FROM (\n SELECT [t0].[CustomerNumber], [t0].[CustomerName]\n FROM [dbo].[Customer] AS [t0]\n WHERE [t0].[CustomerNumber] = @p0\n UNION ALL\n SELECT [t1].[CustomerNumber], [t1].[CustomerName]\n FROM [dbo].[Customer] AS [t1]\n WHERE [t1].[CustomerNumber] = @p1\n ) AS [t2]\n UNION ALL\n SELECT [t3].[CustomerNumber], [t3].[CustomerName]\n FROM [dbo].[Customer] AS [t3]\n WHERE [t3].[CustomerNumber] = @p2\n ) AS [t4]\n-- @p0: Input VarChar (Size = 3; Prec = 0; Scale = 0) [111]\n-- @p1: Input VarChar (Size = 3; Prec = 0; Scale = 0) [222]\n-- @p2: Input VarChar (Size = 3; Prec = 0; Scale = 0) [333]\n-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.21022.8\n"
},
{
"answer_id": 4147098,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "DbCommand myCommand = myDataContext.GetCommand(query);\n\nforeach (DbParameter dbParameter in myCommand.Parameters)\n{\n if (dbParameter.DbType == System.Data.DbType.String)\n {\n dbParameter.DbType = System.Data.DbType.AnsiString;\n }\n} \n\nmyDataContext.Connection.Open();\n\nSystem.Data.Common.DbDataReader reader = myCommand.ExecuteReader();\nList<RecordType> result = myDataContext.Translate<RecordType>(reader).ToList();\n\nmyDataContext.Connection.Close();\n"
},
{
"answer_id": 18703616,
"author": "Alex Fairchild",
"author_id": 613635,
"author_profile": "https://Stackoverflow.com/users/613635",
"pm_score": 0,
"selected": false,
"text": "ObjectContext DbContext GetCommand() DbParameters ObjectContext List<string> myList = new List<string>() { \"111\", \"222\", \"333\" };\n\nIQueryable<Customers> badQuery = myDC.Customers\n .Where(c => myList.Contains(c.CustomerNumber));\n\nstring query = ((System.Data.Objects.ObjectQuery)badQuery).ToTraceString();\nquery = query.Replace(\",N'\", \",'\").Replace(\"(N'\",\"('\");\n\nList<Customers> customers = myDC.ExecuteStoreQuery<Customers>(query).ToList();\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8155/"
] |
310,010 | <p>There are (at least) two ways that technical debts make their way into projects. The first is by conscious decision. Some problems just are not worth tackling up front, so they are consciously allowed to accumulate as technical debt. The second is by ignorance. The people working on the project don't know or don't realize that they are incurring a technical debt. This question deals with the second. Are there technical debts that you let into your project that would have been trivial to keep out ("If I had only known...") but once they were embedded in the project, they became dramatically more costly? </p>
| [
{
"answer_id": 310076,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "alert('hello there!')"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17834/"
] |
310,017 | <p>I see two types of examples in various places. One uses form fields like</p>
<blockquote>
<p>curl -X PUT -d "phone=123.456.7890" "<a href="http://127.0.0.1/services/rest/user/123" rel="nofollow noreferrer">http://127.0.0.1/services/rest/user/123</a>"</p>
</blockquote>
<p>and the other uses an XML content like (some variation of) this</p>
<blockquote>
<p>echo "<user><id>123</id><phone>123.456.7890</phone></user>" | curl -X PUT -d @- "<a href="http://127.0.0.1/services/rest/user/" rel="nofollow noreferrer">http://127.0.0.1/services/rest/user/</a>"</p>
</blockquote>
<p>It seems like using the form fields has the advantage of brevity and clearly identifying the client's intent by targeting just the modified fields, but makes it awkward to address "deeper" metadata.</p>
<p>Using the XML content has an advantage of being more complete, but the disadvantage of the overhead of figuring out which field the client is actually modifying (assuming that they send back the entire resource with small modifications).</p>
<p>Is there a best practice, or even a more-common practice?</p>
| [
{
"answer_id": 310172,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "<phone type=\"work, mobile\"><num>555-555</num><ext>123</ext></phone>\n phone=555-555&phone-ext=123&phone-type=work&phone-type=mobile\n"
},
{
"answer_id": 313126,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "$ echo '{user: {id: 123, phone: 123.456.7890}}' |\\\n> curl -X PUT -d @- 'http://127.0.0.1/services/rest/user/'\n $ echo '{phone: 123.456.7890}' |\\\n> curl -X PUT -d @- 'http://127.0.0.1/services/rest/user/123.json'\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39784/"
] |
310,018 | <p>Is there any GUI-based tools to assist you with writing and maintaining the configuration file? Any code tools to codegen the config file? What are the best ways to make this a little bit easier? Are most people just using Castle ActiveRecord now?</p>
| [
{
"answer_id": 310221,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": 3,
"selected": true,
"text": "public CustomerMap : ClassMap<Customer>\n{\n public CustomerMap()\n {\n Id(x => x.ID);\n Map(x => x.Name);\n Map(x => x.Credit);\n HasMany<Product>(x => x.Products)\n .AsBag();\n Component<Address>(x => x.Address, m => \n { \n m.Map(x => x.AddressLine1); \n m.Map(x => x.AddressLine2); \n m.Map(x => x.CityName); \n m.Map(x => x.CountryName); \n });\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36590/"
] |
310,031 | <p>I am using Borland Builder C++ 2009. I want to add a button to a form that allows the user to open a file in Excel that I specify. I can't think of how to do this. I know how to link with other code and executables -- is there a Microsoft Excel executable that I could use? How could I specify the file then? Any hints on this, or at least a place to look online, would be greatly appreciated.</p>
| [
{
"answer_id": 310598,
"author": "Shishiree",
"author_id": 23970,
"author_profile": "https://Stackoverflow.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "ShellExecute(NULL, \"open\" ,\"Excel.exe\", \"C:\\\\Documents and Settings\\\\Lab1\\\\My Documents\\\\Waypoint Tool.xls\", NULL, SW_SHOWNORMAL);\n"
},
{
"answer_id": 338842,
"author": "Mesidin",
"author_id": 454,
"author_profile": "https://Stackoverflow.com/users/454",
"pm_score": 2,
"selected": false,
"text": "print(\"ShellExecute(NULL, \"open\" ,\"Waypoint Tool.xls\", \"C:\\\\Documents and Settings\\\\Lab1\\\\My Documents\\\\\", NULL, SW_SHOWNORMAL);\");\n"
},
{
"answer_id": 13121463,
"author": "Elangovan Shanmugam",
"author_id": 1782884,
"author_profile": "https://Stackoverflow.com/users/1782884",
"pm_score": 1,
"selected": false,
"text": "System() system(\"PATH C:\\\\Program\\ Files\\\\Microsoft\\ Office\\\\OFFICE11;%PATH% & excel \\\"C:\\\\Documents and Settings\\\\User\\\\Desktop\\\\ExcelFile.xls\\\"\");\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23970/"
] |
310,032 | <p>When printing a single character in a C program, must I use "%1s" in the format string? Can I use something like "%c"?</p>
| [
{
"answer_id": 310040,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 7,
"selected": false,
"text": "%c printf(\"%c\", 'h');\n putchar putc #include <stdio.h>\n\nint fputc(int c, FILE *stream);\nint putc(int c, FILE *stream);\nint putchar(int c);\n\n* fputc() writes the character c, cast to an unsigned char, to stream.\n* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.\n* putchar(c); is equivalent to putc(c,stdout).\n const char *h = \"hello world\";\nprintf(\"%c\\n\", h[4]); /* outputs an 'o' character */\n"
},
{
"answer_id": 310100,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 4,
"selected": false,
"text": "'c' \"c\" 'c' \"c\""
},
{
"answer_id": 310368,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "char variable = 'x'; // the variable is a char whose value is lowercase x\n\nprintf(\"<%c>\", variable); // print it with angle brackets around the character\n"
},
{
"answer_id": 53697721,
"author": "klutt",
"author_id": 6699433,
"author_profile": "https://Stackoverflow.com/users/6699433",
"pm_score": 2,
"selected": false,
"text": "putchar"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37952/"
] |
310,035 | <p>Is tilde a legitimate character in an XML SOAP message? I get a <code>SAXParseException:Content not allowed in prolog</code>. I included most of the SOAP message just in case I'm barking up the wrong tree.</p>
<pre><code>POST /... HTTP/1.0
Content-Type: text/xml; charset=utf-8
Accept: application/soap+xml, application/dime, multipart/related, text/*
User-Agent: Axis/1.4
Host: 127.0.0.1:1234
Cache-Control: no-cache
Pragma: no-cache
SOAPAction: ""
Content-Length: 1497
Authorization: Basic b3BlbnBkbTpvdHRvMTIz
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns1:query soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://localhost">
<where xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">type ~~ 'command'</where>
</ns1:query>
</soapenv:Body>
</soapenv:Envelope>
</code></pre>
| [
{
"answer_id": 310135,
"author": "Tim Pietzcker",
"author_id": 20670,
"author_profile": "https://Stackoverflow.com/users/20670",
"pm_score": 2,
"selected": false,
"text": "codecs.open(filename, \"UTF-8\") open(filename)"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39787/"
] |
310,036 | <p>Evidently hash keys are compared in a case-sensitive manner.</p>
<pre><code>$ perl -e '%hash = ( FOO => 1 ); printf "%s\n", ( exists $hash{foo} ) ? "Yes" : "No";'
No
$ perl -e '%hash = ( FOO => 1 ); printf "%s\n", ( exists $hash{FOO} ) ? "Yes" : "No";'
Yes
</code></pre>
<p>Is there a setting to change that for the current script?</p>
| [
{
"answer_id": 2886996,
"author": "amphetamachine",
"author_id": 237955,
"author_profile": "https://Stackoverflow.com/users/237955",
"pm_score": 3,
"selected": false,
"text": "my %hash = (FOO => 1);\nmy $key = 'fOo'; # or 'foo' for that matter\n\nmy %lookup = map {(lc $_, $hash{$_})} keys %hash;\nprintf \"%s\\n\", ( exists $hash{(lc $key)} ) ? \"Yes\" : \"No\";\n"
},
{
"answer_id": 26674727,
"author": "Pascal Cimon",
"author_id": 4202466,
"author_profile": "https://Stackoverflow.com/users/4202466",
"pm_score": 1,
"selected": false,
"text": "grep perl -e '%hash = ( FOO => 1 );\n printf \"%s\\n\", ( scalar(grep (/^foo$/i, keys %hash)) > 0) ? \"Yes\" : \"No\";'"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39153/"
] |
310,058 | <p><strong>Problem Statement:</strong>
I would like to create an offline database to lookup prices/info on the n most useful books to sell in the United States (where n is probably 3 million or so). </p>
<p><strong>Question:</strong>
So, my question is (and I am open to other approaches here as well), I am trying to figure out how to use Amazon AWS to download a list of the n higest salesrank books being sold as well as some information about the book (i.e. title, prices, etc...).</p>
<p><strong>What I have done so far:</strong>
First, something like this exists already (asellertool.com), however, I thought this would be an interesting project to work on and quite frankly, we aren't serious enough to need to pay the $30/month subscription.</p>
<p>Now, AWS is great (and easy) if you have a few items you want to look up, but I can't seem to figure out how enumerate on sales rank.
Originally, I was hoping to enumerate all of the book items Amazon had by ISBN. But that wasn't available either. Then I thought I could find a list of all ISBN numbers out there, but that was a dead end too. Finally I thought I could create my own list of ISBN numbers, but as I did some back of the envelope calculations, I thought better of it as my solutions would take roughly a year to go through a third of the 10 digit space at 100/second (and it was overkill anyway).</p>
<p>So, I am back on Sales Ranking, which is currently seems like a dead end as well. So, if you have any thoughts, I would appreciate it.</p>
| [
{
"answer_id": 364339,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 1,
"selected": false,
"text": "Amazon E-Commerce Service"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39758/"
] |
310,062 | <p>I can handle the process that file part, but before I go crazy, has someone built a simple wcf service & client (running under windows services or IIS) that I can use to upload a file, and download that file back? with the fewest lines of code? (C# or VB)</p>
<p>compression & encryption would be cool, but i'll layer that on later!!</p>
<p>Thanks!!</p>
| [
{
"answer_id": 310955,
"author": "Mitch Baker",
"author_id": 37896,
"author_profile": "https://Stackoverflow.com/users/37896",
"pm_score": 3,
"selected": true,
"text": "[ServiceContract]\npublic interface IFileService\n{\n [OperationContract]\n byte[] ProcessFile(byte[] FileData);\n}\n"
},
{
"answer_id": 3456486,
"author": "flayn",
"author_id": 173711,
"author_profile": "https://Stackoverflow.com/users/173711",
"pm_score": 2,
"selected": false,
"text": "[ServiceContract]\npublic interface IFileService\n{\n // returns a Guid which you can use later to request the processed files\n [OperationContract]\n Guid SendFileToProcess(stream streamedFile);\n\n [OperationContract]\n Stream GetProcessedFile(Guid fileId);\n\n // use this to poll whether the service has finished processing\n [OperationContract]\n bool IsFileProcessed(Guid fileId);\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3522/"
] |
310,090 | <p>For 2 child template files inheriting a block, the <code>{{ block.super }}</code> does not resolve</p>
<p>Python 2.5.2, Django 1.0, Windows XP SP3</p>
<p>Sample skeleton code for files involved:</p>
<ol>
<li><code>base.html</code></li>
<li><code>item_base.html</code></li>
<li><code>show_info_for_all_items.html</code></li>
<li><code>show_info_for_single_item.html</code></li>
</ol>
<p>FILE : <code>base.html</code></p>
<pre><code>{% block content %}
{% endblock %}
</code></pre>
<p>FILE : <code>item_base.html</code></p>
<pre><code>{% extends "base.html" %}
{% block item_info %}
Item : {{ item.name }}<br/>
Price : {{ item.price }}<br/>
{% endblock %}
</code></pre>
<p>FILE : <code>show_info_for_all_items.html</code></p>
<pre><code>{% extends "item_base.html" %}
{% block content %}
<h1>info on all items</h1>
<hr/>
{% for item in items %}
{% block item_info %}
{{ block.super }}
{% endblock %}
<hr/>
{% endfor %}
{% endblock %}
</code></pre>
<p>FILE : <code>show_info_for_single_item.html</code></p>
<pre><code>{% extends "item_base.html" %}
{% block content %}
<h1>info on single item</h1>
{% block item_info %}
{{ block.super }}
{% endblock %}
{% endblock %}
</code></pre>
<p><code>show_info_for_all_items.html</code> shows a list of items along with each item's info.</p>
<p><code>show_info_for_single_item.html</code> shows a single item with the item's info.</p>
<p><code>show_info_for_all_items.html</code> and <code>show_info_for_single_item.html</code> share same code for showing item info, so I moved it to <code>item_base.html</code> into <code>block item_info</code></p>
<p>but the <code>{{ block.super }}</code> in <code>show_info_for_all_items.html</code> and <code>show_info_for_single_item.html</code> does not work. <code>{{ block.super }}</code> resolves as blank.</p>
<p>If I move the code back from <code>block item_info</code> in <code>item_base.html</code> into <code>show_info_for_all_items.html</code> and <code>show_info_for_single_item.html</code> it works but then I have to duplicate same <code>block item_info</code> code in 2 files.</p>
<p>If the block.super issue can not be solved, does Django offer something like INCLUDE => <code>{% INCLUDE "item_base.html" %}</code> so blocks from a template file can be included ( instead of <code>extends</code> )</p>
<p>How do I avoid duplicating <code>block item_info</code> in both html files?</p>
| [
{
"answer_id": 310123,
"author": "David Arcos",
"author_id": 30300,
"author_profile": "https://Stackoverflow.com/users/30300",
"pm_score": 4,
"selected": true,
"text": "{% include 'foo.html' %}\n"
},
{
"answer_id": 310819,
"author": "Matthew Marshall",
"author_id": 39856,
"author_profile": "https://Stackoverflow.com/users/39856",
"pm_score": 2,
"selected": false,
"text": "include {% show_item user.favorite_item %}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11452/"
] |
310,094 | <p>In the tradition of <a href="https://stackoverflow.com/questions/309492/user-defined-functions-sql-server-2005-flagged-incorrectly-as-non-deterministic">this question</a> and in light of <a href="http://msdn.microsoft.com/en-us/library/ms178091(SQL.90).aspx" rel="nofollow noreferrer">the documentation</a>, how does one make this function deterministic:</p>
<pre><code>ALTER FUNCTION [udf_DateTimeFromDataDtID]
(
@DATA_DT_ID int -- In form YYYYMMDD
)
RETURNS datetime
WITH SCHEMABINDING
AS
BEGIN
RETURN CONVERT(datetime, CONVERT(varchar, @DATA_DT_ID))
END
</code></pre>
<p>Or this one (because of the string/date literals - and yes, I've also tried '1900-01-01'):</p>
<pre><code>ALTER FUNCTION udf_CappedDate
(
@DateTimeIn datetime
)
RETURNS datetime
WITH SCHEMABINDING
AS
BEGIN
IF @DateTimeIn < '1/1/1900'
RETURN '1/1/1900'
ELSE IF @DateTimeIn > '1/1/2100'
RETURN '1/1/2100'
RETURN @DateTimeIn
END
</code></pre>
| [
{
"answer_id": 310113,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": "CONVERT(datetime, '2008-01-01', 121)\n"
},
{
"answer_id": 310146,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 4,
"selected": true,
"text": "CONVERT RETURN CONVERT(datetime, CONVERT(varchar, @DATA_DT_ID), 112)\n IF @DateTimeIn < CONVERT(datetime, '1/1/1900', 101)\n RETURN CONVERT(datetime, '1/1/1900', 101)\n IF @DateTimeIn < {d '1900-01-01'}\n RETURN {d '1900-01-01'}\n...etc.\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18255/"
] |
310,105 | <p>I've been discussing a code style issue with a friend. We have a series of packages that implement an interface by returning a specific type of value via a named subroutine. For example:</p>
<pre><code>package Foo::Type::Bar;
sub generate_foo {
# about 5-100 lines of code
return stuff here;
}
</code></pre>
<p>So you can go:</p>
<pre><code>my $bar_foo = Foo::Type::Bar->generate_foo;
my $baz_foo = Foo::Type::Baz->generate_foo;
</code></pre>
<p>We have many of these, all under the same <code>Foo::Type::*</code> hierarchy.</p>
<p>I think the packages should clearly indicate that they implement the <code>foo_generate</code> interface, e.g.:</p>
<pre><code>package Foo::Type::Bar;
use base 'Foo::Type';
sub generate_foo {
...
return stuff here;
}
</code></pre>
<p>I think this is good code style, much more clear and clean for other coders exploring the code. It also lets you check <code>Foo::Type::Bar->isa('Foo::Type')</code> to see if it implements the interface (other parts of the subsystem are entirely OO).</p>
<p>My friend disagrees. Some arguments he makes are:</p>
<ul>
<li><code>Foo::Type::*</code> packages are clearly named, and used only in an internal project, and therefore there's no question of wondering whether or not a given package implements an interface</li>
<li>the packages are often small and part of a standalone subsystem, and they feel to him like batch files or conf files, not heavy Perl OO code</li>
<li>Perl expresses implementation via inheritance, which may be complex or problematic, particularly when one gets to multiple inheritance</li>
<li>adding a <code>Foo::Type</code> superclass doesn't add any value, as it would literally be an empty package, used only to enable <code>->isa</code> lookups</li>
<li>programmatically indicating interface implementation is a matter of personal code style</li>
</ul>
<p>Is one or the other of us "right"? What would you do?</p>
<p><em>Edit: in examples, renamed Foo::Generator to Foo::Type</em></p>
| [
{
"answer_id": 310433,
"author": "Joe McMahon",
"author_id": 39791,
"author_profile": "https://Stackoverflow.com/users/39791",
"pm_score": 1,
"selected": false,
"text": "Foo::Type Type Foo::Bar->generate\nFoo::Baz->generate\n Bar Baz Type"
},
{
"answer_id": 310471,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 2,
"selected": false,
"text": "UNIVERSAL::can $unknown->doodle() if $unknown->can( 'doodle' );\n $path_or_OS_I_dont_know_which->format( \"c:\", 'y' );\n if ( $duck->can( 'talk' ) && $duck->can( 'walk' )) { \n $duck->walk();\n $duck->talk();\n}\n if ( $cand->can( 'walk' ) && $cand->can( 'talk' ) && ... && $cand->can( 'gargle' )) {\n ...\n}\n $cand->snicker() if $cand->can( 'snicker' );\n Date @ISA our @ISA = qw<... Date::Compatible ...>;\n isa is_one sub UNIVERSAL::is_one { \n my ( $self, @args ) = @_;\n foreach my $pkg ( @args ) { \n return 1 if $self->isa( $pkg );\n }\n return 0;\n}\n\nsub UNIVERSAL::is_compatible_with {\n my ( $self, $class ) = @_;\n return $self->is_one( $class, \"${class}::Compatible\" );\n}\n"
},
{
"answer_id": 310796,
"author": "Sam Kington",
"author_id": 6832,
"author_profile": "https://Stackoverflow.com/users/6832",
"pm_score": 2,
"selected": false,
"text": "my $bar_foo = Foo::Type::Bar->generate_foo\n my $bar_foo = Foo::Type::Bar::generate_foo\n if (Foo::Type::Bar->isa('Foo::Type')) { ... }\n my $bar_foo = Foo::Type::Bar::generate_foo;\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31100/"
] |
310,108 | <p>Following is some obviously-defective code for which I think the compiler should emit a diagnostic. But neither <code>gcc</code> nor <code>g++</code> does, even with all the warnings options I could think of: <code>-pedantic -Wall -Wextra</code></p>
<pre><code>#include <stdio.h>
short f(short x)
{
return x;
}
int main()
{
long x = 0x10000007; /* bigger than short */
printf("%d\n", f(x)); /* hoping for a warning here */
return 0;
}
</code></pre>
<p>Is there a way to make <code>gcc</code> and <code>g++</code> warn about this? On a side note, do you have another compiler which warns about this by default or in a fairly common extra-warnings configuration?</p>
<p>Note: I'm using GCC (both C and C++ compilers) version 4.2.4.</p>
<p>Edit: I just found that <code>gcc -Wconversion</code> does the trick, but the same option to <code>g++</code> doesn't, and I'm really using C++ here, so I need a solution for <code>g++</code> (and am now wondering why <code>-Wconversion</code> doesn't seem to be it).</p>
<p>Edit: <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34389" rel="noreferrer">http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34389</a> suggests that this may be fixed in <code>g++ 4.4</code>...maybe? It's not clear to me yet if it's the same issue and/or if the fix is really coming in that version. Maybe someone with 4.3 or 4.4 can try my test case.</p>
| [
{
"answer_id": 310163,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 0,
"selected": false,
"text": "diy.cpp 14 Info 734: Loss of precision (arg. no. 1) (31 bits to 15 bits)\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4323/"
] |
310,115 | <p>I am writing a script which is likely to be modified by users. Currently I am storing the configuration settings inside the script. It exists in the form of a hash-of-hashes.</p>
<p>I would like to guard against people accidentally using lowercase characters in the hash keys, because that will break my script.</p>
<p>It would be simple to inspect the hash keys and merely issue warnings for any keys with lowercase characters, but I would rather fix the case sensitivity automatically.</p>
<p>In other words, I want to convert all the hash keys in the top-level hash to uppercase.</p>
| [
{
"answer_id": 310134,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 4,
"selected": false,
"text": "for my $key ( grep { uc($_) ne $_ } keys %hash ) {\n my $newkey = uc $key;\n $hash{$newkey} = delete $hash{$key};\n}\n"
},
{
"answer_id": 310325,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 5,
"selected": true,
"text": "uc uc uc %hash = map { uc $_ => $hash{$_} } keys %hash;\n package UCaseHash;\nrequire Tie::Hash;\n\nour @ISA = qw<Tie::StdHash>;\n\nsub FETCH { \n my ( $self, $key ) = @_;\n return $self->{ uc $key };\n}\n\nsub STORE { \n my ( $self, $key, $value ) = @_;\n $self->{ uc $key } = $value;\n}\n\n1;\n tie my %hash, 'UCaseHash'; \n tie package UCaseHash;\nuse Tie::Hash;\nuse Carp qw<croak>;\n\n...\n\nsub TIEHASH { \n my ( $class_name, $config_file_path ) = @_;\n my $self = $class_name->SUPER::TIEHASH;\n open my $fh, '<', $config_file_path \n or croak \"Could not open config file $config_file_path!\"\n ;\n my %phash = _process_config_lines( <$fh> );\n close $fh;\n $self->STORE( $_, $phash{$_} ) foreach keys %phash;\n return $self;\n}\n tie my %hash, 'UCaseHash', CONFIG_FILE_PATH;\n CONFIG_FILE_PATH"
},
{
"answer_id": 43149710,
"author": "xxnations",
"author_id": 1212036,
"author_profile": "https://Stackoverflow.com/users/1212036",
"pm_score": 0,
"selected": false,
"text": "my $lowercaseghash = convertmaptolowercase(\\%hash);\n\nsub convertmaptolowercase(){\n my $output=$_[0];\n while(my($key,$value) = each(%$output)){\n my $ref;\n if(ref($value) eq \"HASH\"){\n $ref=convertmaptolowercase($value);\n } else {\n $ref=$value;\n }\n delete $output->{$key}; #Removing the existing key\n $key = lc $key;\n $output->{$key}=$ref; #Adding new key\n }\n return $output;\n}\n"
},
{
"answer_id": 74280980,
"author": "Clarius",
"author_id": 4470510,
"author_profile": "https://Stackoverflow.com/users/4470510",
"pm_score": -1,
"selected": false,
"text": "use CGI;\nuse Data::Dumper;\n\nmy $cgi = CGI->new;\n\nprint \"Content-Type: text/html\\n\\n\";\n\n$params = $cgi->Vars();\n\nprint \"<p>Before - \", Dumper($params);\n\nmap { \n if ( $_ =~ qr/[a-z]+/mp ){ \n $params->{uc $_} = $params->{$_}; \n delete($params->{$_}); \n } \n} keys %{$params};\n\nprint \"<p>After - \", Dumper($params);\n\nexit;\n Before - $VAR1 = { 'table' => 'orders', 'SALESMAN_ID' => '2', 'customer_id' => '49' };\n\nAfter - $VAR1 = { 'SALESMAN_ID' => '2', 'TABLE' => 'orders', 'CUSTOMER_ID' => '49' };\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39153/"
] |
310,117 | <p><strong>Caveat:</strong>
I try all the posibilities listed here: <a href="https://stackoverflow.com/questions/254002/how-can-i-ignore-everything-under-a-folder-in-mercurial">How can I ignore everything under a folder in Mercurial</a>.<br>
None works as I hope. </p>
<p>I want to ignore every thing under the folder <code>test</code>. But not ignore <code>srcProject\test\TestManager</code> </p>
<p>I try</p>
<pre><code>syntax: glob
test/**
</code></pre>
<p>And it ignores <code>test</code> and <code>srcProject\test\TestManager</code></p>
<p>With:</p>
<pre><code>syntax: regexp
^/test/
</code></pre>
<p>It's the same thing.</p>
<p>Also with:</p>
<pre><code>syntax: regexp
test\\*
</code></pre>
<p>I have install TortoiseHG 0.4rc2 with Mercurial-626cb86a6523+tortoisehg, Python-2.5.1, PyGTK-2.10.6, GTK-2.10.11 in Windows</p>
| [
{
"answer_id": 310416,
"author": "Nathan Kitchen",
"author_id": 31000,
"author_profile": "https://Stackoverflow.com/users/31000",
"pm_score": 2,
"selected": false,
"text": "test srcProject TestManager syntax: regexp\n(?<!srcProject\\\\)test\\\\(?!TestManager)\n"
},
{
"answer_id": 313392,
"author": "Ry4an Brase",
"author_id": 8992,
"author_profile": "https://Stackoverflow.com/users/8992",
"pm_score": 7,
"selected": true,
"text": "^test/\n ~$ mkdir hg-folder-ignore\n~$ cd hg-folder-ignore\n~/hg-folder-ignore$ echo '^test/' > .hgignore\n~/hg-folder-ignore$ hg init\n~/hg-folder-ignore$ mkdir test\n~/hg-folder-ignore$ touch test/ignoreme\n~/hg-folder-ignore$ mkdir -p srcProject/test/TestManager\n~/hg-folder-ignore$ touch srcProject/test/TestManager/dont-ignore\n~/hg-folder-ignore$ hg stat\n? .hgignore\n? srcProject/test/TestManager/dont-ignore\n"
},
{
"answer_id": 2988676,
"author": "Dziamid",
"author_id": 219931,
"author_profile": "https://Stackoverflow.com/users/219931",
"pm_score": 2,
"selected": false,
"text": "syntax: regexp\n^backup/ #root folder\nnbproject/ #any folder\n syntax: glob\n./backup/* #root folder\nnbproject/* #any folder\n [ui]\nignore = .hg/.hgignore\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356709/"
] |
310,121 | <p>In HTML in the td of a table you can break text by using <code><BR></code> between the words. This also works in the HeaderText of a TemplateItem but not the HeaderText of a BoundField. How do I break up the Header text of a BoundField.</p>
| [
{
"answer_id": 310145,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 6,
"selected": true,
"text": "HtmlEncode = false BoundField <asp:BoundField DataField=\"SomeDataField\" \n HeaderText=\"SomeHeader<br />(OtherData)\" \n HtmlEncode=\"false\" />\n BoundField.HtmlEncode"
},
{
"answer_id": 27554073,
"author": "Tom Padilla",
"author_id": 724317,
"author_profile": "https://Stackoverflow.com/users/724317",
"pm_score": 2,
"selected": false,
"text": "<asp:BoundField DataField=\"ProposedExtractionStartDate\" HeaderText=\"Proposed\n Extraction Start Date\" SortExpression=\"ProposedExtractionStartDate\" DataFormatString=\"{0:MM/dd/yyyy}\" />\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
310,126 | <p>I have a project with a post build event:</p>
<pre><code>copy $(ProjectDir)DbVerse\Lunaverse.DbVerse.*.exe $(TargetDir)
</code></pre>
<p>It works fine every time on my machine. I have a new developer who always gets the "exited with code 1" error. I had her run the same command in a DOS prompt, and it worked fine. What could be causing this? Is there any way to get to the real error?</p>
<p>We are both using Visual Studio 2008.</p>
| [
{
"answer_id": 2291724,
"author": "JanBorup",
"author_id": 276414,
"author_profile": "https://Stackoverflow.com/users/276414",
"pm_score": 6,
"selected": false,
"text": "copy $(TargetDir)$(TargetName).* $(SolutionDir)bin\n copy \"$(TargetDir)$(TargetName).*\" \"$(SolutionDir)bin\"\n"
},
{
"answer_id": 10441677,
"author": "Valamas",
"author_id": 511438,
"author_profile": "https://Stackoverflow.com/users/511438",
"pm_score": 6,
"selected": false,
"text": "robocopy exit code 0 = no files copied\nrobocopy exit code 1 = files copied\nWhen the result is 1, this becomes an error exit code in visual studio.\n exit 0\n rem each robocopy statement and then underneath have the error check.\nif %ERRORLEVEL% GEQ 8 goto failed\n\nrem end of batch file\nGOTO success\n\n:failed\nrem do not pause as it will pause msbuild.\nexit 1\n\n:success\nexit 0 \n timeout 10"
},
{
"answer_id": 13662369,
"author": "firedfly",
"author_id": 3123,
"author_profile": "https://Stackoverflow.com/users/3123",
"pm_score": 2,
"selected": false,
"text": "c:\\projects\\%NotAnEnvironmentVariable%\n c:\\projects\\%%NotAnEnvironmentVariable%%\n"
},
{
"answer_id": 14056037,
"author": "Bohdan Kuts",
"author_id": 1776789,
"author_profile": "https://Stackoverflow.com/users/1776789",
"pm_score": 3,
"selected": false,
"text": "copy \"source of files\" \"destination for files\""
},
{
"answer_id": 40344900,
"author": "TechSavvySam",
"author_id": 453992,
"author_profile": "https://Stackoverflow.com/users/453992",
"pm_score": 3,
"selected": false,
"text": " <PropertyGroup>\n <PostBuildEvent>copy $(ProjectDir)bin\\BLAH.Common.xml $(ProjectDir)App_Data\\BLAH.Common.xml</PostBuildEvent>\n </PropertyGroup>\n <Target Name=\"AfterBuild\">\n <Copy SourceFiles=\"$(ProjectDir)bin\\BLAH.Common.xml\" DestinationFolder=\"$(ProjectDir)App_Data\\\" />\n </Target>\n (PostBuildEvent target) -> \n C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Microsoft.Common.targets(4291,5): error MSB3073: The command \"copy <http://1.2.3.4/job/BLAHv2/ws/Api/bin/BLAH.Common.xml> <http://1.2.3.4/job/BLAHv2/ws/Api/App_Data/BLAH.Common.xml\"> exited with code 1. [<http://1.2.3.4/job/BLAHv2/ws/Api/Api.csproj]>\n"
},
{
"answer_id": 50920544,
"author": "RenniePet",
"author_id": 253938,
"author_profile": "https://Stackoverflow.com/users/253938",
"pm_score": 0,
"selected": false,
"text": "<TargetFrameworks>netstandard1.3;net20</TargetFrameworks>\n copy \"E:\\Yacks\\YacksCore\\YacksCore\\bin\\net20\\Merlinia.YacksCore.dll\" \"E:\\Merlinia\\Trunk-Debug\\Shared Bin\\\"\n MSB3073 The command \"copy \"E:\\Yacks\\YacksCore\\YacksCore\\bin\\net20\\Merlinia.YacksCore.dll\" \"E:\\Merlinia\\Trunk-Debug\\Shared Bin\\\"\" exited with code 1.\n <TargetFrameworks>net20;netstandard1.3</TargetFrameworks>\n"
},
{
"answer_id": 57387925,
"author": "CrazyTim",
"author_id": 737393,
"author_profile": "https://Stackoverflow.com/users/737393",
"pm_score": 0,
"selected": false,
"text": "cd :: Copy file\ncd \"$(ProjectDir)files\\build_scripts\\\"\ncall \"copy.bat\"\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29493/"
] |
310,160 | <p>I'm experimenting with WCF Services, and have come across a problem with passing Interfaces.</p>
<p>This works:</p>
<pre><code>[ServiceContract]
public interface IHomeService
{
[OperationContract]
string GetString();
}
</code></pre>
<p>but this doesn't:</p>
<pre><code>[ServiceContract]
public interface IHomeService
{
[OperationContract]
IDevice GetInterface();
}
</code></pre>
<p>When I try to compile the client it fails on the GetInterface method. I get an Exception saying that it can't convert Object to IDevice.</p>
<p>On the clientside the IHomeService class correctly implements GetString with a string as it's returntype, but the GetInterface has a returntype of object. Why isn't it IDevice?</p>
| [
{
"answer_id": 310179,
"author": "Brian Genisio",
"author_id": 36687,
"author_profile": "https://Stackoverflow.com/users/36687",
"pm_score": 5,
"selected": true,
"text": "[ServiceKnownType(typeof(ConcreteDeviceType)]\n"
},
{
"answer_id": 310291,
"author": "Frode Lillerud",
"author_id": 33431,
"author_profile": "https://Stackoverflow.com/users/33431",
"pm_score": 3,
"selected": false,
"text": "[ServiceContract]\n[ServiceKnownType(typeof(PhotoCamera))]\n[ServiceKnownType(typeof(TemperatureSensor))]\n[ServiceKnownType(typeof(DeviceBase))]\npublic interface IHomeService\n{\n [OperationContract]\n IDevice GetInterface();\n}\n"
},
{
"answer_id": 9992615,
"author": "Myles J",
"author_id": 236573,
"author_profile": "https://Stackoverflow.com/users/236573",
"pm_score": 1,
"selected": false,
"text": "[DataContract]\n[KnownType(typeof(LoadTypeData))]\n[KnownType(typeof(PlanReviewStatusData))]\npublic abstract class RefEntityData : EntityData, IRefEntityData\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33431/"
] |
310,164 | <p>I'm trying to work my way through Ron Jeffries's Extreme Programming Adventures in C#. I am stuck, however, in Chapter 3 because the code does not, and <b>cannot</b>, do what the author says it does. </p>
<p>Basically, the text says that I should be able to write some text in a word-wrap enabled text box. If I then move the cursor to an intermediate line and hit enter, the code should re-display the lines before the cursor, add a couple of lines and a set of HTML paragraph tags, then append the rest of the lines. The code doesn't match the text because it uses the textbox.lines property. Well, no matter how many word-wrapped lines there are in a text box, there's only ONE line in the Lines property until you hit a carriage return. So, the statement that the code should, "Copy the rest of the lines into the buffer" appears wrong to me. </p>
<p>I'd appreciate anybody having experience with the book telling me what I'm reading, or doing, wrong!</p>
<p>Thanks.</p>
<p>EoRaptor</p>
| [
{
"answer_id": 310367,
"author": "EoRaptor013",
"author_id": 16851,
"author_profile": "https://Stackoverflow.com/users/16851",
"pm_score": 0,
"selected": false,
"text": "print(\"using System;\n private String[] lines;\nprivate int selectionStart;\nprivate int cursorPosition;\n\npublic TextModel() {\n\n}\n\npublic String[] Lines {\n get {\n return lines;\n }\n set {\n lines = value;\n }\n}\n\npublic int SelectionStart {\n get {\n return selectionStart;\n }\n set {\n selectionStart = value;\n }\n}\n\npublic int CursorPosition {\n get {\n return cursorPosition;\n }\n set {\n cursorPosition = value;\n }\n}\n\npublic void InsertControlPText() {\n lines[lines.Length - 1] += \"ControlP\";\n}\n\npublic void InsertParagraphTags() {\n int cursorLine = CursorLine();\n String[] newlines = new String[lines.Length + 2];\n for (int i = 0; i <= cursorLine; i++) {\n newlines[i] = lines[i];\n }\n newlines[cursorLine + 1] = \"\";\n newlines[cursorLine + 2] = \"<P></P>\";\n for (int i = cursorLine + 1; i < lines.Length; i++) {\n newlines[i + 2] = lines[i];\n }\n lines = newlines;\n selectionStart = NewSelectionStart(cursorLine + 2);\n}\n\nprivate int CursorLine() {\n int length = 0;\n int lineNr = 0;\n foreach (String s in lines) {\n if (length <= SelectionStart && SelectionStart <= length + s.Length + 2) {\n break;\n length += s.Length + Environment.NewLine.Length;\n lineNr++;\n }\n lineNr++;\n }\n return lineNr;\n}\n\nprivate int NewSelectionStart(int cursorLine) {\n int length = 0;\n for (int i = 0; i < cursorLine; i++) {\n length += lines[i].Length + Environment.NewLine.Length;\n }\n return length + 3;\n}\n"
},
{
"answer_id": 1819581,
"author": "Knightlore",
"author_id": 221310,
"author_profile": "https://Stackoverflow.com/users/221310",
"pm_score": 1,
"selected": false,
"text": "int curPos = txtbox.SelectionStart;\nstring Wrd = Environment.NewLine + \"<P></P>\" + Environment.NewLine; \ntxtbox.SelectedText = Wrd;\nint pl = Environment.NewLine.Length + 3; // \"<P>\" length is 3\n// Put text cursor inbetween <P> tags\ntxtbox.SelectionStart = curPos + pl;\n txtbox.GetLineFromCharIndex(txtbox.SelectionStart)\n txtbox.GetLineFromCharIndex(txtbox.TextLength)\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16851/"
] |
310,167 | <p>At the XmlSerializer constructor line the below causes an InvalidOperationException which also complains about not having a default accesor implemented for the generic type.</p>
<pre><code>Queue<MyData> myDataQueue = new Queue<MyData>();
// Populate the queue here
XmlSerializer mySerializer =
new XmlSerializer(myDataQueue.GetType());
StreamWriter myWriter = new StreamWriter("myData.xml");
mySerializer.Serialize(myWriter, myDataQueue);
myWriter.Close();
</code></pre>
| [
{
"answer_id": 310171,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "List<T> Queue<T> IEnumerable<T> List<T> list = new List<T>(queue);\n"
},
{
"answer_id": 54520107,
"author": "Gianmaria Dalla Torre",
"author_id": 9935017,
"author_profile": "https://Stackoverflow.com/users/9935017",
"pm_score": 0,
"selected": false,
"text": "List<dynamic> sampleListOfRecords = new List<dynamic>();\nQueue<dynamic> recordQueue = new Queue<dynamic>();\n//I add data to queue from a sample list\nforeach(dynamic r in sampleListOfRecords)\n{\n recordQueue.Enqueue(r);\n}\n\n//Serialize\nFile.WriteAllText(\"queue.json\",\n JsonConvert.SerializeObject(recordQueue.ToList(), Formatting.Indented));\n//Deserialize\nList<dynamic> data = \n JsonConvert.DeserializeObject<List<dynamic>>(File.ReadAllText(\"queue.json\"));\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16260/"
] |
310,178 | <p>I need to design a SOAP api (my first one!). What are the best practices regarding errors returned to the caller.</p>
<p>Assuming an api as follow</p>
<pre><code>[WebMethod]
public List<someClass> GetList(String param1)
{
}
</code></pre>
<p>Should I</p>
<ul>
<li>Throw an exception. Let the SOAP infrastructure generate a SOAP fault -- and the caller would have to try/catch. This is not very explanatory to the caller
<ol start="2">
<li>Have the return parameter be a XMLDOcument of some sort, with the first element being a return value and then the List. </li>
<li>Looking at the return SOAP packet I see that the response generated looks like the following</li>
</ol></li>
</ul>
<blockquote>
<p></p>
</blockquote>
<pre><code> <GetListResponse>
<GetListResult>
...
...
</GetListResult>
</GetListResponse>
</code></pre>
<p>Can we somehow change the return packet so that the "GetListResult" element is changed to "GetListError" in case of error</p>
<ul>
<li>Any other way?</li>
</ul>
<p>Thanks!</p>
| [
{
"answer_id": 310356,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 2,
"selected": false,
"text": "public partial interface MyServiceContract\n{\n [System.ServiceModel.FaultContract(typeof(MyService.FaultContracts.ErrorMessageFaultContract))]\n [System.ServiceModel.OperationContract(...)]\n ResponseMessage SOAMethod(RequestMessage request) {...}\n}\n SoapException mySoapException = new SoapException(message, SoapException.ServerFaultCode, \"\", serialzedErrorDataClass);\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37955/"
] |
310,191 | <p>My log file is:</p>
<pre><code> Wed Nov 12 blah blah blah blah cat1
Wed Nov 12 blah blah blah blah
Wed Nov 12 blah blah blah blah
Wed Nov 12 blah blah blah blah cat2
more blah blah
even more blah blah
Wed Nov 12 blah blah blah blah cat3
Wed Nov 12 blah blah blah blah cat4
</code></pre>
<p>I want to parse out the full multiline entries where cat is found on the first line. What's the best way to do this in <code>sed</code> and/or <code>awk</code>?</p>
<p>i.e. i want my parse to produce:</p>
<pre><code> Wed Nov 12 blah blah blah blah cat1
Wed Nov 12 blah blah blah blah cat2
more blah blah
even more blah blah
Wed Nov 12 blah blah blah blah cat3
Wed Nov 12 blah blah blah blah cat4
</code></pre>
| [
{
"answer_id": 310266,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "'\\01' '\\02' c1=`echo -en '\\01'`\nc2=`echo -en '\\02'`\ncat logfile | tr '\\n' $c1 | sed \"s/$c1 /$c2/g\" | sed \"s/$c1/\\n/g\" | grep cat | sed \"s/$c2/\\n /g\"\n"
},
{
"answer_id": 310293,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": 2,
"selected": true,
"text": "awk \" BEGIN { multiline = 0;} \n ! /^ / { if (whatever) \n { print; multiline = 1;} \n else \n multiline = 0; \n } \n /^ / {if (multiline == 1) \n print;\n } \n \" \n yourfile\n whatever"
},
{
"answer_id": 310309,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 0,
"selected": false,
"text": "awk 'function print_part() { if(cat) print part } /^ / { part = part \"\\n\" $0; next } /cat[0-9]$/ { print_part(); part = $0; cat = 1; next; } { print_part(); cat=0} END { print_part() }' inputfile\n /^ / /cat[0-9]$/"
},
{
"answer_id": 23149758,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "RS \\n $ awk -v Pre=Wed 'BEGIN {RS = \"\\\\n?\\\\s*\" Pre} /cat.\\n?/ {print Pre $0}' file.log\nWed Nov 12 blah blah blah blah cat1\nWed Nov 12 blah blah blah blah cat2\n more blah blah\n even more blah blah\nWed Nov 12 blah blah blah blah cat3\nWed Nov 12 blah blah blah blah cat4\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39529/"
] |
310,199 | <p>I am battling regular expressions now as I type. </p>
<p>I would like to determine a pattern for the following example file: <code>b410cv11_test.ext</code>. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. </p>
<p><strong><em>Further clarification of question:</em></strong></p>
<p>I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'</p>
| [
{
"answer_id": 310924,
"author": "Brian C. Lane",
"author_id": 27461,
"author_profile": "https://Stackoverflow.com/users/27461",
"pm_score": 0,
"selected": false,
"text": "/^b\\d\\d\\dcv\\d\\d_test\\.ext$/\n"
},
{
"answer_id": 311033,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 2,
"selected": false,
"text": "^b\\d{3}cv\\d{2}_release\\.ext$\n"
},
{
"answer_id": 311214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "^ ^b [] [ASDF] A S D F [0-9] sed awk [[:digit:]] \\d ^b\\d \\d\\d\\d {} {x,y} ^b\\d{3} ^b\\d{3}cv ^b\\d{3}cv\\d{2} . ^\\d{3}cv\\d{2}_release\\.ext $ ^b\\d{3}cv\\d{2}_release\\.ext$\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37804/"
] |
310,226 | <p>We currently have a heated internal debate as to whether the actual .NET assembly name should include the code's version number (e.g. CodeName02.exe or CompanyName.CodeName02.dll). Does anyone know of an authoritative source, like Microsoft, that provides guidance on this issue?</p>
| [
{
"answer_id": 310241,
"author": "csexton",
"author_id": 19839,
"author_profile": "https://Stackoverflow.com/users/19839",
"pm_score": 5,
"selected": true,
"text": "[assembly: AssemblyVersion(\"1.1.0.256\"]\n[assembly: AssemblyFileVersion(\"1.1.0.256\")]\n"
},
{
"answer_id": 310244,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 3,
"selected": false,
"text": "<Company>.<Component>.dll\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21410/"
] |
310,245 | <p>I'm trying to get a stored procedure to work for a co-worker who is out sick (and thus can't be asked for guidance).</p>
<p>I have a SQL Server 2005 database that has this exact procedure, and I'm trying to make the scripts to convert a test database to match this dev database. My script has several lines like:</p>
<pre><code>CAST(RELATIVE_ERROR_RATIO AS FLOAT),
CAST(REPORTING_LIMIT AS FLOAT),
</code></pre>
<p>The procedure is essentially doing an "insert into table (all the fields) from another table where field = @input"</p>
<p>When I run the script, I get the error:</p>
<pre><code>CAST or CONVERT: invalid attributes specified for type 'float'
</code></pre>
<p>and the procedure is not created. But, I've compared the source tables in both the dev and test environments, and they match exactly. And the procedure exists exactly as scripted in the dev environment. </p>
<p>I can't ask my co-worker if he had to do any special acrobatics to create this script, so I'm asking you. I've done some searching, and see that perhaps float should be of the form FLOAT(6,1) (or some such), but that's NOT what he has, and I'm not comfortable changing the test environment so that it won't really match dev.</p>
<p><strong>Added</strong></p>
<p>The commenter is correct. I've been told that the error is with the following cast: </p>
<pre><code>CAST(TRACER_YIELD AS FLOAT(10,3)),
</code></pre>
<p>I could post the entire query, but it's a long one! So, instead, I'll just include the casted fields, and the first and last field. I'd like to ask my co-worker if that one field was a mistake, and it just needed a straight cast. He'll be back next monday, so it may need to wait that long.</p>
<pre><code>CREATE PROCEDURE [dbo].[our_LOAD_INPUT]
@ourNUMBER INT
AS
INSERT INTO our_FILE (our_NUMBER,
DILUTION_FACTOR,
DISTILLATION_VOLUME,
MAXIMUM_CONTROL_LIMIT,
MDA,
MINIMUM_CONTROL_LIMIT,
NUMBER_OF_TICS_FOUND,
PERCENT_MOISTURE,
PERCENT_RECOVERY,
PERCENT_SOLIDS,
RELATIVE_ERROR_RATIO,
REPORTING_LIMIT,
REQUIRED_DETECTION_LIMIT,
RER_MAX,
RESULT,
RETENTION_TIME,
RPD,
RPD_MAXIMUM,
SAMPLE_ALIQUOT_SIZE,
SPIKE_CONCENTRATION,
TOTAL_PROPAGATED_UNCERTAINTY,
TRACER_YIELD,
TWO_SIGMA_COUNTING_ERROR,
VERSION)
SELECT FILE_NUMBER,
CAST(DILUTION_FACTOR AS FLOAT),
CAST(DISTILLATION_VOLUME AS FLOAT),
CAST(MAXIMUM_CONTROL_LIMIT AS FLOAT),
CAST(MDA AS FLOAT),
CAST(MINIMUM_CONTROL_LIMIT AS FLOAT),
CAST(NUMBER_OF_TICS_FOUND AS FLOAT),
CAST(PERCENT_MOISTURE AS FLOAT),
CAST(PERCENT_RECOVERY AS FLOAT),
CAST(PERCENT_SOLIDS AS FLOAT),
CAST(RELATIVE_ERROR_RATIO AS FLOAT),
CAST(REPORTING_LIMIT AS FLOAT),
CAST(REQUIRED_DETECTION_LIMIT AS FLOAT),
CAST(RER_MAX AS FLOAT),
CAST(RESULT AS FLOAT),
CAST(RETENTION_TIME AS FLOAT),
CAST(RPD AS FLOAT),
CAST(RPD_MAXIMUM AS FLOAT),
CAST(SAMPLE_ALIQUOT_SIZE AS FLOAT),
CAST(SPIKE_CONCENTRATION AS FLOAT),
CAST(TOTAL_PROPAGATED_UNCERTAINTY AS FLOAT),
CAST(TRACER_YIELD AS FLOAT(10,3)),
CAST(TWO_SIGMA_COUNTING_ERROR AS FLOAT),
VERSION
FROM our_FILE_CHAR
WHERE our_NUMBER = @ourNUMBER
GO
</code></pre>
<p>our_File_CHAR is defined as</p>
<pre><code>CREATE TABLE [dbo].[our_FILE_CHAR]
(
[our_NUMBER] [int] NOT NULL,
[DILUTION_FACTOR] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[DISTILLATION_VOLUME] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[MAXIMUM_CONTROL_LIMIT] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[MDA] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[MINIMUM_CONTROL_LIMIT] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[NUMBER_OF_TICS_FOUND] [varchar] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PERCENT_MOISTURE] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PERCENT_RECOVERY] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PERCENT_SOLIDS] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[RELATIVE_ERROR_RATIO] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[REPORTING_LIMIT] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[REQUIRED_DETECTION_LIMIT] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[RER_MAX] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[RESULT] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[RETENTION_TIME] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[RPD] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[RPD_MAXIMUM] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[SAMPLE_ALIQUOT_SIZE] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[SPIKE_CONCENTRATION] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[TOTAL_PROPAGATED_UNCERTAINTY] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[TRACER_YIELD] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[TWO_SIGMA_COUNTING_ERROR] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[VERSION] [varchar] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)
</code></pre>
<p>our_File is defined as</p>
<pre><code>CREATE TABLE [dbo].[our_FILE]
(
[our_NUMBER] [int] NOT NULL,
[DILUTION_FACTOR] [numeric] (10, 3) NULL,
[DISTILLATION_VOLUME] [numeric] (5, 1) NULL,
[MAXIMUM_CONTROL_LIMIT] [numeric] (10, 3) NULL,
[MDA] [numeric] (10, 3) NULL,
[MINIMUM_CONTROL_LIMIT] [numeric] (10, 3) NULL,
[NUMBER_OF_TICS_FOUND] [numeric] (2, 0) NULL,
[PERCENT_MOISTURE] [numeric] (5, 1) NULL,
[PERCENT_RECOVERY] [numeric] (10, 3) NULL,
[PERCENT_SOLIDS] [numeric] (5, 1) NULL,
[RELATIVE_ERROR_RATIO] [numeric] (10, 3) NULL,
[REPORTING_LIMIT] [numeric] (10, 2) NULL,
[REQUIRED_DETECTION_LIMIT] [numeric] (10, 2) NULL,
[RER_MAX] [numeric] (10, 3) NULL,
[RESULT] [numeric] (13, 3) NULL,
[RETENTION_TIME] [numeric] (6, 2) NULL,
[RPD] [numeric] (10, 3) NULL,
[RPD_MAXIMUM] [numeric] (10, 3) NULL,
[SAMPLE_ALIQUOT_SIZE] [numeric] (10, 3) NULL,
[SPIKE_CONCENTRATION] [numeric] (10, 3) NULL,
[TOTAL_PROPAGATED_UNCERTAINTY] [numeric] (13, 3) NULL,
[TRACER_YIELD] [numeric] (10, 3) NULL,
[TWO_SIGMA_COUNTING_ERROR] [numeric] (10, 3) NULL,
[VERSION] [varchar] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)
</code></pre>
| [
{
"answer_id": 315330,
"author": "thursdaysgeek",
"author_id": 22523,
"author_profile": "https://Stackoverflow.com/users/22523",
"pm_score": 1,
"selected": true,
"text": "CAST(TRACER_YIELD AS FLOAT(10,3)),\n CAST(TRACER_YIELD AS FLOAT),\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22523/"
] |
310,247 | <p>Whenever I create a method signature in VS 2008 (C#), I type the two braces:</p>
<p>public void Something() {}</p>
<p>This leaves the cursor to the right of the closing brace. Then I have to use the arrow keys to reposition the cursor in between the braces. Is there a better way to do this without using the arrow keys?</p>
<p>I'd expect it to place the cursor in between the braces when I type the closing one so I can start typing code.</p>
| [
{
"answer_id": 310616,
"author": "CrashCodes",
"author_id": 16260,
"author_profile": "https://Stackoverflow.com/users/16260",
"pm_score": 3,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<CodeSnippets xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n <CodeSnippet Format=\"1.0.0\">\n <Header>\n <Title>b</Title>\n <Shortcut>b</Shortcut>\n <Description>Braces with cursor inside</Description>\n <Author>CrashCodes</Author>\n </Header>\n <Snippet>\n <Code Language=\"csharp\"><![CDATA[{\n $end$\n }]]>\n </Code>\n </Snippet>\n </CodeSnippet>\n</CodeSnippets> \n"
},
{
"answer_id": 15749746,
"author": "reggaeguitar",
"author_id": 2125444,
"author_profile": "https://Stackoverflow.com/users/2125444",
"pm_score": 1,
"selected": false,
"text": " Sub InsertCurlyBraces()\n DTE.ActiveDocument.Selection.NewLine()\n DTE.ActiveDocument.Selection.Text = \"{\"\n DTE.ActiveDocument.Selection.NewLine(2)\n DTE.ActiveDocument.Selection.Text = \"}\"\n DTE.ActiveDocument.Selection.LineUp()\nEnd Sub\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,269 | <p>I am unable to build my Web Application (not Web Site) in our build environement. We use DMAKE in our build environment (this unfortunately is non negotiable, therefore using MSBUILD is not permitted ) and when invoking the asp.net precompiler through</p>
<p>C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler -d -nologo -p Site -f -fixednames -errorstack -v / Debug</p>
<p>We get the following error</p>
<p>error ASPPARSE: Could not load type 'X.Y.Admin.Site.Global</p>
<p>If I compile from the ide it is successful. If i then compile with aspnet_compilier it is successful. So i only get a successful compile with aspnet_compiler when the target dll i am trying to compile is in the bin of the web application i am compiling.</p>
<p>I keep running into postings that talk about solutions using MSBUILD which unfortunately I cant try.</p>
<p>Any help would be appreciated</p>
| [
{
"answer_id": 19512633,
"author": "user2537805",
"author_id": 2537805,
"author_profile": "https://Stackoverflow.com/users/2537805",
"pm_score": 0,
"selected": false,
"text": "aspnet_compiler -p D:\\Projects\\MGM\\mgm\\mgm -v / D:\\Projects\\MGM-deploy\\mgm_compiled\n"
},
{
"answer_id": 37549194,
"author": "dmathisen",
"author_id": 1308734,
"author_profile": "https://Stackoverflow.com/users/1308734",
"pm_score": 1,
"selected": false,
"text": "bin obj .sou"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39802/"
] |
310,271 | <p>I'm an end-user of one of my company's products. It is not very suitable for integration into Spring, however I am able to get a handle on the context and retrieve the required bean by name. However, I would still like to know if it was possible to inject a bean into this class, even though the class is not managed by Spring itself.</p>
<p>Clarification: The same application which is managing the lifecycle of some class MyClass, is also managing the lifecycle of the Spring context. Spring does not have any knowledge of the instance of MyClass, and I would like to some how provide the instance to the context, but cannot create the instance in the context itself.</p>
| [
{
"answer_id": 312367,
"author": "Yonatan Maman",
"author_id": 20065,
"author_profile": "https://Stackoverflow.com/users/20065",
"pm_score": 2,
"selected": false,
"text": "class C implmenets ApplicationContextAware{\n public static ApplicationContex ac;\n void setApplicationContext(ApplicationContext applicationContext) {\n ac = applicationContext;\n }\n .............\n}\n (Z)(C.ac.getBean(\"classZ\")).doSomething()\n"
},
{
"answer_id": 1377740,
"author": "David Tinker",
"author_id": 159434,
"author_profile": "https://Stackoverflow.com/users/159434",
"pm_score": 7,
"selected": true,
"text": "ApplicationContext ctx = ...\nYourClass someBeanNotCreatedBySpring = ...\nctx.getAutowireCapableBeanFactory().autowireBeanProperties(\n someBeanNotCreatedBySpring,\n AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);\n @Autowired YourClass"
},
{
"answer_id": 18215559,
"author": "Dave",
"author_id": 218028,
"author_profile": "https://Stackoverflow.com/users/218028",
"pm_score": 2,
"selected": false,
"text": "new"
},
{
"answer_id": 18217273,
"author": "Donal Fellows",
"author_id": 301832,
"author_profile": "https://Stackoverflow.com/users/301832",
"pm_score": 2,
"selected": false,
"text": "@Configuration @Bean prototype @Configuration\npublic class FooBarMaker {\n @Bean(autowire = Autowire.BY_TYPE)\n @Scope(\"prototype\")\n public FooBar makeAFooBar() {\n // You probably need to do some more work in here, I imagine\n return new FooBar();\n }\n}\n @Configuration"
},
{
"answer_id": 22239268,
"author": "GreenGiant",
"author_id": 539048,
"author_profile": "https://Stackoverflow.com/users/539048",
"pm_score": 0,
"selected": false,
"text": "Object externalObject = ...\nGenericApplicationContext parent = new StaticApplicationContext();\nparent.getBeanFactory().registerSingleton( \"externalObject\", externalObject );\nparent.refresh();\nApplicationContext appContext = new ClassPathXmlApplicationContext( ... , parent);\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8528/"
] |
310,276 | <p>I'm working on a programming language, and today I got the point where I could compile the factorial function(recursive), however due to the maximum size of an integer the largest I can get is factorial(12). What are some techniques for handling integers of an arbitrary maximum size. The language currently works by translating code to C++.</p>
| [
{
"answer_id": 310464,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 2,
"selected": false,
"text": "class BigAssNumber {\n private byte[] value;\n\n // This constructor can handle numbers where overflows have occurred.\n public BigAssNumber(byte[] value) {\n this.value=normalize(value);\n }\n\n // Adds two numbers and returns the sum. Originals not changed.\n public BigAssNumber add(BigAssNumber other) {\n // This needs to be a byte by byte copy in newly allocated space, not pointer copy!\n byte[] dest = value.length > other.length ? value : other.value; \n\n // Just add each pair of numbers, like in a pencil and paper addition problem.\n for(int i=0; i<min(value.length, other.value.length); i++)\n dest[i]=value[i]+other.value[i];\n\n // constructor will fix overflows.\n return new BigAssNumber(dest);\n }\n\n // Fix things that might have overflowed 0,17,22 will turn into 1,9,2 \n private byte[] normalize(byte [] value) {\n if (most significant digit of value is not zero)\n extend the byte array by a few zero bytes in the front (MSB) position.\n\n // Simple cheap adjust. Could lose inner loop easily if It mattered.\n for(int i=0;i<value.length;i++)\n while(value[i] > 9) {\n value[i] -=10;\n value[i+1] +=1;\n }\n }\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37181/"
] |
310,282 | <p>Recently, I found myself having to write up some concerns I have about race conditions in an application that is in development (not by me). This will likely be brought to the attention of stakeholders who are non-technical and with whom I do not have a direct line of communication, so my explanation needs to be in written form.</p>
<p>I have already made an attempt at this write-up. I gloss over the technical specifics as best I can, give an example of how a race condition would occur in the application, and describe its impact. I feel I did pretty well, but it's far from perfect.</p>
<p>The problem is, as much as I try to shield the reader from computer science, I have still found it difficult to eliminate phrases like "threads of execution" and "mutual exclusion" without losing correctness and substance. The risk is that, with too much hand-waving, these concerns could be dismissed as a made-up boogeyman.</p>
<p>Anyway, my question to you is this: <strong>How would <em>you</em> explain race conditions to a non-technical audience?</strong> Would you dare to explain CPU scheduling? Would you invoke the <a href="http://en.wikipedia.org/wiki/Dining_philosophers_problem" rel="noreferrer">dining philosophers</a>?</p>
<p><em>You don't have to work within the constraints of my situation (but it would be awesomely helpful if you did).</em></p>
| [
{
"answer_id": 35898639,
"author": "Michiel van der Blonk",
"author_id": 219041,
"author_profile": "https://Stackoverflow.com/users/219041",
"pm_score": 0,
"selected": false,
"text": "player 1 grabs a red block\nplayer 1 places red block - player 2 grabs an orange block\nplayer 1 grabs an orange block - player 2 places an orange block\nplayer 1 places an orange block\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28340/"
] |
310,286 | <p>The default behavior of NHibernate is the write all changes to objects to the database when Session.Flush() is called. It does this whether you want it to or not.</p>
<p>How do we prevent writing bad data to the database when we need to do things like validate business rules or input?</p>
<p>For instance .. </p>
<ul>
<li>Customer Name is not null. </li>
<li>User opens a web browser (without javascript) and deletes the customer name. </li>
<li>Hits update. </li>
<li><code>Customer.Name</code> property is updated and .. </li>
<li><code>Customer.IsValid()</code> is called. </li>
<li>Even if <code>IsValid()</code> is false and we show error messages NHibernate still updates the database.</li>
</ul>
| [
{
"answer_id": 310891,
"author": "KevinT",
"author_id": 39561,
"author_profile": "https://Stackoverflow.com/users/39561",
"pm_score": 0,
"selected": false,
"text": "SessionScope session = new SessionScope(FlushAction.Never);\n"
},
{
"answer_id": 310906,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 1,
"selected": false,
"text": "Flush() WriteAllChangesToObjectsToTheDatabase()"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34133/"
] |
310,294 | <p>I'm using a regex that <a href="http://regexlib.com/REDetails.aspx?regexp_id=646" rel="nofollow noreferrer">strips the href tags out of an html doc</a> saved to a string. The following code is how I'm using it in my C# console app.</p>
<pre><code>Match m = Regex.Match(htmlSourceString, "href=[\\\"\\\'](http:\\/\\/|\\.\\/|\\/)?\\w+(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?[\\\"\\\']");
if (m.Success)
{
Console.WriteLine("values = " + m);
}
</code></pre>
<p>However, it only returns one result, instead of a list of all the href tags on the html page. I know it works, because when I trying <code>RegexOptions.RightToLeft</code>, it returns the last href tag in the string. </p>
<p>Is there something with my if statement that doesn't allow me to return all the results?</p>
| [
{
"answer_id": 314097,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 3,
"selected": true,
"text": " Match m = Regex.Match(htmlSourceString, \"href=[\\\\\\\"\\\\\\'](http:\\\\/\\\\/|\\\\.\\\\/|\\\\/)?\\\\w+(\\\\.\\\\w+)*(\\\\/\\\\w+(\\\\.\\\\w+)?)*(\\\\/|\\\\?\\\\w*=\\\\w*(&\\\\w*=\\\\w*)*)?[\\\\\\\"\\\\\\']\");\n Console.Write(\"values = \");\n while (m.Success) \n { \n Console.Write(m.Value);\n Console.Write(\", \"); // Delimiter\n m = m.NextMatch();\n }\n Console.WriteLine();\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557/"
] |
310,307 | <p>Earlier I asked this question <a href="https://stackoverflow.com/questions/309708/how-to-correctly-unit-test-my-dal">How to correctly unit test my DAL?</a>, one thing left unanswered for me is if to really test my DAL is to have a Test DB, then what is the role of mocking vs. a testing DB?</p>
<p>To add on this, another person suggested to "use transactions and rollback at the end of the unit test, so the db is clean", test db that is. What do you guys think of this testing + test DB + transaction rollback (so db is not really written) approach to test DAL?</p>
<p>To be complete, my DAL is built with Entity Framework, there is no stored proc in DB. Since EF is so new, I really need to test DAL to make sure they work correctly.</p>
| [
{
"answer_id": 310609,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 1,
"selected": false,
"text": "List<Item> getAllItems()"
},
{
"answer_id": 12303003,
"author": "Darren Rich",
"author_id": 1652428,
"author_profile": "https://Stackoverflow.com/users/1652428",
"pm_score": -1,
"selected": false,
"text": "DbSet public class MusicStoreEntities : DbContext\n {\n public DbSet<Album> Albums { get; set; }\n public DbSet<Genre> Genres { get; set; }\n public DbSet<Artist> Artists { get; set; }\n public DbSet<Cart> Carts { get; set; }\n public DbSet<Order> Orders { get; set; }\n public DbSet<OrderDetail> OrderDetails { get; set; }\n }\n List<t>"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32240/"
] |
310,333 | <p>What's wrong with the following snippet ?</p>
<pre><code>#include <tr1/functional>
#include <functional>
#include <iostream>
using namespace std::tr1::placeholders;
struct abc
{
typedef void result_type;
void hello(int)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
void hello(int) const
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
abc()
{}
};
int
main(int argc, char *argv[])
{
const abc x;
int a = 1;
std::tr1::bind(&abc::hello, x , _1)(a);
return 0;
}
</code></pre>
<p>Trying to compile it with g++-4.3, it seems that <em>cv</em>-qualifier overloaded functions confuse both <code>tr1::mem_fn<></code> and <code>tr1::bind<></code> and it comes out the following error:</p>
<pre><code>no matching function for call to ‘bind(<unresolved overloaded function type>,...
</code></pre>
<p>Instead the following snippet compiles but seems to break the <strong>const-correctness</strong>:</p>
<pre><code>struct abc
{
typedef void result_type;
void operator()(int)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
void operator()(int) const
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
abc()
{}
};
...
const abc x;
int a = 1;
std::tr1::bind( x , _1)(a);
</code></pre>
<p>Any clue?</p>
| [
{
"answer_id": 310364,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 3,
"selected": true,
"text": "this typedef void (abc::*fptr)(int) const; // or remove const\nstd::tr1::bind((fptr)&abc::hello, x , _1)(a);\n const this typedef void (abc::*fptr)(int) const; // won't compile without const (good!)\nstd::tr1::bind((fptr)&abc::hello, &x , _1)(a);\n & bind"
},
{
"answer_id": 311169,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 1,
"selected": false,
"text": "bind() std::tr1::bind(static_cast< void(abc::*)(int) const >(&abc::hello), x, _1)(a);\n reference_wrapper<> std::tr1::bind( std::tr1::ref(x) , _1)(a);\n bind() a operator()"
},
{
"answer_id": 328593,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 1,
"selected": false,
"text": "std::tr1::bind<void(foo::*)(int)>(&foo::bar);\n static_cast"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19630/"
] |
310,342 | <p>A quick search gave me this <a href="http://www.mail-archive.com/dbdi-dev@perl.org/msg00002.html" rel="nofollow noreferrer">announcement of Parrot DBDI</a> from January 2004 and a <a href="http://www.mail-archive.com/dbdi-dev@perl.org/" rel="nofollow noreferrer">dbdi-dev mailing list</a> which appears to be long dead. Is Parrot DBDI still being developed? Is anyone working on a different database API or interface for Parrot?</p>
| [
{
"answer_id": 310364,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 3,
"selected": true,
"text": "this typedef void (abc::*fptr)(int) const; // or remove const\nstd::tr1::bind((fptr)&abc::hello, x , _1)(a);\n const this typedef void (abc::*fptr)(int) const; // won't compile without const (good!)\nstd::tr1::bind((fptr)&abc::hello, &x , _1)(a);\n & bind"
},
{
"answer_id": 311169,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 1,
"selected": false,
"text": "bind() std::tr1::bind(static_cast< void(abc::*)(int) const >(&abc::hello), x, _1)(a);\n reference_wrapper<> std::tr1::bind( std::tr1::ref(x) , _1)(a);\n bind() a operator()"
},
{
"answer_id": 328593,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 1,
"selected": false,
"text": "std::tr1::bind<void(foo::*)(int)>(&foo::bar);\n static_cast"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311/"
] |
310,355 | <p>Is there any way to access the Windows Event Log from a java class. Has anyone written any APIs for this, and would there be any way to access the data from a remote machine?</p>
<p>The scenario is:</p>
<p>I run a process on a remote machine, from a controlling Java process.
This remote process logs stuff to the Event Log, which I want to be able to see in the controlling process.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 786129,
"author": "Dan Fleet",
"author_id": 95492,
"author_profile": "https://Stackoverflow.com/users/95492",
"pm_score": 4,
"selected": false,
"text": "import java.io.IOException;\nimport java.util.logging.Level;\n\nimport org.jinterop.dcom.common.JIException;\nimport org.jinterop.dcom.common.JISystem;\nimport org.jinterop.dcom.core.JIComServer;\nimport org.jinterop.dcom.core.JIProgId;\nimport org.jinterop.dcom.core.JISession;\nimport org.jinterop.dcom.core.JIString;\nimport org.jinterop.dcom.core.JIVariant;\nimport org.jinterop.dcom.impls.JIObjectFactory;\nimport org.jinterop.dcom.impls.automation.IJIDispatch;\n\npublic class EventLogListener\n{\n\n private static final String WMI_DEFAULT_NAMESPACE = \"ROOT\\\\CIMV2\";\n\n\n private static JISession configAndConnectDCom( String domain, String user, String pass ) throws Exception\n {\n JISystem.getLogger().setLevel( Level.OFF );\n\n try\n {\n JISystem.setInBuiltLogHandler( false );\n }\n catch ( IOException ignored )\n {\n ;\n }\n\n JISystem.setAutoRegisteration( true );\n\n JISession dcomSession = JISession.createSession( domain, user, pass );\n dcomSession.useSessionSecurity( true );\n return dcomSession;\n }\n\n\n private static IJIDispatch getWmiLocator( String host, JISession dcomSession ) throws Exception\n {\n JIComServer wbemLocatorComObj = new JIComServer( JIProgId.valueOf( \"WbemScripting.SWbemLocator\" ), host, dcomSession );\n return (IJIDispatch) JIObjectFactory.narrowObject( wbemLocatorComObj.createInstance().queryInterface( IJIDispatch.IID ) );\n }\n\n\n private static IJIDispatch toIDispatch( JIVariant comObjectAsVariant ) throws JIException\n {\n return (IJIDispatch) JIObjectFactory.narrowObject( comObjectAsVariant.getObjectAsComObject() );\n }\n\n\n public static void main( String[] args )\n {\n\n if ( args.length != 4 )\n {\n System.out.println( \"Usage: \" + EventLogListener.class.getSimpleName() + \" domain host username password\" );\n return;\n }\n\n String domain = args[ 0 ];\n String host = args[ 1 ];\n String user = args[ 2 ];\n String pass = args[ 3 ];\n\n JISession dcomSession = null;\n\n try\n {\n // Connect to DCOM on the remote system, and create an instance of the WbemScripting.SWbemLocator object to talk to WMI.\n dcomSession = configAndConnectDCom( domain, user, pass );\n IJIDispatch wbemLocator = getWmiLocator( host, dcomSession );\n\n // Invoke the \"ConnectServer\" method on the SWbemLocator object via it's IDispatch COM pointer. We will connect to\n // the default ROOT\\CIMV2 namespace. This will result in us having a reference to a \"SWbemServices\" object.\n JIVariant results[] =\n wbemLocator.callMethodA( \"ConnectServer\", new Object[] { new JIString( host ), new JIString( WMI_DEFAULT_NAMESPACE ),\n JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), new Integer( 0 ),\n JIVariant.OPTIONAL_PARAM() } );\n\n IJIDispatch wbemServices = toIDispatch( results[ 0 ] );\n\n // Now that we have a SWbemServices DCOM object reference, we prepare a WMI Query Language (WQL) request to be informed whenever a\n // new instance of the \"Win32_NTLogEvent\" WMI class is created on the remote host. This is submitted to the remote host via the\n // \"ExecNotificationQuery\" method on SWbemServices. This gives us all events as they come in. Refer to WQL documentation to\n // learn how to restrict the query if you want a narrower focus.\n final String QUERY_FOR_ALL_LOG_EVENTS = \"SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA 'Win32_NTLogEvent'\";\n final int RETURN_IMMEDIATE = 16;\n final int FORWARD_ONLY = 32;\n\n JIVariant[] eventSourceSet =\n wbemServices.callMethodA( \"ExecNotificationQuery\", new Object[] { new JIString( QUERY_FOR_ALL_LOG_EVENTS ), new JIString( \"WQL\" ),\n new JIVariant( new Integer( RETURN_IMMEDIATE + FORWARD_ONLY ) ) } );\n IJIDispatch wbemEventSource = (IJIDispatch) JIObjectFactory.narrowObject( ( eventSourceSet[ 0 ] ).getObjectAsComObject() );\n\n // The result of the query is a SWbemEventSource object. This object exposes a method that we can call in a loop to retrieve the\n // next Windows Event Log entry whenever it is created. This \"NextEvent\" operation will block until we are given an event.\n // Note that you can specify timeouts, see the Microsoft documentation for more details.\n while ( true )\n {\n // this blocks until an event log entry appears.\n JIVariant eventAsVariant = (JIVariant) ( wbemEventSource.callMethodA( \"NextEvent\", new Object[] { JIVariant.OPTIONAL_PARAM() } ) )[ 0 ];\n IJIDispatch wbemEvent = toIDispatch( eventAsVariant );\n\n // WMI gives us events as SWbemObject instances (a base class of any WMI object). We know in our case we asked for a specific object\n // type, so we will go ahead and invoke methods supported by that Win32_NTLogEvent class via the wbemEvent IDispatch pointer.\n // In this case, we simply call the \"GetObjectText_\" method that returns us the entire object as a CIM formatted string. We could,\n // however, ask the object for its property values via wbemEvent.get(\"PropertyName\"). See the j-interop documentation and examples\n // for how to query COM properties.\n JIVariant objTextAsVariant = (JIVariant) ( wbemEvent.callMethodA( \"GetObjectText_\", new Object[] { new Integer( 1 ) } ) )[ 0 ];\n String asText = objTextAsVariant.getObjectAsString().getString();\n System.out.println( asText );\n }\n }\n catch ( Exception e )\n {\n e.printStackTrace();\n }\n finally\n {\n if ( null != dcomSession )\n {\n try\n {\n JISession.destroySession( dcomSession );\n }\n catch ( Exception ex )\n {\n ex.printStackTrace();\n }\n }\n }\n }\n\n}\n"
},
{
"answer_id": 3838930,
"author": "dB.",
"author_id": 123094,
"author_profile": "https://Stackoverflow.com/users/123094",
"pm_score": 3,
"selected": false,
"text": "EventLogIterator iter = new EventLogIterator(\"Application\"); \nwhile(iter.hasNext()) { \n EventLogRecord record = iter.next(); \n System.out.println(record.getRecordNumber() \n + \": Event ID: \" + record.getEventId() \n + \", Event Type: \" + record.getType() \n + \", Event Source: \" + record.getSource()); \n} \n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1836/"
] |
310,363 | <p>I have a time represented as the number of seconds elapsed since midnight, January 1, 1970, UTC (the results of an earlier call to time()). How do I add one day to this time?</p>
<p>Adding 24 * 60 * 60 works in most cases, but fails if the daylight saving time comes on or off in between. In other words, I mostly want to add 24 hours, but sometimes 23 or 25 hours.</p>
<p>To illustrate - the program:</p>
<pre><code>#include <time.h>
#include <iostream>
int main()
{
time_t base = 1142085600;
for(int i = 0; i < 4; ++i) {
time_t time = base + i * 24 * 60 * 60;
std::cout << ctime(&time);
}
return 0;
</code></pre>
<p>}</p>
<p>Produces:</p>
<pre><code>Sat Mar 11 08:00:00 2006
Sun Mar 12 09:00:00 2006
Mon Mar 13 09:00:00 2006
Tue Mar 14 09:00:00 2006
</code></pre>
<p>I want the times for March 12, 13, ... to also be 8 AM.</p>
<hr>
<p>The answer provided by FigBug pointed me in the right direction. But I had to use localtime instead of gmtime.</p>
<pre><code>int main()
{
time_t base = 1142085600;
for(int i = 0; i < 4; ++i) {
struct tm* tm = localtime(&base);
tm->tm_mday += i;
std::cout << asctime(tm);
}
return 0;
}
</code></pre>
<p>Give me:</p>
<pre><code>Sat Mar 11 08:00:00 2006
Sat Mar 12 08:00:00 2006
Sat Mar 13 08:00:00 2006
Sat Mar 14 08:00:00 2006
</code></pre>
<p>Which is what I want. Using gmtime gives me the times at 14:00:00</p>
<p>However, note that all days are Sat. Also, it goes to March 32, 33, etc. If I throw in the mktime function I am back where I started:</p>
<pre><code>#include <time.h>
#include <iostream>
int main()
{
time_t base = 1142085600;
for(int i = 0; i < 4; ++i) {
struct tm* tm = localtime(&base);
tm->tm_mday += i;
time_t time = mktime(tm);
std::cout << asctime(tm);
}
return 0;
}
</code></pre>
<p>Gives me:</p>
<pre><code>Sat Mar 11 08:00:00 2006
Sun Mar 12 09:00:00 2006
Mon Mar 13 09:00:00 2006
Tue Mar 14 09:00:00 2006
</code></pre>
<p>What am I missing???</p>
<hr>
<p>OK, I have tried out FigBug's latest suggestion that is to use:</p>
<pre><code> std::cout << ctime(&time);
</code></pre>
<p>instead of asctime, but I get the same results. So I guess that my library and/or compiler is messed up. I am using g++ 3.4.4 on cygwin. I copied the files over to Solaris 5.8 and used g++ 3.3 there to compile. I get the correct results there! In fact I get the correct results whether I use ctime or asctime for output:</p>
<pre><code>Sat Mar 11 08:00:00 2006
Sun Mar 12 08:00:00 2006
Mon Mar 13 08:00:00 2006
Tue Mar 14 08:00:00 2006
</code></pre>
<p>I also get the correct results (with both output functions) on Red Hut Linux with g++ 3.4.6.</p>
<p>So I guess that I have come across a Cygwin bug. </p>
<p>Thank you for all your help and advice....</p>
| [
{
"answer_id": 310374,
"author": "Roland Rabien",
"author_id": 39138,
"author_profile": "https://Stackoverflow.com/users/39138",
"pm_score": 6,
"selected": true,
"text": "int main()\n{\n time_t base = 1142085600;\n for(int i = 0; i < 4; ++i) {\n struct tm* tm = localtime(&base);\n tm->tm_mday += i;\n time_t next = mktime(tm);\n std::cout << ctime(&next);\n }\n return 0;\n}\n"
},
{
"answer_id": 643257,
"author": "Andrew Selivanov",
"author_id": 55466,
"author_profile": "https://Stackoverflow.com/users/55466",
"pm_score": 3,
"selected": false,
"text": "int main()\n{\n time_t base = 1142085600;\n for(int i = 0; i < 4; ++i) {\n struct tm* tm = localtime(&base);\n tm->tm_mday += i;\n tm->tm_isdst = -1; // don't know if DST is in effect, please determine\n // this for me\n time_t next = mktime(tm);\n std::cout << ctime(&next);\n }\n return 0;\n}\n int main()\n{\n // 28 March 2009 05:00:00 GMT ( local - 08:00 (MSK) )\n time_t base = 1238216400;\n\n std::time_t start_date_t = base;\n std::time_t end_date_t = base;\n\n std::tm start_date = *std::localtime(&start_date_t);\n std::tm end_date = *std::localtime(&end_date_t);\n\n end_date.tm_mday += 1;\n// end_date.tm_isdst = -1;\n\n std::time_t b = mktime(&start_date);\n std::time_t e = mktime(&end_date);\n\n std::string start_date_str(ctime(&b));\n std::string stop_date_str(ctime(&e));\n\n cout << \" begin (MSK) (DST is not active): \" << start_date_str;\n cout << \" end (MSD) (DST is active): \" << stop_date_str;\n}\n begin (MSK) (DST is not active): Sat Mar 28 08:00:00 2009\nend (MSD) (DST is active): Sun Mar 29 09:00:00 2009\n"
},
{
"answer_id": 37530208,
"author": "Howard Hinnant",
"author_id": 576911,
"author_profile": "https://Stackoverflow.com/users/576911",
"pm_score": 2,
"selected": false,
"text": "<chrono> #include \"tz.h\"\n#include <iostream>\n\nint\nmain()\n{\n using namespace std::chrono;\n using namespace date;\n auto base = make_zoned(\"Pacific/Easter\", sys_seconds{1142085600s});\n for (int i = 0; i < 4; ++i)\n {\n std::cout << format(\"%a %b %d %T %Y %Z\", base) << '\\n';\n base = base.get_local_time() + days{1};\n }\n}\n zoned_time Sat Mar 11 09:00:00 2006 -05\nSun Mar 12 09:00:00 2006 -06\nMon Mar 13 09:00:00 2006 -06\nTue Mar 14 09:00:00 2006 -06\n base = base.get_sys_time() + days{1};\n base.get_sys_time() base.get_local_time() Sat Mar 11 09:00:00 2006 -05\nSun Mar 12 08:00:00 2006 -06\nMon Mar 13 08:00:00 2006 -06\nTue Mar 14 08:00:00 2006 -06\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13029/"
] |
310,376 | <p>Many (most?) sites aiming for accessibility and standards compliance use unordered lists for their navigation. Does this make the site more accessible or does it just provide useful elements for styling?</p>
<p>I don't mind them, and I have been using unordered lists in this way. It's just that, when I remove the styling from a page to try to gauge it's accessibility, it strikes me that it could just as well could be plain links. Where does this come from?</p>
| [
{
"answer_id": 310391,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<div> <span>"
},
{
"answer_id": 310447,
"author": "Carl Camera",
"author_id": 12804,
"author_profile": "https://Stackoverflow.com/users/12804",
"pm_score": 4,
"selected": true,
"text": "<UL> <OL>"
},
{
"answer_id": 310794,
"author": "Ola Tuvesson",
"author_id": 6903,
"author_profile": "https://Stackoverflow.com/users/6903",
"pm_score": 3,
"selected": false,
"text": "<ul id=\"mainMenu\">\n <li>Home</li>\n <li>Something</li>\n <li>Something Else</li>\n <li>Current section\n <ul>\n <li>A Subsection</li>\n <li>Another subsection</li>\n <li>More!\n <ul>\n <li>We go deeper</li>\n <li>Who knows where it ends</li>\n </ul>\n </li>\n <li>Back up one step</li>\n </ul>\n </li>\n <li>And another step</li>\n <li>All done!</li>\n</ul>\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16526/"
] |
310,394 | <p>I am still learning sql server somewhat and recently came across a select query in a stored procedure which was causing a very slow fill of a dataset in c#. At first I thought this was to do with .NET but then found a suggestion to put in the stored procedure:</p>
<p>set implicit_transactions off</p>
<p>this seems to cure it but I would like to know why also I have seen other options such as:</p>
<ul>
<li>set nocount off</li>
<li>set arithabort on</li>
<li>set concat_null_yields_null on</li>
<li>set ansi_nulls on</li>
<li>set cursor_close_on_commit off</li>
<li>set ansi_null_dflt_on on</li>
<li>set ansi_padding on</li>
<li>set ansi_warnings on</li>
<li>set quoted_identifier on</li>
</ul>
<p>Does anyone know where to find good info on what each of these does and what is safe to use when I have stored procedures setup just to query of data for viewing. </p>
<p>I should note just to stop the usual use/don't use stored procedures debate these queries are complex select statements used on multiple programs in multiple languages it is the best place for them.</p>
<p><strong>Edit: Got my answer didn't end up fully reviewing all the options but did find</strong></p>
<p><strong>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED</strong></p>
<p><strong>Sped up the complex queries dramatically, I am not worried about the dirty read in this instance.</strong></p>
| [
{
"answer_id": 339581,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 2,
"selected": false,
"text": "set implicit_transactions on \ngo\nselect top 10 * from sysobjects\n set implicit_transactions off \ngo\nbegin tran\nselect top 10 * from sysobjects\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16989/"
] |
310,408 | <p>Let's say we have a concrete <code>class Apple</code>. (Apple objects can be instantiated.)
Now, someone comes and derives an abstract <code>class Peach</code> from Apple. It's abstract because it introduces a new pure virtual function. The user of Peach is now forced to derive from it and define this new function. Is this a common pattern? Is this correct to do?</p>
<p>Sample:<pre><code>
class Apple
{
public:
virtual void MakePie();
// more stuff here
};</p>
<p>class Peach : public Apple
{
public:
virtual void MakeDeliciousDesserts() = 0;
// more stuff here
};</code></pre>
Now let's say we have a concrete <code>class Berry</code>. Someone derives an abstract <code>class Tomato</code> from Berry. It's abstract because it overwrites one of Berry's virtual functions, and makes it pure virtual. The user of Tomato has to re-implement the function previously defined in Berry. Is this a common pattern? Is this correct to do?</p>
<p>Sample:<pre><code>
class Berry
{
public:
virtual void EatYummyPie();
// more stuff here
};</p>
<p>class Tomato : public Berry
{
public:
virtual void EatYummyPie() = 0;
// more stuff here
};</code></pre>
Note: The names are contrived and do not reflect any actual code (hopefully). No fruits have been harmed in the writing of this question.</p>
| [
{
"answer_id": 310499,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 4,
"selected": true,
"text": "Juice() Juice() Berry::Juice() class Tomato : public Berry\n{\npublic:\n void Juice() \n {\n PrepareJuice();\n Berry::Juice();\n }\n virtual void PrepareJuice() = 0;\n};\n PrepareJuice Berry::Juice"
},
{
"answer_id": 310529,
"author": "Ray Tayek",
"author_id": 51292,
"author_profile": "https://Stackoverflow.com/users/51292",
"pm_score": 1,
"selected": false,
"text": "class Concrete\n{\npublic:\n virtual void eat() {}\n};\nclass Sub::public Concrete { // some concrete subclass\n virtual void eat() {}\n};\nclass Abstract:public Concrete // abstract subclass\n{\npublic:\n virtual void eat()=0;\n // and some stuff common to Sub1 and Sub2\n};\nclass Sub1:public Abstract {\n void eat() {}\n};\nclass Sub2:public Abstract {\n void eat() {}\n};\nint main() {\n Concrete *sub1=new Sub1(),*sub2=new Sub2();\n sub1->eat();\n sub2->eat();\n return 0;\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22724/"
] |
310,418 | <p>I've given up trying to apply lipstick to the pigs of installers that come out of <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio" rel="noreferrer">Visual Studio</a> and have decided to look at <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">WiX</a>.</p>
<p>What resources would you recommend to learn and reference?</p>
<p><em>(Note - this is not a which-installer-technology-do-you-use question - it's specific to WiX.)</em></p>
| [
{
"answer_id": 310760,
"author": "Rob Mensching",
"author_id": 23852,
"author_profile": "https://Stackoverflow.com/users/23852",
"pm_score": 3,
"selected": false,
"text": "wix-users@lists.wixtoolset.org"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20198/"
] |
310,425 | <p>Currently I have a table that I search upon 4 fields, FirstName, LastName, MiddleName, And AKA's. I currently have a <strong>CONTAINSTABLE</strong> search for the rows and it works. Not well but it works. Now <strong>I want to make the First Name weighted higher and middle name lower.</strong></p>
<p>I found the command <strong>ISABOUT</strong> but that seems pretty worthless if I have to do it by word not column (hopefully I understood this wrong). This is not an option if its by word because I do not know how many words the user will enter.</p>
<p>I found the thread <a href="https://stackoverflow.com/questions/198152/how-do-i-assign-weights-to-different-columns-in-a-full-text-search">here</a> that talks about this same solution however I was unable to get the accepted solution to work. Maybe I have done something wrong but regardless I cannot get it to work, and its logic seems really... odd. There has to be an easier way. </p>
| [
{
"answer_id": 322191,
"author": "Dave_H",
"author_id": 17109,
"author_profile": "https://Stackoverflow.com/users/17109",
"pm_score": 4,
"selected": true,
"text": "DECLARE @Results TABLE (PersonId Int, Rank Int, Source Int)\n PersonId Int PK Identity, FirstName VarChar(100), MiddleName VarChar(100), LastName VarChar(100), AlsoKnown VarChar(100) INSERT INTO @Results (PersonId, Rank, Source)\n\nSELECT PersonId, Rank, 1\nFROM ContainsTable(People, FirstName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId\n\nUNION\nSELECT PersonId, Rank, 2\nFROM ContainsTable(People, MiddleName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId\n\nUNION\nSELECT PersonId, Rank, 3\nFROM ContainsTable(People, LastName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId\n\nUNION\nSELECT PersonId, Rank, 4\nFROM ContainsTable(People, AlsoKnown, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId\n\n/*\nNow that the results from above are in the @Results table, you can manipulate the\nrankings in one of several ways, the simplest is to pull the results ordered first by Source then by Rank. Of course you would probably join to the People table to pull the name fields.\n*/\n\nSELECT PersonId\nFROM @Results\nORDER BY Source, Rank DESC\n\n/*\nA more complex manipulation would use a statement to multiply the ranking \nby a value above 1 (to increase rank) or less than 1 (to lower rank), then \nreturn results based on the new rank. This provides more fine tuning, \nsince I could make first name 10% higher and middle name 15% lower and \nleave last name and also known the original value.\n*/\n\nSELECT PersonId, CASE Source WHEN 1 THEN Rank * 1.1 WHEN 2 THEN Rank * .9 ELSE Rank END AS NewRank FROM @Results\nORDER BY NewRank DESC\n UNION ALL UNION ALL"
},
{
"answer_id": 4124995,
"author": "Pavel Urbančík",
"author_id": 497130,
"author_profile": "https://Stackoverflow.com/users/497130",
"pm_score": 2,
"selected": false,
"text": "FirstName + FirstName + LastName + MiddleName"
},
{
"answer_id": 24055571,
"author": "Simon Green",
"author_id": 1786865,
"author_profile": "https://Stackoverflow.com/users/1786865",
"pm_score": 1,
"selected": false,
"text": " SELECT p.* from Person p\nleft join ContainsTable(Person, FirstName, @SearchValue) firstnamefilter on firstnamefiler.key = p.id\nleft join ContainsTable(Person, MiddleName, @SearchValue) middlenamefilter on middlenamefilter.key = p.id\nwhere (firstnamefilter.rank is not null or middlenamefilter.rank is not null)\norder by firstnamefilter.rank desc, middlenamefilter.rank desc\n Person"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925/"
] |
310,426 | <p>To do the equivalent of Python list comprehensions, I'm doing the following:</p>
<pre><code>some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3}
</code></pre>
<p>Is there a better way to do this...perhaps with one method call?</p>
| [
{
"answer_id": 310466,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 7,
"selected": true,
"text": "class Array\n def comprehend(&block)\n return self if block.nil?\n self.collect(&block).compact\n end\nend\n\nsome_array = [1, 2, 3, 4, 5, 6]\nnew_array = some_array.comprehend {|x| x * 3 if x % 2 == 0}\nputs new_array\n 6\n12\n18\n"
},
{
"answer_id": 310705,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 7,
"selected": false,
"text": "some_array.map {|x| x % 2 == 0 ? x * 3 : nil}.compact\n"
},
{
"answer_id": 1616703,
"author": "Christopher Roach",
"author_id": 195713,
"author_profile": "https://Stackoverflow.com/users/195713",
"pm_score": -1,
"selected": false,
"text": "some_array.select{ |x| x * 3 if x % 2 == 0 }\n select false map collect"
},
{
"answer_id": 2754163,
"author": "Pedro Rolo",
"author_id": 330889,
"author_profile": "https://Stackoverflow.com/users/330889",
"pm_score": 3,
"selected": false,
"text": "some_array.inject([]){|res,x| x % 2 == 0 ? res << 3*x : res}\n"
},
{
"answer_id": 2759595,
"author": "Vince",
"author_id": 173661,
"author_profile": "https://Stackoverflow.com/users/173661",
"pm_score": 2,
"selected": false,
"text": "[1, 2, 3, 4, 5, 6].collect{|x| x * 3 if x % 2 == 0}.compact\n=> [6, 12, 18]\n map collect select(&:even?).map()\n"
},
{
"answer_id": 2760293,
"author": "jvoorhis",
"author_id": 331685,
"author_profile": "https://Stackoverflow.com/users/331685",
"pm_score": 2,
"selected": false,
"text": "Enumerable#select Enumerable#map Enumerable#select inject comprehend select map"
},
{
"answer_id": 2761548,
"author": "anoiaque",
"author_id": 331842,
"author_profile": "https://Stackoverflow.com/users/331842",
"pm_score": 2,
"selected": false,
"text": "[1,2,3,4,5,6].select(&:even?).map{|x| x*3}\n"
},
{
"answer_id": 2762337,
"author": "jvoorhis",
"author_id": 331685,
"author_profile": "https://Stackoverflow.com/users/331685",
"pm_score": 4,
"selected": false,
"text": "map { ... }.compact\n Enumerable#inject select {...}.map{...}\n Enumerable#select"
},
{
"answer_id": 5046057,
"author": "knuton",
"author_id": 4991,
"author_profile": "https://Stackoverflow.com/users/4991",
"pm_score": 5,
"selected": false,
"text": "require 'test_helper'\nrequire 'performance_test_help'\n\nclass ListComprehensionTest < ActionController::PerformanceTest\n\n TEST_ARRAY = (1..100).to_a\n\n def test_map_compact\n 1000.times do\n TEST_ARRAY.map{|x| x % 2 == 0 ? x * 3 : nil}.compact\n end\n end\n\n def test_select_map\n 1000.times do\n TEST_ARRAY.select{|x| x % 2 == 0 }.map{|x| x * 3}\n end\n end\n\n def test_inject\n 1000.times do\n TEST_ARRAY.inject([]) {|all, x| all << x*3 if x % 2 == 0; all }\n end\n end\n\nend\n /usr/bin/ruby1.8 -I\"lib:test\" \"/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb\" \"test/performance/list_comprehension_test.rb\" -- --benchmark\nLoaded suite /usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader\nStarted\nListComprehensionTest#test_inject (1230 ms warmup)\n wall_time: 1221 ms\n memory: 0.00 KB\n objects: 0\n gc_runs: 0\n gc_time: 0 ms\n.ListComprehensionTest#test_map_compact (860 ms warmup)\n wall_time: 855 ms\n memory: 0.00 KB\n objects: 0\n gc_runs: 0\n gc_time: 0 ms\n.ListComprehensionTest#test_select_map (961 ms warmup)\n wall_time: 955 ms\n memory: 0.00 KB\n objects: 0\n gc_runs: 0\n gc_time: 0 ms\n.\nFinished in 66.683039 seconds.\n\n15 tests, 0 assertions, 0 failures, 0 errors\n"
},
{
"answer_id": 9881339,
"author": "Mark",
"author_id": 329998,
"author_profile": "https://Stackoverflow.com/users/329998",
"pm_score": 4,
"selected": false,
"text": "squares = [x**2 for x in range(10)]\n a = Array.new(4).map{rand(2**49..2**50)} \n"
},
{
"answer_id": 14901868,
"author": "histocrat",
"author_id": 1747583,
"author_profile": "https://Stackoverflow.com/users/1747583",
"pm_score": 3,
"selected": false,
"text": "require 'comprehend'\n\nsome_array.comprehend{ |x| x * 3 if x % 2 == 0 }\n"
},
{
"answer_id": 16051639,
"author": "Alexandre Magro",
"author_id": 1544716,
"author_profile": "https://Stackoverflow.com/users/1544716",
"pm_score": 2,
"selected": false,
"text": "def lazy(collection, &blk)\n collection.map{|x| blk.call(x)}.compact\nend\n lazy (1..6){|x| x * 3 if x.even?}\n => [6, 12, 18]\n"
},
{
"answer_id": 19128951,
"author": "Peter Moulder",
"author_id": 2837024,
"author_profile": "https://Stackoverflow.com/users/2837024",
"pm_score": 3,
"selected": false,
"text": "grep some_array.grep(proc {|x| x % 2 == 0}) {|x| x*3}\n select.map nil compact"
},
{
"answer_id": 53068873,
"author": "joegiralt",
"author_id": 2340298,
"author_profile": "https://Stackoverflow.com/users/2340298",
"pm_score": 1,
"selected": false,
"text": "some_array.flat_map {|x| x % 2 == 0 ? [x * 3] : [] }\n some_array.each_with_object([]) {|x, list| x % 2 == 0 ? list.push(x * 3) : nil }\n"
},
{
"answer_id": 57819276,
"author": "Sam Michael",
"author_id": 10869874,
"author_profile": "https://Stackoverflow.com/users/10869874",
"pm_score": 0,
"selected": false,
"text": "c = -> x do $*.clear \n if x['if'] && x[0] != 'f' . \n y = x[0...x.index('for')] \n x = x[x.index('for')..-1]\n (x.insert(x.index(x.split[3]) + x.split[3].length, \" do $* << #{y}\")\n x.insert(x.length, \"end; $*\")\n eval(x)\n $*)\n elsif x['if'] && x[0] == 'f'\n (x.insert(x.index(x.split[3]) + x.split[3].length, \" do $* << x\")\n x.insert(x.length, \"end; $*\")\n eval(x)\n $*)\n elsif !x['if'] && x[0] != 'f'\n y = x[0...x.index('for')]\n x = x[x.index('for')..-1]\n (x.insert(x.index(x.split[3]) + x.split[3].length, \" do $* << #{y}\")\n x.insert(x.length, \"end; $*\")\n eval(x)\n $*)\n else\n eval(x.split[3]).to_a\n end\nend \n c['for x in 1..10']\nc['for x in 1..10 if x.even?']\nc['x**2 for x in 1..10 if x.even?']\nc['x**2 for x in 1..10']\n\n# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n# [2, 4, 6, 8, 10]\n# [4, 16, 36, 64, 100]\n# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n S = [for x in 0...9 do $* << x*2 if x.even? end, $*][1]\n# [0, 4, 8, 12, 16]\n"
},
{
"answer_id": 59471437,
"author": "Sam Michael",
"author_id": 10869874,
"author_profile": "https://Stackoverflow.com/users/10869874",
"pm_score": -1,
"selected": false,
"text": "$l[for x in 1..10 do x + 2 end] #=> [3, 4, 5 ...]\n"
},
{
"answer_id": 62779544,
"author": "Matheus Richard",
"author_id": 8650655,
"author_profile": "https://Stackoverflow.com/users/8650655",
"pm_score": 2,
"selected": false,
"text": "filter_map some_array.filter_map { |x| x * 3 if x % 2 == 0 }\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
310,436 | <p>Is there a way to only load child nodes when the parent node is expanded? The problem that I’m running into is that the “expand” icon doesn’t show up if a node doesn’t have any children. Since I don’t want to load the children until the icon is clicked, I’m left with a bit of a catch 22.</p>
| [
{
"answer_id": 1535877,
"author": "Homer",
"author_id": 176537,
"author_profile": "https://Stackoverflow.com/users/176537",
"pm_score": 2,
"selected": false,
"text": "public class TreeViewItemEx : TreeViewItem {\n protected override DependencyObject GetContainerForItemOverride() {\n TreeViewItemEx tvi = new TreeViewItemEx();\n Binding expandedBinding = new Binding(\"IsExpanded\");\n expandedBinding.Mode = BindingMode.TwoWay;\n tvi.SetBinding(TreeViewItemEx.IsExpandedProperty, expandedBinding);\n return tvi;\n }\n}\n\npublic class TreeViewEx : TreeView {\n protected override DependencyObject GetContainerForItemOverride() {\n TreeViewItemEx tvi = new TreeViewItemEx();\n Binding expandedBinding = new Binding(\"IsExpanded\");\n expandedBinding.Mode = BindingMode.TwoWay;\n tvi.SetBinding(TreeViewItemEx.IsExpandedProperty, expandedBinding);\n\n return tvi;\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13181/"
] |
310,441 | <p>I need to reformat a text file into a PDF. Using Perl, I am modifying an existing PostScript template file based on what is in the text file. Sometimes this text file will be long enough to require a two page PDF.</p>
<p>Can I create a two page PDF file from one .ps file using GhostScript? If so, what tells GhostScript where the page break should occur?</p>
<p>Maybe I need to use two template files. One for a one page pdf and another for a two page PDF.</p>
| [
{
"answer_id": 310463,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 0,
"selected": false,
"text": "showpage"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7519/"
] |
310,451 | <p>Both <code>static_cast</code> and <code>reinterpret_cast</code> seem to work fine for casting <code>void*</code> to another pointer type. Is there a good reason to favor one over the other?</p>
| [
{
"answer_id": 310489,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 8,
"selected": false,
"text": "static_cast reinterpret_cast reinterpret_cast reinterpret_cast reinterpret_cast void* T* static_cast reinterpret_cast static_cast"
},
{
"answer_id": 1899898,
"author": "Pavel Radzivilovsky",
"author_id": 73656,
"author_profile": "https://Stackoverflow.com/users/73656",
"pm_score": 0,
"selected": false,
"text": "reinterpret_cast float char* reinterpret_pointer_cast"
},
{
"answer_id": 5013617,
"author": "Asha",
"author_id": 392315,
"author_profile": "https://Stackoverflow.com/users/392315",
"pm_score": 0,
"selected": false,
"text": "static_cast reinterpret_cast"
},
{
"answer_id": 5013653,
"author": "sharptooth",
"author_id": 57428,
"author_profile": "https://Stackoverflow.com/users/57428",
"pm_score": 2,
"selected": false,
"text": "void* static_cast"
},
{
"answer_id": 5013658,
"author": "mukeshkumar",
"author_id": 240857,
"author_profile": "https://Stackoverflow.com/users/240857",
"pm_score": -1,
"selected": false,
"text": "reinterpret_cast void* myclass* void* reinterpret_cast yourclass* static_cast"
},
{
"answer_id": 5013661,
"author": "templatetypedef",
"author_id": 501557,
"author_profile": "https://Stackoverflow.com/users/501557",
"pm_score": 6,
"selected": false,
"text": "static_cast void* static_cast static_cast static_cast int char reinterpret_cast reinterpret_cast void * int sizeof (void*) sizeof (int) reinterpret_cast float* int* float int reinterpret_cast static_cast reinterpret_cast dynamic_cast static_cast void* static_cast reinterpret_cast A* ptr = (A*) myVoidPointer;\n static_cast reinterpret_cast reinterpret_cast"
},
{
"answer_id": 68139849,
"author": "anton_rh",
"author_id": 5447906,
"author_profile": "https://Stackoverflow.com/users/5447906",
"pm_score": 2,
"selected": false,
"text": "void* static_cast reinterpret_cast static_cast"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37992/"
] |
310,456 | <p>I'm trying to find a way to get the open tasks in C#. I've been searching on google and can only find how to get a list of the <strong>processes</strong>. I want the only the tasks that would show up on the taskbar.</p>
<p>Also, along with that, it would be cool if I could get the process the task is associated with. And if possible get the thumbnail images that Vista uses for the ALT-TAB menu, like in this image:</p>
<p><a href="https://i.stack.imgur.com/CcPQP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CcPQP.png" alt="alt-tab"></a></p>
<p>I assume that I will have to use pinvokes because it really doesn't look like there are any libraries to do this already. Any ideas?</p>
| [
{
"answer_id": 310481,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 1,
"selected": false,
"text": "using System.Diagnostics;\nstatic void MyFunc()\n{\n Process[] processes = Process.GetProcesses();\n foreach(Process p in processes)\n {\n if (p.MainWindowHandle != 0)\n { // This is a GUI process\n }\n else\n { // this is a non-GUI / invisible process\n }\n }\n}\n"
},
{
"answer_id": 310503,
"author": "Asher",
"author_id": 38265,
"author_profile": "https://Stackoverflow.com/users/38265",
"pm_score": 0,
"selected": false,
"text": "p.ProcessName != \"explorer\"\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13713/"
] |
310,458 | <p>In ASP.NET (not MVC), what is the best approach to programmatically setting styles on an unordered list used for navigation so the appropriate menu item is styled as the active item if that page is being viewed? </p>
<p>This would most likely be used in conjunction with a MasterPage.</p>
| [
{
"answer_id": 310477,
"author": "Frank V",
"author_id": 18196,
"author_profile": "https://Stackoverflow.com/users/18196",
"pm_score": 2,
"selected": true,
"text": "<{...} class=\"GeneratedMenuItem\"> {...}\n"
},
{
"answer_id": 310535,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "Public Sub SetNavigationPage(ByVal MenuName As String)\n\n DirectCast(Me.FindControl(MenuName), HyperLink).CssClass = \"MenuCurrent\"\n\nEnd Sub\n Dim myMaster As EAF = DirectCast(Me.Master, EAF)\nmyMaster.SetNavigationPage(\"hypSearchRequest\")\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30552/"
] |
310,459 | <p>I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words:</p>
<pre><code>>>> my_ar = numpy.array((0,5,10))
[0, 5, 10]
>>> transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful
array([
[ 0, 0, 0],
[ 5, 10, 15],
[10, 20, 30]])
>>> transformed.shape
(3, 3)
</code></pre>
<p>I've tried:</p>
<pre><code>def my_fun_e(val):
return numpy.array((val, val*2, val*3))
my_fun = numpy.frompyfunc(my_fun_e, 1, 3)
</code></pre>
<p>but get:</p>
<pre><code>my_fun(my_ar)
(array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object), array([None, None, None], dtype=object), array([None, None, None], dtype=object))
</code></pre>
<p>and I've tried:</p>
<pre><code>my_fun = numpy.frompyfunc(my_fun_e, 1, 1)
</code></pre>
<p>but get:</p>
<pre><code>>>> my_fun(my_ar)
array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object)
</code></pre>
<p>This is close, but not quite right -- I get an array of objects, not an array of ints.</p>
<p><b>Update 3!</b> OK. I've realized that my example was too simple beforehand -- I don't just want to replicate my data in a third dimension, I'd like to transform it at the same time. Maybe this is clearer?</p>
| [
{
"answer_id": 310493,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 1,
"selected": false,
"text": " numpy.resize(my_ar, (3,3)).transpose()\n (my_ar.shape[0],)*2"
},
{
"answer_id": 310893,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 1,
"selected": false,
"text": "tile(my_ar, (1,1,3))\n"
},
{
"answer_id": 313427,
"author": "Theran",
"author_id": 40180,
"author_profile": "https://Stackoverflow.com/users/40180",
"pm_score": 3,
"selected": false,
"text": ">>> import numpy as N\n>>> a = N.array([[1,2,3],[4,5,6],[7,8,9]])\n>>> a\narray([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n>>> b = N.dstack((a,a,a))\n>>> b\narray([[[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]],\n\n [[4, 4, 4],\n [5, 5, 5],\n [6, 6, 6]],\n\n [[7, 7, 7],\n [8, 8, 8],\n [9, 9, 9]]])\n>>> b[1,1]\narray([5, 5, 5])\n"
},
{
"answer_id": 318869,
"author": "jimmyorr",
"author_id": 19239,
"author_profile": "https://Stackoverflow.com/users/19239",
"pm_score": 3,
"selected": true,
"text": "import numpy\n\nmy_ar = numpy.array((0,5,10))\nprint my_ar\n\ntransformed = numpy.array(map(lambda x:numpy.array((x,x*2,x*3)), my_ar))\nprint transformed\n\nprint transformed.shape\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12779/"
] |
310,469 | <p>I want a workflow that, when an entry is created in List A, will generate one entry in List B for each entry in List C. Is this possible? If so, how?</p>
| [
{
"answer_id": 310493,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 1,
"selected": false,
"text": " numpy.resize(my_ar, (3,3)).transpose()\n (my_ar.shape[0],)*2"
},
{
"answer_id": 310893,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 1,
"selected": false,
"text": "tile(my_ar, (1,1,3))\n"
},
{
"answer_id": 313427,
"author": "Theran",
"author_id": 40180,
"author_profile": "https://Stackoverflow.com/users/40180",
"pm_score": 3,
"selected": false,
"text": ">>> import numpy as N\n>>> a = N.array([[1,2,3],[4,5,6],[7,8,9]])\n>>> a\narray([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n>>> b = N.dstack((a,a,a))\n>>> b\narray([[[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]],\n\n [[4, 4, 4],\n [5, 5, 5],\n [6, 6, 6]],\n\n [[7, 7, 7],\n [8, 8, 8],\n [9, 9, 9]]])\n>>> b[1,1]\narray([5, 5, 5])\n"
},
{
"answer_id": 318869,
"author": "jimmyorr",
"author_id": 19239,
"author_profile": "https://Stackoverflow.com/users/19239",
"pm_score": 3,
"selected": true,
"text": "import numpy\n\nmy_ar = numpy.array((0,5,10))\nprint my_ar\n\ntransformed = numpy.array(map(lambda x:numpy.array((x,x*2,x*3)), my_ar))\nprint transformed\n\nprint transformed.shape\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,479 | <p>I am developing a cocoa application that will be making heavy use of both web services and a standard dbms (most likely MySQL) and I am wondering if anyone has a good option for a database library or ORM solution they have used. CoreData is not an option due to the need to support a standard DBMS and to be able to modify the data outside of the normal application operation.</p>
<p>I have found a number of possible options from new open source libraries:
<a href="http://github.com/aptiva/activerecord/tree/master" rel="noreferrer">http://github.com/aptiva/activerecord/tree/master</a></p>
<p>To writing my own wrapper for the C MySQL api.</p>
<p>Any advice is welcome,</p>
<p>Thanks!</p>
<p>Paul</p>
| [
{
"answer_id": 468461,
"author": "Dirk Stoop",
"author_id": 24051,
"author_profile": "https://Stackoverflow.com/users/24051",
"pm_score": 4,
"selected": true,
"text": "NSBundle *pluginBundle = [NSBundle bundleWithPath:pluginPath];\n[pluginBundle load];\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39819/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.