qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
153,507
|
<p>How do I calculate the position of an accelerating body (e.g. a car) after a certain time (e.g. 1 second)?</p>
<p>For a moving body that it not accelerating, it is a linear relationship, so I presume for an accelerating body it involves a square somewhere.</p>
<p>Any ideas? </p>
|
[
{
"answer_id": 153517,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 6,
"selected": true,
"text": "s = s + u * dt;\nu = u + a * dt;\n"
},
{
"answer_id": 153551,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 3,
"selected": false,
"text": "s = ut+1/2 at^2\n v[n] = v[n-1] * t * a[t]\n n t"
},
{
"answer_id": 153557,
"author": "jholl",
"author_id": 5065,
"author_profile": "https://Stackoverflow.com/users/5065",
"pm_score": 1,
"selected": false,
"text": "x(t) = (1/2 * a * t^2) + (v0 * t)\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11911/"
] |
153,527
|
<p>I have a page that contains a form. This page is served with content type text/html;charset=utf-8. I need to submit this form to server using ISO-8859-1 character encoding. Is this possible with Internet Explorer?</p>
<p>Setting accept-charset attribute to form element, like this, works for Firefox, Opera etc. but not for IE.</p>
<pre><code><form accept-charset="ISO-8859-1">
...
</form>
</code></pre>
<p>Edit: This form is created by server A and will be submitted to server B. I have no control over server B.</p>
<p>If I set server A to serve content with charset ISO-8859-1 everything works, but I am looking a way to make this work without changes to server A's encoding. I have another question <a href="https://stackoverflow.com/questions/153482/setting-iso-8859-1-encoding-for-a-single-tapestry-4-page-in-application-that-is">about setting the encoding in server A.</a></p>
|
[
{
"answer_id": 153578,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": -1,
"selected": false,
"text": "accept-charset form"
},
{
"answer_id": 1213849,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n"
},
{
"answer_id": 1367468,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<input name=\"iehack\" type=\"hidden\" value=\"☠\" />\n"
},
{
"answer_id": 3322237,
"author": "David Mongeau-Petitpas",
"author_id": 400666,
"author_profile": "https://Stackoverflow.com/users/400666",
"pm_score": 1,
"selected": false,
"text": "<?php\n$params = array();\nforeach($_POST as $key=>$value) {\n $params[] = $key.\"=\".rawurlencode(utf8_decode($value));\n}\n$params = implode(\"&\",$params);\n\n//then you redirect to the final page in iso-8859-1\n?>\n"
},
{
"answer_id": 5633163,
"author": "Christian",
"author_id": 703762,
"author_profile": "https://Stackoverflow.com/users/703762",
"pm_score": 3,
"selected": false,
"text": "<form accept-charset=\"ISO-8859-15\">\n ...\n</form>\n"
},
{
"answer_id": 10067631,
"author": "dr.dimitru",
"author_id": 1320932,
"author_profile": "https://Stackoverflow.com/users/1320932",
"pm_score": 1,
"selected": false,
"text": "<form action=\"yourProcessPage.php\" method=\"POST\" accept-charset=\"utf-8\">\n<input name=\"string\" value=\"string\" />\n...\n</form>\n $string = $_POST['string'];\n$string = mb_convert_encoding($string, \"CP1251\", \"UTF-8\");\n"
},
{
"answer_id": 11863480,
"author": "dgaspar",
"author_id": 198080,
"author_profile": "https://Stackoverflow.com/users/198080",
"pm_score": 5,
"selected": false,
"text": "<form accept-charset=\"ISO-8859-1\" .... >\n document.charset = 'ISO-8859-1'; // do this before submitting your non-utf8 <form>!\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431/"
] |
153,573
|
<p>Take the following C# class:</p>
<pre><code>c1 {
event EventHandler someEvent;
}
</code></pre>
<p>If there are a lot of subscriptions to <code>c1</code>'s <code>someEvent</code> event and I want to clear them all, what is the best way to achieve this? <strong>Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.</strong></p>
<p>Currently my solution is to add a <code>ResetSubscriptions()</code> method to <code>c1</code> that sets <code>someEvent</code> to null. I don't know if this has any unseen consequences.</p>
|
[
{
"answer_id": 153577,
"author": "programmer",
"author_id": 5289,
"author_profile": "https://Stackoverflow.com/users/5289",
"pm_score": 5,
"selected": false,
"text": "public class c1\n{\n event EventHandler someEvent;\n public ResetSubscriptions() => someEvent = null; \n}\n"
},
{
"answer_id": 5423873,
"author": "umlcat",
"author_id": 535724,
"author_profile": "https://Stackoverflow.com/users/535724",
"pm_score": 2,
"selected": false,
"text": "const\n WM_Paint = 998; // <-- \"question\" can be done by several talkers\n WM_Clear = 546;\n\ntype\n MyWindowClass = class(Window)\n procedure NotEventHandlerMethod_1;\n procedure NotEventHandlerMethod_17;\n\n procedure DoPaintEventHandler; message WM_Paint; // <-- \"answer\" by this listener\n procedure DoClearEventHandler; message WM_Clear;\n end;\n"
},
{
"answer_id": 12914223,
"author": "Cary",
"author_id": 250428,
"author_profile": "https://Stackoverflow.com/users/250428",
"pm_score": 3,
"selected": false,
"text": "Delegate.RemoveAll SomeEvent=null ClearSubscribers() public void ClearSubscribers ()\n{\n SomeEvent = (EventHandler) Delegate.RemoveAll(SomeEvent, SomeEvent);\n // Then you will find SomeEvent is set to null.\n}\n"
},
{
"answer_id": 20711094,
"author": "Googol",
"author_id": 3123953,
"author_profile": "https://Stackoverflow.com/users/3123953",
"pm_score": 1,
"selected": false,
"text": "Delegate[] dary = TermCheckScore.GetInvocationList();\n\nif ( dary != null )\n{\n foreach ( Delegate del in dary )\n {\n TermCheckScore -= ( Action ) del;\n }\n}\n"
},
{
"answer_id": 23393492,
"author": "Feng",
"author_id": 3590189,
"author_profile": "https://Stackoverflow.com/users/3590189",
"pm_score": 3,
"selected": false,
"text": "class c1\n{\n event EventHandler someEvent;\n ResetSubscriptions() => someEvent = delegate { };\n}\n delegate { } null"
},
{
"answer_id": 49105203,
"author": "Jalal",
"author_id": 375958,
"author_profile": "https://Stackoverflow.com/users/375958",
"pm_score": 0,
"selected": false,
"text": "public class Foo : IDisposable\n{\n private event EventHandler _statusChanged;\n public event EventHandler StatusChanged\n {\n add\n {\n _statusChanged += value;\n }\n remove\n {\n _statusChanged -= value;\n }\n }\n\n public void Dispose()\n {\n _statusChanged = null;\n }\n}\n Dispose() using(new Foo()){/*...*/}"
},
{
"answer_id": 59970512,
"author": "barthdamon",
"author_id": 4530616,
"author_profile": "https://Stackoverflow.com/users/4530616",
"pm_score": -1,
"selected": false,
"text": "// The hard way\npublic delegate void ObjectCallback(ObjectType broadcaster);\n\npublic class Object\n{\n public event ObjectCallback m_ObjectCallback;\n \n void SetupListener()\n {\n ObjectCallback callback = null;\n callback = (ObjectType broadcaster) =>\n {\n // one time logic here\n broadcaster.m_ObjectCallback -= callback;\n };\n m_ObjectCallback += callback;\n\n }\n \n void BroadcastEvent()\n {\n m_ObjectCallback?.Invoke(this);\n }\n}\n public class Object\n{\n public Broadcast<Object> m_EventToBroadcast = new Broadcast<Object>();\n\n void SetupListener()\n {\n m_EventToBroadcast.SubscribeOnce((ObjectType broadcaster) => {\n // one time logic here\n });\n }\n\n ~Object()\n {\n m_EventToBroadcast.Dispose();\n m_EventToBroadcast = null;\n }\n\n void BroadcastEvent()\n {\n m_EventToBroadcast.Broadcast(this);\n }\n}\n\n\npublic delegate void ObjectDelegate<T>(T broadcaster);\npublic class Broadcast<T> : IDisposable\n{\n private event ObjectDelegate<T> m_Event;\n private List<ObjectDelegate<T>> m_SingleSubscribers = new List<ObjectDelegate<T>>();\n\n ~Broadcast()\n {\n Dispose();\n }\n\n public void Dispose()\n {\n Clear();\n System.GC.SuppressFinalize(this);\n }\n\n public void Clear()\n {\n m_SingleSubscribers.Clear();\n m_Event = delegate { };\n }\n\n // add a one shot to this delegate that is removed after first broadcast\n public void SubscribeOnce(ObjectDelegate<T> del)\n {\n m_Event += del;\n m_SingleSubscribers.Add(del);\n }\n\n // add a recurring delegate that gets called each time\n public void Subscribe(ObjectDelegate<T> del)\n {\n m_Event += del;\n }\n\n public void Unsubscribe(ObjectDelegate<T> del)\n {\n m_Event -= del;\n }\n\n public void Broadcast(T broadcaster)\n {\n m_Event?.Invoke(broadcaster);\n for (int i = 0; i < m_SingleSubscribers.Count; ++i)\n {\n Unsubscribe(m_SingleSubscribers[i]);\n }\n m_SingleSubscribers.Clear();\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5289/"
] |
153,581
|
<p>Is it possible to assign a global hotkey to a specific feature in an Adobe AIR app, i.e. the app feature responds to the hotkey whether the app is active or not (it must be running of course, but only in the system tray).</p>
|
[
{
"answer_id": 155786,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 3,
"selected": true,
"text": "c:\\programs\\thvo42\\coolapp.exe --hotkey q"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13041/"
] |
153,584
|
<p>How do I iterate over a timespan after days, hours, weeks or months?</p>
<p>Something like:</p>
<pre><code>for date in foo(from_date, to_date, delta=HOURS):
print date
</code></pre>
<p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p>
|
[
{
"answer_id": 153667,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 6,
"selected": false,
"text": "from datetime import date, datetime, timedelta\n\ndef datespan(startDate, endDate, delta=timedelta(days=1)):\n currentDate = startDate\n while currentDate < endDate:\n yield currentDate\n currentDate += delta\n >>> for day in datespan(date(2007, 3, 30), date(2007, 4, 3), \n>>> delta=timedelta(days=1)):\n>>> print day\n2007-03-30\n2007-03-31\n2007-04-01\n2007-04-02\n >>> for timestamp in datespan(datetime(2007, 3, 30, 15, 30), \n>>> datetime(2007, 3, 30, 18, 35), \n>>> delta=timedelta(hours=1)):\n>>> print timestamp\n2007-03-30 15:30:00\n2007-03-30 16:30:00\n2007-03-30 17:30:00\n2007-03-30 18:30:00\n"
},
{
"answer_id": 154055,
"author": "giltay",
"author_id": 21106,
"author_profile": "https://Stackoverflow.com/users/21106",
"pm_score": 3,
"selected": false,
"text": "from datetime import date\n\ndef jump_by_month(start_date, end_date, month_step=1):\n current_date = start_date\n while current_date < end_date:\n yield current_date\n carry, new_month = divmod(current_date.month - 1 + month_step, 12)\n new_month += 1\n current_date = current_date.replace(year=current_date.year + carry,\n month=new_month)\n new_month datetime.date"
},
{
"answer_id": 155172,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 8,
"selected": true,
"text": "from dateutil import rrule\nfrom datetime import datetime, timedelta\n\nnow = datetime.now()\nhundredDaysLater = now + timedelta(days=100)\n\nfor dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater):\n print dt\n 2008-09-30 23:29:54\n2008-10-30 23:29:54\n2008-11-30 23:29:54\n2008-12-30 23:29:54\n"
},
{
"answer_id": 39471227,
"author": "Rafa He So",
"author_id": 4480002,
"author_profile": "https://Stackoverflow.com/users/4480002",
"pm_score": 0,
"selected": false,
"text": "def months_between(date_start, date_end):\n months = []\n\n # Make sure start_date is smaller than end_date\n if date_start > date_end:\n tmp = date_start\n date_start = date_end\n date_end = tmp\n\n tmp_date = date_start\n while tmp_date.month <= date_end.month or tmp_date.year < date_end.year:\n months.append(tmp_date) # Here you could do for example: months.append(datetime.datetime.strftime(tmp_date, \"%b '%y\"))\n\n if tmp_date.month == 12: # New year\n tmp_date = datetime.date(tmp_date.year + 1, 1, 1)\n else:\n tmp_date = datetime.date(tmp_date.year, tmp_date.month + 1, 1)\n return months\n"
},
{
"answer_id": 50484799,
"author": "Thilina Madumal",
"author_id": 9814901,
"author_profile": "https://Stackoverflow.com/users/9814901",
"pm_score": 3,
"selected": false,
"text": "import pandas as pd\nfrom datetime import datetime\n\n\nDATE_TIME_FORMAT = '%Y-%m-%d %H:%M:%S'\n\nstart_datetime = datetime.strptime('2018-05-18 00:00:00', DATE_TIME_FORMAT)\nend_datetime = datetime.strptime('2018-05-23 13:00:00', DATE_TIME_FORMAT)\n\ntimedelta_index = pd.date_range(start=start_datetime, end=end_datetime, freq='H').to_series()\nfor index, value in timedelta_index.iteritems():\n dt = index.to_pydatetime()\n print(dt)\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/473/"
] |
153,585
|
<p>In MS Transact SQL, let's say I have a table (Orders) like this:</p>
<pre><code> Order Date Order Total Customer #
09/30/2008 8.00 1
09/15/2008 6.00 1
09/01/2008 9.50 1
09/01/2008 1.45 2
09/16/2008 4.50 2
09/17/2008 8.75 3
09/18/2008 2.50 3
</code></pre>
<p>What I need out of this is: for each customer the average order amount for the most recent two orders. So for Customer #1, I should get 7.00 (and not 7.83).</p>
<p>I've been staring at this for an hour now (inside a larger problem, which I've solved) and I think my brain has frozen. Help for a simple problem?</p>
|
[
{
"answer_id": 153601,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 4,
"selected": true,
"text": "select avg(total), customer \nfrom orders o1 \nwhere orderdate in \n ( select top 2 date \n from orders o2 \n where o2.customer = o1.customer \n order by date desc )\ngroup by customer\n"
},
{
"answer_id": 153612,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 0,
"selected": false,
"text": "USE AdventureWorks;\nGO\nSELECT i.ProductID, p.Name, i.LocationID, i.Quantity\n ,RANK() OVER \n (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS 'RANK'\nFROM Production.ProductInventory i \n INNER JOIN Production.Product p \n ON i.ProductID = p.ProductID\nORDER BY p.Name;\nGO\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8173/"
] |
153,592
|
<p>I'm using .NET to make an application with a drawing surface, similar to Visio. The UI connects two objects on the screen with Graphics.DrawLine. This simple implementation works fine, but as the surface gets more complex, I need a more robust way to represent the objects. One of these robust requirements is determining the intersection point for two lines so I can indicate separation via some kind of graphic.</p>
<p>So my question is, can anyone suggest a way to do this? Perhaps with a different technique (maybe GraphViz) or an algorithm?</p>
|
[
{
"answer_id": 153780,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 4,
"selected": true,
"text": "a = (v2.v2 v1.(x2-x1) - v1.v2 v2.(x2-x1)) / ((v1.v1)(v2.v2) - (v1.v2)^2)\nb = (v1.v2 v1.(x2-x1) - v1.v1 v2.(x2-x1)) / ((v1.v1)(v2.v2) - (v1.v2)^2)\n x1 + a * v1\n x1 + a*v1 = x2 + b*v2\n v1 v2 v1.v1*a - v2.v1*b = v1.(x2-x1)\nv1.v2*a - v2.v2*b = v2.(x2-x1)\n"
},
{
"answer_id": 154257,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 2,
"selected": false,
"text": "A A.O A.O + A.V | A.V.X A.V.Y A.O.X |\nM = | A.V.Y -A.V.X A.O.Y |\n | 0 0 1 |\n A B C.O = M*(B.O)\nC.V = M*(B.O + B.V) - C.O\n * C Y C t C.O.Y + t * C.V.Y = 0\n -C.O.Y\nt = --------\n C.V.Y\n t C C x = C.O.X + t * C.V.X\n x A p = A.O + A.V * x\n C.V.Y = 0 C.V.X"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7565/"
] |
153,596
|
<p>What would be the most efficient way of recording to a log (.txt) from a console program on C# and .NET 2.2? My program loops multiple times always outputting different data based on what the user wants, so I'm searching for the most efficient way to achieve this.</p>
<p>I know I can always reopen a stream and then close it, but everytime I do that it would be writing just one line, then next time around (seconds later) the program reloops and needs tor write again. In my opinion, that doesn't seem very resourse friendly.</p>
<p>I'm using multiple threads that all have output data that I want to log (opening/closing the same file or accessing the same file on different threads might be bad). The "holds a reference to a stream writer that auto-flushes" sounds like a good idea, however I don't know how to do that.</p>
|
[
{
"answer_id": 153672,
"author": "Wolfwyrd",
"author_id": 15570,
"author_profile": "https://Stackoverflow.com/users/15570",
"pm_score": 3,
"selected": true,
"text": "private Tracing trace = new Tracing(\"My.Namespace.Class\");\n MyClass()\n{\n trace.Verbose(\"Entered MyClass\");\n int x = 12;\n trace.Information(\"X is: {0}\", x);\n trace.Verbose(\"Leaving MyClass\");\n}\n <system.diagnostics>\n <trace autoflush=\"false\" indentsize=\"4\">\n <listeners>\n <add name=\"myListener\" type=\"System.Diagnostics.TextWriterTraceListener\" initializeData=\"c:\\mylogfile.log\" />\n </listeners>\n </trace>\n <switches>\n <add name=\"My.Namespace.Class\" value=\"4\"/> \n </switches>\n</system.diagnostics>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22582/"
] |
153,598
|
<p>I have a simple query:</p>
<pre><code>SELECT u_name AS user_name FROM users WHERE user_name = "john";
</code></pre>
<p>I get <code>Unknown Column 'user_name' in where clause</code>. Can I not refer to <code>'user_name'</code> in other parts of the statement even after <code>select 'u_name as user_name'</code>?</p>
|
[
{
"answer_id": 153614,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "SELECT u_name AS user_name FROM users WHERE u_name = 'john';\n"
},
{
"answer_id": 153626,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 3,
"selected": false,
"text": "SELECT u_name AS user_name\nFROM users\nWHERE u_name = \"john\";\n SELECT user_name\nfrom\n(\nSELECT u_name AS user_name\nFROM users\n)\nWHERE u_name = \"john\";\n"
},
{
"answer_id": 153627,
"author": "Mark S.",
"author_id": 13968,
"author_profile": "https://Stackoverflow.com/users/13968",
"pm_score": 4,
"selected": false,
"text": "select u_name as user_name from users where u_name = \"john\";\n select distinct(u_name) as user_name from users where u_name = \"john\";\n"
},
{
"answer_id": 780821,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "SELECT user_name\nFROM\n(\nSELECT name AS user_name\nFROM users\n) AS test\nWHERE user_name = \"john\"\n"
},
{
"answer_id": 2158701,
"author": "oliyide",
"author_id": 261431,
"author_profile": "https://Stackoverflow.com/users/261431",
"pm_score": 1,
"selected": false,
"text": "WHERE $sql = \"SELECT * FROM users WHERE username =\".$userName; $sql = \"SELECT * FROM users WHERE username =\".$userName.\"\"; $sql = \"SELECT * FROM users WHERE username ='\".$userName.\"'\";"
},
{
"answer_id": 3856473,
"author": "Septimus",
"author_id": 465945,
"author_profile": "https://Stackoverflow.com/users/465945",
"pm_score": 6,
"selected": false,
"text": "SELECT u_name AS user_name FROM users HAVING user_name = \"john\";\n"
},
{
"answer_id": 6137496,
"author": "Jon",
"author_id": 762647,
"author_profile": "https://Stackoverflow.com/users/762647",
"pm_score": 4,
"selected": false,
"text": "SELECT nodes.*, (SELECT (COUNT(*) FROM attachments \nWHERE attachments.nodeid = nodes.id) AS attachmentcount \nFROM nodes\nWHERE attachmentcount > 0;\n SELECT nodes.*, (SELECT (COUNT(*) FROM attachments \nWHERE attachments.nodeid = nodes.id) AS attachmentcount \nFROM nodes \nWHERE (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) > 0;\n"
},
{
"answer_id": 8225681,
"author": "F_S",
"author_id": 1059620,
"author_profile": "https://Stackoverflow.com/users/1059620",
"pm_score": 1,
"selected": false,
"text": "SET @somevar := '';\nSELECT @somevar AS user_name FROM users WHERE (@somevar := `u_name`) = \"john\";\n"
},
{
"answer_id": 14170718,
"author": "devWaleed",
"author_id": 1560907,
"author_profile": "https://Stackoverflow.com/users/1560907",
"pm_score": -1,
"selected": false,
"text": "mysql_query(\"SELECT * FROM `users` WHERE `user_name`='$user'\");\n"
},
{
"answer_id": 17953521,
"author": "M Khalid Junaid",
"author_id": 853360,
"author_profile": "https://Stackoverflow.com/users/853360",
"pm_score": 3,
"selected": false,
"text": "alias WHERE HAVING SELECT u_name AS user_name FROM users HAVING user_name = \"john\";\n WHERE SELECT u_name AS user_name FROM users WHERE u_name = \"john\";\n HAVING WHERE SELECT u_name AS user_name ,\n(SELECT last_name FROM users2 WHERE id=users.id) as user_last_name\nFROM users WHERE u_name = \"john\" HAVING user_last_name ='smith'\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
153,617
|
<p>How can I write a scheduler application in C# .NET?</p>
|
[
{
"answer_id": 153688,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 0,
"selected": false,
"text": "// Set event to occur on October 1st, 2008 at 12:30pm.\nDateTime eventStarts = new DateTime(2008,10,1,12,30,00);\nTimer timer = new Timer((eventStarts - DateTime.Now).TotalMilliseconds);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
153,630
|
<p>Unfortunately, I need to do this. I'm using ELMAH for my error log. Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception. You used to be able to use </p>
<pre><code>Elmah.ErrorLog.Default
</code></pre>
<p>However, this is now marked as obsolete. The compiler directs me to use the method</p>
<pre><code>Elmah.ErrorLog.GetDefault(HttpContext context)
</code></pre>
<p>MVC's context is of type HttpContextBase, which enables us to mock it (YAY!). How can we deal with MVC-unaware libraries that require the old style HttpContext?</p>
|
[
{
"answer_id": 153683,
"author": "SHODAN",
"author_id": 2622,
"author_profile": "https://Stackoverflow.com/users/2622",
"pm_score": 8,
"selected": true,
"text": "System.Web.HttpContext.Current"
},
{
"answer_id": 1469734,
"author": "rodrigo caballero",
"author_id": 178234,
"author_profile": "https://Stackoverflow.com/users/178234",
"pm_score": 5,
"selected": false,
"text": "this.HttpContext.ApplicationInstance.Context\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
153,633
|
<p>Is there an elegant way to have performant, natural sorting in a MySQL database?</p>
<p>For example if I have this data set:</p>
<ul>
<li>Final Fantasy</li>
<li>Final Fantasy 4</li>
<li>Final Fantasy 10</li>
<li>Final Fantasy 12</li>
<li>Final Fantasy 12: Chains of Promathia</li>
<li>Final Fantasy Adventure</li>
<li>Final Fantasy Origins</li>
<li>Final Fantasy Tactics</li>
</ul>
<p>Any other <strong>elegant</strong> solution than to split up the games' names into their components </p>
<ul>
<li><em>Title</em>: "Final Fantasy"</li>
<li><em>Number</em>: "12"</li>
<li><em>Subtitle</em>: "Chains of Promathia"</li>
</ul>
<p>to make sure that they come out in the right order? (10 after 4, not before 2).</p>
<p>Doing so is a pain in the a** because every now and then there's another game that breaks that mechanism of parsing the game title (e.g. "Warhammer 40,000", "James Bond 007")</p>
|
[
{
"answer_id": 153660,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 4,
"selected": false,
"text": "ORDER BY SELECT * FROM table ORDER BY CAST(mid(name, 6, LENGTH(c) -5) AS unsigned) \n"
},
{
"answer_id": 153699,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 3,
"selected": false,
"text": "ORDER BY rank ORDER BY release_date"
},
{
"answer_id": 458260,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "SELECT names FROM your_table ORDER BY games + 0 ASC\n"
},
{
"answer_id": 5222136,
"author": "Bob Fanger",
"author_id": 19165,
"author_profile": "https://Stackoverflow.com/users/19165",
"pm_score": 1,
"selected": false,
"text": "$keys = array();\n$values = array();\nforeach ($results as $index => $row) {\n $key = $row['name'].'__'.$index; // Add the index to create an unique key.\n $keys[] = $key;\n $values[$key] = $row; \n}\nnatsort($keys);\n$sortedValues = array(); \nforeach($keys as $index) {\n $sortedValues[] = $values[$index]; \n}\n"
},
{
"answer_id": 5583068,
"author": "plalx",
"author_id": 1211528,
"author_profile": "https://Stackoverflow.com/users/1211528",
"pm_score": 4,
"selected": false,
"text": "/**\n * Returns a string formatted for natural sorting. This function is very useful when having to sort alpha-numeric strings.\n *\n * @author Alexandre Potvin Latreille (plalx)\n * @param {nvarchar(4000)} string The formatted string.\n * @param {int} numberLength The length each number should have (including padding). This should be the length of the longest number. Defaults to 10.\n * @param {char(50)} sameOrderChars A list of characters that should have the same order. Ex: '.-/'. Defaults to empty string.\n *\n * @return {nvarchar(4000)} A string for natural sorting.\n * Example of use: \n * \n * SELECT Name FROM TableA ORDER BY Name\n * TableA (unordered) TableA (ordered)\n * ------------ ------------\n * ID Name ID Name\n * 1. A1. 1. A1-1. \n * 2. A1-1. 2. A1.\n * 3. R1 --> 3. R1\n * 4. R11 4. R11\n * 5. R2 5. R2\n *\n * \n * As we can see, humans would expect A1., A1-1., R1, R2, R11 but that's not how SQL is sorting it.\n * We can use this function to fix this.\n *\n * SELECT Name FROM TableA ORDER BY dbo.udf_NaturalSortFormat(Name, default, '.-')\n * TableA (unordered) TableA (ordered)\n * ------------ ------------\n * ID Name ID Name\n * 1. A1. 1. A1. \n * 2. A1-1. 2. A1-1.\n * 3. R1 --> 3. R1\n * 4. R11 4. R2\n * 5. R2 5. R11\n */\nCREATE FUNCTION dbo.udf_NaturalSortFormat(\n @string nvarchar(4000),\n @numberLength int = 10,\n @sameOrderChars char(50) = ''\n)\nRETURNS varchar(4000)\nAS\nBEGIN\n DECLARE @sortString varchar(4000),\n @numStartIndex int,\n @numEndIndex int,\n @padLength int,\n @totalPadLength int,\n @i int,\n @sameOrderCharsLen int;\n\n SELECT \n @totalPadLength = 0,\n @string = RTRIM(LTRIM(@string)),\n @sortString = @string,\n @numStartIndex = PATINDEX('%[0-9]%', @string),\n @numEndIndex = 0,\n @i = 1,\n @sameOrderCharsLen = LEN(@sameOrderChars);\n\n -- Replace all char that has to have the same order by a space.\n WHILE (@i <= @sameOrderCharsLen)\n BEGIN\n SET @sortString = REPLACE(@sortString, SUBSTRING(@sameOrderChars, @i, 1), ' ');\n SET @i = @i + 1;\n END\n\n -- Pad numbers with zeros.\n WHILE (@numStartIndex <> 0)\n BEGIN\n SET @numStartIndex = @numStartIndex + @numEndIndex;\n SET @numEndIndex = @numStartIndex;\n\n WHILE(PATINDEX('[0-9]', SUBSTRING(@string, @numEndIndex, 1)) = 1)\n BEGIN\n SET @numEndIndex = @numEndIndex + 1;\n END\n\n SET @numEndIndex = @numEndIndex - 1;\n\n SET @padLength = @numberLength - (@numEndIndex + 1 - @numStartIndex);\n\n IF @padLength < 0\n BEGIN\n SET @padLength = 0;\n END\n\n SET @sortString = STUFF(\n @sortString,\n @numStartIndex + @totalPadLength,\n 0,\n REPLICATE('0', @padLength)\n );\n\n SET @totalPadLength = @totalPadLength + @padLength;\n SET @numStartIndex = PATINDEX('%[0-9]%', RIGHT(@string, LEN(@string) - @numEndIndex));\n END\n\n RETURN @sortString;\nEND\n\nGO\n"
},
{
"answer_id": 6344044,
"author": "slotishtype",
"author_id": 122099,
"author_profile": "https://Stackoverflow.com/users/122099",
"pm_score": 7,
"selected": false,
"text": "SELECT alphanumeric, \n integer\nFROM sorting_test\nORDER BY LENGTH(alphanumeric), alphanumeric\n"
},
{
"answer_id": 6353707,
"author": "FilmJ",
"author_id": 133221,
"author_profile": "https://Stackoverflow.com/users/133221",
"pm_score": 3,
"selected": false,
"text": "ORDER BY ORDER BY LPAD(REPLACE(`table`.`column`,'Scene ',''),10,'0')\n"
},
{
"answer_id": 12257917,
"author": "Richard Toth",
"author_id": 1645273,
"author_profile": "https://Stackoverflow.com/users/1645273",
"pm_score": 6,
"selected": false,
"text": "DROP FUNCTION IF EXISTS `udf_FirstNumberPos`;\nDELIMITER ;;\nCREATE FUNCTION `udf_FirstNumberPos` (`instring` varchar(4000)) \nRETURNS int\nLANGUAGE SQL\nDETERMINISTIC\nNO SQL\nSQL SECURITY INVOKER\nBEGIN\n DECLARE position int;\n DECLARE tmp_position int;\n SET position = 5000;\n SET tmp_position = LOCATE('0', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF; \n SET tmp_position = LOCATE('1', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF;\n SET tmp_position = LOCATE('2', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF;\n SET tmp_position = LOCATE('3', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF;\n SET tmp_position = LOCATE('4', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF;\n SET tmp_position = LOCATE('5', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF;\n SET tmp_position = LOCATE('6', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF;\n SET tmp_position = LOCATE('7', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF;\n SET tmp_position = LOCATE('8', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF;\n SET tmp_position = LOCATE('9', instring); IF (tmp_position > 0 AND tmp_position < position) THEN SET position = tmp_position; END IF;\n\n IF (position = 5000) THEN RETURN 0; END IF;\n RETURN position;\nEND\n;;\n\nDROP FUNCTION IF EXISTS `udf_NaturalSortFormat`;\nDELIMITER ;;\nCREATE FUNCTION `udf_NaturalSortFormat` (`instring` varchar(4000), `numberLength` int, `sameOrderChars` char(50)) \nRETURNS varchar(4000)\nLANGUAGE SQL\nDETERMINISTIC\nNO SQL\nSQL SECURITY INVOKER\nBEGIN\n DECLARE sortString varchar(4000);\n DECLARE numStartIndex int;\n DECLARE numEndIndex int;\n DECLARE padLength int;\n DECLARE totalPadLength int;\n DECLARE i int;\n DECLARE sameOrderCharsLen int;\n\n SET totalPadLength = 0;\n SET instring = TRIM(instring);\n SET sortString = instring;\n SET numStartIndex = udf_FirstNumberPos(instring);\n SET numEndIndex = 0;\n SET i = 1;\n SET sameOrderCharsLen = CHAR_LENGTH(sameOrderChars);\n\n WHILE (i <= sameOrderCharsLen) DO\n SET sortString = REPLACE(sortString, SUBSTRING(sameOrderChars, i, 1), ' ');\n SET i = i + 1;\n END WHILE;\n\n WHILE (numStartIndex <> 0) DO\n SET numStartIndex = numStartIndex + numEndIndex;\n SET numEndIndex = numStartIndex;\n\n WHILE (udf_FirstNumberPos(SUBSTRING(instring, numEndIndex, 1)) = 1) DO\n SET numEndIndex = numEndIndex + 1;\n END WHILE;\n\n SET numEndIndex = numEndIndex - 1;\n\n SET padLength = numberLength - (numEndIndex + 1 - numStartIndex);\n\n IF padLength < 0 THEN\n SET padLength = 0;\n END IF;\n\n SET sortString = INSERT(sortString, numStartIndex + totalPadLength, 0, REPEAT('0', padLength));\n\n SET totalPadLength = totalPadLength + padLength;\n SET numStartIndex = udf_FirstNumberPos(RIGHT(instring, CHAR_LENGTH(instring) - numEndIndex));\n END WHILE;\n\n RETURN sortString;\nEND\n;;\n SELECT name FROM products ORDER BY udf_NaturalSortFormat(name, 10, \".\")\n"
},
{
"answer_id": 13346208,
"author": "user1467716",
"author_id": 1467716,
"author_profile": "https://Stackoverflow.com/users/1467716",
"pm_score": -1,
"selected": false,
"text": "SELECT * FROM `table` ORDER BY \nCONCAT(\n GREATEST(\n LOCATE('1', name),\n LOCATE('2', name),\n LOCATE('3', name),\n LOCATE('4', name),\n LOCATE('5', name),\n LOCATE('6', name),\n LOCATE('7', name),\n LOCATE('8', name),\n LOCATE('9', name)\n ),\n name\n) ASC\n"
},
{
"answer_id": 19426904,
"author": "antoine",
"author_id": 2019776,
"author_profile": "https://Stackoverflow.com/users/2019776",
"pm_score": 2,
"selected": false,
"text": "SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum \nFROM table \nORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name\n -\n0 \n1\n2\n3\n4\n5\n10\n13\n19\n99\n102\nChair\nDog\nTable\nWindows\n"
},
{
"answer_id": 27307928,
"author": "Luke Hoggett",
"author_id": 4052357,
"author_profile": "https://Stackoverflow.com/users/4052357",
"pm_score": 3,
"selected": false,
"text": "12 南新宿\n LENGTH() udf_NaturalSortFormat CHAR_LENGTH() LENGTH() DROP FUNCTION IF EXISTS `udf_NaturalSortFormat`;\nDELIMITER ;;\nCREATE FUNCTION `udf_NaturalSortFormat` (`instring` varchar(4000), `numberLength` int, `sameOrderChars` char(50)) \nRETURNS varchar(4000)\nLANGUAGE SQL\nDETERMINISTIC\nNO SQL\nSQL SECURITY INVOKER\nBEGIN\n DECLARE sortString varchar(4000);\n DECLARE numStartIndex int;\n DECLARE numEndIndex int;\n DECLARE padLength int;\n DECLARE totalPadLength int;\n DECLARE i int;\n DECLARE sameOrderCharsLen int;\n\n SET totalPadLength = 0;\n SET instring = TRIM(instring);\n SET sortString = instring;\n SET numStartIndex = udf_FirstNumberPos(instring);\n SET numEndIndex = 0;\n SET i = 1;\n SET sameOrderCharsLen = CHAR_LENGTH(sameOrderChars);\n\n WHILE (i <= sameOrderCharsLen) DO\n SET sortString = REPLACE(sortString, SUBSTRING(sameOrderChars, i, 1), ' ');\n SET i = i + 1;\n END WHILE;\n\n WHILE (numStartIndex <> 0) DO\n SET numStartIndex = numStartIndex + numEndIndex;\n SET numEndIndex = numStartIndex;\n\n WHILE (udf_FirstNumberPos(SUBSTRING(instring, numEndIndex, 1)) = 1) DO\n SET numEndIndex = numEndIndex + 1;\n END WHILE;\n\n SET numEndIndex = numEndIndex - 1;\n\n SET padLength = numberLength - (numEndIndex + 1 - numStartIndex);\n\n IF padLength < 0 THEN\n SET padLength = 0;\n END IF;\n\n SET sortString = INSERT(sortString, numStartIndex + totalPadLength, 0, REPEAT('0', padLength));\n\n SET totalPadLength = totalPadLength + padLength;\n SET numStartIndex = udf_FirstNumberPos(RIGHT(instring, CHAR_LENGTH(instring) - numEndIndex));\n END WHILE;\n\n RETURN sortString;\nEND\n;;\n"
},
{
"answer_id": 28808798,
"author": "bonger",
"author_id": 664741,
"author_profile": "https://Stackoverflow.com/users/664741",
"pm_score": 1,
"selected": false,
"text": "SELECT name,\nLEAST(\n IFNULL(NULLIF(LOCATE('0', name), 0), ~0),\n IFNULL(NULLIF(LOCATE('1', name), 0), ~0),\n IFNULL(NULLIF(LOCATE('2', name), 0), ~0),\n IFNULL(NULLIF(LOCATE('3', name), 0), ~0),\n IFNULL(NULLIF(LOCATE('4', name), 0), ~0),\n IFNULL(NULLIF(LOCATE('5', name), 0), ~0),\n IFNULL(NULLIF(LOCATE('6', name), 0), ~0),\n IFNULL(NULLIF(LOCATE('7', name), 0), ~0),\n IFNULL(NULLIF(LOCATE('8', name), 0), ~0),\n IFNULL(NULLIF(LOCATE('9', name), 0), ~0)\n) AS first_int\nFROM table\nORDER BY IF(first_int = ~0, name, CONCAT(\n SUBSTR(name, 1, first_int - 1),\n LPAD(CAST(SUBSTR(name, first_int) AS UNSIGNED), LENGTH(~0), '0'),\n SUBSTR(name, first_int + LENGTH(CAST(SUBSTR(name, first_int) AS UNSIGNED)))\n)) ASC\n"
},
{
"answer_id": 39150117,
"author": "Tarik",
"author_id": 5105831,
"author_profile": "https://Stackoverflow.com/users/5105831",
"pm_score": 1,
"selected": false,
"text": "SELECT test_column FROM test_table ORDER BY LENGTH(test_column) DESC, test_column DESC\n\n/* \nResult \n--------\nvalue_1\nvalue_2\nvalue_3\nvalue_4\nvalue_5\nvalue_6\nvalue_7\nvalue_8\nvalue_9\nvalue_10\nvalue_11\nvalue_12\nvalue_13\nvalue_14\nvalue_15\n...\n*/\n"
},
{
"answer_id": 43789749,
"author": "Neto Queiroz",
"author_id": 5725336,
"author_profile": "https://Stackoverflow.com/users/5725336",
"pm_score": 2,
"selected": false,
"text": "... ORDER BY natsort_canon(column_name, 'natural')\n"
},
{
"answer_id": 58154535,
"author": "Doin",
"author_id": 999120,
"author_profile": "https://Stackoverflow.com/users/999120",
"pm_score": 2,
"selected": false,
"text": "SELECT myString FROM myTable ORDER BY NatSortKey(myString,0); ### 0 means process all numbers - resulting sort key might be quite long for certain inputs\n INSERT INTO myTable (myString,myStringNSK) VALUES (@theStringValue,NatSortKey(@theStringValue,10)), ...\n...\nSELECT myString FROM myTable ORDER BY myStringNSK;\n CREATE TABLE myTable (\n...\nmyString varchar(100),\nmyStringNSK varchar(150) AS (NatSortKey(myString,10)) STORED,\n...\nKEY (myStringNSK),\n...);\n NatSortKey() REGEXP_REPLACE() delimiter $$\nCREATE DEFINER=CURRENT_USER FUNCTION NatSortKey (s varchar(100), n int) RETURNS varchar(350) DETERMINISTIC\nBEGIN\n/****\n Converts numbers in the input string s into a format such that sorting results in a nat-sort.\n Numbers of up to 359 digits (before the decimal point, if one is present) are supported. Sort results are undefined if the input string contains numbers longer than this.\n For n>0, only the first n numbers in the input string will be converted for nat-sort (so strings that differ only after the first n numbers will not nat-sort amongst themselves).\n Total sort-ordering is preserved, i.e. if s1!=s2, then NatSortKey(s1,n)!=NatSortKey(s2,n), for any given n.\n Numbers may contain ',' as a thousands separator, and '.' as a decimal point. To reverse these (as appropriate for some European locales), the code would require modification.\n Numbers preceded by '+' sort with numbers not preceded with either a '+' or '-' sign.\n Negative numbers (preceded with '-') sort before positive numbers, but are sorted in order of ascending absolute value (so -7 sorts BEFORE -1001).\n Numbers with leading zeros sort after the same number with no (or fewer) leading zeros.\n Decimal-part-only numbers (like .75) are recognised, provided the decimal point is not immediately preceded by either another '.', or by a letter-type character.\n Numbers with thousand separators sort after the same number without them.\n Thousand separators are only recognised in numbers with no leading zeros that don't immediately follow a ',', and when they format the number correctly.\n (When not recognised as a thousand separator, a ',' will instead be treated as separating two distinct numbers).\n Version-number-like sequences consisting of 3 or more numbers separated by '.' are treated as distinct entities, and each component number will be nat-sorted.\n The entire entity will sort after any number beginning with the first component (so e.g. 10.2.1 sorts after both 10 and 10.995, but before 11)\n Note that The first number component in an entity like this is also permitted to contain thousand separators.\n\n To achieve this, numbers within the input string are prefixed and suffixed according to the following format:\n - The number is prefixed by a 2-digit base-36 number representing its length, excluding leading zeros. If there is a decimal point, this length only includes the integer part of the number.\n - A 3-character suffix is appended after the number (after the decimals if present).\n - The first character is a space, or a '+' sign if the number was preceded by '+'. Any preceding '+' sign is also removed from the front of the number.\n - This is followed by a 2-digit base-36 number that encodes the number of leading zeros and whether the number was expressed in comma-separated form (e.g. 1,000,000.25 vs 1000000.25)\n - The value of this 2-digit number is: (number of leading zeros)*2 + (1 if comma-separated, 0 otherwise)\n - For version number sequences, each component number has the prefix in front of it, and the separating dots are removed.\n Then there is a single suffix that consists of a ' ' or '+' character, followed by a pair base-36 digits for each number component in the sequence.\n\n e.g. here is how some simple sample strings get converted:\n 'Foo055' --> 'Foo0255 02'\n 'Absolute zero is around -273 centigrade' --> 'Absolute zero is around -03273 00 centigrade'\n 'The $1,000,000 prize' --> 'The $071000000 01 prize'\n '+99.74 degrees' --> '0299.74+00 degrees'\n 'I have 0 apples' --> 'I have 00 02 apples'\n '.5 is the same value as 0000.5000' --> '00.5 00 is the same value as 00.5000 08'\n 'MariaDB v10.3.0018' --> 'MariaDB v02100130218 000004'\n\n The restriction to numbers of up to 359 digits comes from the fact that the first character of the base-36 prefix MUST be a decimal digit, and so the highest permitted prefix value is '9Z' or 359 decimal.\n The code could be modified to handle longer numbers by increasing the size of (both) the prefix and suffix.\n A higher base could also be used (by replacing CONV() with a custom function), provided that the collation you are using sorts the \"digits\" of the base in the correct order, starting with 0123456789.\n However, while the maximum number length may be increased this way, note that the technique this function uses is NOT applicable where strings may contain numbers of unlimited length.\n\n The function definition does not specify the charset or collation to be used for string-type parameters or variables: The default database charset & collation at the time the function is defined will be used.\n This is to make the function code more portable. However, there are some important restrictions:\n\n - Collation is important here only when comparing (or storing) the output value from this function, but it MUST order the characters \" +0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\" in that order for the natural sort to work.\n This is true for most collations, but not all of them, e.g. in Lithuanian 'Y' comes before 'J' (according to Wikipedia).\n To adapt the function to work with such collations, replace CONV() in the function code with a custom function that emits \"digits\" above 9 that are characters ordered according to the collation in use.\n\n - For efficiency, the function code uses LENGTH() rather than CHAR_LENGTH() to measure the length of strings that consist only of digits 0-9, '.', and ',' characters.\n This works for any single-byte charset, as well as any charset that maps standard ASCII characters to single bytes (such as utf8 or utf8mb4).\n If using a charset that maps these characters to multiple bytes (such as, e.g. utf16 or utf32), you MUST replace all instances of LENGTH() in the function definition with CHAR_LENGTH()\n\n Length of the output:\n\n Each number converted adds 5 characters (2 prefix + 3 suffix) to the length of the string. n is the maximum count of numbers to convert;\n This parameter is provided as a means to limit the maximum output length (to input length + 5*n).\n If you do not require the total-ordering property, you could edit the code to use suffixes of 1 character (space or plus) only; this would reduce the maximum output length for any given n.\n Since a string of length L has at most ((L+1) DIV 2) individual numbers in it (every 2nd character a digit), for n<=0 the maximum output length is (inputlength + 5*((inputlength+1) DIV 2))\n So for the current input length of 100, the maximum output length is 350.\n If changing the input length, the output length must be modified according to the above formula. The DECLARE statements for x,y,r, and suf must also be modified, as the code comments indicate.\n****/\n DECLARE x,y varchar(100); # need to be same length as input s\n DECLARE r varchar(350) DEFAULT ''; # return value: needs to be same length as return type\n DECLARE suf varchar(101); # suffix for a number or version string. Must be (((inputlength+1) DIV 2)*2 + 1) chars to support version strings (e.g. '1.2.33.5'), though it's usually just 3 chars. (Max version string e.g. 1.2. ... .5 has ((length of input + 1) DIV 2) numeric components)\n DECLARE i,j,k int UNSIGNED;\n IF n<=0 THEN SET n := -1; END IF; # n<=0 means \"process all numbers\"\n LOOP\n SET i := REGEXP_INSTR(s,'\\\\d'); # find position of next digit\n IF i=0 OR n=0 THEN RETURN CONCAT(r,s); END IF; # no more numbers to process -> we're done\n SET n := n-1, suf := ' ';\n IF i>1 THEN\n IF SUBSTRING(s,i-1,1)='.' AND (i=2 OR SUBSTRING(s,i-2,1) RLIKE '[^.\\\\p{L}\\\\p{N}\\\\p{M}\\\\x{608}\\\\x{200C}\\\\x{200D}\\\\x{2100}-\\\\x{214F}\\\\x{24B6}-\\\\x{24E9}\\\\x{1F130}-\\\\x{1F149}\\\\x{1F150}-\\\\x{1F169}\\\\x{1F170}-\\\\x{1F189}]') AND (SUBSTRING(s,i) NOT RLIKE '^\\\\d++\\\\.\\\\d') THEN SET i:=i-1; END IF; # Allow decimal number (but not version string) to begin with a '.', provided preceding char is neither another '.', nor a member of the unicode character classes: \"Alphabetic\", \"Letter\", \"Block=Letterlike Symbols\" \"Number\", \"Mark\", \"Join_Control\"\n IF i>1 AND SUBSTRING(s,i-1,1)='+' THEN SET suf := '+', j := i-1; ELSE SET j := i; END IF; # move any preceding '+' into the suffix, so equal numbers with and without preceding \"+\" signs sort together\n SET r := CONCAT(r,SUBSTRING(s,1,j-1)); SET s = SUBSTRING(s,i); # add everything before the number to r and strip it from the start of s; preceding '+' is dropped (not included in either r or s)\n END IF;\n SET x := REGEXP_SUBSTR(s,IF(SUBSTRING(s,1,1) IN ('0','.') OR (SUBSTRING(r,-1)=',' AND suf=' '),'^\\\\d*+(?:\\\\.\\\\d++)*','^(?:[1-9]\\\\d{0,2}(?:,\\\\d{3}(?!\\\\d))++|\\\\d++)(?:\\\\.\\\\d++)*+')); # capture the number + following decimals (including multiple consecutive '.<digits>' sequences)\n SET s := SUBSTRING(s,LENGTH(x)+1); # NOTE: LENGTH() can be safely used instead of CHAR_LENGTH() here & below PROVIDED we're using a charset that represents digits, ',' and '.' characters using single bytes (e.g. latin1, utf8)\n SET i := INSTR(x,'.');\n IF i=0 THEN SET y := ''; ELSE SET y := SUBSTRING(x,i); SET x := SUBSTRING(x,1,i-1); END IF; # move any following decimals into y\n SET i := LENGTH(x);\n SET x := REPLACE(x,',','');\n SET j := LENGTH(x);\n SET x := TRIM(LEADING '0' FROM x); # strip leading zeros\n SET k := LENGTH(x);\n SET suf := CONCAT(suf,LPAD(CONV(LEAST((j-k)*2,1294) + IF(i=j,0,1),10,36),2,'0')); # (j-k)*2 + IF(i=j,0,1) = (count of leading zeros)*2 + (1 if there are thousands-separators, 0 otherwise) Note the first term is bounded to <= base-36 'ZY' as it must fit within 2 characters\n SET i := LOCATE('.',y,2);\n IF i=0 THEN\n SET r := CONCAT(r,LPAD(CONV(LEAST(k,359),10,36),2,'0'),x,y,suf); # k = count of digits in number, bounded to be <= '9Z' base-36\n ELSE # encode a version number (like 3.12.707, etc)\n SET r := CONCAT(r,LPAD(CONV(LEAST(k,359),10,36),2,'0'),x); # k = count of digits in number, bounded to be <= '9Z' base-36\n WHILE LENGTH(y)>0 AND n!=0 DO\n IF i=0 THEN SET x := SUBSTRING(y,2); SET y := ''; ELSE SET x := SUBSTRING(y,2,i-2); SET y := SUBSTRING(y,i); SET i := LOCATE('.',y,2); END IF;\n SET j := LENGTH(x);\n SET x := TRIM(LEADING '0' FROM x); # strip leading zeros\n SET k := LENGTH(x);\n SET r := CONCAT(r,LPAD(CONV(LEAST(k,359),10,36),2,'0'),x); # k = count of digits in number, bounded to be <= '9Z' base-36\n SET suf := CONCAT(suf,LPAD(CONV(LEAST((j-k)*2,1294),10,36),2,'0')); # (j-k)*2 = (count of leading zeros)*2, bounded to fit within 2 base-36 digits\n SET n := n-1;\n END WHILE;\n SET r := CONCAT(r,y,suf);\n END IF;\n END LOOP;\nEND\n$$\ndelimiter ;\n"
},
{
"answer_id": 64812403,
"author": "Frank Forte",
"author_id": 857113,
"author_profile": "https://Stackoverflow.com/users/857113",
"pm_score": 0,
"selected": false,
"text": "ORDER BY CAST(REGEXP_REPLACE(title, \"[a-zA-Z]+\", \"\") AS INT)';\n create table titles(title);\n\ninsert into titles (title) values \n('Final Fantasy'),\n('Final Fantasy #03'),\n('Final Fantasy #11'),\n('Final Fantasy #10'),\n('Final Fantasy #2'),\n('Bond 007 ##2'),\n('Final Fantasy #01'),\n('Bond 007'),\n('Final Fantasy #11}');\n\nselect REGEXP_REPLACE(title, \"#([0-9]+)\", \"\\\\1\") as title from titles\nORDER BY REGEXP_REPLACE(title, \"#[0-9]+\", \"\"),\nCAST(REGEXP_REPLACE(title, \".*#([0-9]+).*\", \"\\\\1\") AS INT); \n+-------------------+\n| title |\n+-------------------+\n| Bond 007 |\n| Bond 007 #2 |\n| Final Fantasy |\n| Final Fantasy 01 |\n| Final Fantasy 2 |\n| Final Fantasy 03 |\n| Final Fantasy 10 |\n| Final Fantasy 11 |\n| Final Fantasy 11} |\n+-------------------+\n8 rows in set, 2 warnings (0.001 sec)\n"
},
{
"answer_id": 69256988,
"author": "Federico Razzoli",
"author_id": 9445059,
"author_profile": "https://Stackoverflow.com/users/9445059",
"pm_score": 1,
"selected": false,
"text": "natural_sort_key()"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999/"
] |
153,639
|
<p>Greetings!</p>
<p>I have a WebService that contains a WebMethod that does some work and returns a boolean value. The work that it does may or may not take some time, so I'd like to call it asynchronously.</p>
<pre><code>[WebService(Namespace = "http://tempuri.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class MyWebSvc : System.Web.Services.WebService
{
[WebMethod]
public bool DoWork()
{
bool succ = false;
try
{
// do some work, which might take a while
}
catch (Exception ex)
{
// handle
succ = false;
}
return succ;
}
}
</code></pre>
<p>This WebService exists on each server in a web farm. So to call the DoWork() method on each server, I have a class library to do so, based on a list of server URLs:</p>
<pre><code>static public class WebSvcsMgr
{
static public void DoAllWork(ICollection<string> servers)
{
MyWebSvc myWebSvc = new MyWebSvc();
foreach (string svr_url in servers)
{
myWebSvc.Url = svr_url;
myWebSvc.DoWork();
}
}
}
</code></pre>
<p>Finally, this is called from the Web interface in an asp:Button click event like so:</p>
<pre><code>WebSvcsMgr.DoAllWork(server_list);
</code></pre>
<p>For the static DoAllWork() method called by the Web Form, I plan to make this an asynchronous call via IAsyncResult. However, I'd like to report a success/fail of the DoWork() WebMethod for each server in the farm as the results are returned. What would be the best approach to this in conjuction with an UpdatePanel? A GridView? Labels? And how could this be returned by the static helper class to the Web Form?</p>
|
[
{
"answer_id": 153854,
"author": "craigmoliver",
"author_id": 12252,
"author_profile": "https://Stackoverflow.com/users/12252",
"pm_score": 0,
"selected": false,
"text": "<asp:UpdatePanel ID=\"up\" runat=\"server\" UpdateMode=\"Conditional\">\n <ContentTemplate>\n <asp:Literal ID=\"litUpdateMe\" runat=\"server\" />\n </ContentTemplate>\n</asp:UpdatePanel>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27870/"
] |
153,644
|
<p>Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array <code>@myarray</code> and a hash <code>%myhash</code>, why do you need to do:</p>
<pre><code>$x = $myarray[1];
$y = $myhash{'foo'};
</code></pre>
<p>instead of just doing :</p>
<pre><code>$x = myarray[1];
$y = myhash{'foo'};
</code></pre>
<p>Why are the above ambiguous? </p>
<p>Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl?</p>
<pre><code>@var[0];
@var{'key'};
%var[0];
%var{'key'};
</code></pre>
|
[
{
"answer_id": 153668,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 3,
"selected": false,
"text": "$x = myarray[1];\n $x = m[1];\n"
},
{
"answer_id": 153692,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 5,
"selected": true,
"text": "@slice = @myarray[1, 2, 5];\n@slice = @myhash{qw/foo bar baz/};\n"
},
{
"answer_id": 153715,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 3,
"selected": false,
"text": "@var[0] @var[0,1] @var['key'] %var[0] and %var['key'] @var{'key'} @var{0}"
},
{
"answer_id": 153725,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 4,
"selected": false,
"text": "@ $ $foo @foo [ { # variables\n$foo\n@foo\n\n# accesses\n$stuff{blubb} # accesses %stuff, returns a scalar\n@stuff{@list} # accesses %stuff, returns an array\n$stuff[blubb] # accesses @stuff, returns a scalar\n # (and calls the blubb() function)\n@stuff[blubb] # accesses @stuff, returns an array\n"
},
{
"answer_id": 153824,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 2,
"selected": false,
"text": "$ @ %"
},
{
"answer_id": 153929,
"author": "hexten",
"author_id": 10032,
"author_profile": "https://Stackoverflow.com/users/10032",
"pm_score": 5,
"selected": false,
"text": "my $x = myarray[1];\n $ perl foo.pl \nFlying Butt Monkeys!\n $ cat foo.pl \n#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nsub myarray {\n print \"Flying Butt Monkeys!\\n\";\n}\n\nmy $x = myarray[1];\n"
},
{
"answer_id": 154039,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 3,
"selected": false,
"text": "$hash{key} $array[0] @hash{key} @hash{qw<key1 key2 ... key_n>} @array[0,3,5..7,$n..$n+5] @array[0] %hash{@keys} %hash{key} \"@\" \"array[0]\""
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] |
153,666
|
<p>I'm having a problem with some mail merge code that is supposed to produce letters within our application. I'm aware that this code is a bit rough at the moment, but we're in the "Get something working" phase before we tidy it up.</p>
<p>Now the way this is supposed to work, and the way it works when we do it manually, is we have a file (the fileOut variable + ".template") which is a template for the letter. We open that template, merge it, and then save it as the filename in the fileOut variable.</p>
<p>However, what it is doing is saving a copy of the template file to the fileout filename, instead of the output of the merge.</p>
<p>I've searched, and I seem to be banging my head against a brick wall.</p>
<p>datafile is the datafile that contains the merge data.</p>
<p>Using the same files, it all works if you do it manually.</p>
<pre><code>Public Function processFile(ByVal datafile As String, ByVal fileOut As String) As String
Dim ans As String = String.Empty
errorLog = "C:\Temp\Template_error.log"
If (File.Exists(datafile)) Then
Try
' Create an instance of Word and make it invisible.'
wrdApp = CreateObject("Word.Application")
wrdApp.Visible = False
' Add a new document.'
wrdDoc = wrdApp.Documents.Add(fileOut & ".template")
wrdDoc.Select()
Dim wrdSelection As Word.Selection
Dim wrdMailMerge As Word.MailMerge
wrdDoc.MailMerge.OpenDataSource(datafile)
wrdSelection = wrdApp.Selection()
wrdMailMerge = wrdDoc.MailMerge()
With wrdMailMerge
.Execute()
End With
wrdDoc.SaveAs(fileOut)
wrdApp.Quit(False)
' Release References.'
wrdSelection = Nothing
wrdMailMerge = Nothing
wrdDoc = Nothing
wrdApp = Nothing
ans = "Merged OK"
Call writeToLogFile(errorLog, "This worked, written to " & fileOut)
Catch ex As Exception
ans = "error : exception thrown " & ex.ToString
Call writeToLogFile(errorLog, ans)
End Try
Else
ans = "error ; unable to open Date File : " & datafile
If (logErrors) Then
Call writeToLogFile(errorLog, "The specified source csv file does not exist. Unable " & _
"to process it. Filename provided: " & datafile)
End If
End If
Return ans
End Function
</code></pre>
|
[
{
"answer_id": 153793,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "wrdDoc.MailMerge.OpenDataSource(templateName)\n data = \"C:\\My Data.xls\"\nwrdDoc.MailMerge.OpenDataSource(data)\n"
},
{
"answer_id": 156509,
"author": "hulver",
"author_id": 11496,
"author_profile": "https://Stackoverflow.com/users/11496",
"pm_score": 3,
"selected": true,
"text": "wrdDoc = wrdApp.Documents.Add(TemplateFileName)\nwrdDoc.Select()\nDim wrdSelection As Word.Selection\nDim wrdMailMerge As Word.MailMerge\n\n\nwrdDoc.MailMerge.OpenDataSource(DataFileName)\n\nwrdSelection = wrdApp.Selection()\nwrdMailMerge = wrdDoc.MailMerge()\nWith wrdMailMerge\n .Execute()\nEnd With\n\n' This is the wrong thing to do. It just re-saves the template file you opened. '\n'wrdDoc.SaveAs(OutputFileName) '\n\n' The resulting merged document is actually stored '\n' in the MailMerge object, so you have to save that '\nwrdMailMerge.Application.ActiveDocument.SaveAs(OutputFileName)\n\nwrdApp.Quit(False)\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11496/"
] |
153,685
|
<p>So I've got an application whose window behavior I would like to behave more like Photoshop CS. In Photoshop CS, the document windows always stay behind the tool windows, but are still top level windows. For MDI child windows, since the document window is actually a child, you can't move it outside of the main window. In CS, though, you can move your image to a different monitor fine, which is a big advantage over docked applications like Visual Studio, and over regular MDI applications.</p>
<p>Anyway, here's my research so far. I've tried to intercept the WM_MOUSEACTIVATE message, and use the DeferWindowPos commands to do my own ordering of the window, and then return MA_NOACTIVATEANDEAT, but that causes the window to not be activated properly, and I believe there are other commands that "activate" a window without calling WM_MOUSEACTIVATE (like SetFocus() I think), so that method probably won't work anyway.</p>
<p>I believe Windows' procedure for "activating" a window is
1. notify the unactivated window with the WM_NCACTIVATE and WM_ACTIVATE messages
2. move the window to the top of the z-order (sending WM_POSCHANGING, WM_POSCHANGED and repaint messages)
3. notify the newly activated window with WM_NCACTIVATE and WM_ACTIVATE messages.</p>
<p>It seems the cleanest way to do it would be to intercept the first WM_ACTIVATE message, and somehow notify Windows that you're going to override their way of doing the z-ordering, and then use the DeferWindowPos commands, but I can't figure out how to do it that way. It seems once Windows sends the WM_ACTIVATE message, it's already going to do the reordering its own way, so any DeferWindowPos commands I use are overridden.</p>
<p>Right now I've got a basic implementation quasy-working that makes the tool windows topmost when the app is activated, but then makes them non-topmost when it's not, but it's very quirky (it sometimes gets on top of other windows like the task manager, whereas Photoshop CS doesn't do that, so I think Photoshop somehow does it differently) and it just seems like there would be a more intuitive way of doing it.</p>
<p>Anyway, does anyone know how Photoshop CS does it, or a better way than using topmost?</p>
|
[
{
"answer_id": 8124168,
"author": "Eugene Belyakov",
"author_id": 851473,
"author_profile": "https://Stackoverflow.com/users/851473",
"pm_score": 2,
"selected": false,
"text": "public class BaseForm : Form\n{\n public virtual int TopMostLevel\n {\n get { return 0; }\n }\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool EnumThreadWindows(uint dwThreadId, Win32Callback lpEnumFunc, IntPtr lParam);\n\n /// <summary>\n /// Get process window handles sorted by z order from top to bottom.\n /// </summary>\n public static IEnumerable<IntPtr> GetWindowsSortedByZOrder()\n {\n List<IntPtr> handles = new List<IntPtr>();\n EnumThreadWindows(GetCurrentThreadId(),\n (hWnd, lparam) =>\n {\n handles.Add(hWnd);\n return true;\n }, IntPtr.Zero);\n return handles;\n }\n\n\n protected override void WndProc(ref Message m)\n {\n if (m.Msg == (int)WindowsMessages.WM_WINDOWPOSCHANGING)\n {\n //Looking for Window at the bottom of Z-order, but with TopMostLevel > this.TopMostLevel\n foreach (IntPtr handle in GetWindowsSortedByZOrder().Reverse())\n {\n var window = FromHandle(handle) as BaseForm;\n if (window != null && this.TopMostLevel < window.TopMostLevel)\n {\n //changing hwndInsertAfter field in WindowPos structure\n if (IntPtr.Size == 4)\n {\n Marshal.WriteInt32(m.LParam, IntPtr.Size, window.Handle.ToInt32());\n }\n else if (IntPtr.Size == 8)\n {\n Marshal.WriteInt64(m.LParam, IntPtr.Size, window.Handle.ToInt64());\n }\n break;\n }\n }\n }\n\n base.WndProc(ref m);\n }\n}\n\npublic class FormWithLevel1 : BaseForm\n{\n public override int TopMostLevel\n {\n get { return 1; }\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23812/"
] |
153,689
|
<p>I'm designing an application which deals with two sets of data - Users and Areas. The data is read from files produced by a third party. I have a User class and an Area class, and the data is read into a Users array and an Areas array (or other appropriate memory structure, depending on the technology we go with).</p>
<p>Both classes have a unique ID member which is read from the file, and the User class contains an array of Area IDs, giving a relationship where one user is associated with many Areas.</p>
<p>The requirements are quite straightforward:</p>
<ul>
<li>List of Users</li>
<li>List of Areas</li>
<li>List of Users for Specified Area</li>
<li>List of Areas for Specified Users</li>
</ul>
<p>My first thought was to leave the data in the two arrays, then for each of the requirements, have a seperate method which would interrogate one or both arrays as required. This would be easy to implement, but I'm not convinced it's necessarily the best way.</p>
<p>Then I thought about having a 'Get Areas' method on the User class and a 'Get Users' member on the Area class which would be more useful if for example I'm at a stage where I have an Area object, I could find it's users by a property, but then how would a 'Get Users' method on the Area class be aware of/have access to the Users array.</p>
<p>I've had this problem a number of times before, but never really came up with a definitive solution. Maybe I'm just making it more complicated than it actually is. Can anyone provide any tips, URLs or books that would help me with this sort of design?</p>
<p>UPDATE:
Thank you all for taking your time to leave some tips. Your comments are very much appreciated.</p>
<p>I agree that the root of this problem is a many-to-many relationship. I understand how that would be modelled in a relational database, that's pretty simple.</p>
<p>The data I receive is in the form of binary files from a third party, so I have no control over the structure of these, but I can store it whichever way is best when I read it in. It is a bit square pegs in round holes, but I thought reading it in then storing it in a database, the program would then have to query the database to get to the results. It's not a massive amount of data, so I thought it would be possible to get out what I need by storing it in memory structures.</p>
|
[
{
"answer_id": 153708,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "User <<--->> Area\n User: Id, name, etc.\nArea: Id, name, etc.\nUserArea: UserId, AreaId\n"
},
{
"answer_id": 153719,
"author": "chessguy",
"author_id": 1908025,
"author_profile": "https://Stackoverflow.com/users/1908025",
"pm_score": 0,
"selected": false,
"text": "Dictionary<Area, List<User>> Dictionary<User, List<Area>>"
},
{
"answer_id": 153736,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 2,
"selected": false,
"text": "struct/class Membership\n{\n int MemberID;\n int userID;\n int areaID;\n}\n public bool addMember(Member m)\n{\n if (/*eligibility Requirements*/)\n {\n memberList.add(m);\n m.addArea(this);\n return true;\n }\n return false;\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8354/"
] |
153,706
|
<p>It seems to me that phpMyAdmin imports tables by default with collation latin1_swedish_ci, how i change this?</p>
|
[
{
"answer_id": 153765,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": false,
"text": "$dbname = 'my_databaseName';\nmysql_connect('127.0.0.1', 'root', '');\nmysql_query(\"ALTER DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci\");\n$res = mysql_query(\"SHOW TABLES FROM `$dbname`\");\nwhile($row = mysql_fetch_row($res)) {\n $query = \"ALTER TABLE {$dbname}.`{$row[0]}` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci\";\n mysql_query($query);\n $query = \"ALTER TABLE {$dbname}.`{$row[0]}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci\";\n mysql_query($query);\n}\necho 'all tables converted';\n"
},
{
"answer_id": 153802,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 6,
"selected": true,
"text": "[mysqld]\ndefault-character-set=utf8\n"
},
{
"answer_id": 11374158,
"author": "Yasen",
"author_id": 662780,
"author_profile": "https://Stackoverflow.com/users/662780",
"pm_score": 4,
"selected": false,
"text": "/etc/mysql/my.cnf ~/my.cnf [mysqld] collation_server = utf8_unicode_ci\ncharacter_set_server=utf8\n service mysqld restart\n"
},
{
"answer_id": 48437982,
"author": "Yash",
"author_id": 5081877,
"author_profile": "https://Stackoverflow.com/users/5081877",
"pm_score": 2,
"selected": false,
"text": "utf8_general_ci UTF 8 Settings D:\\xampp\\mysql\\bin\\my.ini ## UTF 8 Settings\n#init-connect=\\'SET NAMES utf8\\'\ncollation_server=utf8_unicode_ci\ncharacter_set_server=utf8\nskip-character-set-client-handshake\ncharacter_sets-dir=\"D:/xampp/mysql/share/charsets\"\n my.cnf ## UTF 8 Settings\ncollation_server=utf8_unicode_ci\ncharacter_set_server=utf8\n"
},
{
"answer_id": 51503914,
"author": "MAX POWER",
"author_id": 372630,
"author_profile": "https://Stackoverflow.com/users/372630",
"pm_score": 4,
"selected": false,
"text": "utf8mb4 [mysqld] collation_server = utf8mb4_unicode_ci\ncharacter_set_server = utf8mb4\n mysql sudo service mysql restart"
},
{
"answer_id": 57761067,
"author": "user251433",
"author_id": 10002582,
"author_profile": "https://Stackoverflow.com/users/10002582",
"pm_score": 2,
"selected": false,
"text": "my.ini my.cnf [mysqld]\ncollation_server = utf8_unicode_ci\ncharacter_set_server=utf8\n config.inc.php $cfg['DefaultConnectionCollation'] = 'utf8_general_ci';\n"
},
{
"answer_id": 59666073,
"author": "Nelson",
"author_id": 3715973,
"author_profile": "https://Stackoverflow.com/users/3715973",
"pm_score": 0,
"selected": false,
"text": "collation_server = utf8mb4_general_ci\ncharacter_set_server=utf8mb4\n utf8"
},
{
"answer_id": 74413120,
"author": "ChrisH",
"author_id": 1210149,
"author_profile": "https://Stackoverflow.com/users/1210149",
"pm_score": 0,
"selected": false,
"text": "$cfg['DefaultCharset'] = 'utf8'; $cfg['DefaultConnectionCollation'] = 'utf8_general_ci';"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
153,707
|
<p>Suppose I have the following declaration:</p>
<pre><code>class Over1
{
protected:
class Under1
{
};
};
</code></pre>
<p>I know that I could do the following:</p>
<pre><code>class Over2 : public Over1
{
protected:
class Under2 : public Under1
{
};
};
</code></pre>
<p>But is there a way to declare Under2 without Over2? </p>
<p>Since you would have to extend Over1 to use any derivative of Under1 this may seem silly, but in this situation there might be 30 different flavors of Under. I can either:</p>
<ul>
<li>Put them all inside Over1 : Not
attractive since Over2 may only use
1 or 2 of them </li>
<li>Put them each in
their own version of Over : Not
attractive since then you will have
to multiply inherit from almost the
same class. </li>
<li>Find a way to create
children of Under1 without creating
children of Over1</li>
</ul>
<p>So is this possible?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 153830,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 2,
"selected": true,
"text": "class Over1\n{\nprotected:\n class Under1\n {\n };\n\n template <typename T>\n class UnderImplementor;\n};\n\nstruct Under2Tag;\nstruct Under3Tag;\nstruct Under4Tag;\n\ntemplate <>\nclass Over1::UnderImplementor<Under2Tag> : public Over1::Under1\n{\n};\n\ntemplate <>\nclass Over1::UnderImplementor<Under3Tag> : public Over1::Under1\n{\n};\n\ntemplate <>\nclass Over1::UnderImplementor<Under4Tag> : public Over1::Under1\n{\n};\n"
},
{
"answer_id": 153843,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 0,
"selected": false,
"text": "class Over1\n{\n protected:\n class Under1\n {\n };\n\n public:\n class Under1Interface : public Under1 \n {\n };\n};\n\nclass Under2 : public Over1::Under1Interface\n{\n};\n class Over1\n{\n protected:\n class Under1\n {\n };\n};\n\nclass Under2 : private Over1, public Over1::Under1\n{\n};\n class Under2;\n\nclass Over1\n{\n friend class Under2;\n\n protected:\n class Under1\n {\n };\n};\n\nclass Under2 : public Over1::Under1\n{\n};\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23829/"
] |
153,716
|
<p>Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format (someone@domain.subdomain), but that's it's a real active e-mail address.</p>
<p>I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not.</p>
|
[
{
"answer_id": 153751,
"author": "MBCook",
"author_id": 18189,
"author_profile": "https://Stackoverflow.com/users/18189",
"pm_score": 6,
"selected": false,
"text": "private static final Pattern rfc2822 = Pattern.compile(\n \"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$\"\n);\n\nif (!rfc2822.matcher(email).matches()) {\n throw new Exception(\"Invalid address\");\n}\n Hashtable<String, String> env = new Hashtable<String, String>();\n\nenv.put(\"java.naming.factory.initial\", \"com.sun.jndi.dns.DnsContextFactory\");\n\nDirContext ictx = new InitialDirContext(env);\n\nAttributes attrs = ictx.getAttributes(domainName, new String[] {\"MX\"});\n\nAttribute attr = attrs.get(\"MX\");\n\nif (attr == null)\n // No MX record\nelse\n // If attr.size() > 0, there is an MX record\n"
},
{
"answer_id": 12032525,
"author": "Craigo",
"author_id": 418057,
"author_profile": "https://Stackoverflow.com/users/418057",
"pm_score": -1,
"selected": false,
"text": "public static boolean isValidEmail(String emailAddress) {\n return emailAddress.contains(\" \") == false && emailAddress.matches(\".+@.+\\\\.[a-z]+\");\n}\n"
},
{
"answer_id": 13283772,
"author": "asa",
"author_id": 1808359,
"author_profile": "https://Stackoverflow.com/users/1808359",
"pm_score": -1,
"selected": false,
"text": "public static boolean isValidEmail(String emailAddress) {\n return emailAddress.contains(\" \") == false && emailAddress.matches(\".+@.+\\\\.[a-z]+\");\n} \n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
153,724
|
<p>What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.</p>
<p>I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.</p>
<p>I know one method of doing this is to use the <code>String.format</code> method:</p>
<pre><code>String.format("%.5g%n", 0.912385);
</code></pre>
<p>returns:</p>
<pre><code>0.91239
</code></pre>
<p>which is great, however it always displays numbers with 5 decimal places even if they are not significant: </p>
<pre><code>String.format("%.5g%n", 0.912300);
</code></pre>
<p>returns:</p>
<pre><code>0.91230
</code></pre>
<p>Another method is to use the <code>DecimalFormatter</code>:</p>
<pre><code>DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
</code></pre>
<p>returns:</p>
<pre><code>0.91238
</code></pre>
<p>However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this:</p>
<pre><code>0.912385 -> 0.91239
0.912300 -> 0.9123
</code></pre>
<p>What is the best way to achieve this in Java?</p>
|
[
{
"answer_id": 153753,
"author": "asterite",
"author_id": 20459,
"author_profile": "https://Stackoverflow.com/users/20459",
"pm_score": 9,
"selected": false,
"text": "value double (double)Math.round(value * 100000d) / 100000d\n"
},
{
"answer_id": 153764,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 5,
"selected": false,
"text": "double myNum = .912385;\nint precision = 10000; //keep 4 digits\nmyNum= Math.floor(myNum * precision +.5)/precision;\n"
},
{
"answer_id": 153785,
"author": "curtisk",
"author_id": 17651,
"author_profile": "https://Stackoverflow.com/users/17651",
"pm_score": 11,
"selected": true,
"text": "setRoundingMode RoundingMode DecimalFormat df = new DecimalFormat(\"#.####\");\ndf.setRoundingMode(RoundingMode.CEILING);\nfor (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {\n Double d = n.doubleValue();\n System.out.println(df.format(d));\n}\n 12\n123.1235\n0.23\n0.1\n2341234.2125\n Double d = n.doubleValue() + 1e-6;\n"
},
{
"answer_id": 153982,
"author": "Milhous",
"author_id": 17712,
"author_profile": "https://Stackoverflow.com/users/17712",
"pm_score": 7,
"selected": false,
"text": "DecimalFormat df = new DecimalFormat(\"#.00000\");\ndf.format(0.912385);\n"
},
{
"answer_id": 154354,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 8,
"selected": false,
"text": "new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP);\n BigDecimal BigDecimal toString toPlainString package trials;\nimport java.math.BigDecimal;\n\npublic class Trials {\n\n public static void main(String[] args) {\n int yourScale = 10;\n System.out.println(BigDecimal.valueOf(0.42344534534553453453-0.42324534524553453453).setScale(yourScale, BigDecimal.ROUND_HALF_UP));\n }\n"
},
{
"answer_id": 1361874,
"author": "Ovesh",
"author_id": 3751,
"author_profile": "https://Stackoverflow.com/users/3751",
"pm_score": 6,
"selected": false,
"text": "BigDecimal bd = new BigDecimal(Double.toString(d));\nbd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);\nreturn bd.doubleValue();\n BigDecimal bd = new BigDecimal(Double.toString(number));\nbd = bd.setScale(decimalPlaces, RoundingMode.HALF_UP);\nreturn bd.doubleValue();\n"
},
{
"answer_id": 4826827,
"author": "user593581",
"author_id": 593581,
"author_profile": "https://Stackoverflow.com/users/593581",
"pm_score": 7,
"selected": false,
"text": "double d = 9232.129394d;\n BigDecimal BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN);\nd = bd.doubleValue();\n d = Math.round(d*100)/100.0d;\n d == 9232.13"
},
{
"answer_id": 5806991,
"author": "Amit",
"author_id": 706282,
"author_profile": "https://Stackoverflow.com/users/706282",
"pm_score": 4,
"selected": false,
"text": "public static double round(double valueToRound, int numberOfDecimalPlaces)\n{\n double multipicationFactor = Math.pow(10, numberOfDecimalPlaces);\n double interestedInZeroDPs = valueToRound * multipicationFactor;\n return Math.round(interestedInZeroDPs) / multipicationFactor;\n}\n"
},
{
"answer_id": 6563862,
"author": "Ivan",
"author_id": 827031,
"author_profile": "https://Stackoverflow.com/users/827031",
"pm_score": 5,
"selected": false,
"text": "DecimalFormat df = new DecimalFormat(\"#.00000\");\ndf.format(0.912385);\n DecimalFormat df = new DecimalFormat(\"#0.######\");\ndf.format(0.912385);\n 0.912385 DecimalFormat df = new DecimalFormat(\"#0.#####\");\ndf.format(0.912385);\n 0.91239 DecimalFormat df = new DecimalFormat(\"#0.####\");\ndf.format(0.912385);\n 0.9124 3.1415926"
},
{
"answer_id": 6569383,
"author": "Ivan",
"author_id": 827811,
"author_profile": "https://Stackoverflow.com/users/827811",
"pm_score": 3,
"selected": false,
"text": "Use BigDecimal or any other decimal-based format.\n"
},
{
"answer_id": 7347099,
"author": "Jasdeep Singh",
"author_id": 934649,
"author_profile": "https://Stackoverflow.com/users/934649",
"pm_score": 2,
"selected": false,
"text": "double pp = 10000;\n\ndouble myVal = 22.268699999999967;\nString needVal = \"22.2687\";\n\ndouble i = (5.0/pp);\n\nString format = \"%10.4f\";\nString getVal = String.format(format,(Math.round((myVal +i)*pp)/pp)-i).trim();\n"
},
{
"answer_id": 7593617,
"author": "JibW",
"author_id": 824751,
"author_profile": "https://Stackoverflow.com/users/824751",
"pm_score": 6,
"selected": false,
"text": "double d = 3.76628729;\n\nDecimalFormat newFormat = new DecimalFormat(\"#.##\");\ndouble twoDecimal = Double.valueOf(newFormat.format(d));\n"
},
{
"answer_id": 12684082,
"author": "user207421",
"author_id": 207421,
"author_profile": "https://Stackoverflow.com/users/207421",
"pm_score": 7,
"selected": false,
"text": "DecimalFormat BigDecimal public class RoundingCounterExample\n{\n\n static float roundOff(float x, int position)\n {\n float a = x;\n double temp = Math.pow(10.0, position);\n a *= temp;\n a = Math.round(a);\n return (a / (float)temp);\n }\n\n public static void main(String[] args)\n {\n float a = roundOff(0.0009434f,3);\n System.out.println(\"a=\"+a+\" (a % .001)=\"+(a % 0.001));\n int count = 0, errors = 0;\n for (double x = 0.0; x < 1; x += 0.0001)\n {\n count++;\n double d = x;\n int scale = 2;\n double factor = Math.pow(10, scale);\n d = Math.round(d * factor) / factor;\n if ((d % 0.01) != 0.0)\n {\n System.out.println(d + \" \" + (d % 0.01));\n errors++;\n }\n }\n System.out.println(count + \" trials \" + errors + \" errors\");\n }\n}\n 10001 trials 9251 errors\n BigDecimal new MathContext(16) public static void main(String[] args)\n{\n int count = 0, errors = 0;\n int scale = 2;\n double factor = Math.pow(10, scale);\n MathContext mc = new MathContext(16, RoundingMode.DOWN);\n for (double x = 0.0; x < 1; x += 0.0001)\n {\n count++;\n double d = x;\n d = Math.round(d * factor) / factor;\n BigDecimal bd = new BigDecimal(d, mc);\n bd = bd.remainder(new BigDecimal(\"0.01\"), mc);\n if (bd.multiply(BigDecimal.valueOf(100)).remainder(BigDecimal.ONE, mc).compareTo(BigDecimal.ZERO) != 0)\n {\n System.out.println(d + \" \" + bd);\n errors++;\n }\n }\n System.out.println(count + \" trials \" + errors + \" errors\");\n}\n 10001 trials 4401 errors\n"
},
{
"answer_id": 21898592,
"author": "Li Ying",
"author_id": 958160,
"author_profile": "https://Stackoverflow.com/users/958160",
"pm_score": 3,
"selected": false,
"text": "public static double round(double x, int scale) {\n return round(x, scale, BigDecimal.ROUND_HALF_UP);\n}\n\npublic static double round(double x, int scale, int roundingMethod) {\n try {\n return (new BigDecimal\n (Double.toString(x))\n .setScale(scale, roundingMethod))\n .doubleValue();\n } catch (NumberFormatException ex) {\n if (Double.isInfinite(x)) {\n return x;\n } else {\n return Double.NaN;\n }\n }\n}\n"
},
{
"answer_id": 23207932,
"author": "aim",
"author_id": 1107862,
"author_profile": "https://Stackoverflow.com/users/1107862",
"pm_score": 0,
"selected": false,
"text": " double p = Math.pow(10d, dp);\n\n double result = Math.round(value * p)/p;\n"
},
{
"answer_id": 24884082,
"author": "Easwaramoorthy K",
"author_id": 1954390,
"author_profile": "https://Stackoverflow.com/users/1954390",
"pm_score": 3,
"selected": false,
"text": "BigDecimal value = new BigDecimal(\"2.3\");\nvalue = value.setScale(0, RoundingMode.UP);\nBigDecimal value1 = new BigDecimal(\"-2.3\");\nvalue1 = value1.setScale(0, RoundingMode.UP);\nSystem.out.println(value + \"n\" + value1);\n"
},
{
"answer_id": 31099485,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 2,
"selected": false,
"text": "DecimalFormat double String DecimalFormat formatter = new DecimalFormat(\"0.0##\");\nformatter.setRoundingMode(RoundingMode.HALF_UP);\n\ndouble num = 1.234567;\nreturn formatter.format(num);\n RoundingMode"
},
{
"answer_id": 32026036,
"author": "Mifeet",
"author_id": 2032064,
"author_profile": "https://Stackoverflow.com/users/2032064",
"pm_score": 4,
"selected": false,
"text": "DecimalFormat df = new DecimalFormat(\"#.#####\");\ndf.setRoundingMode(RoundingMode.HALF_UP);\nString str1 = df.format(0.912385)); // 0.91239\n String str2 = new BigDecimal(0.912385)\n .setScale(5, BigDecimal.ROUND_HALF_UP)\n .toString();\n double double rounded = Precision.round(0.912385, 5, BigDecimal.ROUND_HALF_UP);\n double rounded = Functions.round(0.00001).apply(0.912385)\n double rounded = Utils.roundDouble(0.912385, 5)\n"
},
{
"answer_id": 33545114,
"author": "marco",
"author_id": 2526021,
"author_profile": "https://Stackoverflow.com/users/2526021",
"pm_score": 3,
"selected": false,
"text": "DecimalFormat BigDecimal double org.apache.commons.math3.util.Precision.round(..) BigDecimal DoubleRounder double a = DoubleRounder.round(2.0/3.0, 3);\n double b = DoubleRounder.round(2.0/3.0, 3, RoundingMode.DOWN);\n double c = DoubleRounder.round(1000.0d, 17);\n double d = DoubleRounder.round(90080070060.1d, 9);\n System.out.println(a);\n System.out.println(b);\n System.out.println(c);\n System.out.println(d);\n 0.667\n 0.666\n 1000.0\n 9.00800700601E10\n DoubleRounder.round(256.025d, 2) BigDecimal(double) valueOf(double)"
},
{
"answer_id": 35771257,
"author": "ashr",
"author_id": 3745505,
"author_profile": "https://Stackoverflow.com/users/3745505",
"pm_score": 3,
"selected": false,
"text": "private String withNoTrailingZeros(final double value, final int nrOfDecimals) {\nreturn new BigDecimal(String.valueOf(value)).setScale(nrOfDecimals, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();\n\n}\n String "
},
{
"answer_id": 40522406,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "public static final int DECIMAL_PLACES = 2;\n\nNumberFormatter formatter = new NumberFormatter(DECIMAL_PLACES);\n\nString value = formatter.format(9.319); // \"9,32\"\nString value2 = formatter.format(0.0000005); // \"5,00E-7\"\nString value3 = formatter.format(1324134123); // \"1,32E9\"\n\ndouble parsedValue1 = formatter.parse(\"0,4E-2\", 0); // 0.004\ndouble parsedValue2 = formatter.parse(\"0,002\", 0); // 0.002\ndouble parsedValue3 = formatter.parse(\"3423,12345\", 0); // 3423.12345\n import java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.DecimalFormatSymbols;\nimport java.text.ParseException;\nimport java.util.Locale;\n\npublic class NumberFormatter {\n\n private static final String SYMBOL_INFINITE = \"\\u221e\";\n private static final char SYMBOL_MINUS = '-';\n private static final char SYMBOL_ZERO = '0';\n private static final int DECIMAL_LEADING_GROUPS = 10;\n private static final int EXPONENTIAL_INT_THRESHOLD = 1000000000; // After this value switch to exponential notation\n private static final double EXPONENTIAL_DEC_THRESHOLD = 0.0001; // Below this value switch to exponential notation\n\n private DecimalFormat decimalFormat;\n private DecimalFormat decimalFormatLong;\n private DecimalFormat exponentialFormat;\n\n private char groupSeparator;\n\n public NumberFormatter(int decimalPlaces) {\n configureDecimalPlaces(decimalPlaces);\n }\n\n public void configureDecimalPlaces(int decimalPlaces) {\n if (decimalPlaces <= 0) {\n throw new IllegalArgumentException(\"Invalid decimal places\");\n }\n\n DecimalFormatSymbols separators = new DecimalFormatSymbols(Locale.getDefault());\n separators.setMinusSign(SYMBOL_MINUS);\n separators.setZeroDigit(SYMBOL_ZERO);\n\n groupSeparator = separators.getGroupingSeparator();\n\n StringBuilder decimal = new StringBuilder();\n StringBuilder exponential = new StringBuilder(\"0.\");\n\n for (int i = 0; i < DECIMAL_LEADING_GROUPS; i++) {\n decimal.append(\"###\").append(i == DECIMAL_LEADING_GROUPS - 1 ? \".\" : \",\");\n }\n\n for (int i = 0; i < decimalPlaces; i++) {\n decimal.append(\"#\");\n exponential.append(\"0\");\n }\n\n exponential.append(\"E0\");\n\n decimalFormat = new DecimalFormat(decimal.toString(), separators);\n decimalFormatLong = new DecimalFormat(decimal.append(\"####\").toString(), separators);\n exponentialFormat = new DecimalFormat(exponential.toString(), separators);\n\n decimalFormat.setRoundingMode(RoundingMode.HALF_UP);\n decimalFormatLong.setRoundingMode(RoundingMode.HALF_UP);\n exponentialFormat.setRoundingMode(RoundingMode.HALF_UP);\n }\n\n public String format(double value) {\n String result;\n if (Double.isNaN(value)) {\n result = \"\";\n } else if (Double.isInfinite(value)) {\n result = String.valueOf(SYMBOL_INFINITE);\n } else {\n double absValue = Math.abs(value);\n if (absValue >= 1) {\n if (absValue >= EXPONENTIAL_INT_THRESHOLD) {\n value = Math.floor(value);\n result = exponentialFormat.format(value);\n } else {\n result = decimalFormat.format(value);\n }\n } else if (absValue < 1 && absValue > 0) {\n if (absValue >= EXPONENTIAL_DEC_THRESHOLD) {\n result = decimalFormat.format(value);\n if (result.equalsIgnoreCase(\"0\")) {\n result = decimalFormatLong.format(value);\n }\n } else {\n result = exponentialFormat.format(value);\n }\n } else {\n result = \"0\";\n }\n }\n return result;\n }\n\n public String formatWithoutGroupSeparators(double value) {\n return removeGroupSeparators(format(value));\n }\n\n public double parse(String value, double defValue) {\n try {\n return decimalFormat.parse(value).doubleValue();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n return defValue;\n }\n\n private String removeGroupSeparators(String number) {\n return number.replace(String.valueOf(groupSeparator), \"\");\n }\n\n}\n"
},
{
"answer_id": 40538095,
"author": "pwojnowski",
"author_id": 3348552,
"author_profile": "https://Stackoverflow.com/users/3348552",
"pm_score": 0,
"selected": false,
"text": " Locale locale = Locale.ENGLISH;\n NumberFormat nf = NumberFormat.getNumberInstance(locale);\n // for trailing zeros:\n nf.setMinimumFractionDigits(2);\n // round to 2 digits:\n nf.setMaximumFractionDigits(2);\n\n System.out.println(nf.format(.99));\n System.out.println(nf.format(123.567));\n System.out.println(nf.format(123.0));\n"
},
{
"answer_id": 40736192,
"author": "Qamar",
"author_id": 5710872,
"author_profile": "https://Stackoverflow.com/users/5710872",
"pm_score": -1,
"selected": false,
"text": " double a = 123.00449;\n double roundOff1 = Math.round(a*10000)/10000.00;\n double roundOff2 = Math.round(roundOff1*1000)/1000.00;\n double roundOff = Math.round(roundOff2*100)/100.00;\n\n System.out.println(\"result:\"+roundOff);\n"
},
{
"answer_id": 40801184,
"author": "Se Song",
"author_id": 3458608,
"author_profile": "https://Stackoverflow.com/users/3458608",
"pm_score": 2,
"selected": false,
"text": "Math.round(selfEvaluate*100000d.0)/100000d.0;\n Math.round(selfEvaluate*100000d.0)*0.00000d1;\n .0 .0"
},
{
"answer_id": 42347442,
"author": "Suragch",
"author_id": 3681880,
"author_profile": "https://Stackoverflow.com/users/3681880",
"pm_score": 2,
"selected": false,
"text": "Math.round() Math.round(3.7) // 4\n .5 .5 int Math.round(3.0); // 3\nMath.round(3.1); // 3\nMath.round(3.5); // 4\nMath.round(3.9); // 4\n\nMath.round(-3.0); // -3\nMath.round(-3.1); // -3\nMath.round(-3.5); // -3 *** careful here ***\nMath.round(-3.9); // -4\n double Math.ceil(3.0); // 3.0\nMath.ceil(3.1); // 4.0\nMath.ceil(3.5); // 4.0\nMath.ceil(3.9); // 4.0\n\nMath.ceil(-3.0); // -3.0\nMath.ceil(-3.1); // -3.0\nMath.ceil(-3.5); // -3.0\nMath.ceil(-3.9); // -3.0\n double Math.floor(3.0); // 3.0\nMath.floor(3.1); // 3.0\nMath.floor(3.5); // 3.0\nMath.floor(3.9); // 3.0\n\nMath.floor(-3.0); // -3.0\nMath.floor(-3.1); // -4.0\nMath.floor(-3.5); // -4.0\nMath.floor(-3.9); // -4.0\n round .5 double Math.rint(3.0); // 3.0\nMath.rint(3.1); // 3.0\nMath.rint(3.5); // 4.0 ***\nMath.rint(3.9); // 4.0\nMath.rint(4.5); // 4.0 ***\nMath.rint(5.5); // 6.0 ***\n\nMath.rint(-3.0); // -3.0\nMath.rint(-3.1); // -3.0\nMath.rint(-3.5); // -4.0 ***\nMath.rint(-3.9); // -4.0\nMath.rint(-4.5); // -4.0 ***\nMath.rint(-5.5); // -6.0 ***\n"
},
{
"answer_id": 45352433,
"author": "MAbraham1",
"author_id": 212950,
"author_profile": "https://Stackoverflow.com/users/212950",
"pm_score": 4,
"selected": false,
"text": " public static double round(double value, int precision) {\n int scale = (int) Math.pow(10, precision);\n return (double) (Math.round(value * scale) / scale);\n }\n"
},
{
"answer_id": 48135104,
"author": "Craigo",
"author_id": 418057,
"author_profile": "https://Stackoverflow.com/users/418057",
"pm_score": 2,
"selected": false,
"text": "double scale = 100000; \ndouble myVal = 0.912385;\ndouble rounded = (int)((myVal * scale) + 0.5d) / scale;\n"
},
{
"answer_id": 48764733,
"author": "Amr Ali",
"author_id": 4208440,
"author_profile": "https://Stackoverflow.com/users/4208440",
"pm_score": 2,
"selected": false,
"text": "1.005 /**\n * Round half away from zero ('commercial' rounding)\n * Uses correction to offset floating-point inaccuracies.\n * Works symmetrically for positive and negative numbers.\n */\npublic static double round(double num, int digits) {\n\n // epsilon correction\n double n = Double.longBitsToDouble(Double.doubleToLongBits(num) + 1);\n double p = Math.pow(10, digits);\n return Math.round(n * p) / p;\n}\n\n// test rounding of half\nSystem.out.println(round(0.5, 0)); // 1\nSystem.out.println(round(-0.5, 0)); // -1\n\n// testing edge cases\nSystem.out.println(round(1.005, 2)); // 1.01\nSystem.out.println(round(2.175, 2)); // 2.18\nSystem.out.println(round(5.015, 2)); // 5.02\n\nSystem.out.println(round(-1.005, 2)); // -1.01\nSystem.out.println(round(-2.175, 2)); // -2.18\nSystem.out.println(round(-5.015, 2)); // -5.02\n"
},
{
"answer_id": 49284415,
"author": "Jorgesys",
"author_id": 250260,
"author_profile": "https://Stackoverflow.com/users/250260",
"pm_score": 3,
"selected": false,
"text": " DecimalFormat df = new DecimalFormat(\"#.00\");\n String resultado = df.format(valor)\n DecimalFormat df = new DecimalFormat(\"0.00\"); :\n private static String getTwoDecimals(double value){\n DecimalFormat df = new DecimalFormat(\"0.00\"); \n return df.format(value);\n }\n 91.32\n5.22\n11.5\n1.2\n2.6\n 91.32\n5.22\n11.50\n1.20\n2.60\n"
},
{
"answer_id": 57584089,
"author": "Md. Jamal Uddin",
"author_id": 6542943,
"author_profile": "https://Stackoverflow.com/users/6542943",
"pm_score": 2,
"selected": false,
"text": "double num = 4.898979485566356;\nDecimalFormat df = new DecimalFormat(\"#.##\"); \ntime = Double.valueOf(df.format(num));\n\nSystem.out.println(num); // 4.89\n"
},
{
"answer_id": 58565101,
"author": "Alain Cruz",
"author_id": 4259032,
"author_profile": "https://Stackoverflow.com/users/4259032",
"pm_score": 3,
"selected": false,
"text": "BigDecimal RoundingMode BigDecimal bd = new BigDecimal(\"1363.2749\");\nbd = bd.setScale(2, RoundingMode.HALF_UP);\nSystem.out.println(bd.doubleValue());\n 1363.28 1363.27 RoundingMode RoundingMode.HALF_UP n-1 private double round(double value, int places) throws IllegalArgumentException {\n\n if (places < 0) throw new IllegalArgumentException();\n\n // Cast the number to a String and then separate the decimals.\n String stringValue = Double.toString(value);\n String decimals = stringValue.split(\"\\\\.\")[1];\n\n // Round all the way to the desired number.\n BigDecimal bd = new BigDecimal(stringValue);\n for (int i = decimals.length()-1; i >= places; i--) {\n bd = bd.setScale(i, RoundingMode.HALF_UP);\n }\n\n return bd.doubleValue();\n}\n 1363.28"
},
{
"answer_id": 61691949,
"author": "Enamul Haque",
"author_id": 3972291,
"author_profile": "https://Stackoverflow.com/users/3972291",
"pm_score": 2,
"selected": false,
"text": " double amount = 1000.431; \n NumberFormat formatter = new DecimalFormat(\"##.00\");\n String output = formatter.format(amount);\n System.out.println(\"output = \" + output);\n output = 1000.43\n"
},
{
"answer_id": 62555681,
"author": "Dmitry Fisenko",
"author_id": 723411,
"author_profile": "https://Stackoverflow.com/users/723411",
"pm_score": 1,
"selected": false,
"text": "double double getRandom(int decimalPoints) {\n double a = Math.random();\n int multiplier = (int) Math.pow(10, decimalPoints);\n int b = (int) (a * multiplier);\n return b / (double) multiplier;\n}\n getRandom(2)"
},
{
"answer_id": 63607720,
"author": "Niraj",
"author_id": 3580786,
"author_profile": "https://Stackoverflow.com/users/3580786",
"pm_score": 1,
"selected": false,
"text": "DecimalFormat decimalFormatter = new DecimalFormat(\"#.00000\");\ndecimalFormatter.format(0.350500); // result 0.350500\n DecimalFormat decimalFormatter= new DecimalFormat(\"#.#####\");\ndecimalFormatter.format(0.350500); // result o.3505\n"
},
{
"answer_id": 64401405,
"author": "Harisudha",
"author_id": 13302453,
"author_profile": "https://Stackoverflow.com/users/13302453",
"pm_score": 0,
"selected": false,
"text": "public static boolean threeDecimalPlaces(double value1, double value2){\n boolean isEqual = false;\n // value1 = 3.1756 \n // value2 = 3.17\n //(int) (value1 * 1000) = 3175\n //(int) (value2 * 1000) = 3170\n\n if ((int) (value1 * 1000) == (int) (value2 * 1000)){\n areEqual = true;\n }\n\n return isEqual;\n}\n"
},
{
"answer_id": 65786718,
"author": "Milan Paudyal",
"author_id": 6770146,
"author_profile": "https://Stackoverflow.com/users/6770146",
"pm_score": 1,
"selected": false,
"text": "public static double formatDecimal(double amount) {\n BigDecimal amt = new BigDecimal(amount);\n amt = amt.divide(new BigDecimal(1), 2, BigDecimal.ROUND_HALF_EVEN);\n return amt.doubleValue();\n}\n @RunWith(Parameterized.class)\npublic class DecimalValueParameterizedTest {\n\n @Parameterized.Parameter\n public double amount;\n\n @Parameterized.Parameter(1)\n public double expectedValue;\n\n@Parameterized.Parameters\npublic static List<Object[]> dataSets() {\n return Arrays.asList(new Object[][]{\n {1000.0, 1000.0},\n {1000, 1000.0},\n {1000.00000, 1000.0},\n {1000.01, 1000.01},\n {1000.1, 1000.10},\n {1000.001, 1000.0},\n {1000.005, 1000.0},\n {1000.007, 1000.01},\n {1000.999, 1001.0},\n {1000.111, 1000.11}\n });\n}\n\n@Test\npublic void testDecimalFormat() {\n Assert.assertEquals(expectedValue, formatDecimal(amount), 0.00);\n}\n"
},
{
"answer_id": 69056857,
"author": "Nur Alam",
"author_id": 10379931,
"author_profile": "https://Stackoverflow.com/users/10379931",
"pm_score": 0,
"selected": false,
"text": "public static double round(double value, int places) {\n if (places < 0) throw new IllegalArgumentException();\n\n DecimalFormat deciFormat = new DecimalFormat();\n deciFormat.setMaximumFractionDigits(places);\n String newValue = deciFormat.format(value);\n\n return Double.parseDouble(newValue);\n\n}\n\ndouble a = round(12.36545, 2);\n"
},
{
"answer_id": 72950324,
"author": "Salix alba",
"author_id": 865481,
"author_profile": "https://Stackoverflow.com/users/865481",
"pm_score": 0,
"selected": false,
"text": "Math.round long l = 10;\nfor(int dp = -1; dp > -10; --dp) {\n double mul = Math.pow(10,dp);\n double res = Math.round(l * mul) / mul;\n System.out.println(\"\"+l+\" rounded to \"+dp+\" dp = \"+res);\n l *=10;\n}\n 10 rounded to -1 dp = 10.0\n100 rounded to -2 dp = 100.0\n1000 rounded to -3 dp = 1000.0\n10000 rounded to -4 dp = 10000.0\n100000 rounded to -5 dp = 99999.99999999999\n1000000 rounded to -6 dp = 1000000.0\n10000000 rounded to -7 dp = 1.0E7\n100000000 rounded to -8 dp = 1.0E8\n1000000000 rounded to -9 dp = 9.999999999999999E8\n double mul = Math.pow(10,dp);\ndouble res;\nif(dp < 0 ) {\n double div = Math.pow(10,-dp);\n res = Math.round(l * mul) *div;\n} else {\n res = Math.round(l * mul) / mul;\n}\n"
},
{
"answer_id": 73609506,
"author": "Jackson Meires",
"author_id": 4906873,
"author_profile": "https://Stackoverflow.com/users/4906873",
"pm_score": 0,
"selected": false,
"text": "double x = 123.123;\nSystem.out.printf( \"%.2f\", x );\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12149/"
] |
153,731
|
<p>I am looking for validation framework and while I am already using NHibernate I am thinking of using NHibernate.validator from contrib project however I also look at MS Validation Block which seem to be robust but i am not yet get into detail of each one yet so I wonder has anyone had step into these two frameworks and how is the experience like?</p>
|
[
{
"answer_id": 787580,
"author": "mookid8000",
"author_id": 6560,
"author_profile": "https://Stackoverflow.com/users/6560",
"pm_score": 4,
"selected": true,
"text": "var engine = new ValidatorEngine();\nInvalidValue[] errors = engine.Validate(someModelObjectWithAttributes);\n\nforeach(var error in errors)\n{\n Console.WriteLine(error.Message);\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15396/"
] |
153,748
|
<p>I've tried this:</p>
<pre><code>string newScript = textBox1.Text;
HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = browserCtrl.Document.CreateElement("script");
lblStatus.Text = scriptEl.GetType().ToString();
scriptEl.SetAttribute("type", "text/javascript");
head.AppendChild(scriptEl);
scriptEl.InnerHtml = "function sayHello() { alert('hello') }";
</code></pre>
<p>scriptEl.InnerHtml and scriptEl.InnerText both give errors:</p>
<pre><code>System.NotSupportedException: Property is not supported on this type of HtmlElement.
at System.Windows.Forms.HtmlElement.set_InnerHtml(String value)
at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code></pre>
<p>Is there an easy way to inject a script into the dom?</p>
|
[
{
"answer_id": 154330,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 3,
"selected": false,
"text": "IHTMLElement iScriptEl = (IHTMLElement)scriptEl.DomElement;\n iScriptEl.insertAdjacentText(\"afterBegin\", \"function sayHello() { alert('hello') }\");\n"
},
{
"answer_id": 154496,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 8,
"selected": true,
"text": "HtmlElement head = webBrowser1.Document.GetElementsByTagName(\"head\")[0];\nHtmlElement scriptEl = webBrowser1.Document.CreateElement(\"script\");\nIHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\nelement.text = \"function sayHello() { alert('hello') }\";\nhead.AppendChild(scriptEl);\nwebBrowser1.Document.InvokeScript(\"sayHello\");\n IHTMLScriptElement"
},
{
"answer_id": 2268843,
"author": "Eyal",
"author_id": 4454,
"author_profile": "https://Stackoverflow.com/users/4454",
"pm_score": 4,
"selected": false,
"text": "MyWebBrowser.Navigate(\"javascript:function foo(){alert('hello');}foo();\")\n"
},
{
"answer_id": 3057506,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 5,
"selected": false,
"text": "dynamic document = this.browser.Document;\ndynamic head = document.GetElementsByTagName(\"head\")[0];\ndynamic scriptEl = document.CreateElement(\"script\");\nscriptEl.text = ...;\nhead.AppendChild(scriptEl);\n"
},
{
"answer_id": 3506531,
"author": "Camilo Sanchez",
"author_id": 247328,
"author_profile": "https://Stackoverflow.com/users/247328",
"pm_score": 3,
"selected": false,
"text": "IHTMLDocument2 doc = new HTMLDocumentClass();\ndoc.write(new object[] { File.ReadAllText(filePath) });\ndoc.close();\n\nIHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags(\"head\")).item(null, 0);\nIHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement(\"script\");\nscriptObject.type = @\"text/javascript\";\nscriptObject.text = @\"function btn1_OnClick(str){\n alert('you clicked' + str);\n}\";\n((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject);\n"
},
{
"answer_id": 6222430,
"author": "typpo",
"author_id": 782100,
"author_profile": "https://Stackoverflow.com/users/782100",
"pm_score": 6,
"selected": false,
"text": "HtmlDocument doc = browser.Document;\nHtmlElement head = doc.GetElementsByTagName(\"head\")[0];\nHtmlElement s = doc.CreateElement(\"script\");\ns.SetAttribute(\"text\",\"function sayHello() { alert('hello'); }\");\nhead.AppendChild(s);\nbrowser.Document.InvokeScript(\"sayHello\");\n"
},
{
"answer_id": 7801574,
"author": "Santiago",
"author_id": 1000163,
"author_profile": "https://Stackoverflow.com/users/1000163",
"pm_score": 3,
"selected": false,
"text": "var jsCode=\"alert('hello world from injected code');\";\nWebBrowser.Document.InvokeScript(\"execScript\", new Object[] { jsCode, \"JavaScript\" });\n var jsCode=\"function greet(msg){alert(msg);};\";\nWebBrowser.Document.InvokeScript(\"execScript\", new Object[] { jsCode, \"JavaScript\" });\n...............\nWebBrowser.Document.InvokeScript(\"greet\",new object[] {\"hello world\"});\n var jsCode=\"alert('hello world');\";\n(new Function(code))();\n var jsCode=\"alert('hello world');\";\nvar inserted=new Function(code);\n.................\ninserted();\n"
},
{
"answer_id": 8157159,
"author": "sh0ber",
"author_id": 1050347,
"author_profile": "https://Stackoverflow.com/users/1050347",
"pm_score": 2,
"selected": false,
"text": "Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)\n Dim head As HtmlElement\n Dim script As HtmlElement\n Dim domElement As IHTMLScriptElement\n\n head = wb.Document.GetElementsByTagName(\"head\")(0)\n script = wb.Document.CreateElement(\"script\")\n domElement = script.DomElement\n domElement.type = \"text/javascript\"\n domElement.text = \"function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }\"\n head.AppendChild(script)\nEnd Sub\n Public Sub Callback_GetVar(ByVal vVar As String)\n Debug.Print(vVar)\nEnd Sub\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n WebBrowser1.Document.InvokeScript(\"CallbackGetVar\", New Object() {\"NameOfVarToRetrieve\"})\nEnd Sub\n"
},
{
"answer_id": 8687037,
"author": "Ilya Rosikhin",
"author_id": 1124105,
"author_profile": "https://Stackoverflow.com/users/1124105",
"pm_score": 5,
"selected": false,
"text": "string javascript = \"alert('Hello');\";\n// or any combination of your JavaScript commands\n// (including function calls, variables... etc)\n\n// WebBrowser webBrowser1 is what you are using for your web browser\nwebBrowser1.Document.InvokeScript(\"eval\", new object[] { javascript });\n eval(str)"
},
{
"answer_id": 10153977,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 3,
"selected": false,
"text": "IHTMLScriptElement [ComImport, ComVisible(true), Guid(@\"3050f28b-98b5-11cf-bb82-00aa00bdce0b\")]\n[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]\n[TypeLibType(TypeLibTypeFlags.FDispatchable)]\npublic interface IHTMLScriptElement\n{\n [DispId(1006)]\n string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }\n}\n protected override void OnDocumentCompleted(\n WebBrowserDocumentCompletedEventArgs e)\n{\n base.OnDocumentCompleted(e);\n\n // Disable text selection.\n var doc = Document;\n if (doc != null)\n {\n var heads = doc.GetElementsByTagName(@\"head\");\n if (heads.Count > 0)\n {\n var scriptEl = doc.CreateElement(@\"script\");\n if (scriptEl != null)\n {\n var element = (IHTMLScriptElement)scriptEl.DomElement;\n element.text =\n @\"function disableSelection()\n { \n document.body.onselectstart=function(){ return false; }; \n document.body.ondragstart=function() { return false; };\n }\";\n heads[0].AppendChild(scriptEl);\n doc.InvokeScript(@\"disableSelection\");\n }\n }\n }\n}\n"
},
{
"answer_id": 26813233,
"author": "pablo",
"author_id": 4229231,
"author_profile": "https://Stackoverflow.com/users/4229231",
"pm_score": 0,
"selected": false,
"text": "With Browser.Document\n Dim Head As HtmlElement = .GetElementsByTagName(\"head\")(0)\n Dim Script As HtmlElement = .CreateElement(\"script\")\n Dim Streamer As New StreamReader(<Here goes path to file as String>)\n Using Streamer\n Script.SetAttribute(\"text\", Streamer.ReadToEnd())\n End Using\n Head.AppendChild(Script)\n .InvokeScript(<Here goes a method name as String and without parentheses>)\nEnd With\n System.IO StreamReader"
},
{
"answer_id": 38459070,
"author": "Oscar David Diaz Fortaleché",
"author_id": 5025091,
"author_profile": "https://Stackoverflow.com/users/5025091",
"pm_score": 2,
"selected": false,
"text": "HtmlElement script = this.WebNavegador.Document.CreateElement(\"SCRIPT\");\nscript.SetAttribute(\"TEXT\", \"function GetNameFromBrowser() {\" + \n\"return 'My name is David';\" + \n\"}\");\n\nthis.WebNavegador.Document.Body.AppendChild(script);\n string myNameIs = (string)this.WebNavegador.Document.InvokeScript(\"GetNameFromBrowser\");\n"
},
{
"answer_id": 50558487,
"author": "Z.R.T.",
"author_id": 7060504,
"author_profile": "https://Stackoverflow.com/users/7060504",
"pm_score": 1,
"selected": false,
"text": "webBrowser.Document.InvokeScript(\"execScript\", new object[] { \"alert(123)\", \"JavaScript\" })\n"
},
{
"answer_id": 74093844,
"author": "painful mindset",
"author_id": 20260899,
"author_profile": "https://Stackoverflow.com/users/20260899",
"pm_score": 0,
"selected": false,
"text": "webBrowser1.DocumentText =\n \"<html><head><script>\" +\n \"function test(message) { alert(message); }\" +\n \"</script></head><body><button \" +\n \"onclick=\\\"window.external.Test('called from script code')\\\">\" +\n \"call client code from script code</button>\" +\n \"</body></html>\";\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432/"
] |
153,759
|
<p>How do I use the jQuery Datepicker with a textbox input:</p>
<pre><code>$("#my_txtbox").datepicker({
// options
});
</code></pre>
<p>that doesn't allow the user to input random text in the textbox.
I want the Datepicker to pop up when the textbox gains focus or the user clicks on it, but I want the textbox to ignore any user input using the keyboard (copy & paste, or any other). I want to fill the textbox exclusively from the Datepicker calendar.</p>
<p>Is this possible?</p>
<p>jQuery 1.2.6<br/>
Datepicker 1.5.2</p>
|
[
{
"answer_id": 153804,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 9,
"selected": true,
"text": "<input type='text' id='foo' readonly='true'>\n"
},
{
"answer_id": 153817,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 2,
"selected": false,
"text": "$(\".selector\").datepicker({ showOn: 'both' })\n <input type=\"text\" name=\"date\" readonly=\"readonly\" />\n"
},
{
"answer_id": 153821,
"author": "Brad8118",
"author_id": 7617,
"author_profile": "https://Stackoverflow.com/users/7617",
"pm_score": 4,
"selected": false,
"text": "$(\"#my_txtbox\").keypress(function(event) {event.preventDefault();});\n"
},
{
"answer_id": 153826,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 1,
"selected": false,
"text": "<input type=\"text\" readonly=\"true\" />\n"
},
{
"answer_id": 1748170,
"author": "Adhip Gupta",
"author_id": 384,
"author_profile": "https://Stackoverflow.com/users/384",
"pm_score": 3,
"selected": false,
"text": "$(\"#my_txtbox\").attr( 'readOnly' , 'true' );\n"
},
{
"answer_id": 1754234,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<input type=\"text\" readonly=\"true\" />\n $(\"#my_txtbox\").keypress(function(event) {event.preventDefault();});\n"
},
{
"answer_id": 7625106,
"author": "2046",
"author_id": 975201,
"author_profile": "https://Stackoverflow.com/users/975201",
"pm_score": 6,
"selected": false,
"text": "$(\"#my_txtbox\").attr( 'readOnly' , 'true' );\n $(\"#my_txtbox\").keypress(function(event) {event.preventDefault();});\n <input type=\"text\" readonly=\"true\" />\n"
},
{
"answer_id": 12943978,
"author": "Steinwolfe",
"author_id": 1736818,
"author_profile": "https://Stackoverflow.com/users/1736818",
"pm_score": -1,
"selected": false,
"text": " <asp:HiddenField ID=\"hfDay\" runat=\"server\" />\n onSelect: function (dateText, inst) {\n $(\"#<% =hfDay.ClientID %>\").val(dateText);\n }\n"
},
{
"answer_id": 15088455,
"author": "Shabbir.A.Hussain",
"author_id": 2111125,
"author_profile": "https://Stackoverflow.com/users/2111125",
"pm_score": -1,
"selected": false,
"text": "<script type=\"text/javascript\">\n$(function () {\n $(\"#datepicker\").datepicker({ maxDate: \"-1D\" }).attr('readonly', 'readonly');\n $(\"#datepicker\").readonlyDatepicker(true);\n\n});\n"
},
{
"answer_id": 20072084,
"author": "LithiumD",
"author_id": 3008859,
"author_profile": "https://Stackoverflow.com/users/3008859",
"pm_score": 0,
"selected": false,
"text": "$('.date').each(function (e) {\n if ($(this).attr('disabled') != 'disabled') {\n $(this).attr('readOnly', 'true');\n $(this).css('cursor', 'pointer');\n $(this).css('color', '#5f5f5f');\n }\n});\n"
},
{
"answer_id": 27057395,
"author": "user2182143",
"author_id": 2182143,
"author_profile": "https://Stackoverflow.com/users/2182143",
"pm_score": 2,
"selected": false,
"text": "onfocus=\"this.blur()\" <input type=\"text\" name=\"currentDate\" id=\"currentDate\" onfocus=\"this.blur()\" readonly/>"
},
{
"answer_id": 28625057,
"author": "kayz1",
"author_id": 1127843,
"author_profile": "https://Stackoverflow.com/users/1127843",
"pm_score": 1,
"selected": false,
"text": "<input class=\"date-input\" type=\"text\" readonly=\"readonly\" />\n .date-input {\n background-color: white;\n cursor: pointer;\n}\n"
},
{
"answer_id": 31738303,
"author": "johnkhadka",
"author_id": 5109531,
"author_profile": "https://Stackoverflow.com/users/5109531",
"pm_score": 0,
"selected": false,
"text": "<input type=\"text\" id=\"my_txtbox\" readonly /> <!--HTML5-->\n\n<input type=\"text\" id=\"my_txtbox\" readonly=\"true\"/>\n"
},
{
"answer_id": 32649509,
"author": "Chenthil",
"author_id": 3181178,
"author_profile": "https://Stackoverflow.com/users/3181178",
"pm_score": 2,
"selected": false,
"text": "$(\"#txtfromdate\").datepicker({ \n numberOfMonths: 2,\n maxDate: 0, \n dateFormat: 'dd-M-yy' \n}).attr('readonly', 'readonly');\n"
},
{
"answer_id": 41892415,
"author": "umutesen",
"author_id": 2093029,
"author_profile": "https://Stackoverflow.com/users/2093029",
"pm_score": 3,
"selected": false,
"text": "$(\".project-date\").datepicker({\n dateFormat: 'd M yy'\n});\n\n$(\".project-date\").keydown(false);\n"
},
{
"answer_id": 42645439,
"author": "Matija",
"author_id": 779965,
"author_profile": "https://Stackoverflow.com/users/779965",
"pm_score": 2,
"selected": false,
"text": "<br/>\n<!-- padding for jsfiddle -->\n<div class=\"input-group date\" id=\"arrival_date_div\">\n <input type=\"text\" class=\"form-control\" id=\"arrival_date\" name=\"arrival_date\" required readonly=\"readonly\" />\n <span class=\"input-group-addon\">\n <span class=\"glyphicon-calendar glyphicon\"></span>\n </span>\n</div>\n $('#arrival_date_div').datetimepicker({\n format: \"YYYY-MM-DD\",\n ignoreReadonly: true\n});\n"
},
{
"answer_id": 44586882,
"author": "Shantaram Tupe",
"author_id": 3425489,
"author_profile": "https://Stackoverflow.com/users/3425489",
"pm_score": 0,
"selected": false,
"text": "readonly readonly required readonly required readonly required $(\"#my_txtbox\").datepicker({\n // options\n});\n\n$(\"#my_txtbox\").keypress(function(event) {\n return ( ( event.keyCode || event.which ) === 9 ? true : false );\n});\n tab readonly required readonly $(function() {\n $('#id-checkbox').change( function(){\n $('#id-input3').prop('required', $(this).is(':checked'));\n });\n $('#id-input3').datepicker();\n $(\"#id-input3\").keypress(function(event) {\n return ( ( event.keyCode || event.which ) === 9 ? true : false );\n});\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n\n<link href=\"https://code.jquery.com/ui/jquery-ui-git.css\" rel=\"stylesheet\"/>\n\n<form action='https://jsfiddle.net/'>\nName: <input type=\"text\" name='xyz' id='id-input3' readonly='true' required='true'> \n <input type='checkbox' id='id-checkbox'> Required <br>\n <br>\n <input type='submit' value='Submit'>\n</form>"
},
{
"answer_id": 55106037,
"author": "Mariana Marica",
"author_id": 3771721,
"author_profile": "https://Stackoverflow.com/users/3771721",
"pm_score": 2,
"selected": false,
"text": "$(\"#my_txtbox\").bind('paste',function(e) { e.preventDefault(); //disable paste }); $('[data-toggle=\"datepicker\"]').datepicker({\n autoHide: true,\n pick: function (e) {\n e.preventDefault();\n $(this).val($(this).datepicker('getDate', true));\n }\n}).keypress(function(event) {\n event.preventDefault(); // prevent keyboard writing but allowing value deletion\n}).bind('paste',function(e) {\n e.preventDefault()\n}); //disable paste;\n"
},
{
"answer_id": 55492178,
"author": "Peter Bowers",
"author_id": 4282342,
"author_profile": "https://Stackoverflow.com/users/4282342",
"pm_score": 0,
"selected": false,
"text": "inputmode=\"none\" <input type=\"text\" ... inputmode=\"none\" />\n $(selector).attr('inputmode', 'none');\n"
},
{
"answer_id": 67671155,
"author": "Ahmed Awan",
"author_id": 1076775,
"author_profile": "https://Stackoverflow.com/users/1076775",
"pm_score": 0,
"selected": false,
"text": "disableTextInput $( \".datepicker\" ).datepicker({'dateFormat' : 'd-m-y', 'disableTextInput':true });\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024/"
] |
153,762
|
<p>Our graphics person uses Adobe Illustrator and we'd like to use her images inside our WPF application as paths. Is there a way to do this?</p>
|
[
{
"answer_id": 26541828,
"author": "DuckMaestro",
"author_id": 29152,
"author_profile": "https://Stackoverflow.com/users/29152",
"pm_score": 2,
"selected": false,
"text": "<DrawingGroup> x:Name=\"...\" <Image>\n <Image.Source>\n <DrawingImage>\n <DrawingImage.Drawing>\n <DrawingGroup ... the output from step #2 ...>...</DrawingGroup>\n </DrawingImage.Drawing>\n </DrawingImage>\n </Image.Source>\n</Image>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
153,769
|
<p>As in subject... is there a way of looking at an empty table schema without inserting any rows and issuing a SELECT?</p>
|
[
{
"answer_id": 153779,
"author": "Plasmer",
"author_id": 397314,
"author_profile": "https://Stackoverflow.com/users/397314",
"pm_score": 4,
"selected": true,
"text": "db2 describe table user1.department Table: USER1.DEPARTMENT\n\nColumn Type Type\nname schema name Length Scale Nulls\n------------------ ----------- ------------------ -------- -------- --------\nAREA SYSIBM SMALLINT 2 0 No\nDEPT SYSIBM CHARACTER 3 0 No\nDEPTNAME SYSIBM CHARACTER 20 0 Yes\n"
},
{
"answer_id": 5348256,
"author": "Amit",
"author_id": 665523,
"author_profile": "https://Stackoverflow.com/users/665523",
"pm_score": 3,
"selected": false,
"text": "SELECT * \nFROM SYSIBM.SYSCOLUMNS \nWHERE \nTBNAME = 'tablename'; \n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8437/"
] |
153,775
|
<p>i have a library with some entities that share the same interface. clients and service share this assembly. now i wonder if there is a way to have this Interface-type as Parameter in my service contracts so that i can use the same method for all classes implementing the interface.</p>
<p>the entities themselve are all decorated with datacontract-attribute and its members with datamember attributes.</p>
<p>is it possible at all? probably with the <em>NetDataContractSerializer</em>?
i know that i can do it with a base class (some abstract class e.g.) and the <em>knowntype</em>-attribute but i´d definitely prefer the Interface as identificator of the objects cause it is used widely in the client app and would ease development.</p>
<p>thanks</p>
|
[
{
"answer_id": 214451,
"author": "lesscode",
"author_id": 18482,
"author_profile": "https://Stackoverflow.com/users/18482",
"pm_score": 0,
"selected": false,
"text": "namespace SharedInterfaces {\n public interface ICompositeType {\n bool BoolValue { get; set; }\n string StringValue { get; set; }\n }\n}\n [DataContract]\npublic class CompositeType : ICompositeType {\n bool boolValue = true;\n string stringValue = \"Hello \";\n\n [DataMember]\n public bool BoolValue {\n get { return boolValue; }\n set { boolValue = value; }\n }\n\n [DataMember]\n public string StringValue {\n get { return stringValue; }\n set { stringValue = value; }\n }\n}\n namespace ServiceClient.ServiceReference1 {\n public partial class CompositeType : ICompositeType {\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20227/"
] |
153,776
|
<p>I am inside of...</p>
<pre><code>public class bgchange : IMapServerDropDownBoxAction
{
void IServerAction.ServerAction(ToolbarItemInfo info)
{
Some code...
</code></pre>
<p>and after "some code" I want to trigger</p>
<pre><code>[WebMethod]
public static void DoSome()
{
}
</code></pre>
<p>Which triggers some javascript. Is this possible?</p>
<p>Ok, switch methods here. I was able to call dosome(); which fired but did not trigger the javascript. I have tried to use the registerstartupscript method but don't fully understand how to implement it. Here's what I tried:</p>
<pre><code>public class bgchange : IMapServerDropDownBoxAction
{
void IServerAction.ServerAction(ToolbarItemInfo info)
{
...my C# code to perform on dropdown selection...
//now I want to trigger some javascript...
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
}
</code></pre>
<p>}</p>
<p>I got the registerstartupscript code from an msdn example. Clearly I am not implementing it correctly. Currently vs says "An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get' refering to the piece of code "Page.Clientscript;" Thanks.</p>
|
[
{
"answer_id": 153873,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 3,
"selected": true,
"text": "<asp:ScriptManager ID=\"scriptManager1\" \n runat=\"server\" EnablePageMethods=\"true\" />\n Page.ClientScript.RegisterStartupScript(\n this.GetType(), \n \"callDoSome\",\n \"PageMethods.DoSome(Callback_Function, null)\", \n true);\n <script language=\"javascript\" type=\"text/javascript\">\n function Callback_Function(result, context) {\n alert('WebMethod was called');\n }\n</script>\n public void ServerAction(ToolbarItemInfo info) {\n string jsfunction = \"alert('Hello');\";\n Map mapctrl = (Map)info.BuddyControls[0];\n CallbackResult cr = new CallbackResult(null, null, \"javascript\", jsfunction);\n mapctrl.CallbackResults.Add(cr);\n}\n"
},
{
"answer_id": 153876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "string script = \"<script language='javascript'>\\n\";\nscript += \"javascriptFunctionHere();\\n\";\nscript += \"</script>\";\n\nPage.RegisterStartupScript(\"ForceClientToCallServerMethod\", script);\n"
},
{
"answer_id": 154022,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 2,
"selected": false,
"text": "public partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n Page.ClientScript.RegisterStartupScript(\n this.GetType(),\n \"helloworldpopup\",\n \"alert('hello world');\",\n true); \n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] |
153,782
|
<p>I am using a codebehind page in ASP.NET to perform a SQL query. The query is loaded into a string, the connection is established (To Oracle), and we get it started by having the connection perform .ExecuteReader into a OleDBDataReader (We'll call it DataRead). I'll try to hammer out an example below. (Consider Drop as an ASP DropDownList control)</p>
<pre><code>Dim LookFor as String = "Fuzzy Bunnies"
While DataRead.Read
If LookFor = DataRead.Item("Kinds of Bunnies") Then
'Meets special critera, do secondary function'
Drop.Items.Add(DataRead.Item("Subgroup of Bunnies"))
...
End if
...
End While
</code></pre>
<p>This is the only way I know of doing a dynamic add to a DropDownList. However, each item in a DropDownList has a .text property and a .value property. How can we define the .value as being different from the .text in code?</p>
|
[
{
"answer_id": 153788,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 1,
"selected": false,
"text": "Dim item as New ListItem()\nitem.Value = \"foo\"\nitem.Text = \"bar\"\n\nDrop.Items.Add(item)\n"
},
{
"answer_id": 153792,
"author": "AaronSieb",
"author_id": 16911,
"author_profile": "https://Stackoverflow.com/users/16911",
"pm_score": 2,
"selected": false,
"text": "\nDrop.Items.Add(New ListItem(\"Text\", \"Value\"))\n"
},
{
"answer_id": 153794,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 4,
"selected": true,
"text": "Dim li as new ListItem(DataRead.Item(\"Subgroup of Bunnies\"), \"myValue\")\nDrop.Items.Add(li)\n"
},
{
"answer_id": 153798,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "Dim item as new listitem\nitem.text = DataRead.Item(\"SubGroup Of Bunnies\")\nitem.value = DataRead.Item(\"ID\")\nDrop.Items.Add(item)\n"
},
{
"answer_id": 153800,
"author": "Grank",
"author_id": 12975,
"author_profile": "https://Stackoverflow.com/users/12975",
"pm_score": 2,
"selected": false,
"text": "Drop.Items.Add(new ListItem(\"text\", \"value\"))\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12545/"
] |
153,795
|
<p>I'm getting some objects from an external library and I need to store those objects in a database. Is there a way to create the tables and relationships starting from the objects, or I have to dig into them and create migrations and models by hand?</p>
<p>Thanks!
Roberto</p>
|
[
{
"answer_id": 155764,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "class Animal\n attr_accessor :name, :number_of_legs\nend\na = SomeThirdPartyLibrary.get_animal\n table_name = a.class.to_s.tableize\ncolumn_names = a.instance_variables.map{ |n| n[1..-1] } # remove the @\ncolumn_types = a.instance_variables.map{ |n| a.instance_variable_get(n).class \n }.map{ |c| sql_type_for_class(c) } # go write sql_type_for_class please\n ActiveRecord::Migration.class_eval do\n create_table table_name do |t|\n column_names.zip(column_types).each do |colname, coltype|\n t.column colname, coltype\n end\n end\nend\n # Note we declare a module so the new classes don't conflict with the existing ones\nmodule GeneratedClasses; end\neval \"class GeneratedClasses::#{a.class} < ActiveRecord::Base; end\"\n a = GeneratedClasses::Animal.new\na.update_attributes whatever\na.save\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22083/"
] |
153,796
|
<p>I'm trying to loop through all the controls on a sharepoint page, for the purposes of testing i just want to output the control ID</p>
<p>this is the code i'm using</p>
<p>Public Shared Sub SubstituteValues3(ByVal CurrentPage As Page, ByRef s As StringBuilder)</p>
<pre><code> 'Page()
'- MasterPage
'- HtmlForm
'- ContentPlaceHolder
'- The TextBoxes, etc.
For Each ctlMaster As Control In CurrentPage.Controls
If TypeOf ctlMaster Is MasterPage Then
HttpContext.Current.Response.Output.Write("Master Page <br/>")
For Each ctlForm As Control In ctlMaster.Controls
If TypeOf ctlForm Is HtmlForm Then
HttpContext.Current.Response.Output.Write("HTML Form <br/>")
For Each ctlContent As Control In ctlForm.Controls
If TypeOf ctlContent Is ContentPlaceHolder Then
HttpContext.Current.Response.Output.Write("Content Placeholder <br/>")
For Each ctlChild As Control In ctlContent.Controls
HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />")
Next
End If
Next
End If
Next
End If
Next
HttpContext.Current.Response.Output.Write("--------------")
HttpContext.Current.Response.End()
</code></pre>
<p>however it's not getting past the 'MasterPage' output.</p>
<p>I would expect to see the names of all the controls i have inside my content placeholder but i find it all a bit confusing.</p>
|
[
{
"answer_id": 160539,
"author": "Cruiser",
"author_id": 16971,
"author_profile": "https://Stackoverflow.com/users/16971",
"pm_score": 1,
"selected": false,
"text": " For Each ctlForm As Control In Page.Master.Controls\n\n If TypeOf ctlForm Is HtmlForm Then\n HttpContext.Current.Response.Output.Write(\"HTML Form <br/>\")\n\n For Each ctlContent As Control In ctlForm.Controls\n If TypeOf ctlContent Is ContentPlaceHolder Then\n HttpContext.Current.Response.Output.Write(\"Content Placeholder <br/>\")\n\n For Each ctlChild As Control In ctlContent.Controls\n HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & \"<br />\")\n Next\n End If\n Next\n End If\n Next\n"
},
{
"answer_id": 161489,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "For i = 0 To CurrentPage.Request.Form.AllKeys.Length - 1\n If CurrentPage.Request.Form.GetKey(i).Contains(\"ctl00$PlaceHolderMain$\") Then\n\n\n Dim key As String = CurrentPage.Request.Form.GetKey(i).Substring(22)\n Dim keyText As String = String.Format(\"[{0}]\", key)\n\n HttpContext.Current.Response.Output.Write(keyText & \"<br/>\")\n\n 'Text.Replace(keyText, CurrentPage.Request.Form(\"ctl00$PlaceHolderMain$\" & key))\n End If\n Next\n"
},
{
"answer_id": 215061,
"author": "naspinski",
"author_id": 14777,
"author_profile": "https://Stackoverflow.com/users/14777",
"pm_score": 0,
"selected": false,
"text": "{\n foreach (Control c in input.Controls)\n {\n Response.Write(c.GetType().ToString() + \" - \" + c.ID + \"<br />\");\n getControls(c);\n }\n}\n getControls(Page);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
153,801
|
<p>I've got a script that takes a user uploaded RTF document and merges in some person data into the letter (name, address, etc), and does this for multiple people. I merge the letter contents, then combine that with the next merge letter contents, for all people records.</p>
<p>Affectively I'm combining a single RTF document into itself for as many people records to which I need to merge the letter. However, I need to first remove the closing RTF markup and opening of the RTF markup of each merge or else the RTF won't render correctly. This sounds like a job for regular expressions.</p>
<p>Essentially I need a regex that will remove the entire string:</p>
<p>}\n\page ANYTHING \par</p>
<p>Example, this regex would match this:</p>
<pre><code>crap
}
\page{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}}
{\*\generator Msftedit 5.41.15.1515;}\viewkind4\uc1\pard\f0\fs20 September 30, 2008\par
more crap
</code></pre>
<p>So I could make it just:</p>
<pre><code>crap
\page
more crap
</code></pre>
<p>Is RegEx the best approach here?</p>
<p>UPDATE: Why do I have to use RTF?</p>
<p>I want to enable the user to upload a form letter that the system will then use to create the merged letters. Since RTF is plain text, I can do this pretty easily in code. I know, RTF is a disaster of a spec, but I don't know any other good alternative.</p>
|
[
{
"answer_id": 155094,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 3,
"selected": true,
"text": "$output = preg_replace(\"/}\\s?\\n\\\\\\\\page.*?\\\\\\\\par\\s?\\n/ms\", \"\\\\page\\n\", $input);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
] |
153,812
|
<p>In SVN, <code>trunk</code> is the recommended place for the main development and I use this convention for all of my projects. However, this means that <strong>trunk is sometimes unstable, or even broken</strong>. This happens for instance when</p>
<ul>
<li>I commit something by mistake</li>
<li>When the trunk simply has to be broken because of the way SVN works. Canonical example is file renames - you must commit any file renames first and do any further modifications later; however, file rename may require code refactoring to reflect namespace or class name change so you basically need to commit a single logic operation in two steps. And the build is broken between steps 1 and 2.</li>
</ul>
<p>I can imagine there would be tools to prevent commiting something by mistake (TeamCity and delayed commits, for instance) but can you really overcome the second problem? If not, wouldn't it be better to do the "wild development" on some branch like <code>/branch/dev</code> and only merge to trunk when the build is reasonably solid?</p>
|
[
{
"answer_id": 154324,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "# Create new branch and switch to it\nfunction svn_bswitch()\n{\n branch=$1; shift\n msg=\"$1\"; shift\n\n URL=$(svn info . | sed -ne 's@URL: \\(.*\\)@\\1@p')\n REPO=$(svn info . | sed -ne 's@Repository Root: \\(.*\\)@\\1@p')\n BRANCH_URL=$REPO/branch/$branch\n\n svn copy $URL $BRANCH_URL -m \"$msg\"\n}\n\n\n# Switch to a branch or tag\nfunction svn_switch()\n{\n d=$1; shift\n REPO=$(svn info . | sed -ne 's@Repository Root: \\(.*\\)@\\1@p')\n URL=$REPO/$d\n svn switch $URL\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21728/"
] |
153,815
|
<p>I am coming from the SQL server world where we had uniqueidentifier. Is there an equivalent in oracle? This column will be frequently queried so performance is the key.</p>
<p>I am generating the GUID in .Net and will be passing it to Oracle. For a couple reasons it cannot be generated by oracle so I cannot use sequence. </p>
|
[
{
"answer_id": 153849,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 7,
"selected": true,
"text": "CREATE table test (testguid RAW(16) default SYS_GUID() ) \n"
},
{
"answer_id": 153851,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 2,
"selected": false,
"text": "INSERT INTO mytable (col1, col2) VALUES (myseq.NEXTVAL, 'some other data');\n"
},
{
"answer_id": 1534261,
"author": "Erik Anderson",
"author_id": 130614,
"author_profile": "https://Stackoverflow.com/users/130614",
"pm_score": 3,
"selected": false,
"text": "SQL> SELECT SYS_GUID() FROM DUAL;\n\nSYS_GUID()\n--------------------------------\n248AACE7F7DE424E8B9E1F31A9F101D5\n CREATE OR REPLACE FUNCTION GET_FORMATTED_GUID RETURN VARCHAR2 IS guid VARCHAR2(38) ;\nBEGIN\n SELECT SYS_GUID() INTO guid FROM DUAL ;\n \n guid :=\n '{' || SUBSTR(guid, 1, 8) ||\n '-' || SUBSTR(guid, 9, 4) ||\n '-' || SUBSTR(guid, 13, 4) ||\n '-' || SUBSTR(guid, 17, 4) ||\n '-' || SUBSTR(guid, 21) || '}' ;\n\n RETURN guid ;\nEND GET_FORMATTED_GUID ;\n/\n SQL> SELECT GET_FORMATTED_GUID() FROM DUAL ;\n\nGET_FORMATTED_GUID()\n--------------------------------------\n{15417950-9197-4ADD-BD49-BA043F262180}\n REGEXP_REPLACE() REGEXP_REPLACE(\n SYS_GUID(),\n '([0-9A-F]{8})([0-9A-F]{4})([0-9A-F]{4})([0-9A-F]{4})([0-9A-F]{12})',\n '{\\1-\\2-\\3-\\4-\\5}'\n)\n SYS_GUID()"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1514/"
] |
153,825
|
<p>I've got the following query to determine how many votes a story has received:</p>
<pre><code>SELECT s_id, s_title, s_time, (s_time-now()) AS s_timediff,
(
(SELECT COUNT(*) FROM s_ups WHERE stories.q_id=s_ups.s_id) -
(SELECT COUNT(*) FROM s_downs WHERE stories.s_id=s_downs.s_id)
) AS votes
FROM stories
</code></pre>
<p>I'd like to apply the following mathematical function to it for upcoming stories (I think it's what reddit uses) -
<a href="http://redflavor.com/reddit.cf.algorithm.png" rel="noreferrer">http://redflavor.com/reddit.cf.algorithm.png</a></p>
<p>I can perform the function on the application side (which I'm doing now), but I can't sort it by the ranking which the function provides.</p>
<p>Any advise?</p>
|
[
{
"answer_id": 154094,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 2,
"selected": false,
"text": "DELIMINATOR //\n\nCREATE FUNCTION y_element(x INT) \n RETURNS INT\n\nBEGIN\n DECLARE y INT;\n\nIF x > 0 SET y = 1;\nELSEIF x = 0 SET y = 0;\nELSEIF x < 0 SET y = -1;\nEND IF;\n\nRETURN y;\n\nEND //;\n\nDELIMINATOR;\n"
},
{
"answer_id": 155645,
"author": "Jonathan",
"author_id": 19272,
"author_profile": "https://Stackoverflow.com/users/19272",
"pm_score": 3,
"selected": true,
"text": " SELECT s_id, s_title, log10(Z) + (Y * s_timediff)/45000 AS redditfunction \n FROM (\n SELECT stories.s_id, stories.s_title, stories.s_time, \n stories.s_time - now() AS s_timediff, \n count(s_ups.s_id) - count(s_downs.s_id) as X, \n if(X>0,1,if(x<0,-1,0)) as Y, \n if(abs(x)>=1,abs(x),1) as Z\n FROM stories \n LEFT JOIN s_ups ON stories.q_id=s_ups.s_id\n LEFT JOIN s_downs ON stories.s_id=s_downs.s_id\n GROUP BY stories.s_id\n ) as derived_table1\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
153,846
|
<p>We have a WCF service deployed on a Windows 2003 server that is exhibiting some problems. The configuration is using <code>wsHttpBinding</code> and we are specifying the IP address. The services is being hosted by a Windows Service.</p>
<p>When we start the service up, most of the time it grabs the wrong IP address. A few times it bound to the correct address only to drop that binding and go to the other address (there are 2) bound to the NIC after processing for a short while.</p>
<p>It is currently using port 80 (we've configured IIS to bind to only 1 address via <code>httpcfg</code>) although we have tried it using different ports with the same results.</p>
<p>When the Windows Service starts hosting the WCF service, the properties show that it is being bound to the correct address; however, tcpview shows that it is indeed listening on the incorrect address.</p>
<p>Here is the portion of the config that sets up tehe baseAddress. The one that gets bound to ends up being .4 instead of .9</p>
<pre><code><services>
<service name="Service.MyService"
behaviorConfiguration="serviceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://xx.xx.xx.9:80/" />
</baseAddresses>
</host>
<endpoint address="MyService"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IMyService"
contract="Service.IMyService" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
</code></pre>
<ul>
<li>Is there some other configuration that needs to be set? </li>
<li>Is there a tool that can help track down where this is getting bound to the wrong address?</li>
</ul>
|
[
{
"answer_id": 155083,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 0,
"selected": false,
"text": "Description:\nUnable to bind to the underlying transport for xx.xx.xx.4:80. The IP Listen-Only list may contain a reference to an interface which may not exist on this machine. The data field contains the error number.\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312/"
] |
153,861
|
<p>What do the brackets do in a sql statement?</p>
<p>For example, in the statement: </p>
<pre>insert into table1 ([columnname1], columnname2) values (val1, val2)</pre>
<p>Also, what does it do if the table name is in brackets?</p>
|
[
{
"answer_id": 153870,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE test\n(\n [select] varchar(15)\n)\n\nINSERT INTO test VALUES('abc')\n\nSELECT [select] FROM test\n"
},
{
"answer_id": 153871,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 7,
"selected": true,
"text": "select [Order qty] from [Client sales]\n"
},
{
"answer_id": 153878,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 0,
"selected": false,
"text": "insert into [Table One] ([Column Name 1], columnname2) values (val1, val2)\n"
},
{
"answer_id": 154416,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": false,
"text": "SET QUOTED_IDENTIFIER ON;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
] |
153,863
|
<p>I have a large 'Manager' class which I think is doing too much but I am unsure on how to divide it into more logical units. </p>
<p>Generally speaking the class basically consists of the following methods:</p>
<pre>
class FooBarManager
{
GetFooEntities();
AddFooEntity(..);
UpdateFooEntity(..);
SubmitFooEntity(..);
GetFooTypes();
GetBarEntities();
}
</pre>
<p>The Manager class is part of my business logic and constains an instance of another "Manager" class on the data access level which contains all CRUD operations for all entities.</p>
<p>I have different entities coming from the data access layer and therefore have a converter in place outside of the Manager class to convert data entities to business entities.</p>
<p>The reason for the manager classes was that I wanted to be able to mock out each of the "Manager" classes when I do unittesting. Each of the manager classes is now over 1000 loc and contain 40-50 methods each. I consider them to be quite bloated and find it awkward to put all of the data access logic into a single class. What should I be doing differently?</p>
<p>How would I go about splitting them and is there any specific design-pattern should I be using?</p>
|
[
{
"answer_id": 153917,
"author": "scable",
"author_id": 8942,
"author_profile": "https://Stackoverflow.com/users/8942",
"pm_score": 0,
"selected": false,
"text": " / FooManager\nManager (derive from Manager)\n \\ BarManager\n"
},
{
"answer_id": 153926,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class EntityCollection<T> : IList<T> \n where T : BaseEntity\n{ /* all management logic here */}\npublic class FooCollection : EntityCollection<foo> {}\npublic class BarCollection : EntityCollection<bar> {}\npublic class FooBarManager \n{ \npublic FooCollection { /*...*/ } \npublic BarCollection { /*...*/ } \npublic FooBarManager() : this(new FooCollection(), new BarCollection()){}\npublic FooBarManager(FooCollection fc, BarCollection bc) { /*...*/ } \n}\n"
},
{
"answer_id": 153935,
"author": "Mac",
"author_id": 8696,
"author_profile": "https://Stackoverflow.com/users/8696",
"pm_score": 1,
"selected": false,
"text": "FooBarManager"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
] |
153,874
|
<h3>See: <a href="https://stackoverflow.com/questions/5727/understanding-pointers">Understanding Pointers</a></h3>
<hr />
<p>In many C flavoured languages, and some older languages like Fortran, one can use <strong>Pointers</strong>.</p>
<p>As someone who has only really programmed in basic, javascript, and actionscript, can you explain to me what a Pointer is, and what it is most useful for?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 153880,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 3,
"selected": false,
"text": "// x is an integer variable\nint x = 5;\n// xpointer is a variable that references (points to) integer variables\nint *xpointer;\n// We store the address (& operator) of x into xpointer.\nxpointer = &x;\n// We use the dereferencing operator (*) to say that we want to work with\n// the variable that xpointer references\n*xpointer = 7;\nif (5 == x) {\n // Not true\n} else if (7 == x) {\n // True since we used xpointer to modify x\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10875/"
] |
153,877
|
<p>I have read the documentation on this and I think I understand. An <a href="http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx" rel="noreferrer"><code>AutoResetEvent</code></a> resets when the code passes through <code>event.WaitOne()</code>, but a <a href="http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx" rel="noreferrer"><code>ManualResetEvent</code></a> does not.</p>
<p>Is this correct?</p>
|
[
{
"answer_id": 154005,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 11,
"selected": true,
"text": "ManualResetEvent AutoResetEvent"
},
{
"answer_id": 154442,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 7,
"selected": false,
"text": "AutoResetEvent WaitOne() Reset() AutoResetEvent"
},
{
"answer_id": 24854015,
"author": "Teoman shipahi",
"author_id": 929902,
"author_profile": "https://Stackoverflow.com/users/929902",
"pm_score": 4,
"selected": false,
"text": "ManualResetEvent AutoResetEvent AutoResetEvent WaitOne() WaitOne() autoReset.Set();\nThread.Sleep(1000);\nautoReset.Set();\n Set() WaitOne() Set() public class AutoResetEventSample\n{\n private AutoResetEvent autoReset = new AutoResetEvent(false);\n\n public void RunAll()\n {\n new Thread(Worker1).Start();\n new Thread(Worker2).Start();\n new Thread(Worker3).Start();\n autoReset.Set();\n Thread.Sleep(1000);\n autoReset.Set();\n Console.WriteLine(\"Main thread reached to end.\");\n }\n\n public void Worker1()\n {\n Console.WriteLine(\"Entered in worker 1\");\n for (int i = 0; i < 5; i++) {\n Console.WriteLine(\"Worker1 is running {0}\", i);\n Thread.Sleep(2000);\n autoReset.WaitOne();\n }\n }\n public void Worker2()\n {\n Console.WriteLine(\"Entered in worker 2\");\n\n for (int i = 0; i < 5; i++) {\n Console.WriteLine(\"Worker2 is running {0}\", i);\n Thread.Sleep(2000);\n autoReset.WaitOne();\n }\n }\n public void Worker3()\n {\n Console.WriteLine(\"Entered in worker 3\");\n\n for (int i = 0; i < 5; i++) {\n Console.WriteLine(\"Worker3 is running {0}\", i);\n Thread.Sleep(2000);\n autoReset.WaitOne();\n }\n }\n}\n Set() WaitOne() Reset() manualReset.Set();\nThread.Sleep(1000);\nmanualReset.Reset();\nConsole.WriteLine(\"Press to release all threads.\");\nConsole.ReadLine();\nmanualReset.Set();\n Reset() public class ManualResetEventSample\n{\n private ManualResetEvent manualReset = new ManualResetEvent(false);\n\n public void RunAll()\n {\n new Thread(Worker1).Start();\n new Thread(Worker2).Start();\n new Thread(Worker3).Start();\n manualReset.Set();\n Thread.Sleep(1000);\n manualReset.Reset();\n Console.WriteLine(\"Press to release all threads.\");\n Console.ReadLine();\n manualReset.Set();\n Console.WriteLine(\"Main thread reached to end.\");\n }\n\n public void Worker1()\n {\n Console.WriteLine(\"Entered in worker 1\");\n for (int i = 0; i < 5; i++) {\n Console.WriteLine(\"Worker1 is running {0}\", i);\n Thread.Sleep(2000);\n manualReset.WaitOne();\n }\n }\n public void Worker2()\n {\n Console.WriteLine(\"Entered in worker 2\");\n\n for (int i = 0; i < 5; i++) {\n Console.WriteLine(\"Worker2 is running {0}\", i);\n Thread.Sleep(2000);\n manualReset.WaitOne();\n }\n }\n public void Worker3()\n {\n Console.WriteLine(\"Entered in worker 3\");\n\n for (int i = 0; i < 5; i++) {\n Console.WriteLine(\"Worker3 is running {0}\", i);\n Thread.Sleep(2000);\n manualReset.WaitOne();\n }\n }\n}\n"
},
{
"answer_id": 31005822,
"author": "vezenkov",
"author_id": 1025264,
"author_profile": "https://Stackoverflow.com/users/1025264",
"pm_score": 4,
"selected": false,
"text": "autoResetEvent.WaitOne() try\n{\n manualResetEvent.WaitOne();\n}\nfinally\n{\n manualResetEvent.Reset();\n}\n"
},
{
"answer_id": 41085271,
"author": "Masoud Siahkali",
"author_id": 6687274,
"author_profile": "https://Stackoverflow.com/users/6687274",
"pm_score": 3,
"selected": false,
"text": "AutoResetEvent autoResetEvent = new AutoResetEvent(false);\n autoResetEvent.WaitOne();\n static void ThreadMethod()\n{\n while(!autoResetEvent.WaitOne(TimeSpan.FromSeconds(2)))\n {\n Console.WriteLine(\"Continue\");\n Thread.Sleep(TimeSpan.FromSeconds(1));\n }\n\n Console.WriteLine(\"Thread got signal\");\n}\n autoResetEvent.Set();\n ManualResetEvent manualResetEvent = new ManualResetEvent(false);\n manualResetEvent.WaitOne();\n bool isSignalled = manualResetEvent.WaitOne(TimeSpan.FromSeconds(5));\n manualResetEvent.Set();\n manualResetEvent.Reset();\n"
},
{
"answer_id": 43414138,
"author": "Teoman shipahi",
"author_id": 929902,
"author_profile": "https://Stackoverflow.com/users/929902",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.Threading;\n\nnamespace ConsoleApplicationDotNetBasics.ThreadingExamples\n{\n public class ManualResetEventSample\n {\n private readonly ManualResetEvent _manualReset = new ManualResetEvent(false);\n\n public void RunAll()\n {\n new Thread(Worker1).Start();\n new Thread(Worker2).Start();\n new Thread(Worker3).Start();\n Console.WriteLine(\"All Threads Scheduled to RUN!. ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n Console.WriteLine(\"Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below.\");\n Thread.Sleep(15000);\n Console.WriteLine(\"1- Main will call ManualResetEvent.Set() in 5 seconds, watch out!\");\n Thread.Sleep(5000);\n _manualReset.Set();\n Thread.Sleep(2000);\n Console.WriteLine(\"2- Main will call ManualResetEvent.Set() in 5 seconds, watch out!\");\n Thread.Sleep(5000);\n _manualReset.Set();\n Thread.Sleep(2000);\n Console.WriteLine(\"3- Main will call ManualResetEvent.Set() in 5 seconds, watch out!\");\n Thread.Sleep(5000);\n _manualReset.Set();\n Thread.Sleep(2000);\n Console.WriteLine(\"4- Main will call ManualResetEvent.Reset() in 5 seconds, watch out!\");\n Thread.Sleep(5000);\n _manualReset.Reset();\n Thread.Sleep(2000);\n Console.WriteLine(\"It ran one more time. Why? Even Reset Sets the state of the event to nonsignaled (false), causing threads to block, this will initial the state, and threads will run again until they WaitOne().\");\n Thread.Sleep(10000);\n Console.WriteLine();\n Console.WriteLine(\"This will go so on. Everytime you call Set(), ManualResetEvent will let ALL threads to run. So if you want synchronization between them, consider using AutoReset event, or simply user TPL (Task Parallel Library).\");\n Thread.Sleep(5000);\n Console.WriteLine(\"Main thread reached to end! ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n\n }\n\n public void Worker1()\n {\n for (int i = 1; i <= 10; i++)\n {\n Console.WriteLine(\"Worker1 is running {0}/10. ThreadId: {1}.\", i, Thread.CurrentThread.ManagedThreadId);\n Thread.Sleep(5000);\n // this gets blocked until _autoReset gets signal\n _manualReset.WaitOne();\n }\n Console.WriteLine(\"Worker1 is DONE. ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n }\n public void Worker2()\n {\n for (int i = 1; i <= 10; i++)\n {\n Console.WriteLine(\"Worker2 is running {0}/10. ThreadId: {1}.\", i, Thread.CurrentThread.ManagedThreadId);\n Thread.Sleep(5000);\n // this gets blocked until _autoReset gets signal\n _manualReset.WaitOne();\n }\n Console.WriteLine(\"Worker2 is DONE. ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n }\n public void Worker3()\n {\n for (int i = 1; i <= 10; i++)\n {\n Console.WriteLine(\"Worker3 is running {0}/10. ThreadId: {1}.\", i, Thread.CurrentThread.ManagedThreadId);\n Thread.Sleep(5000);\n // this gets blocked until _autoReset gets signal\n _manualReset.WaitOne();\n }\n Console.WriteLine(\"Worker3 is DONE. ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n }\n }\n\n}\n using System;\nusing System.Threading;\n\nnamespace ConsoleApplicationDotNetBasics.ThreadingExamples\n{\n public class AutoResetEventSample\n {\n private readonly AutoResetEvent _autoReset = new AutoResetEvent(false);\n\n public void RunAll()\n {\n new Thread(Worker1).Start();\n new Thread(Worker2).Start();\n new Thread(Worker3).Start();\n Console.WriteLine(\"All Threads Scheduled to RUN!. ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n Console.WriteLine(\"Main Thread is waiting for 15 seconds, observe 3 thread behaviour. All threads run once and stopped. Why? Because they call WaitOne() internally. They will wait until signals arrive, down below.\");\n Thread.Sleep(15000);\n Console.WriteLine(\"1- Main will call AutoResetEvent.Set() in 5 seconds, watch out!\");\n Thread.Sleep(5000);\n _autoReset.Set();\n Thread.Sleep(2000);\n Console.WriteLine(\"2- Main will call AutoResetEvent.Set() in 5 seconds, watch out!\");\n Thread.Sleep(5000);\n _autoReset.Set();\n Thread.Sleep(2000);\n Console.WriteLine(\"3- Main will call AutoResetEvent.Set() in 5 seconds, watch out!\");\n Thread.Sleep(5000);\n _autoReset.Set();\n Thread.Sleep(2000);\n Console.WriteLine(\"4- Main will call AutoResetEvent.Reset() in 5 seconds, watch out!\");\n Thread.Sleep(5000);\n _autoReset.Reset();\n Thread.Sleep(2000);\n Console.WriteLine(\"Nothing happened. Why? Becasuse Reset Sets the state of the event to nonsignaled, causing threads to block. Since they are already blocked, it will not affect anything.\");\n Thread.Sleep(10000);\n Console.WriteLine(\"This will go so on. Everytime you call Set(), AutoResetEvent will let another thread to run. It will make it automatically, so you do not need to worry about thread running order, unless you want it manually!\");\n Thread.Sleep(5000);\n Console.WriteLine(\"Main thread reached to end! ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n\n }\n\n public void Worker1()\n {\n for (int i = 1; i <= 5; i++)\n {\n Console.WriteLine(\"Worker1 is running {0}/5. ThreadId: {1}.\", i, Thread.CurrentThread.ManagedThreadId);\n Thread.Sleep(500);\n // this gets blocked until _autoReset gets signal\n _autoReset.WaitOne();\n }\n Console.WriteLine(\"Worker1 is DONE. ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n }\n public void Worker2()\n {\n for (int i = 1; i <= 5; i++)\n {\n Console.WriteLine(\"Worker2 is running {0}/5. ThreadId: {1}.\", i, Thread.CurrentThread.ManagedThreadId);\n Thread.Sleep(500);\n // this gets blocked until _autoReset gets signal\n _autoReset.WaitOne();\n }\n Console.WriteLine(\"Worker2 is DONE. ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n }\n public void Worker3()\n {\n for (int i = 1; i <= 5; i++)\n {\n Console.WriteLine(\"Worker3 is running {0}/5. ThreadId: {1}.\", i, Thread.CurrentThread.ManagedThreadId);\n Thread.Sleep(500);\n // this gets blocked until _autoReset gets signal\n _autoReset.WaitOne();\n }\n Console.WriteLine(\"Worker3 is DONE. ThreadId: {0}\", Thread.CurrentThread.ManagedThreadId);\n }\n }\n\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1455/"
] |
153,879
|
<p>As part of a build setup on a windows machine I need to add a registry entry and I'd like to do it from a simple batch file.</p>
<p>The entry is for a third party app so the format is fixed.</p>
<p>The entry takes the form of a REG_SZ string but needs to contain newlines ie. 0xOA characters as separators.</p>
<p>I've hit a few problems.</p>
<p>First attempt used regedit to load a generated .reg file. This failed as it did not seem to like either either long strings or strings with newlines. I discovered that export works fine import fails. I was able to test export as the third party app adds similar entries directly through the win32 api.</p>
<p>Second attempt used the command REG ADD but I can't find anyway to add the newline characters everything I try just ends up with a literal string being added.</p>
|
[
{
"answer_id": 153952,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 3,
"selected": true,
"text": "set WSHShell = CreateObject(\"WScript.Shell\") \nWSHShell.RegWrite \"HKEY_LOCAL_MACHINE\\SOMEKEY\", \"value\", \"type\"\n"
},
{
"answer_id": 154062,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 2,
"selected": false,
"text": "Registry.CurrentUser.OpenSubKey(@\"software\\classes\\something\", true).SetValue(\"some key\", \"sometext\\nothertext\", RegistryValueKind.String);\n"
},
{
"answer_id": 13255189,
"author": "kbulgrien",
"author_id": 856172,
"author_profile": "https://Stackoverflow.com/users/856172",
"pm_score": 2,
"selected": false,
"text": ",00,00 REG.EXE IMPORT MULTILINETEXT.REG"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5427/"
] |
153,890
|
<p>I'm trying to find a good way to print leading <code>0</code>, such as <code>01001</code> for a <a href="https://en.wikipedia.org/wiki/ZIP_Code" rel="noreferrer">ZIP Code</a>. While the number would be stored as <code>1001</code>, what is a good way to do it?</p>
<p>I thought of using either <code>case</code> statements or <code>if</code> to figure out how many digits the number is and then convert it to an <code>char</code> array with extra <code>0</code>'s for printing, but I can't help but think there may be a way to do this with the <code>printf</code> format syntax that is eluding me.</p>
|
[
{
"answer_id": 153895,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 10,
"selected": true,
"text": "printf(\"%05d\", zipCode);\n 0 5 \"%02d\" 06 6 \"%03d\" 007 017"
},
{
"answer_id": 153898,
"author": "Trent",
"author_id": 9083,
"author_profile": "https://Stackoverflow.com/users/9083",
"pm_score": 3,
"selected": false,
"text": "printf(\"leading zeros %05d\", 123);\n"
},
{
"answer_id": 153899,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 6,
"selected": false,
"text": "printf(\"%05d\", zipcode);\n"
},
{
"answer_id": 153904,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 4,
"selected": false,
"text": "man 3 printf\n"
},
{
"answer_id": 153907,
"author": "Dan Hewett",
"author_id": 17975,
"author_profile": "https://Stackoverflow.com/users/17975",
"pm_score": 4,
"selected": false,
"text": "sprintf(mystring, \"%05d\", myInt);\n"
},
{
"answer_id": 153924,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 4,
"selected": false,
"text": "printf(\"%05d\", number);"
},
{
"answer_id": 23167000,
"author": "rch",
"author_id": 3551091,
"author_profile": "https://Stackoverflow.com/users/3551091",
"pm_score": 0,
"selected": false,
"text": "//---- Header\nstd::string getFmt ( int wid, long val )\n{ \n char buf[64];\n sprintf ( buf, \"% *ld\", wid, val );\n return buf;\n}\n#define FMT (getFmt(8,x).c_str())\n\n//---- Put to use\nprintf ( \" COUNT USED FREE\\n\" );\nprintf ( \"A: %s %s %s\\n\", FMT(C[0]), FMT(U[0]), FMT(F[0]) );\nprintf ( \"B: %s %s %s\\n\", FMT(C[1]), FMT(U[1]), FMT(F[1]) );\nprintf ( \"C: %s %s %s\\n\", FMT(C[2]), FMT(U[2]), FMT(F[2]) );\n\n//-------- Output\n COUNT USED FREE\nA: 354 148523 3283\nB: 54138259 12392759 200391\nC: 91239 3281 61423\n"
},
{
"answer_id": 30940716,
"author": "Brad Jennings",
"author_id": 1668928,
"author_profile": "https://Stackoverflow.com/users/1668928",
"pm_score": 0,
"selected": false,
"text": "zipcode[] snprintf(zipcode, 6, \"%05.5d\", atoi(zipcode));\n"
},
{
"answer_id": 66082660,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 3,
"selected": false,
"text": "0 int zipcode = 123;\nprintf(\"%05d\\n\", zipcode); // Outputs 00123\n int zipcode = 123;\nprintf(\"%.5d\\n\", zipcode); // Outputs 00123\n printf(\"%05d\\n\", -123); // Outputs -0123 (pad to 5 characters)\nprintf(\"%.5d\\n\", -123); // Outputs -00123 (pad to 5 digits)\n 5 int int width = 5;\nprintf(\"%0*d\\n\", width, 123); // Outputs 00123\nprintf(\"%.*d\\n\", width, 123); // Outputs 00123\n 0 0 printf(\"|%0d|%0d|\\n\", 0, 1); // Outputs |0|1|\nprintf(\"|%.0d|%.0d|\\n\", 0, 1); // Outputs ||1|\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628/"
] |
153,909
|
<p>I call my JavaScript function. Why do I <em>sometimes</em> get the error 'myFunction is not defined' when it <em>is</em> defined?</p>
<p>For example. I'll occasionally get 'copyArray is not defined' even in this example:</p>
<pre><code>function copyArray( pa ) {
var la = [];
for (var i=0; i < pa.length; i++)
la.push( pa[i] );
return la;
}
Function.prototype.bind = function( po ) {
var __method = this;
var __args = [];
// Sometimes errors -- in practice I inline the function as a workaround.
__args = copyArray( arguments );
return function() {
/* bind logic omitted for brevity */
}
}
</code></pre>
<p>As you can see, copyArray is defined <em>right there</em>, so this can't be about the order in which script files load.</p>
<p>I've been getting this in situations that are harder to work around, where the calling function is located in another file that <em>should</em> be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem.</p>
<p>It doesn't happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what.</p>
<p>@Hojou: That's part of the problem. The function in which I'm now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function.</p>
<p>@James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the 'not defined' error.</p>
<p>@David: The script in this case resides in an external file that is referenced using the normal <script src="file.js"></script> method in the page's head section.</p>
<p>@Douglas: Interesting idea, but if this were the case, how could we <em>ever</em> call a user-defined function with confidence? In any event, I tried this and it didn't work.</p>
<p>@sk: This technique has been tested across browsers and is basically copied from the <a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="noreferrer">Prototype</a> library.</p>
|
[
{
"answer_id": 153951,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 0,
"selected": false,
"text": "(function() {\n function copyArray(pa) {\n // Details\n }\n\n Function.prototype.bind = function ( po ) {\n __args = copyArray( arguments );\n }\n})();\n"
},
{
"answer_id": 154356,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 2,
"selected": false,
"text": "copyArray() __args = Array.prototype.slice.call(arguments);\n"
},
{
"answer_id": 2485994,
"author": "Niloct",
"author_id": 152016,
"author_profile": "https://Stackoverflow.com/users/152016",
"pm_score": 5,
"selected": false,
"text": "SCRIPT <SCRIPT src=\"mycode.js\"/>\n <SCRIPT src=\"mycode.js\"></SCRIPT>\n"
},
{
"answer_id": 45927016,
"author": "juan Isaza",
"author_id": 2394901,
"author_profile": "https://Stackoverflow.com/users/2394901",
"pm_score": 2,
"selected": false,
"text": " <script type=\"text/javascript\" src=\"{% static 'js/my_js_file.js' %}\" async></script>\n <script type=\"text/javascript\" src=\"{% static 'js/my_js_file.js' %}\"></script>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4525/"
] |
153,912
|
<p>I'm looking for a good way to visualize ASP.NET session state data stored in SQL server, preferably without creating a throwaway .aspx page. Is there a good way to get a list of the keys (and serialized data, if possible) directly from SQL server?</p>
<p>Ideally, I'd like to run some T-SQL commands directly against the database to get a list of session keys that have been stored for a given session ID. It would be nice to see the serialized data for each key as well.</p>
|
[
{
"answer_id": 153951,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 0,
"selected": false,
"text": "(function() {\n function copyArray(pa) {\n // Details\n }\n\n Function.prototype.bind = function ( po ) {\n __args = copyArray( arguments );\n }\n})();\n"
},
{
"answer_id": 154356,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 2,
"selected": false,
"text": "copyArray() __args = Array.prototype.slice.call(arguments);\n"
},
{
"answer_id": 2485994,
"author": "Niloct",
"author_id": 152016,
"author_profile": "https://Stackoverflow.com/users/152016",
"pm_score": 5,
"selected": false,
"text": "SCRIPT <SCRIPT src=\"mycode.js\"/>\n <SCRIPT src=\"mycode.js\"></SCRIPT>\n"
},
{
"answer_id": 45927016,
"author": "juan Isaza",
"author_id": 2394901,
"author_profile": "https://Stackoverflow.com/users/2394901",
"pm_score": 2,
"selected": false,
"text": " <script type=\"text/javascript\" src=\"{% static 'js/my_js_file.js' %}\" async></script>\n <script type=\"text/javascript\" src=\"{% static 'js/my_js_file.js' %}\"></script>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23632/"
] |
153,920
|
<p>Code I am trying to run:</p>
<pre><code>$query = "DESCRIBE TABLE TABLENAME";
$result = odbc_exec($h, $query);
</code></pre>
<p>The result:</p>
<blockquote>
<p>PHP Warning: odbc_exec(): SQL error: [unixODBC][IBM][iSeries Access
ODBC Driver][DB2 UDB]SQL0104 - Token TABLENAME was not valid. Valid
tokens: INTO., SQL state 37000 in SQLExecDirect in ...</p>
</blockquote>
<p>There were no other problems with SELECT, INSERT, UPDATE or DELETE queries on the same connection. Is this a syntax error?</p>
|
[
{
"answer_id": 173865,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 0,
"selected": false,
"text": "select * from <TABLE> where 0 = 1\n"
},
{
"answer_id": 184474,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 3,
"selected": false,
"text": "select * from qsys2.columns where table_schema = 'my_schema' and table_name = 'my_table'\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8437/"
] |
153,928
|
<p>We currently are using both Visual Source Safe and Team Foundation Server at work (VSS for old projects, TFS for current or new projects).</p>
<p>We have always used Labels in source control for each build. In VSS if you chose to see a file history you could include labels. In TFS I cannot find an option to include the lables in the history window.</p>
<p>Since one of the most common questions that I get asked by support or management is 'What version did we fix/add/remove/change xxxx?', I have always relied on our build labels showing up in the history. </p>
<p>Can I get Labels to show up in a file history? </p>
|
[
{
"answer_id": 6822899,
"author": "Mike Sage",
"author_id": 862414,
"author_profile": "https://Stackoverflow.com/users/862414",
"pm_score": 1,
"selected": false,
"text": "select DisplayName, cs.CreationDate, Comment, 'CheckIn' \nfrom TfsVersionControl.dbo.tbl_Identity i, TfsVersionControl.dbo.tbl_ChangeSet cs \nwhere cs.ownerid = i.IdentityId\nunion\nselect DisplayName, LastModified, Comment, 'Label' \nfrom TfsVersionControl.dbo.tbl_Identity i, TfsVersionControl.dbo.tbl_Label l \nwhere l.ownerid = i.IdentityId\norder by 2 desc\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5882/"
] |
153,934
|
<p>I'm trying to modify the class of an element if an ajax call based on that element is successful</p>
<pre><code><script type='text/javascript'>
$("#a.toggle").click(function(e){
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text){
if(data.error=='')
{
if($(this).hasClass('class1'))
{
$(this).removeClass('class1');
$(this).addClass('class2');
}
else if($(this).hasClass('class2'))
{
$(this).removeClass('class2');
$(this).addClass('class1');
}
}
else(alert(data.error));
}
});
return false;
});
</script>
<a class="toggle class1" title='toggle-this'>Item</a>
</code></pre>
<p>My understanding of the problem is that in the success function <em>this</em> references the ajax object parameters, NOT the calling dom element like it does within other places of the click function. So, how do I reference the calling dom element and check / add / remove classes?</p>
|
[
{
"answer_id": 153948,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 5,
"selected": true,
"text": "$(\"#a.toggle\").click(function(e)\n{\n var target = $(this);\n $.ajax({\n url: '/changeItem.php',\n dataType: 'json',\n type: 'POST',\n success: function(data,text)\n {\n if(data.error=='')\n {\n if(target.hasClass('class1'))\n {\n target\n .removeClass('class1')\n .addClass('class2');\n }\n else if(target.hasClass('class2'))\n {\n target\n .removeClass('class2')\n .addClass('class1');\n }\n }\n else(alert(data.error));\n } \n });\n return false;\n});\n"
},
{
"answer_id": 25442621,
"author": "Mikhail Korolev",
"author_id": 3920854,
"author_profile": "https://Stackoverflow.com/users/3920854",
"pm_score": 2,
"selected": false,
"text": "context: this $.ajax({\n url: '/changeItem.php',\n dataType: 'json',\n type: 'POST',\n context: this,\n success: function(data,text){\n if(data.error=='')\n {\n if($(this).hasClass('class1'))\n {\n $(this).removeClass('class1');\n $(this).addClass('class2');\n }\n else if($(this).hasClass('class2'))\n {\n $(this).removeClass('class2');\n $(this).addClass('class1');\n }\n }\n else(alert(data.error));\n } \n});\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
] |
153,942
|
<p>After developing a WPF application without Source Control, I decided to add the solution to TFS.</p>
<p>After doing so whenever I opened the main window.xaml file in Design View Visual Studio would disappear and the following event would be logged in the Application Event log:</p>
<blockquote>
<p>.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506)</p>
<p>For more information, see Help and
Support Center at
<a href="http://go.microsoft.com/fwlink/events.asp" rel="noreferrer">http://go.microsoft.com/fwlink/events.asp</a>.</p>
</blockquote>
|
[
{
"answer_id": 463719,
"author": "Zhaph - Ben Duguid",
"author_id": 33051,
"author_profile": "https://Stackoverflow.com/users/33051",
"pm_score": 3,
"selected": false,
"text": "<dependentAssembly>\n <assemblyIdentity name=\"office\" publicKeyToken=\"71e9bce111e9429c\" culture=\"neutral\"/>\n <codeBase version=\"12.0.0.0\" href=\"PrivateAssemblies\\Office12\\Office.dll\"/>\n</dependentAssembly>\n\n<!-NEW STUFF-->\n<dependentAssembly>\n <assemblyIdentity name=\"Microsoft.PowerCommands\" publicKeyToken=\"null\" culture=\"neutral\"/>\n\n <!-- For 64-bit systems, uncomment this one\n <codeBase version=\"1.1.0.0\" href=\"C:\\Program Files (x86)\\PowerCommands\\Microsoft.PowerCommands.dll\"/> -->\n\n <!-- For 32-bit systems, uncomment this one\n <codeBase version=\"1.1.0.0\" href=\"href=\"C:\\Program Files\\PowerCommands\\Microsoft.PowerCommands.dll\"/> -->\n\n</dependentAssembly>\n"
},
{
"answer_id": 799080,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 2,
"selected": false,
"text": "ngen /delete *\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13368/"
] |
153,944
|
<p>Is SQL case sensitive? I've used <a href="https://en.wikipedia.org/wiki/MySQL" rel="nofollow noreferrer">MySQL</a> and <a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a> which both seem to be case insensitive. Is this always the case? Does the standard define case-sensitivity?</p>
|
[
{
"answer_id": 153964,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 2,
"selected": false,
"text": "select cOL1, col2 FrOM taBLeName WheRE ...\n"
},
{
"answer_id": 153965,
"author": "cmcculloh",
"author_id": 58,
"author_profile": "https://Stackoverflow.com/users/58",
"pm_score": 3,
"selected": false,
"text": "SELECT * FROM foo;\n select * from foo;\n select * from FOO;\n"
},
{
"answer_id": 153967,
"author": "Stefan Rusek",
"author_id": 19704,
"author_profile": "https://Stackoverflow.com/users/19704",
"pm_score": 9,
"selected": true,
"text": "SELECT FROM WHERE"
},
{
"answer_id": 340782,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 4,
"selected": false,
"text": "SELECT fieldName\nFROM tableName;\n SELECT \"fieldName\"\nFROM \"tableName\";\n"
},
{
"answer_id": 19933159,
"author": "SztupY",
"author_id": 120917,
"author_profile": "https://Stackoverflow.com/users/120917",
"pm_score": 5,
"selected": false,
"text": "table_name == TAble_nAmE \"table_name\" != \"TAble_naME\" TABLE_NAME == \"TABLE_NAME\" TABLE_NAME != \"table_name\" TABLE_NAME != \"TAble_NaMe\" table_name == \"table_name\""
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415/"
] |
153,953
|
<p>I’m trying to debug a memory leak problem. I’m using <a href="http://www.gnu.org/software/libc/manual/html_node/Tracing-malloc.html#Tracing-malloc" rel="noreferrer">mtrace()</a> to get a malloc/free/realloc trace. I’ve ran my prog and have now a huge log file. So far so good. But I have problems interpreting the file. Look at these lines:</p>
<pre><code>@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1502570 0x68
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1502620 0x30
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa80
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1501460 0xa64
</code></pre>
<p>The strange about this is that one call (same return address) is responsible for 4 allocations.</p>
<p>Even stranger:</p>
<pre><code>@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa2c
…
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa80
</code></pre>
<p>Between those two lines the block 0x2aaab43a1700 is never being freed.</p>
<p>Does anyone know how to explain this? How could one call result in 4 allocations? And how could malloc return an address which was already allocated previously?</p>
<p>edit 2008/09/30:
The script to analyze the mtrace() output provided by GLIBC (mtrace.pl) isn't of any help here. It will just say: Alloc 0x2aaab43a1700 duplicate. But how could this happen?</p>
|
[
{
"answer_id": 154419,
"author": "Sufian",
"author_id": 9241,
"author_profile": "https://Stackoverflow.com/users/9241",
"pm_score": 3,
"selected": false,
"text": "$ gcc -g -o test test.c\n$ MALLOC_TRACE=mtrace.out ./test\n$ mtrace test mtrace.out\n\nMemory not freed:\n-----------------\n Address Size Caller\n0x094d9378 0x400 at test.c:6\n"
},
{
"answer_id": 168915,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 4,
"selected": true,
"text": "void *allocate (void)\n{\n return (malloc(1000));\n}\n\nint main()\n{\n mtrace();\n allocate();\n allocate();\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17428/"
] |
153,974
|
<p>I'm wondering how (un)common it is to encapsulate an algorithm into a class? More concretely, instead of having a number of separate functions that forward common parameters between each other:</p>
<pre><code>void f(int common1, int param1, int *out1);
void g(int common1, int common2, int param1, int *out2)
{
f(common1, param1, ..);
}
</code></pre>
<p>to encapsulate common parameters into a class and do all of the work in the constructor:</p>
<pre><code>struct Algo
{
int common1;
int common2;
Algo(int common1, int common2, int param)
{ // do most of the work }
void f(int param1, int *out1);
void g(int param1, int *out2);
};
</code></pre>
<p>It seems very practical not having to forward common parameters and intermediate results through function arguments.. But I haven't seen this "pattern" being widely used.. What are the possible downsides?</p>
|
[
{
"answer_id": 154001,
"author": "David Segonds",
"author_id": 13673,
"author_profile": "https://Stackoverflow.com/users/13673",
"pm_score": 1,
"selected": false,
"text": "class MyFunctor {\n public:\n MyFunctor( /* List of Parameters */ );\n bool execute();\n private:\n /* Local storage for parameters and intermediary data structures */\n}\n bool success = MyFunctor( /*Parameter*/ ).execute();\n"
},
{
"answer_id": 154028,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "public class MyFooConfigurator\n{\n public MyFooConfigurator(string Param1, int, Param2) //Etc...\n {\n //Set all the internal properties here\n //Another option would also be to expose public properties that the user could\n //set from outside, or you could create a struct that ecapsulates all the\n //parameters.\n _Param1 = Param1; //etc...\n }\n\n Public ConfigureFoo()\n {\n If(!FooIsConfigured)\n return;\n Else\n //Process algorithm here.\n }\n}\n"
},
{
"answer_id": 154035,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": 2,
"selected": false,
"text": "class InputData {};\nclass OutputData {};\n\nclass TheAlgorithm \n{\nprivate:\n //functions and common data\n\npublic:\n TheAlgorithm(InputData); \n //other functions\n Run();\n ReturnOutputData();\n};\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2583/"
] |
153,983
|
<p>For some reason the Windows command prompt is "special" in that you have to go to a properties dialog to resize it horizontally rather than just dragging the corner of the window like every other app. Unsurprisingly this feature made it into P-P-P-Powershell as well -- is there any way around this via command prompt replacement or Windows hackery?</p>
|
[
{
"answer_id": 188086,
"author": "avgbody",
"author_id": 8737,
"author_profile": "https://Stackoverflow.com/users/8737",
"pm_score": 4,
"selected": false,
"text": "##\n## Author : Roman Kuzmin\n## Synopsis : Resize console window/buffer using arrow keys\n##\n\nfunction Size($w, $h)\n{\n New-Object System.Management.Automation.Host.Size($w, $h)\n}\n\nfunction resize()\n{\nWrite-Host '[Arrows] resize [Esc] exit ...'\n$ErrorActionPreference = 'SilentlyContinue'\nfor($ui = $Host.UI.RawUI;;) {\n $b = $ui.BufferSize\n $w = $ui.WindowSize\n switch($ui.ReadKey(6).VirtualKeyCode) {\n 37 {\n $w = Size ($w.width - 1) $w.height\n $ui.WindowSize = $w\n $ui.BufferSize = Size $w.width $b.height\n break\n }\n 39 {\n $w = Size ($w.width + 1) $w.height\n $ui.BufferSize = Size $w.width $b.height\n $ui.WindowSize = $w\n break\n }\n 38 {\n $ui.WindowSize = Size $w.width ($w.height - 1)\n break\n }\n 40 {\n $w = Size $w.width ($w.height + 1)\n if ($w.height -gt $b.height) {\n $ui.BufferSize = Size $b.width $w.height\n }\n $ui.WindowSize = $w\n break\n }\n 27 {\n return\n }\n }\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
153,988
|
<p>I need to copy some records from our SQLServer 2005 test server to our live server. It's a flat lookup table, so no foreign keys or other referential integrity to worry about.</p>
<p>I could key-in the records again on the live server, but this is tiresome. I could export the test server records and table data in its entirety into an SQL script and run that, but I don't want to overwrite the records present on the live system, only add to them.</p>
<p>How can I select just the records I want and get them transferred or otherwise into the live server? We don't have Sharepoint, which I understand would allow me to copy them directly between the two instances.</p>
|
[
{
"answer_id": 154071,
"author": "Kwirk",
"author_id": 21879,
"author_profile": "https://Stackoverflow.com/users/21879",
"pm_score": 7,
"selected": true,
"text": "Execute sp_addlinkedserver PRODUCTION_SERVER_NAME\n INSERT INTO [PRODUCTION_SERVER_NAME].DATABASE_NAME.dbo.TABLE_NAME (Names_of_Columns_to_be_inserted)\nSELECT Names_of_Columns_to_be_inserted\nFROM TABLE_NAME\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7703/"
] |
153,989
|
<p>I have a little logging app (written in wxPython) that receives data from a bit of kit we're developing, and I want to display the text in a scrolling window. As it stands I'm using a wx.TextCtrl for the text display, but I'm having some issues with the scrolling behaviour.</p>
<p>Basically, I'd like it so that if the scrollbar is at the bottom of the window (i.e. the end of the incoming data), adding more data should scroll the view onwards. If, however the view has been scrolled up a little (i.e. the user is looking at something interesting like an error message), the app should just add the text on the end without scrolling any more.</p>
<p>I've got two problems at the moment:</p>
<ol>
<li>I can't work out how to retrieve the current scroll position (calls to GetScrollPos() don't seem to work - they just return 0).</li>
<li>I can't work out how to retrieve the current range of the scroll bar (calls to GetScrollRange() just return 1).</li>
</ol>
<p>I've googled a bit and there seem to be a few hints that suggest GetScrollPos and GetScrollRange won't work for a wx.TextCtrl? Has anyone else had any experience in this area? Is there a nice easy way to solve the problem or am I going to have to roll my own wx.TextCtrl?</p>
|
[
{
"answer_id": 154225,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 2,
"selected": true,
"text": "GetScrollPos(0) GetScrollRange(0) EVT_TEXT wx.TextCtrl >>> import wx\n>>> wx.version()\n'2.8.9.1 (msw-unicode)'\n"
},
{
"answer_id": 155781,
"author": "Jon Cage",
"author_id": 15369,
"author_profile": "https://Stackoverflow.com/users/15369",
"pm_score": 2,
"selected": false,
"text": "import wx\nfrom threading import Timer\nimport time\n\nclass Form1(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n\n self.logger = wx.TextCtrl(self,5, \"\",wx.Point(20,20), wx.Size(200,200), \\\n wx.TE_MULTILINE | wx.TE_READONLY)# | wx.TE_RICH2)\n\n t = Timer(0.1, self.AddText)\n t.start()\n\n def AddText(self):\n # Resart the timer\n t = Timer(0.25, self.AddText)\n t.start() \n\n # Work out if we're at the end of the file\n currentCaretPosition = self.logger.GetInsertionPoint()\n currentLengthOfText = self.logger.GetLastPosition()\n if currentCaretPosition != currentLengthOfText:\n self.holdingBack = True\n else:\n self.holdingBack = False\n\n timeStamp = str(time.time())\n\n # If we're not at the end of the file, we're holding back\n if self.holdingBack:\n print \"%s FROZEN\"%(timeStamp)\n self.logger.Freeze()\n (currentSelectionStart, currentSelectionEnd) = self.logger.GetSelection()\n self.logger.AppendText(timeStamp+\"\\n\")\n self.logger.SetInsertionPoint(currentCaretPosition)\n self.logger.SetSelection(currentSelectionStart, currentSelectionEnd)\n self.logger.Thaw()\n else:\n print \"%s THAWED\"%(timeStamp)\n self.logger.AppendText(timeStamp+\"\\n\")\n\napp = wx.PySimpleApp()\nframe = wx.Frame(None, size=(550,425))\nForm1(frame)\nframe.Show(1)\napp.MainLoop()\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
] |
153,994
|
<p>I want to have a class which implements an interface, which specifies the specific subclass as a parameter.</p>
<pre><code>public abstract Task implements TaskStatus<Task> {
TaskStatus<T> listener;
protected complete() {
// ugly, unsafe cast
callback.complete((T) this);
}
}
public interface TaskStatus<T> {
public void complete(T task);
}
</code></pre>
<p>But instead of just task, or , I want to guarantee the type-arg used is that of the specific class extending this one.</p>
<p>So the best I've come up with is:</p>
<pre><code>public abstract Task<T extends Task> implements TaskStatus<T> {
}
</code></pre>
<p>You'd extend that by writing:</p>
<pre><code>public class MyTask extends Task<MyTask> {
}
</code></pre>
<p>But this would also be valid:</p>
<pre><code>public class MyTask extends Task<SomeOtherTask> {
}
</code></pre>
<p>And the invocation of callback will blow up with ClassCastException. So, is this approach just wrong and broken, or is there a right way to do this I've somehow missed?</p>
|
[
{
"answer_id": 154340,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 3,
"selected": true,
"text": "Task Task<T> class Task<T extends Task<T>> { ... }\n class MyTask extends Task<MyTask> { ... }\nclass YourTask extends Task<MyTask> { ... }\n class MyTask extends Task<String> { ... }\n Task"
},
{
"answer_id": 154363,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "public abstract class Task<THIS extends Task<THIS>> {\n private TaskStatus<THIS> callback;\n\n public void setCallback(TaskStatus<THIS> callback) {\n this.callback = callback==null ? NullCallback.INSTANCE : callback;\n }\n\n protected void complete() {\n // ugly, unsafe cast\n callback.complete(getThis());\n }\n\n protected abstract THIS getThis();\n}\n\npublic interface TaskStatus<T/* extends Task<T>*/> {\n void complete(T task);\n}\n\npublic class MyTask extends Task<MyTask> {\n @Override protected MyTask getThis() {\n return this;\n }\n}\n"
},
{
"answer_id": 154367,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 0,
"selected": false,
"text": "assert getClass() == ((ParameterizedType) getSuperType()).getTypeArguments()[0];\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758/"
] |
154,004
|
<p>I have a link that I dynamically create which looks something like the following:</p>
<pre><code><a onclick="Edit('value from a text column here')" href="javascript:void(null);">Edit</a>
</code></pre>
<p>with the Edit function then taking the passed in value and putting it into a Yahoo Rich Text Editor. This works well except for when there is a single quote in the text being passed. The obvious problem being that the link then looks something like:</p>
<pre><code><a onclick="Edit('I'm a jelly donut')" href="javascript:void(null);">Edit</a>
</code></pre>
<p>Any suggestions on what I can do? I'd rather not stray too far from the structure I am currently using because it is something of a standard (and maybe the standard sucks, but that's another question altogether).</p>
<p>Note: I am using ASP as my server side language.</p>
|
[
{
"answer_id": 154018,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 5,
"selected": true,
"text": """
},
{
"answer_id": 155095,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 1,
"selected": false,
"text": "<a onclick=\"Edit('I\\u0027m a jelly donut')\" href=\"javascript:void(null);\">Edit</a>\n <script>function getQuote() { return \"'\" }</script>\n<a onclick=\"Edit('I' + getQuote() + 'm a jelly donut')\" href=\"javascript:void(null);\">Edit</a>\n <script>var g_strJellyText = \"I\\u0027m a jelly donut\"</script>\n<a onclick=\"Edit(g_strJellyText)\" href=\"javascript:void(null);\">Edit</a>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22777/"
] |
154,013
|
<p>My Django app has a Person table, which contains the following text in a field named <code>details</code>:</p>
<p><code><script>alert('Hello');</script></code></p>
<p>When I call <code>PersonForm.details</code> in my template, the page renders the script accordingly (a.k.a., an alert with the word "Hello" is displayed). I'm confused by this behavior because I always thought <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs" rel="nofollow noreferrer">Django 1.0 autoescaped</a> template content by default.</p>
<p>Any idea what may be going on here?</p>
<p><strong>UPDATE:</strong> Here's the snippet from my template. Nothing terribly sexy:</p>
<pre><code>{{ person_form.details }}
</code></pre>
<p><strong>UPDATE 2:</strong> I have tried <code>escape</code>, <code>force-escape</code>, and <code>escapejs</code>. None of these work.</p>
|
[
{
"answer_id": 154027,
"author": "Jon Cage",
"author_id": 15369,
"author_profile": "https://Stackoverflow.com/users/15369",
"pm_score": 4,
"selected": true,
"text": "{{ value|safe }}\n {{ value|escape }}\n escapejs\n\nNew in Django 1.0.\n\nEscapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.\n {{ value|force_escape }}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] |
154,031
|
<pre><code>Pattern pattern = Pattern.compile("^[a-z]+$");
String string = "abc-def";
assertTrue( pattern.matcher(string).matches() ); // obviously fails
</code></pre>
<p>Is it possible to have the character class match a "-" ?</p>
|
[
{
"answer_id": 154037,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 3,
"selected": false,
"text": "[a-z\\\\-]\n"
},
{
"answer_id": 154040,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": true,
"text": "\"[a-z-]\"\n"
},
{
"answer_id": 154061,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 2,
"selected": false,
"text": " Pattern p = Pattern.compile(\"^[a-z\\\\-]+$\");\n String line = \"abc-def\";\n Matcher matcher = p.matcher(line);\n System.out.println(matcher.matches()); // true\n"
},
{
"answer_id": 4223458,
"author": "codaddict",
"author_id": 227665,
"author_profile": "https://Stackoverflow.com/users/227665",
"pm_score": 3,
"selected": false,
"text": "[...] - - ^[a-z-]+$\n ^[-a-z]+$\n - - ^(?:[a-z]|-)+$\n | ^[a-z]|-+$\n -"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11858/"
] |
154,042
|
<p>I'm using spring 2.5 and annotations to configure my spring-mvc web context. Unfortunately, I am unable to get the following to work. I'm not sure if this is a bug (seems like it) or if there is a basic misunderstanding on how the annotations and interface implementation subclassing works.</p>
<p>For example,</p>
<pre><code>@Controller
@RequestMapping("url-mapping-here")
public class Foo {
@RequestMapping(method=RequestMethod.GET)
public void showForm() {
...
}
@RequestMapping(method=RequestMethod.POST)
public String processForm() {
...
}
}
</code></pre>
<p>works fine. When the context starts up, the urls this handler deals with are discovered, and everything works great. </p>
<p>This however does not:</p>
<pre><code>@Controller
@RequestMapping("url-mapping-here")
public class Foo implements Bar {
@RequestMapping(method=RequestMethod.GET)
public void showForm() {
...
}
@RequestMapping(method=RequestMethod.POST)
public String processForm() {
...
}
}
</code></pre>
<p>When I try to pull up the url, I get the following nasty stack trace:</p>
<pre><code>javax.servlet.ServletException: No adapter for handler [com.shaneleopard.web.controller.RegistrationController@e973e3]: Does your handler implement a supported interface like Controller?
org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:1091)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:874)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
javax.servlet.http.HttpServlet.service(HttpServlet.java:627)
</code></pre>
<p>However, if I change Bar to be an abstract superclass and have Foo extend it, then it works again.</p>
<pre><code>@Controller
@RequestMapping("url-mapping-here")
public class Foo extends Bar {
@RequestMapping(method=RequestMethod.GET)
public void showForm() {
...
}
@RequestMapping(method=RequestMethod.POST)
public String processForm() {
...
}
}
</code></pre>
<p>This seems like a bug. The @Controller annotation should be sufficient to mark this as a controller, and I should be able to implement one or more interfaces in my controller without having to do anything else. Any ideas?</p>
|
[
{
"answer_id": 2358726,
"author": "Michal Bachman",
"author_id": 220912,
"author_profile": "https://Stackoverflow.com/users/220912",
"pm_score": 4,
"selected": false,
"text": "<bean class=\"org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping\"/>\n<bean class=\"org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter\"/>\n"
},
{
"answer_id": 3190630,
"author": "James Kingsbery",
"author_id": 72908,
"author_profile": "https://Stackoverflow.com/users/72908",
"pm_score": 4,
"selected": false,
"text": " <tx:annotation-driven/>\n <tx:annotation-driven proxy-target-class=\"true\"/>\n"
},
{
"answer_id": 3645511,
"author": "Boris Kirzner",
"author_id": 421113,
"author_profile": "https://Stackoverflow.com/users/421113",
"pm_score": 0,
"selected": false,
"text": "DefaultAnnotationHandlerMapping#determineUrlsForHandler() ListableBeanFactory#findAnnotationOnBean @RequestMapping @Controller AnnotationUtils#findAnnotation"
},
{
"answer_id": 13029177,
"author": "Kieran",
"author_id": 314901,
"author_profile": "https://Stackoverflow.com/users/314901",
"pm_score": 3,
"selected": false,
"text": "@Controller\n@RequestMapping(value = \"/secure/exhibitor\")\npublic interface ExhibitorController {\n\n @RequestMapping(value = \"/{id}\")\n void exhibitor(@PathVariable(\"id\") Long id);\n}\n\n@Controller\npublic class ExhibitorControllerImpl implements ExhibitorController {\n\n @Secured({\"ROLE_EXHIBITOR\"})\n @Transactional(readOnly = true)\n @Override\n public void exhibitor(final Long id) {\n\n }\n}\n"
},
{
"answer_id": 36590758,
"author": "Amir",
"author_id": 2260172,
"author_profile": "https://Stackoverflow.com/users/2260172",
"pm_score": 3,
"selected": false,
"text": "@Configuration\n@ComponentScan(\"org.foo.controller.*\")\n@EnableAspectJAutoProxy(proxyTargetClass=true)\npublic class AppConfig { ...}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9955/"
] |
154,059
|
<p>Is there a <code>string.Empty</code> in JavaScript, or is it just a case of checking for <code>""</code>?</p>
|
[
{
"answer_id": 154068,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 13,
"selected": true,
"text": "if (strValue) {\n // strValue was non-empty string, true, 42, Infinity, [], ...\n}\n if (!strValue) {\n // strValue was empty string, false, 0, null, undefined, ...\n}\n \"\" === if (strValue === \"\") {\n // strValue was empty string\n}\n !== if (strValue !== \"\") {\n // strValue was not an empty string\n}\n"
},
{
"answer_id": 154073,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 5,
"selected": false,
"text": "strVar == \"\""
},
{
"answer_id": 154161,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 5,
"selected": false,
"text": "var s; // undefined\nvar s = \"\"; // \"\"\ns.length // 0\n length \"\""
},
{
"answer_id": 154520,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 7,
"selected": false,
"text": "str.Empty if (!str.length) { ...\n"
},
{
"answer_id": 155525,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 7,
"selected": false,
"text": "if(str.replace(/\\s/g,\"\") == \"\"){\n}\n"
},
{
"answer_id": 2263817,
"author": "jmc734",
"author_id": 273208,
"author_profile": "https://Stackoverflow.com/users/273208",
"pm_score": 3,
"selected": false,
"text": "if (str == \"\") {\n //Do Something\n}\nelse {\n //Do Something Else\n}\n"
},
{
"answer_id": 2944306,
"author": "oem",
"author_id": 354687,
"author_profile": "https://Stackoverflow.com/users/354687",
"pm_score": 4,
"selected": false,
"text": "if((/^\\s*$/).test(str)) { }\n"
},
{
"answer_id": 3215653,
"author": "Jet",
"author_id": 348008,
"author_profile": "https://Stackoverflow.com/users/348008",
"pm_score": 6,
"selected": false,
"text": "function empty(e) {\n switch (e) {\n case \"\":\n case 0:\n case \"0\":\n case null:\n case false:\n case undefined:\n return true;\n default:\n return false;\n }\n}\n\nempty(null) // true\nempty(0) // true\nempty(7) // false\nempty(\"\") // true\nempty((function() {\n return \"\"\n})) // false\n"
},
{
"answer_id": 3261380,
"author": "Jano González",
"author_id": 389026,
"author_profile": "https://Stackoverflow.com/users/389026",
"pm_score": 10,
"selected": false,
"text": "function isEmpty(str) {\n return (!str || str.length === 0 );\n}\n length const isEmpty = (str) => (!str?.length);\n undefined function isBlank(str) {\n return (!str || /^\\s*$/.test(str));\n}\n String String.prototype.isEmpty = function() {\n // This doesn't work the same way as the isEmpty function used \n // in the first example, it will return true for strings containing only whitespace\n return (this.length === 0 || !this.trim());\n};\nconsole.log(\"example\".isEmpty());\n"
},
{
"answer_id": 3310585,
"author": "Doug",
"author_id": 399277,
"author_profile": "https://Stackoverflow.com/users/399277",
"pm_score": 3,
"selected": false,
"text": "str.value.length == 0\n"
},
{
"answer_id": 3425761,
"author": "Muhammad Salman",
"author_id": 413269,
"author_profile": "https://Stackoverflow.com/users/413269",
"pm_score": 2,
"selected": false,
"text": "function tell()\n{\n var pass = document.getElementById('pasword').value;\n var plen = pass.length;\n\n // Now you can check if your string is empty as like\n if(plen==0)\n {\n alert('empty');\n }\n else\n {\n alert('you entered something');\n }\n}\n\n<input type='text' id='pasword' />\n"
},
{
"answer_id": 5487027,
"author": "karthick.sk",
"author_id": 683996,
"author_profile": "https://Stackoverflow.com/users/683996",
"pm_score": 9,
"selected": false,
"text": "!! if (!!str) {\n // Some code here\n}\n if (Boolean(str)) {\n // Code here\n}\n str false null undefined 0 000 \"\" false true \"0\" \" \""
},
{
"answer_id": 6203869,
"author": "Will",
"author_id": 557117,
"author_profile": "https://Stackoverflow.com/users/557117",
"pm_score": 4,
"selected": false,
"text": "function isBlank(pString) {\n if (!pString) {\n return true;\n }\n // Checks for a non-white space character\n // which I think [citation needed] is faster\n // than removing all the whitespace and checking\n // against an empty string\n return !/[^\\s]+/.test(pString);\n}\n"
},
{
"answer_id": 11552927,
"author": "mricci",
"author_id": 1452807,
"author_profile": "https://Stackoverflow.com/users/1452807",
"pm_score": 3,
"selected": false,
"text": "var obj = {};\n(!!obj.str) // Returns false\n\nobj.str = \"\";\n(!!obj.str) // Returns false\n\nobj.str = null;\n(!!obj.str) // Returns false\n"
},
{
"answer_id": 11741988,
"author": "Bikush",
"author_id": 1565905,
"author_profile": "https://Stackoverflow.com/users/1565905",
"pm_score": 4,
"selected": false,
"text": "var y = \"\\0\"; // an empty string, but has a null character\n(y === \"\") // false, testing against an empty string does not work\n(y.length === 0) // false\n(y) // true, this is also not expected\n(y.match(/^[\\s]*$/)) // false, again not wanted\n String.prototype.isNull = function(){ \n return Boolean(this.match(/^[\\0]*$/)); \n}\n...\n\"\\0\".isNull() // true\n"
},
{
"answer_id": 13942574,
"author": "dkinzer",
"author_id": 256854,
"author_profile": "https://Stackoverflow.com/users/256854",
"pm_score": 2,
"selected": false,
"text": "function TestMe() {\n if((typeof str != 'undefined') && str) {\n alert(str);\n }\n };\n\nTestMe();\n\nvar str = 'hello';\n\nTestMe();\n"
},
{
"answer_id": 14227612,
"author": "Yang Dong",
"author_id": 1129221,
"author_profile": "https://Stackoverflow.com/users/1129221",
"pm_score": 5,
"selected": false,
"text": "if (str && str.trim().length) { \n //...\n}\n"
},
{
"answer_id": 14796708,
"author": "GibboK",
"author_id": 379008,
"author_profile": "https://Stackoverflow.com/users/379008",
"pm_score": 2,
"selected": false,
"text": "var myString = 'hello'; \nif(myString.charAt(0)){\n alert('no empty');\n}\nalert('empty');\n"
},
{
"answer_id": 16446530,
"author": "Andron",
"author_id": 284602,
"author_profile": "https://Stackoverflow.com/users/284602",
"pm_score": 3,
"selected": false,
"text": "function empty(str){\n return !str || !/[^\\s]+/.test(str);\n}\n\nempty(null); // true\nempty(0); // true\nempty(7); // false\nempty(\"\"); // true\nempty(\"0\"); // false\nempty(\" \"); // true\n"
},
{
"answer_id": 16540602,
"author": "JHM",
"author_id": 1894107,
"author_profile": "https://Stackoverflow.com/users/1894107",
"pm_score": 4,
"selected": false,
"text": "function IsNullOrEmpty(value)\n{\n return (value == null || value === \"\");\n}\nfunction IsNullOrWhiteSpace(value)\n{\n return (value == null || !/\\S/.test(value));\n}\n String.IsNullOrEmpty = function (value) { ... }\n String.prototype.IsNullOrEmpty = function (value) { ... }\nvar myvar = null;\nif (1 == 2) { myvar = \"OK\"; } // Could be set\nmyvar.IsNullOrEmpty(); // Throws error\n // Helper items\nvar MyClass = function (b) { this.a = \"Hello World!\"; this.b = b; };\nMyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };\nvar z;\nvar arr = [\n// 0: Explanation for printing, 1: actual value\n ['undefined', undefined],\n ['(var) z', z],\n ['null', null],\n ['empty', ''],\n ['space', ' '],\n ['tab', '\\t'],\n ['newline', '\\n'],\n ['carriage return', '\\r'],\n ['\"\\\\r\\\\n\"', '\\r\\n'],\n ['\"\\\\n\\\\r\"', '\\n\\r'],\n ['\" \\\\t \\\\n \"', ' \\t \\n '],\n ['\" txt \\\\t test \\\\n\"', ' txt \\t test \\n'],\n ['\"txt\"', \"txt\"],\n ['\"undefined\"', 'undefined'],\n ['\"null\"', 'null'],\n ['\"0\"', '0'],\n ['\"1\"', '1'],\n ['\"1.5\"', '1.5'],\n ['\"1,5\"', '1,5'], // Valid number in some locales, not in JavaScript\n ['comma', ','],\n ['dot', '.'],\n ['\".5\"', '.5'],\n ['0', 0],\n ['0.0', 0.0],\n ['1', 1],\n ['1.5', 1.5],\n ['NaN', NaN],\n ['/\\S/', /\\S/],\n ['true', true],\n ['false', false],\n ['function, returns true', function () { return true; } ],\n ['function, returns false', function () { return false; } ],\n ['function, returns null', function () { return null; } ],\n ['function, returns string', function () { return \"test\"; } ],\n ['function, returns undefined', function () { } ],\n ['MyClass', MyClass],\n ['new MyClass', new MyClass()],\n ['empty object', {}],\n ['non-empty object', { a: \"a\", match: \"bogus\", test: \"bogus\"}],\n ['object with toString: string', { a: \"a\", match: \"bogus\", test: \"bogus\", toString: function () { return \"test\"; } }],\n ['object with toString: null', { a: \"a\", match: \"bogus\", test: \"bogus\", toString: function () { return null; } }]\n];\n"
},
{
"answer_id": 16568401,
"author": "Wab_Z",
"author_id": 1215159,
"author_profile": "https://Stackoverflow.com/users/1215159",
"pm_score": 4,
"selected": false,
"text": "!/\\S/.test(string); // Returns true if blank.\n"
},
{
"answer_id": 17439572,
"author": "Mubashar",
"author_id": 806076,
"author_profile": "https://Stackoverflow.com/users/806076",
"pm_score": 2,
"selected": false,
"text": "function isNotBlank(str) {\n return (str && /^\\s*$/.test(str));\n}\n"
},
{
"answer_id": 17652575,
"author": "Kev",
"author_id": 741657,
"author_profile": "https://Stackoverflow.com/users/741657",
"pm_score": 3,
"selected": false,
"text": "\nvar getLastChar = function (str) {\n if (str.length > 0)\n return str.charAt(str.length - 1)\n}\n\ngetLastChar('hello')\n=> \"o\"\n\ngetLastChar([0,1,2,3])\n=> TypeError: Object [object Array] has no method 'charAt'\n \nif (myVar === '')\n ...\n"
},
{
"answer_id": 18144362,
"author": "user2086641",
"author_id": 2086641,
"author_profile": "https://Stackoverflow.com/users/2086641",
"pm_score": 4,
"selected": false,
"text": "if (!str.length) {\n // Do something\n}\n"
},
{
"answer_id": 22079686,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": 5,
"selected": false,
"text": "function is_empty(x)\n{\n return ( //don't put newline after return\n (typeof x == 'undefined')\n ||\n (x == null)\n ||\n (x == false) //same as: !x\n ||\n (x.length == 0)\n ||\n (x == 0) // note this line, you might not need this. \n ||\n (x == \"\")\n ||\n (x.replace(/\\s/g,\"\") == \"\")\n ||\n (!/[^\\s]/.test(x))\n ||\n (/^\\s*$/.test(x))\n );\n}\n"
},
{
"answer_id": 22933119,
"author": "Gaurav",
"author_id": 3297388,
"author_profile": "https://Stackoverflow.com/users/3297388",
"pm_score": -1,
"selected": false,
"text": "var x =\" \";\nvar patt = /^\\s*$/g;\nisBlank = patt.test(x);\nalert(isBlank); // Is it blank or not??\nx = x.replace(/\\s*/g, \"\"); // Another way of replacing blanks with \"\"\nif (x===\"\"){\n alert(\"ya it is blank\")\n}\n"
},
{
"answer_id": 23487540,
"author": "Sazid",
"author_id": 1941132,
"author_profile": "https://Stackoverflow.com/users/1941132",
"pm_score": 3,
"selected": false,
"text": " let undefinedStr;\n if (!undefinedStr) {\n console.log(\"String is undefined\");\n }\n \n let emptyStr = \"\";\n if (!emptyStr) {\n console.log(\"String is empty\");\n }\n \n let nullStr = null;\n if (!nullStr) {\n console.log(\"String is null\");\n }"
},
{
"answer_id": 24843517,
"author": "Alban Kaperi",
"author_id": 3527794,
"author_profile": "https://Stackoverflow.com/users/3527794",
"pm_score": -1,
"selected": false,
"text": "var str = \"Hello World!\";\nif(str === ''){alert(\"THE string str is EMPTY\");}\n var str = \"Hello World!\";\nif(typeof(str) === 'string'){alert(\"This is a String\");}\n"
},
{
"answer_id": 26135702,
"author": "Josef.B",
"author_id": 1149606,
"author_profile": "https://Stackoverflow.com/users/1149606",
"pm_score": 4,
"selected": false,
"text": "function isEmpty(s){\n return !s.length; \n}\n\nfunction isBlank(s){\n return isEmpty(s.trim()); \n}\n"
},
{
"answer_id": 28699962,
"author": "Timothy Nwanwene",
"author_id": 2258599,
"author_profile": "https://Stackoverflow.com/users/2258599",
"pm_score": 4,
"selected": false,
"text": "var a; false spaces emptiness if ((a)&&(a.trim()!=''))\n{\n // if variable a is not empty do this \n}\n"
},
{
"answer_id": 30751362,
"author": "Thaddeus Albers",
"author_id": 1684480,
"author_profile": "https://Stackoverflow.com/users/1684480",
"pm_score": 2,
"selected": false,
"text": "_.isEmpty() _.isEmpty(object) _.isEmpty([1, 2, 3]); _.isEmpty({}); _.isNull(object) _.isUndefined(value) _.has(object, key)"
},
{
"answer_id": 36328062,
"author": "tfont",
"author_id": 1804013,
"author_profile": "https://Stackoverflow.com/users/1804013",
"pm_score": 4,
"selected": false,
"text": "if (!str.length) {...} function empty(str)\n{\n if (typeof str == 'undefined' || !str || str.length === 0 || str === \"\" || !/[^\\s]/.test(str) || /^\\s*$/.test(str) || str.replace(/\\s/g,\"\") === \"\")\n return true;\n else\n return false;\n}"
},
{
"answer_id": 40432585,
"author": "Agustí Sánchez",
"author_id": 791694,
"author_profile": "https://Stackoverflow.com/users/791694",
"pm_score": 3,
"selected": false,
"text": "isEmpty() if (typeof test === 'string' && test.length === 0){\n ...\n test undefined null"
},
{
"answer_id": 45728354,
"author": "Moshi",
"author_id": 1349365,
"author_profile": "https://Stackoverflow.com/users/1349365",
"pm_score": 6,
"selected": false,
"text": "{} '' null undefined true Number _.isEmpty(10) _.isEmpty(Number.MAX_VALUE) true"
},
{
"answer_id": 46616110,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 3,
"selected": false,
"text": "'' String.prototype.isEmpty = String.prototype.isEmpty || function() {\n return !(!!this.length);\n}\n '' ' ' trim() String.prototype.isEmpty = String.prototype.isEmpty || function() {\n return !(!!this.trim().length);\n}\n ''.isEmpty(); //return true\n'alireza'.isEmpty(); //return false\n"
},
{
"answer_id": 47567144,
"author": "KARTHIKEYAN.A",
"author_id": 4652706,
"author_profile": "https://Stackoverflow.com/users/4652706",
"pm_score": 3,
"selected": false,
"text": "var j = undefined;\nconsole.log((typeof j == 'undefined') ? \"true\":\"false\");\nvar j = null; \nconsole.log((j == null) ? \"true\":\"false\");\nvar j = \"\";\nconsole.log((!j) ? \"true\":\"false\");\nvar j = \"Hi\";\nconsole.log((!j) ? \"true\":\"false\");"
},
{
"answer_id": 49231174,
"author": "Imran Ahmad",
"author_id": 9908141,
"author_profile": "https://Stackoverflow.com/users/9908141",
"pm_score": 4,
"selected": false,
"text": "var isEmpty = function(data) {\n if(typeof(data) === 'object'){\n if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){\n return true;\n }else if(!data){\n return true;\n }\n return false;\n }else if(typeof(data) === 'string'){\n if(!data.trim()){\n return true;\n }\n return false;\n }else if(typeof(data) === 'undefined'){\n return true;\n }else{\n return false;\n }\n}\n console.log(isEmpty()); // true\nconsole.log(isEmpty(null)); // true\nconsole.log(isEmpty('')); // true\nconsole.log(isEmpty(' ')); // true\nconsole.log(isEmpty(undefined)); // true\nconsole.log(isEmpty({})); // true\nconsole.log(isEmpty([])); // true\nconsole.log(isEmpty(0)); // false\nconsole.log(isEmpty('Hey')); // false\n"
},
{
"answer_id": 56085096,
"author": "oviniciusfeitosa",
"author_id": 1330323,
"author_profile": "https://Stackoverflow.com/users/1330323",
"pm_score": 3,
"selected": false,
"text": "export const isEmpty = string => (!string || !string.length);\n"
},
{
"answer_id": 58447444,
"author": "Japesh",
"author_id": 9247582,
"author_profile": "https://Stackoverflow.com/users/9247582",
"pm_score": 2,
"selected": false,
"text": "(/(null|undefined|^$)/).test(null)\n (/(null|undefined|^$|^\\d+$)/).test()\n"
},
{
"answer_id": 58531070,
"author": "Davi Daniel Siepmann",
"author_id": 5535130,
"author_profile": "https://Stackoverflow.com/users/5535130",
"pm_score": 4,
"selected": false,
"text": "value === undefined || value === null || value === \"\"; if(value) 0 public static isEmpty(value: any): boolean {\n return value === undefined || value === null || value === \"\";\n}"
},
{
"answer_id": 59547575,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 6,
"selected": false,
"text": "!str == === length test replace charAt \"\" \"a\" \" \" [] {} f 0 1 NaN Infinity true false null undefined function A(str) {\n let r=1;\n if (!str)\n r=0;\n return r;\n}\n\nfunction B(str) {\n let r=1;\n if (str == \"\")\n r=0;\n return r;\n}\n\nfunction C(str) {\n let r=1;\n if (str === \"\")\n r=0;\n return r;\n}\n\nfunction D(str) {\n let r=1;\n if(!str || 0 === str.length)\n r=0;\n return r;\n}\n\nfunction E(str) {\n let r=1;\n if(!str || /^\\s*$/.test(str))\n r=0;\n return r;\n}\n\nfunction F(str) {\n let r=1;\n if(!Boolean(str))\n r=0;\n return r;\n}\n\nfunction G(str) {\n let r=1;\n if(! ((typeof str != 'undefined') && str) )\n r=0;\n return r;\n}\n\nfunction H(str) {\n let r=1;\n if(!/\\S/.test(str))\n r=0;\n return r;\n}\n\nfunction I(str) {\n let r=1;\n if (!str.length)\n r=0;\n return r;\n}\n\nfunction J(str) {\n let r=1;\n if(str.length <= 0)\n r=0;\n return r;\n}\n\nfunction K(str) {\n let r=1;\n if(str.length === 0 || !str.trim())\n r=0;\n return r;\n}\n\nfunction L(str) {\n let r=1;\n if ( str.replace(/\\s/g,\"\") == \"\")\n r=0;\n return r;\n}\n\nfunction M(str) {\n let r=1;\n if((/^\\s*$/).test(str))\n r=0;\n return r;\n}\n\n\nfunction N(str) {\n let r=1;\n if(!str || !str.trim().length)\n r=0;\n return r;\n}\n\nfunction O(str) {\n let r=1;\n if(!str || !str.trim())\n r=0;\n return r;\n}\n\nfunction P(str) {\n let r=1;\n if(!str.charAt(0))\n r=0;\n return r;\n}\n\nfunction Q(str) {\n let r=1;\n if(!str || (str.trim()==''))\n r=0;\n return r;\n}\n\nfunction R(str) {\n let r=1;\n if (typeof str == 'undefined' ||\n !str ||\n str.length === 0 ||\n str === \"\" ||\n !/[^\\s]/.test(str) ||\n /^\\s*$/.test(str) ||\n str.replace(/\\s/g,\"\") === \"\")\n\n r=0;\n return r;\n}\n\n\n\n\n// --- TEST ---\n\nconsole.log( ' \"\" \"a\" \" \" [] {} 0 1 NaN Infinity f true false null undefined ');\nlet log1 = (s,f)=> console.log(`${s}: ${f(\"\")} ${f(\"a\")} ${f(\" \")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);\nlet log2 = (s,f)=> console.log(`${s}: ${f(\"\")} ${f(\"a\")} ${f(\" \")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);\nlet log3 = (s,f)=> console.log(`${s}: ${f(\"\")} ${f(\"a\")} ${f(\" \")}`);\n\nlog1('A', A);\nlog1('B', B);\nlog1('C', C);\nlog1('D', D);\nlog1('E', E);\nlog1('F', F);\nlog1('G', G);\nlog1('H', H);\n\nlog2('I', I);\nlog2('J', J);\n\nlog3('K', K);\nlog3('L', L);\nlog3('M', M);\nlog3('N', N);\nlog3('O', O);\nlog3('P', P);\nlog3('Q', Q);\nlog3('R', R); str = \"\""
},
{
"answer_id": 60146663,
"author": "Abhishek Luthra",
"author_id": 9494420,
"author_profile": "https://Stackoverflow.com/users/9494420",
"pm_score": 4,
"selected": false,
"text": "return (!value || value == undefined || value == \"\" || value.length == 0);\n return (!value || value == undefined || value == \"\");\n return (!value || value == undefined);\n return (!value);\n return !value\n"
},
{
"answer_id": 63558697,
"author": "Ibraheem",
"author_id": 1525751,
"author_profile": "https://Stackoverflow.com/users/1525751",
"pm_score": 4,
"selected": false,
"text": "if ((str?.trim()?.length || 0) > 0) {\n // str must not be any of:\n // undefined\n // null\n // \"\"\n // \" \" or just whitespace\n}\n const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;\n\nconst isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;\n"
},
{
"answer_id": 64704021,
"author": "trn450",
"author_id": 1833999,
"author_profile": "https://Stackoverflow.com/users/1833999",
"pm_score": 3,
"selected": false,
"text": "null undefined \"\" var a = \"\"\nvar b = null\nvar c = undefined\n\nconsole.log(a || \"falsy string provided\") // prints ->\"falsy string provided\"\nconsole.log(b || \"falsy string provided\") // prints ->\"falsy string provided\"\nconsole.log(c || \"falsy string provided\") // prints ->\"falsy string provided\"\n \"\" null undefined const validStr = (str) => str ? true : false\n\nvalidStr(undefined) // returns false\nvalidStr(null) // returns false\nvalidStr(\"\") // returns false\nvalidStr(\"My String\") // returns true\n"
},
{
"answer_id": 65141412,
"author": "sean",
"author_id": 1149962,
"author_profile": "https://Stackoverflow.com/users/1149962",
"pm_score": 3,
"selected": false,
"text": "if (!str?.trim()) {\n // do something...\n}\n"
},
{
"answer_id": 65723526,
"author": "Tasos Tsournos",
"author_id": 11572155,
"author_profile": "https://Stackoverflow.com/users/11572155",
"pm_score": 2,
"selected": false,
"text": "const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0\n"
},
{
"answer_id": 68242211,
"author": "Labham Jain",
"author_id": 12009979,
"author_profile": "https://Stackoverflow.com/users/12009979",
"pm_score": 0,
"selected": false,
"text": "const checkEmpty = string => (string.trim() === \"\") || !string.trim(); checkEmpty(\"\"); // returns true.\ncheckEmpty(\"mystr\"); // returns false.\n"
},
{
"answer_id": 68880332,
"author": "CrazyStack",
"author_id": 1274273,
"author_profile": "https://Stackoverflow.com/users/1274273",
"pm_score": 2,
"selected": false,
"text": "/**\n * Will return:\n * False for: for all strings with chars\n * True for: false, null, undefined, 0, 0.0, \"\", \" \".\n *\n * @param str\n * @returns {boolean}\n */\nfunction isBlank(str){\n return (!!!str || /^\\s*$/.test(str));\n}\n\n// tests\nconsole.log(\"isBlank TRUE variants:\");\nconsole.log(isBlank(false));\nconsole.log(isBlank(undefined));\nconsole.log(isBlank(null));\nconsole.log(isBlank(0));\nconsole.log(isBlank(0.0));\nconsole.log(isBlank(\"\"));\nconsole.log(isBlank(\" \"));\n\nconsole.log(\"isBlank FALSE variants:\");\nconsole.log(isBlank(\"0\"));\nconsole.log(isBlank(\"0.0\"));\nconsole.log(isBlank(\" 0\"));\nconsole.log(isBlank(\"0 \"));\nconsole.log(isBlank(\"Test string\"));\nconsole.log(isBlank(\"true\"));\nconsole.log(isBlank(\"false\"));\nconsole.log(isBlank(\"null\"));\nconsole.log(isBlank(\"undefined\"));"
},
{
"answer_id": 69492416,
"author": "Anis KCHAOU",
"author_id": 12553922,
"author_profile": "https://Stackoverflow.com/users/12553922",
"pm_score": 3,
"selected": false,
"text": "function isEmpty(strValue)\n{\n // Test whether strValue is empty\n if (!strValue || strValue.trim() === \"\" ||\n (strValue.trim()).length === 0) {\n // Do something\n }\n}\n"
},
{
"answer_id": 69560397,
"author": "Ali Yaghoubi",
"author_id": 11662335,
"author_profile": "https://Stackoverflow.com/users/11662335",
"pm_score": 2,
"selected": false,
"text": "const str = \"\";\nreturn str || \"Hello\"\n const str = \"\";\nreturn (!!str) || \"Hello\"; // !!str is Boolean\n const str = \"\";\nreturn (+str) || \"Hello\"; // !!str is Boolean\n"
},
{
"answer_id": 69905074,
"author": "sMyles",
"author_id": 378506,
"author_profile": "https://Stackoverflow.com/users/378506",
"pm_score": 0,
"selected": false,
"text": "const v1 = 0\nconst v2 = '4'\nconst v2e = undefined\nconst v2e2 = null\nconst v3 = [1, 2, 3, 4]\nconst v3e = []\nconst v4 = true\nconst v4e = false\nconst v5 = {\n test: 'value'\n}\nconst v5e = {}\nconst v6 = 'NotEmpty'\nconst v6e = ''\n\nfunction isNumeric(n) {\n return !isNaN(parseFloat(n)) && isFinite(n)\n}\n\nfunction isEmpty(v, zeroIsEmpty = false) {\n /**\n * When doing a typeof check, null will always return \"object\" so we filter that out first\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null\n */\n if (v === null) {\n return true\n }\n\n if (v === true) {\n return false\n }\n\n if (typeof v === 'object') {\n return !Object.keys(v).length\n }\n\n if (isNumeric(v)) {\n return zeroIsEmpty ? parseFloat(v) === 0 : false\n }\n\n return !v || !v.length || v.length < 1\n}\n\nconsole.log(isEmpty(v1), isEmpty(v1, true))\nconsole.log(isEmpty(v2), isEmpty(v2e), isEmpty(v2e))\nconsole.log(isEmpty(v3), isEmpty(v3e))\nconsole.log(isEmpty(v4), isEmpty(v4e))\nconsole.log(isEmpty(v5), isEmpty(v5e))\nconsole.log(isEmpty(v6), isEmpty(v6e))"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
] |
154,075
|
<p>I have a Virtual Machine in Virtual PC 2007.</p>
<p>To start it from the desktop, I have the following command in a batch file:</p>
<pre><code>"c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch
</code></pre>
<p>But that leaves a dos prompt on the host machine until the virtual machine shuts down, and I exit out of the Virtual PC console. That's annoying.</p>
<p>So I changed my command to use the START command, instead:</p>
<pre><code>start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch
</code></pre>
<p>But it chokes on the parameters passed into Virtual PC.</p>
<p><code>START /?</code> indicates that parameters do indeed go in that location. Has anyone used START to launch a program with multiple command-line arguments?</p>
|
[
{
"answer_id": 154083,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": -1,
"selected": false,
"text": "start \"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe\" \"-pc MY-PC -launch\"\n"
},
{
"answer_id": 154087,
"author": "Mark Allen",
"author_id": 5948,
"author_profile": "https://Stackoverflow.com/users/5948",
"pm_score": -1,
"selected": false,
"text": "start \"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe -pc MY-PC -launch\"\n"
},
{
"answer_id": 154090,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 10,
"selected": true,
"text": "start \"\" \"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe\" -pc MY-PC -launch\n"
},
{
"answer_id": 154104,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 4,
"selected": false,
"text": "\"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe\" -pc \"MY-PC\" -launch\n"
},
{
"answer_id": 11274735,
"author": "ghostdog21",
"author_id": 1493094,
"author_profile": "https://Stackoverflow.com/users/1493094",
"pm_score": 2,
"selected": false,
"text": "cd \"c:\\program files\\Microsoft Virtual PC\"\n start Virtual~1.exe -pc MY-PC -launch\n ~1 exe \"Virtual\" \"Virtual PC.exe\" \"Virtual PC1.exe\" Virtual~1.exe Virtual~2.exe"
},
{
"answer_id": 14842307,
"author": "Mrbios",
"author_id": 2066341,
"author_profile": "https://Stackoverflow.com/users/2066341",
"pm_score": 3,
"selected": false,
"text": "/D\"Path\" /D start /D \"C:\\Program Files\\Internet Explorer\\\" IEXPLORE.EXE\n start /D \"TITLE\" \"C:\\Program Files\\Internet Explorer\\\" IEXPLORE.EXE\n start /D \"TITLE\" \"C:\\Program Files\\Internet Explorer\\\" IEXPLORE.EXE www.bing.com\n /D start /D \"TITLE\" \"C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE\"\n /D"
},
{
"answer_id": 17140965,
"author": "Rafael Pereira",
"author_id": 2492168,
"author_profile": "https://Stackoverflow.com/users/2492168",
"pm_score": -1,
"selected": false,
"text": "start \"path\" CD\\\nCD Program Files\nCD Microsoft Virtual PC\nstart VirtualPC.exe\ntimeout 2\nexit\n"
},
{
"answer_id": 30354779,
"author": "BitDreamer",
"author_id": 4921154,
"author_profile": "https://Stackoverflow.com/users/4921154",
"pm_score": 0,
"selected": false,
"text": "start \"some valid command with spaces\"\n"
},
{
"answer_id": 35458436,
"author": "Mack",
"author_id": 2429821,
"author_profile": "https://Stackoverflow.com/users/2429821",
"pm_score": 1,
"selected": false,
"text": "start \"parameter\" \"C:\\test\\test1.exe\" -pc My Name-PC -launch start \"\" \"C:\\test\\test1.exe\" -pc My Name-PC -launch start \"\" \"H:\\test\\test1.exe\" -pc My Name-PC -launch"
},
{
"answer_id": 37229957,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": -1,
"selected": false,
"text": "/b start /b \"\" \"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe\" -pc \"MY-PC\" -launch\n"
},
{
"answer_id": 56447305,
"author": "JustAnotherMikhail",
"author_id": 11599952,
"author_profile": "https://Stackoverflow.com/users/11599952",
"pm_score": 2,
"selected": false,
"text": "Call \"\\\\Path To Program\\Program.exe\" <parameters>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
154,078
|
<p>When I open a file in eclipse it shows with the improper line spacing showing an extra line break between every line. When I open the file with notepad or wordpad it doesn't show these extra line breaks that only eclipse shows. How do I get eclipse to read these files like notepad and wordpad without those line breaks?</p>
<p>-edit: I don't have this problem with all files but only a select few where I have made local changes > uploaded them to our sun station > then pulled those files back to my local workstation for future modifications.</p>
|
[
{
"answer_id": 154125,
"author": "Nate",
"author_id": 12779,
"author_profile": "https://Stackoverflow.com/users/12779",
"pm_score": 3,
"selected": false,
"text": "File -> Convert Line Delimiters To..."
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5831/"
] |
154,079
|
<p>I have a number of RGBA pixels, each of them has an alpha component.</p>
<p>So I have a list of pixels: (<em>p0 p1 p2 p3 p4 ... pn</em>) where p_0_ is the front pixel and p_n_ is the farthest (at the back).</p>
<p>The last (or any) pixel is not necessary opaque, so the resulting blended pixel can be somehow transparent also.
I'm blending from the beginning of the list to the end, not vice-versa (yes, it is raytracing). So if the result at any moment becomes opaque enough I can stop with correct enough result.
I'll apply the blending algorithm in this way: ((((<em>p0</em> @ <em>p1</em>) @ <em>p2</em>) @ <em>p3</em>) ... )</p>
<p>Can anyone suggest me a correct blending formula not only for R, G and B, but for A component also?</p>
<p><strong>UPD</strong>: I wonder how is it possible that for determined process of blending colors we can have many formulas? Is it some kind of aproximation? This looks crazy, as for me: formulas are not so different that we really gain efficiency or optimization. Can anyone clarify this?</p>
|
[
{
"answer_id": 154108,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 2,
"selected": false,
"text": "lightr=lightg=lightb=0 lightleft=1 lightr += lightleft*r*(1-a)\nlightg += lightleft*g*(1-a)\nlightb += lightleft*b*(1-a)\nlightleft *= 1-a;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514/"
] |
154,089
|
<p>Anyone know how to programmatically mute the Windows XP Volume using C#?</p>
|
[
{
"answer_id": 154128,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": false,
"text": "private const int APPCOMMAND_VOLUME_MUTE = 0x80000;\nprivate const int WM_APPCOMMAND = 0x319;\n\n[DllImport(\"user32.dll\")]\npublic static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);\n SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr) APPCOMMAND_VOLUME_MUTE);\n"
},
{
"answer_id": 12534509,
"author": "Mike de Klerk",
"author_id": 1567665,
"author_profile": "https://Stackoverflow.com/users/1567665",
"pm_score": 3,
"selected": false,
"text": "try\n{\n //Instantiate an Enumerator to find audio devices\n NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator();\n //Get all the devices, no matter what condition or status\n NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All);\n //Loop through all devices\n foreach (NAudio.CoreAudioApi.MMDevice dev in DevCol)\n {\n try\n {\n //Show us the human understandable name of the device\n System.Diagnostics.Debug.Print(dev.FriendlyName);\n //Mute it\n dev.AudioEndpointVolume.Mute = true;\n }\n catch (Exception ex)\n {\n //Do something with exception when an audio endpoint could not be muted\n }\n }\n}\ncatch (Exception ex)\n{\n //When something happend that prevent us to iterate through the devices\n}\n"
},
{
"answer_id": 21510757,
"author": "Aleks",
"author_id": 3258422,
"author_profile": "https://Stackoverflow.com/users/3258422",
"pm_score": 2,
"selected": false,
"text": "void SetPlayerMute(int playerMixerNo, bool value)\n{\n Mixer mx = new Mixer();\n mx.MixerNo = playerMixerNo;\n DestinationLine dl = mx.GetDestination(Mixer.Playback);\n if (dl != null)\n {\n foreach (MixerControl ctrl in dl.Controls)\n {\n if (ctrl is MixerMuteControl)\n {\n ((MixerMuteControl)ctrl).Value = (value) ? 1 : 0;\n break;\n }\n }\n }\n}\n"
},
{
"answer_id": 64412819,
"author": "J. Andersen",
"author_id": 7048651,
"author_profile": "https://Stackoverflow.com/users/7048651",
"pm_score": 0,
"selected": false,
"text": "using (var enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator())\n{\n foreach (var device in enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.DeviceState.Active))\n {\n if (device.AudioEndpointVolume?.HardwareSupport.HasFlag(NAudio.CoreAudioApi.EEndpointHardwareSupport.Mute) == true)\n {\n Console.WriteLine(device.FriendlyName);\n device.AudioEndpointVolume.Mute = false;\n }\n }\n}\n"
},
{
"answer_id": 70971045,
"author": "Guest",
"author_id": 18109606,
"author_profile": "https://Stackoverflow.com/users/18109606",
"pm_score": -1,
"selected": false,
"text": "CoreAudioDevice defaultPlaybackDevice = new \nCoreAudioController().DefaultPlaybackDevice; \n if (!defaultPlaybackDevice.IsMuted)\n defaultPlaybackDevice.ToggleMute();\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316/"
] |
154,097
|
<p>I've switched computers a few times recently, and somewhere along the way I lost my .emacs. I'm trying to build it up again, but while I'm at it, I thought I'd pick up other good configurations that other people use.</p>
<p>So, if you use Emacs, what's in <i>your</i> .emacs?</p>
<p>Mine is pretty barren right now, containing only:</p>
<ol>
<li>Global font-lock-mode! <code>(global-font-lock-mode 1)</code></li>
<li>My personal preferences with respect to indentation, tabs, and spaces.</li>
<li>Use cperl-mode instead of perl-mode.</li>
<li>A shortcut for compilation.</li>
</ol>
<p>What do you think is useful?</p>
|
[
{
"answer_id": 154105,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 1,
"selected": false,
"text": "(put 'erase-buffer 'disabled nil)\n(put 'downcase-region 'disabled nil)\n(set-variable 'visible-bell t)\n(set-variable 'tool-bar-mode nil)\n(set-variable 'menu-bar-mode nil)\n\n(setq load-path (cons (expand-file-name \"/usr/share/doc/git-core/contrib/emacs\") load-path))\n (require 'vc-git)\n (when (featurep 'vc-git) (add-to-list 'vc-handled-backends 'git))\n (require 'git)\n (autoload 'git-blame-mode \"git-blame\"\n \"Minor mode for incremental blame for Git.\" t)\n"
},
{
"answer_id": 154146,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 3,
"selected": false,
"text": "(global-set-key [(control \\,)] 'goto-line)\n(global-set-key [(control \\.)] 'call-last-kbd-macro)\n(global-set-key [(control tab)] 'indent-region)\n(global-set-key [(control j)] 'join-line)\n(global-set-key [f1] 'man)\n(global-set-key [f2] 'igrep-find)\n(global-set-key [f3] 'isearch-forward)\n(global-set-key [f4] 'next-error)\n(global-set-key [f5] 'gdb)\n(global-set-key [f6] 'compile)\n(global-set-key [f7] 'recompile)\n(global-set-key [f8] 'shell)\n(global-set-key [f9] 'find-next-matching-tag)\n(global-set-key [f11] 'list-buffers)\n(global-set-key [f12] 'shell)\n ;; Use C++ mode for .h files (instead of plain-old C mode)\n(setq auto-mode-alist (cons '(\"\\\\.h$\" . c++-mode) auto-mode-alist))\n\n;; Use python-mode for SCons files\n(setq auto-mode-alist (cons '(\"SConstruct\" . python-mode) auto-mode-alist))\n(setq auto-mode-alist (cons '(\"SConscript\" . python-mode) auto-mode-alist))\n\n;; Parse CppUnit failure reports in compilation-mode\n(require 'compile)\n(setq compilation-error-regexp-alist\n (cons '(\"\\\\(!!!FAILURES!!!\\nTest Results:\\nRun:[^\\n]*\\n\\n\\n\\\\)?\\\\([0-9]+\\\\)) test: \\\\([^(]+\\\\)(F) line: \\\\([0-9]+\\\\) \\\\([^ \\n]+\\\\)\" 5 4)\n compilation-error-regexp-alist))\n\n;; Enable cmake-mode from http://www.cmake.org/Wiki/CMake_Emacs_mode_patch_for_comment_formatting\n(require 'cmake-mode)\n(setq auto-mode-alist\n (append '((\"CMakeLists\\\\.txt\\\\'\" . cmake-mode)\n (\"\\\\.cmake\\\\'\" . cmake-mode))\n auto-mode-alist))\n\n;; \"M-x reload-buffer\" will revert-buffer without requiring confirmation\n(defun reload-buffer ()\n \"revert-buffer without confirmation\"\n (interactive)\n (revert-buffer t t))\n"
},
{
"answer_id": 154980,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 3,
"selected": false,
"text": "(defadvice show-paren-function (after show-matching-paren-offscreen\n activate)\n \"If the matching paren is offscreen, show the matching line in the \necho area. Has no effect if the character before point is not of \nthe syntax class ')'.\"\n (interactive)\n (let ((matching-text nil))\n ;; Only call `blink-matching-open' if the character before point \n ;; is a close parentheses type character. Otherwise, there's not \n ;; really any point, and `blink-matching-open' would just echo \n ;; \"Mismatched parentheses\", which gets really annoying. \n (if (char-equal (char-syntax (char-before (point))) ?\\))\n (setq matching-text (blink-matching-open)))\n (if (not (null matching-text))\n (message matching-text))))\n\n;;;;;;;;;;;;;;;\n;; UTF-8\n;;;;;;;;;;;;;;;;;;;;\n;; set up unicode\n(prefer-coding-system 'utf-8)\n(set-default-coding-systems 'utf-8)\n(set-terminal-coding-system 'utf-8)\n(set-keyboard-coding-system 'utf-8)\n;; This from a japanese individual. I hope it works.\n(setq default-buffer-file-coding-system 'utf-8)\n;; From Emacs wiki\n(setq x-select-request-type '(UTF8_STRING COMPOUND_TEXT TEXT STRING))\n;; Wwindows clipboard is UTF-16LE \n(set-clipboard-coding-system 'utf-16le-dos)\n\n\n(defun jonnay-timestamp ()\n \"Spit out the current time\"\n (interactive)\n (insert (format-time-string \"%Y-%m-%d\")))\n\n(defun jonnay-sign ()\n \"spit out my name, email and the current time\"\n (interactive)\n (insert \"-- Jonathan Arkell (jonathana@criticalmass.com)\")\n (jonnay-timestamp))\n\n\n;; Cygwin requires some seriosu setting up to work the way i likes it\n(message \"Setting up Cygwin...\")\n(let* ((cygwin-root \"c:\")\n (cygwin-bin (concat cygwin-root \"/bin\"))\n (gambit-bin \"/usr/local/Gambit-C/4.0b22/bin/\")\n (snow-bin \"/usr/local/snow/current/bin\")\n (mysql-bin \"/wamp/bin/mysql/mysql5.0.51a/bin/\"))\n (setenv \"PATH\" (concat cygwin-bin \";\" ;\n snow-bin \";\" \n gambit-bin \";\"\n mysql-bin \";\"\n \".;\") \n (getenv \"PATH\"))\n (setq exec-path (cons cygwin-bin exec-path)))\n\n(setq shell-file-name \"bash\")\n(setq explicit-shell-file-name \"bash\")\n\n(require 'cygwin-mount)\n(cygwin-mount-activate)\n(message \"Setting up Cygwin...Done\")\n\n\n; Completion isn't perfect, but close\n(defun my-shell-setup ()\n \"For Cygwin bash under Emacs 20+\"\n (setq comint-scroll-show-maximum-output 'this)\n (setq comint-completion-addsuffix t)\n (setq comint-eol-on-send t)\n (setq w32-quote-process-args ?\\\")\n (make-variable-buffer-local 'comint-completion-addsuffix))\n\n(setq shell-mode-hook 'my-shell-setup)\n(add-hook 'emacs-startup-hook 'cygwin-shell)\n\n\n; Change how home key works\n(global-set-key [home] 'beginning-or-indentation)\n(substitute-key-definition 'beginning-of-line 'beginning-or-indentation global-map)\n\n\n(defun yank-and-down ()\n \"Yank the text and go down a line.\"\n (interactive)\n (yank)\n (exchange-point-and-mark)\n (next-line))\n\n(defun kill-syntax (&optional arg)\n \"Kill ARG sets of syntax characters after point.\"\n (interactive \"p\")\n (let ((arg (or arg 1))\n (inc (if (and arg (< arg 0)) 1 -1))\n (opoint (point)))\n (while (not (= arg 0))\n (if (> arg 0)\n (skip-syntax-forward (string (char-syntax (char-after))))\n (skip-syntax-backward (string (char-syntax (char-before)))))\n (setq arg (+ arg inc)))\n (kill-region opoint (point))))\n\n(defun kill-syntax-backward (&optional arg)\n \"Kill ARG sets of syntax characters preceding point.\"\n (interactive \"p\")\n (kill-syntax (- 0 (or arg 1))))\n\n(global-set-key [(control shift y)] 'yank-and-down)\n(global-set-key [(shift backspace)] 'kill-syntax-backward)\n(global-set-key [(shift delete)] 'kill-syntax)\n\n\n(defun insert-file-name (arg filename)\n \"Insert name of file FILENAME into buffer after point.\n Set mark after the inserted text.\n\n Prefixed with \\\\[universal-argument], expand the file name to\n its fully canocalized path.\n\n See `expand-file-name'.\"\n ;; Based on insert-file in Emacs -- ashawley 2008-09-26\n (interactive \"*P\\nfInsert file name: \")\n (if arg\n (insert (expand-file-name filename))\n (insert filename)))\n\n(defun kill-ring-save-filename ()\n \"Copy the current filename to the kill ring\"\n (interactive)\n (kill-new (buffer-file-name)))\n\n(defun insert-file-name ()\n \"Insert the name of the current file.\"\n (interactive)\n (insert (buffer-file-name)))\n\n(defun insert-directory-name ()\n \"Insert the name of the current directory\"\n (interactive)\n (insert (file-name-directory (buffer-file-name))))\n\n(defun jonnay-toggle-debug ()\n \"Toggle debugging by toggling icicles, and debug on error\"\n (interactive)\n (toggle-debug-on-error)\n (icicle-mode))\n\n\n(defvar programming-modes\n '(emacs-lisp-mode scheme-mode lisp-mode c-mode c++-mode \n objc-mode latex-mode plain-tex-mode java-mode\n php-mode css-mode js2-mode nxml-mode nxhtml-mode)\n \"List of modes related to programming\")\n\n; Text-mate style indenting\n(defadvice yank (after indent-region activate)\n (if (member major-mode programming-modes)\n (indent-region (region-beginning) (region-end) nil)))\n"
},
{
"answer_id": 156998,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 4,
"selected": false,
"text": "yes no y n (fset 'yes-or-no-p 'y-or-n-p)\n (setq inhibit-startup-echo-area-message t)\n(setq inhibit-startup-message t)\n (defun rename-file-and-buffer (new-name)\n \"Renames both current buffer and file it's visiting to NEW-NAME.\"\n (interactive \"sNew name: \")\n (let ((name (buffer-name))\n (filename (buffer-file-name)))\n (if (not filename)\n (message \"Buffer '%s' is not visiting a file!\" name)\n (if (get-buffer new-name)\n (message \"A buffer named '%s' already exists!\" new-name)\n (progn\n (rename-file name new-name 1)\n (rename-buffer new-name)\n (set-visited-file-name new-name)\n (set-buffer-modified-p nil))))))\n"
},
{
"answer_id": 158057,
"author": "Jason Dufair",
"author_id": 20540,
"author_profile": "https://Stackoverflow.com/users/20540",
"pm_score": 5,
"selected": false,
"text": ";; real lisp hackers use the lambda character\n;; courtesy of stefan monnier on c.l.l\n(defun sm-lambda-mode-hook ()\n (font-lock-add-keywords\n nil `((\"\\\\<lambda\\\\>\"\n (0 (progn (compose-region (match-beginning 0) (match-end 0)\n ,(make-char 'greek-iso8859-7 107))\n nil))))))\n(add-hook 'emacs-lisp-mode-hook 'sm-lambda-mode-hook)\n(add-hook 'lisp-interactive-mode-hook 'sm-lamba-mode-hook)\n(add-hook 'scheme-mode-hook 'sm-lambda-mode-hook)\n (global-set-key \"^Cr\" '(λ () (interactive) (revert-buffer t t nil)))\n"
},
{
"answer_id": 158641,
"author": "Sard",
"author_id": 9831,
"author_profile": "https://Stackoverflow.com/users/9831",
"pm_score": 3,
"selected": false,
"text": "(defun moz-connect()\n (interactive)\n (make-comint \"moz-buffer\" (cons \"127.0.0.1\" \"4242\"))\n (global-set-key \"\\C-x\\C-g\" '(lambda () \n (interactive)\n (save-buffer)\n (comint-send-string \"*moz-buffer*\" \"this.BrowserReload()\\n\"))))\n"
},
{
"answer_id": 172736,
"author": "jamesnvc",
"author_id": 7699,
"author_profile": "https://Stackoverflow.com/users/7699",
"pm_score": 4,
"selected": false,
"text": "mode-configs.el keys.el"
},
{
"answer_id": 214586,
"author": "Adam Crume",
"author_id": 25498,
"author_profile": "https://Stackoverflow.com/users/25498",
"pm_score": 3,
"selected": false,
"text": "(transient-mark-mode 1) ; makes the region visible\n(line-number-mode 1) ; makes the line number show up\n(column-number-mode 1) ; makes the column number show up\n"
},
{
"answer_id": 214592,
"author": "Chris Dolan",
"author_id": 14783,
"author_profile": "https://Stackoverflow.com/users/14783",
"pm_score": 2,
"selected": false,
"text": "(setq locale-coding-system 'utf-8)\n(set-terminal-coding-system 'utf-8)\n(set-keyboard-coding-system 'utf-8)\n(set-selection-coding-system 'utf-8)\n(prefer-coding-system 'utf-8)\n"
},
{
"answer_id": 549856,
"author": "justinhj",
"author_id": 53120,
"author_profile": "https://Stackoverflow.com/users/53120",
"pm_score": 1,
"selected": false,
"text": "(require 'webjump)\n(global-set-key [f2] 'webjump)\n(setq webjump-sites\n (append '(\n (\"Reddit Search\" .\n [simple-query \"www.reddit.com\" \"http://www.reddit.com/search?q=\" \"\"])\n (\"Google Image Search\" .\n [simple-query \"images.google.com\" \"images.google.com/images?hl=en&q=\" \"\"])\n (\"Flickr Search\" .\n [simple-query \"www.flickr.com\" \"flickr.com/search/?q=\" \"\"])\n (\"Astar algorithm\" . \n \"http://www.heyes-jones.com/astar\")\n )\n webjump-sample-sites))\n (setq visible-bell t) ; no beeping\n\n(setq transient-mark-mode t) ; visually show region\n\n(setq line-number-mode t) ; show line numbers\n\n(setq global-font-lock-mode 1) ; everything should use fonts\n\n(setq font-lock-maximum-decoration t)\n (if (fboundp 'scroll-bar-mode) (scroll-bar-mode -1))\n (if (fboundp 'tool-bar-mode) (tool-bar-mode -1))\n (if (fboundp 'menu-bar-mode) (menu-bar-mode -1)))\n"
},
{
"answer_id": 750502,
"author": "viam0Zah",
"author_id": 73603,
"author_profile": "https://Stackoverflow.com/users/73603",
"pm_score": 2,
"selected": false,
"text": "custom-file"
},
{
"answer_id": 845311,
"author": "Borbus",
"author_id": 104107,
"author_profile": "https://Stackoverflow.com/users/104107",
"pm_score": 4,
"selected": false,
"text": ";; keep backup files neatly out of the way in .~/\n(setq backup-directory-alist '((\".\" . \".~\")))\n ;; uniquify changes conflicting buffer names from file<2> etc\n(require 'uniquify)\n(setq uniquify-buffer-name-style 'reverse)\n(setq uniquify-separator \"/\")\n(setq uniquify-after-kill-buffer-p t) ; rename after killing uniquified\n(setq uniquify-ignore-buffers-re \"^\\\\*\") ; don't muck with special buffers\n"
},
{
"answer_id": 845381,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 0,
"selected": false,
"text": "vimpulse.el whitespace.el yasnippet textmate.el newsticker.el (add-to-list 'load-path (concat dotfiles-dir \"/vendor/\"))\n\n;; Snippets\n(add-to-list 'load-path \"~/.emacs.d/vendor/yasnippet/\")\n(require 'yasnippet)\n\n(yas/initialize)\n(yas/load-directory \"~/.emacs.d/vendor/yasnippet/snippets\")\n\n;; TextMate module\n(require 'textmate)\n(textmate-mode 'on)\n\n;; Whitespace module\n(require 'whitespace)\n(add-hook 'ruby-mode-hook 'whitespace-mode)\n(add-hook 'python-mode-hook 'whitespace-mode)\n\n;; Misc\n(flyspell-mode 'on)\n(setq viper-mode t)\n(require 'viper)\n(require 'vimpulse)\n\n;; IM\n(eval-after-load 'rcirc '(require 'rcirc-color))\n(setq rcirc-default-nick \"_dbr\")\n(setq rcirc-default-user-name \"_dbr\")\n(setq rcirc-default-user-full-name \"_dbr\")\n\n(require 'jabber)\n\n;;; Google Talk account\n(custom-set-variables\n '(jabber-connection-type (quote ssl))\n '(jabber-network-server \"talk.google.com\")\n '(jabber-port 5223)\n '(jabber-server \"mysite.tld\")\n '(jabber-username \"myusername\"))\n\n;; Theme\n(color-theme-zenburn)\n\n;; Key bindings\n(global-set-key (kbd \"M-z\") 'undo)\n(global-set-key (kbd \"M-s\") 'save-buffer)\n(global-set-key (kbd \"M-S-z\") 'redo)\n"
},
{
"answer_id": 2277001,
"author": "paprika",
"author_id": 61815,
"author_profile": "https://Stackoverflow.com/users/61815",
"pm_score": 2,
"selected": false,
"text": "~/.elisp ~/.emacs ~/.elisp/dotemacs ~/.elisp/cfg/init require provide (provide 'my-ibuffer-cfg) my- init.el ;; byte compile config file if changed\n(add-hook 'after-save-hook\n '(lambda ()\n (when (string-match\n (concat (expand-file-name \"~/.elisp/cfg/\") \".*\\.el$\")\n buffer-file-name)\n (byte-compile-file buffer-file-name))))\n ~/.elisp ~/.elisp/todo.org ~/.elisp/dotemacs ~/.emacs ~/.elisp/cfg/init ~/.elisp/cfg ~/.elisp/modes ~/.elisp/packages ~/.elisp/packages/foobar-0.1.3 lisp info ~/.elisp/packages/foobar ~/.elisp/packages/foobar.installation"
},
{
"answer_id": 2643094,
"author": "SurvivalMachine",
"author_id": 105466,
"author_profile": "https://Stackoverflow.com/users/105466",
"pm_score": 2,
"selected": false,
"text": "(defun insertdate ()\n (interactive)\n (insert (format-time-string \"%Y-%m-%d\")))\n\n(global-set-key [(f5)] 'insertdate)\n (defun createclass ()\n (interactive)\n (setq classname (file-name-sans-extension (file-name-nondirectory buffer-file-name)))\n (insert \n\"/**\n * \" classname\".h \n *\n * Author: Your Mom\n * Modified: \" (format-time-string \"%Y-%m-%d\") \"\n * Licence: GNU GPL\n */\n#ifndef \"(upcase classname)\"\n#define \"(upcase classname)\"\n\nclass \" classname \"\n{\n public:\n \"classname\"();\n ~\"classname\"();\n\n private:\n\n};\n#endif\n\"))\n (setq skeleton-pair t)\n(setq skeleton-pair-on-word t)\n(global-set-key (kbd \"[\") 'skeleton-pair-insert-maybe)\n(global-set-key (kbd \"(\") 'skeleton-pair-insert-maybe)\n(global-set-key (kbd \"{\") 'skeleton-pair-insert-maybe) \n(global-set-key (kbd \"<\") 'skeleton-pair-insert-maybe)\n"
},
{
"answer_id": 4000932,
"author": "oluies",
"author_id": 203968,
"author_profile": "https://Stackoverflow.com/users/203968",
"pm_score": 0,
"selected": false,
"text": ";; Load the ensime lisp code... http://github.com/aemoncannon/ensime\n(add-to-list 'load-path \"ENSIME_ROOT/elisp/\")\n(require 'ensime)\n;; This step causes the ensime-mode to be started whenever ;; scala-mode is started for a buffer. You may have to customize this step ;; if you're not using the standard scala mode.\n(add-hook 'scala-mode-hook 'ensime-scala-mode-hook)\n;; MINI HOWTO: ;; Open .scala file. M-x ensime (once per project)\n"
},
{
"answer_id": 10373930,
"author": "Chmouel Boudjnah",
"author_id": 145125,
"author_profile": "https://Stackoverflow.com/users/145125",
"pm_score": 0,
"selected": false,
"text": ";Down/UP the current line\n(global-set-key '[(control x) (up)] 'my-up-line)\n(global-set-key '[(control x) (down)] 'my-down-line)\n(defun my-down-line()\n (interactive)\n (let ((col (current-column)))\n (forward-line 1)\n (transpose-lines 1)\n (forward-line -1)\n (forward-char col)\n )\n )\n\n(defun my-up-line()\n (interactive)\n (let ((col (current-column)))\n (transpose-lines 1)\n (forward-line -2)\n (forward-char col)\n )\n )\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3508/"
] |
154,109
|
<p>When using the ObsoleteAtribute in .Net it gives you compiler warnings telling you that the object/method/property is obsolete and somthing else should be used. I'm currently working on a project that requires a lot of refactoring an ex-employees code. I want to write a custom attribute that I can use to mark methods or properties that will generate compiler warnings that give messages that I write. Something like this</p>
<pre class="lang-cs prettyprint-override"><code>[MyAttribute("This code sux and should be looked at")]
public void DoEverything()
{
}
</code></pre>
<pre class="lang-vb prettyprint-override"><code><MyAttribute("This code sux and should be looked at")>
Public Sub DoEverything()
End Sub
</code></pre>
<p>I want this to generate a compiler warning that says, "This code sux and should be looked at". I know how to create a custom attribute, the question is how do I cause it to generate compiler warnings in visual studio.</p>
|
[
{
"answer_id": 154120,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 6,
"selected": false,
"text": "#warning \"Do not use ABC, which is deprecated. Use XYZ instead.\"\n #pragma message ( \"text\" )\n"
},
{
"answer_id": 154254,
"author": "Pablo Fernandez",
"author_id": 7595,
"author_profile": "https://Stackoverflow.com/users/7595",
"pm_score": 7,
"selected": false,
"text": "[Obsolete(\"Should be refactored\")]\npublic class MustRefactor: System.Attribute{}\n public class User\n{\n private String userName;\n\n [TooManyArgs] // Will show warning: Try removing some arguments\n public User(String userName)\n {\n this.userName = userName; \n }\n\n public String UserName\n {\n get { return userName; }\n }\n [MustRefactor] // will show warning: Refactor is needed Here\n public override string ToString()\n {\n return \"User: \" + userName;\n }\n}\n[Obsolete(\"Refactor is needed Here\")]\npublic class MustRefactor : System.Attribute\n{\n\n}\n[Obsolete(\"Try removing some arguments\")]\npublic class TooManyArgs : System.Attribute\n{\n\n}\n"
},
{
"answer_id": 154622,
"author": "Ted Elliott",
"author_id": 16501,
"author_profile": "https://Stackoverflow.com/users/16501",
"pm_score": 6,
"selected": false,
"text": "public void DoEverything() {\n #warning \"This code sucks\"\n}\n"
},
{
"answer_id": 2038833,
"author": "Tomasz Modelski",
"author_id": 195922,
"author_profile": "https://Stackoverflow.com/users/195922",
"pm_score": 3,
"selected": false,
"text": "[Obsolete(\"Mapping ToDo\")]\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]\npublic class MappingToDo : System.Attribute\n{\n public string Comment = \"\";\n\n public MappingToDo(string comment)\n {\n Comment = comment;\n }\n\n public MappingToDo()\n {}\n}\n [MappingToDo(\"Some comment\")]\npublic class MembershipHour : Entity\n{\n // .....\n}\n"
},
{
"answer_id": 26089913,
"author": "user4089256",
"author_id": 4089256,
"author_profile": "https://Stackoverflow.com/users/4089256",
"pm_score": 3,
"selected": false,
"text": "//TODO: This code sux and should be looked at\npublic class SuckyClass(){\n //TODO: Do something really sucky here!\n}\n"
},
{
"answer_id": 45419471,
"author": "johnny 5",
"author_id": 1938988,
"author_profile": "https://Stackoverflow.com/users/1938988",
"pm_score": 2,
"selected": false,
"text": "IdeMessage [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]\npublic class IDEMessageAttribute : Attribute\n{\n public string Message;\n\n public IDEMessageAttribute(string message);\n}\n public override void Initialize(AnalysisContext context)\n{\n context.RegisterSyntaxNodeAction(AnalyzerInvocation, SyntaxKind.InvocationExpression);\n}\n\nprivate static void AnalyzerInvocation(SyntaxNodeAnalysisContext context)\n{\n var invocation = (InvocationExpressionSyntax)context.Node;\n\n var methodDeclaration = (context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken).Symbol as IMethodSymbol);\n\n //There are several reason why this may be null e.g invoking a delegate\n if (null == methodDeclaration)\n {\n return;\n }\n\n var methodAttributes = methodDeclaration.GetAttributes();\n var attributeData = methodAttributes.FirstOrDefault(attr => IsIDEMessageAttribute(context.SemanticModel, attr, typeof(IDEMessageAttribute)));\n if(null == attributeData)\n {\n return;\n }\n\n var message = GetMessage(attributeData); \n var diagnostic = Diagnostic.Create(Rule, invocation.GetLocation(), methodDeclaration.Name, message);\n context.ReportDiagnostic(diagnostic);\n}\n\nstatic bool IsIDEMessageAttribute(SemanticModel semanticModel, AttributeData attribute, Type desiredAttributeType)\n{\n var desiredTypeNamedSymbol = semanticModel.Compilation.GetTypeByMetadataName(desiredAttributeType.FullName);\n\n var result = attribute.AttributeClass.Equals(desiredTypeNamedSymbol);\n return result;\n}\n\nstatic string GetMessage(AttributeData attribute)\n{\n if (attribute.ConstructorArguments.Length < 1)\n {\n return \"This method is obsolete\";\n }\n\n return (attribute.ConstructorArguments[0].Value as string);\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17744/"
] |
154,112
|
<p>Without running this code, identify which <code>Foo</code> method will be called:</p>
<pre><code>class A
{
public void Foo( int n )
{
Console.WriteLine( "A::Foo" );
}
}
class B : A
{
/* note that A::Foo and B::Foo are not related at all */
public void Foo( double n )
{
Console.WriteLine( "B::Foo" );
}
}
static void Main( string[] args )
{
B b = new B();
/* which Foo is chosen? */
b.Foo( 5 );
}
</code></pre>
<p>Which method? And why? No cheating by running the code.</p>
<p>I found this puzzle on the web; I like it and I think I'm going to use it as an interview question...Opinions?</p>
<p>EDIT: I wouldn't judge a candidate on getting this wrong, I'd use it as a way to open a fuller discussion about the C# and CLR itself, so I can get a good understanding of the candidates abilities.</p>
<p><strong>Source:</strong> <a href="http://netpl.blogspot.com/2008/06/c-puzzle-no8-beginner.html" rel="noreferrer">http://netpl.blogspot.com/2008/06/c-puzzle-no8-beginner.html</a></p>
|
[
{
"answer_id": 155771,
"author": "Mike Rosenblum",
"author_id": 10429,
"author_profile": "https://Stackoverflow.com/users/10429",
"pm_score": 3,
"selected": false,
"text": "Public Class Form1\n Private Sub Button1_Click(ByVal sender As System.Object, _\n ByVal e As System.EventArgs) _\n Handles Button1.Click\n Dim b As New B\n b.Foo(5) ' A::Foo\n b.Foo(5.0) ' B::Foo\n End Sub\nEnd Class\n\nClass A\n Sub Foo(ByVal n As Integer)\n MessageBox.Show(\"A::Foo\")\n End Sub\nEnd Class\n\nClass B\n Inherits A\n\n Overloads Sub Foo(ByVal n As Double)\n MessageBox.Show(\"B::Foo\")\n End Sub\nEnd Class\n"
},
{
"answer_id": 216116,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "class Program\n{\n class P\n {}\n class Q : P\n {}\n\n class A \n { \n public void Fee(Q q)\n {\n Console.WriteLine(\"A::Fee\");\n }\n }\n\n class B : A \n { \n public void Fee(P p)\n {\n Console.WriteLine(\"B::Fee\");\n }\n }\n\n static void Main(string[] args) \n { \n B b = new B(); \n /* which Fee is chosen? */ \n\n b.Fee(new Q());\n Console.ReadKey();\n }\n}\n"
},
{
"answer_id": 1612066,
"author": "Anwar",
"author_id": 195163,
"author_profile": "https://Stackoverflow.com/users/195163",
"pm_score": 0,
"selected": false,
"text": "B::Foo"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
154,119
|
<p>This was an interview question. Given Visual Studio 2008 and an icon saved as a .PNG file, they required the image as an embedded resource and to be used as the icon within the title bar of a form.</p>
<p>I'm looking for what would have been the model answer to this question, Both (working!) code and any Visual Studio tricks. (Model answer is one that should get me the job if I meet it next time around.)</p>
<p>Specifically I don't know how to load the image once it is an embedded resource nor how to get it as the icon for the title bar.</p>
<p>As a part solution, ignoring the embedded bit, I copied the resource to the ouput directory and tried the following:-</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Icon = new Icon("Resources\\IconImage.png");
}
}
</code></pre>
<p>This failed with the error "Argument 'picture' must be a picture that can be used as a Icon."</p>
<p>I presuming that the .PNG file actually needed to be a .ICO, but I couldn't see how to make the conversion. Is this presumption correct or is there a different issue?</p>
|
[
{
"answer_id": 156118,
"author": "Silver Dragon",
"author_id": 9440,
"author_profile": "https://Stackoverflow.com/users/9440",
"pm_score": 7,
"selected": true,
"text": " public Form1()\n {\n InitializeComponent();\n Bitmap bmp = WindowsFormsApplication10.Properties.Resources.glider;\n this.Icon = Icon.FromHandle(bmp.GetHicon());\n }\n"
},
{
"answer_id": 157151,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 5,
"selected": false,
"text": "Icon.FromHandle"
},
{
"answer_id": 22994531,
"author": "dizzy.stackoverflow",
"author_id": 2506209,
"author_profile": "https://Stackoverflow.com/users/2506209",
"pm_score": 1,
"selected": false,
"text": "[System.Runtime.InteropServices.DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\nextern static bool DestroyIcon(IntPtr handle);\n\n// From http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.gethicon.aspx\nprivate Icon bitmapToIcon(Bitmap myBitmap)\n{\n // Get an Hicon for myBitmap.\n IntPtr Hicon = myBitmap.GetHicon();\n\n // Create a new icon from the handle.\n Icon newIcon = Icon.FromHandle(Hicon);\n\n return newIcon;\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22284/"
] |
154,132
|
<p>What are the most common browser compatibility issues across the major desktop browsers?</p>
<p>No dups please. Up-vote problems you've run into. I'm hoping for the list to self-sort. "IE sux" is not a pitfall, but a call for down-vote.</p>
<p>[Edit] Yes, I know it's a poll - I'm not posting answers in this to gather points - I'm actually interested in knowing what people typically run into.</p>
|
[
{
"answer_id": 155639,
"author": "Adam Franco",
"author_id": 15872,
"author_profile": "https://Stackoverflow.com/users/15872",
"pm_score": 2,
"selected": false,
"text": "function getOffsetTop (element) {\n var offset = 0;\n\n if (element.offsetTop)\n offset = offset + element.offsetTop;\n\n if (element.offsetParent)\n offset = offset + getOffsetTop(element.offsetParent); \n\n return offset;\n}\n function getOffsetTop (element) {\n var offset = 0;\n\n if (element.offsetTop)\n offset = offset + element.offsetTop;\n\n var parent = element.offsetParent;\n while (parent) {\n if (parent.offsetTop)\n offset = offset + parent.offsetTop;\n parent = parent.offsetParent;\n }\n\n return offset;\n}\n"
},
{
"answer_id": 1442530,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 1,
"selected": false,
"text": " +-------------------------------+\n |+------+ +-----------+ +------+|\n || | | | | ||\n || foo | | bar | | baz ||\n || | | | | ||\n || | | | | ||\n |+------+ +-----------+ +------+|\n +-------------------------------+\n +-------------------------------+\n |+--------+ +------------+ |\n || | | | |\n || foo | | bar | |\n || | | | |\n || | | | |\n |+--------+ +------------+ |\n |+------+ |\n || | |\n || | |\n || baz | |\n || | |\n || | |\n |+------+ |\n +-------------------------------+\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489/"
] |
154,136
|
<p>In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless <code>do while</code> loop. Here are examples.</p>
<pre><code>#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
</code></pre>
<p>I can't see what the <code>do while</code> is doing. Why not just write this without it?</p>
<pre><code>#define FOO(X) f(X); g(X)
</code></pre>
|
[
{
"answer_id": 154138,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 11,
"selected": true,
"text": "do ... while if ... else #define BAR(X) f(x); g(x)\n BAR(X); if ... else if (corge)\n BAR(corge);\nelse\n gralt();\n if (corge)\n f(corge); g(corge);\nelse\n gralt();\n if (corge)\n {f(corge); g(corge);};\nelse\n gralt();\n #define BAR(X) f(X), g(X)\n BAR if (corge)\n f(corge), g(corge);\nelse\n gralt();\n f(X) do ... while #define BAR(X) do { \\\n int i = f(X); \\\n if (i > 4) g(i); \\\n} while (0)\n do ... while if ... else if ... else if ... else if (corge)\n if (1) { f(corge); g(corge); } else;\nelse\n gralt();\n BAR do ... while"
},
{
"answer_id": 154239,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 6,
"selected": false,
"text": "#define FOO(x) f(x); g(x)\n\nif (test) FOO( baz);\n if (test) f(baz); g(baz);\n"
},
{
"answer_id": 154264,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": false,
"text": "doSomething(1) ;\nDO_SOMETHING_ELSE(2) // <== Hey? What's this?\ndoSomethingElseAgain(3) ;\n if(bIsOk)\n MY_MACRO(42) ;\n #define MY_MACRO(x) f(x) ; g(x)\n\nif(bIsOk)\n f(42) ; g(42) ; // was MY_MACRO(42) ;\n g bIsOk #define MY_MACRO(x) { f(x) ; g(x) ; }\n\nif(bIsOk)\n { f(42) ; g(42) ; } ; // was MY_MACRO(42) ;\n #define MY_MACRO(x) int i = x + 1 ; f(i) ;\n void doSomething()\n{\n int i = 25 ;\n MY_MACRO(32) ;\n}\n void doSomething()\n{\n int i = 25 ;\n int i = 32 + 1 ; f(i) ; ; // was MY_MACRO(32) ;\n}\n #define MY_MACRO(x) { int i = x + 1 ; f(i) ; }\n\nvoid doSomething()\n{\n int i = 25 ;\n { int i = 32 + 1 ; f(i) ; } ; // was MY_MACRO(32) ;\n}\n do\n{\n // code\n}\nwhile(false) ;\n #define MY_MACRO(x) \\\ndo \\\n{ \\\n const int i = x + 1 ; \\\n f(i) ; g(i) ; \\\n} \\\nwhile(false)\n\nvoid doSomething(bool bIsOk)\n{\n int i = 25 ;\n\n if(bIsOk)\n MY_MACRO(42) ;\n\n // Etc.\n}\n void doSomething(bool bIsOk)\n{\n int i = 25 ;\n\n if(bIsOk)\n do\n {\n const int i = 42 + 1 ; // was MY_MACRO(42) ;\n f(i) ; g(i) ;\n }\n while(false) ;\n\n // Etc.\n}\n void doSomething(bool bIsOk)\n{\n int i = 25 ;\n\n if(bIsOk)\n {\n f(43) ; g(43) ;\n }\n\n // Etc.\n}\n"
},
{
"answer_id": 215633,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 2,
"selected": false,
"text": "while(i<100)\n FOO(i++);\n while(i<100)\n do { f(i++); g(i++); } while (0)\n i++"
},
{
"answer_id": 1547389,
"author": "Marius",
"author_id": 174650,
"author_profile": "https://Stackoverflow.com/users/174650",
"pm_score": 4,
"selected": false,
"text": "do { ... } while(false); #define FOO(X) (f(X),g(X))\n #define FOO(X) g((f(X),(X)))\n #define #define FOO(X) (int s=5,f((X)+s),g((X)+s))\n"
},
{
"answer_id": 8594736,
"author": "Mike Meyer",
"author_id": 1003027,
"author_profile": "https://Stackoverflow.com/users/1003027",
"pm_score": 3,
"selected": false,
"text": "#define FOO(X) do { int i; for (i = 0; i < (X); ++i) do_something(i); } while (0)\n void some_func(void) {\n int i;\n for (i = 0; i < 10; ++i)\n FOO(i);\n}\n"
},
{
"answer_id": 11798599,
"author": "Yakov Galka",
"author_id": 277176,
"author_profile": "https://Stackoverflow.com/users/277176",
"pm_score": 5,
"selected": false,
"text": "do ... while if ... else if ... else FOO(1)\nprintf(\"abc\");\n if (1) { f(X); g(X); } else\nprintf(\"abc\");\n printf do ... while while(0)"
},
{
"answer_id": 22590644,
"author": "Cœur",
"author_id": 1033581,
"author_profile": "https://Stackoverflow.com/users/1033581",
"pm_score": 4,
"selected": false,
"text": "do {} while (0) if (1) {} else if (something)\n FOO(X); \n if (something)\n f(X); g(X); \n g(X) if do {} while (0) if (1) {} else do {} while (0) if (1) {} else ({}) #define FOO(X) ({f(X); g(X);})\n do {} while (0) return FOO(\"X\");\n"
},
{
"answer_id": 27021741,
"author": "Isaac Schwabacher",
"author_id": 4270855,
"author_profile": "https://Stackoverflow.com/users/4270855",
"pm_score": 4,
"selected": false,
"text": "if(1) { ... } else #define P99_NOP ((void)0)\n#define P99_PREFER(...) if (1) { __VA_ARGS__ } else\n#define P99_BLOCK(...) P99_PREFER(__VA_ARGS__) P99_NOP\n do { ... } while(0) break continue ((void)0) else if"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11138/"
] |
154,159
|
<p>Looking for good techniques to justify "great than normal" machine for developers. The company I work for buys the same underpowered $500 dollar systems for everyone, and looking for ways to prove ROI or arguments to use. Sorry, I didn't say this in the initial question, the stack is VS 2008, SQL 2005/2008. As duties dictate we are SQL admins as well as Web/Winform/WebService Developers. So its very typical to have 2 VS sessions and at least one SQL session open at the same time.</p>
|
[
{
"answer_id": 154229,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "AnnualSavings := DeveloperCostPerHour * (AnnualWaitHours(OldPC) - AnnualWaitHours(NewPC));\n\nif AnnualSavings > (MachineCost(NewPC) - MachineCost(OldPC)) then\n ShowMessage('Time to pony up for a new machine!!')\nelse\n ShowMessage('Sorry bub, gotta keep the old clunker.');\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
154,163
|
<p>I need to detect whether my application is running within a virtualized OS instance or not.</p>
<p>I've found <A HREF="http://www.codeproject.com/KB/system/VmDetect.aspx" rel="noreferrer">an article</A> with some useful information on the topic. The same article appears in multiple places, I'm unsure of the original source. <A HREF="http://www.vmware.com/" rel="noreferrer">VMware</A> implements a particular invalid x86 instruction to return information about itself, while <A HREF="http://www.microsoft.com/windows/products/winfamily/virtualpc/default.mspx" rel="noreferrer">VirtualPC</A> uses a magic number and I/O port with an IN instruction.</p>
<p>This is workable, but appears to be undocumented behavior in both cases. I suppose a future release of VMWare or VirtualPC might change the mechanism. Is there a better way? Is there a supported mechanism for either product?</p>
<p>Similarly, is there a way to detect <A HREF="http://www.xen.org/" rel="noreferrer">Xen</A> or <A HREF="http://www.virtualbox.org/" rel="noreferrer">VirtualBox</A>?</p>
<p>I'm not concerned about cases where the platform is deliberately trying to hide itself. For example, honeypots use virtualization but sometimes obscure the mechanisms that malware would use to detect it. I don't care that my app would think it is not virtualized in these honeypots, I'm just looking for a "best effort" solution.</p>
<p>The application is mostly Java, though I'm expecting to use native code plus JNI for this particular function. Windows XP/Vista support is most important, though the mechanisms described in the referenced article are generic features of x86 and don't rely on any particular OS facility.</p>
|
[
{
"answer_id": 154222,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 7,
"selected": true,
"text": " int swallow_redpill () {\n unsigned char m[2+4], rpill[] = \"\\x0f\\x01\\x0d\\x00\\x00\\x00\\x00\\xc3\";\n *((unsigned*)&rpill[3]) = (unsigned)m;\n ((void(*)())&rpill)();\n return (m[5]>0xd0) ? 1 : 0;\n } \n"
},
{
"answer_id": 4299531,
"author": "michaelbn",
"author_id": 434792,
"author_profile": "https://Stackoverflow.com/users/434792",
"pm_score": 5,
"selected": false,
"text": "Handle 0x0001, DMI type 1, 25 bytes\nSystem Information\n Manufacturer: Microsoft Corporation\n Product Name: Virtual Machine\n Version: 5.0\n Serial Number: some-strings\n UUID: some-strings\n Wake-up Type: Power Switch\n\n\nHandle 0x0002, DMI type 2, 8 bytes\nBase Board Information\n Manufacturer: Microsoft Corporation\n Product Name: Virtual Machine\n Version: 5.0\n Serial Number: some-strings\n"
},
{
"answer_id": 23392455,
"author": "icasimpan",
"author_id": 579516,
"author_profile": "https://Stackoverflow.com/users/579516",
"pm_score": 3,
"selected": false,
"text": "dmidecode -s bios-version\n VirtualBox\n"
},
{
"answer_id": 32012696,
"author": "user2242746",
"author_id": 2242746,
"author_profile": "https://Stackoverflow.com/users/2242746",
"pm_score": 3,
"selected": false,
"text": "#include <intrin.h>\n\n bool isGuestOSVM()\n {\n unsigned int cpuInfo[4];\n __cpuid((int*)cpuInfo,1);\n return ((cpuInfo[2] >> 31) & 1) == 1;\n }\n"
},
{
"answer_id": 32430301,
"author": "Pedro Lobito",
"author_id": 797495,
"author_profile": "https://Stackoverflow.com/users/797495",
"pm_score": 2,
"selected": false,
"text": "C# using System;\nusing System.Management;\nusing System.Text.RegularExpressions;\n\nnamespace ConsoleApplication1\n{\n public class sysInfo\n {\n public static Boolean isVM()\n {\n bool foundMatch = false;\n ManagementObjectSearcher search1 = new ManagementObjectSearcher(\"select * from Win32_BIOS\");\n var enu = search1.Get().GetEnumerator();\n if (!enu.MoveNext()) throw new Exception(\"Unexpected WMI query failure\");\n string biosVersion = enu.Current[\"version\"].ToString();\n string biosSerialNumber = enu.Current[\"SerialNumber\"].ToString();\n\n try\n {\n foundMatch = Regex.IsMatch(biosVersion + \" \" + biosSerialNumber, \"VMware|VIRTUAL|A M I|Xen\", RegexOptions.IgnoreCase);\n }\n catch (ArgumentException ex)\n {\n // Syntax error in the regular expression\n }\n\n ManagementObjectSearcher search2 = new ManagementObjectSearcher(\"select * from Win32_ComputerSystem\");\n var enu2 = search2.Get().GetEnumerator();\n if (!enu2.MoveNext()) throw new Exception(\"Unexpected WMI query failure\");\n string manufacturer = enu2.Current[\"manufacturer\"].ToString();\n string model = enu2.Current[\"model\"].ToString();\n\n try\n {\n foundMatch = Regex.IsMatch(manufacturer + \" \" + model, \"Microsoft|VMWare|Virtual\", RegexOptions.IgnoreCase);\n }\n catch (ArgumentException ex)\n {\n // Syntax error in the regular expression\n }\n\n return foundMatch;\n }\n }\n\n}\n if (sysInfo.isVM()) { \n Console.WriteLine(\"VM FOUND\");\n }\n"
},
{
"answer_id": 39994934,
"author": "Mohit Dabas",
"author_id": 1485906,
"author_profile": "https://Stackoverflow.com/users/1485906",
"pm_score": 2,
"selected": false,
"text": "#include \"stdafx.h\"\n\n#define _WIN32_DCOM\n#include <iostream>\nusing namespace std;\n#include <comdef.h>\n#include <Wbemidl.h>\n\n#pragma comment(lib, \"wbemuuid.lib\")\n\nint main(int argc, char **argv)\n{\n HRESULT hres;\n\n // Step 1: --------------------------------------------------\n // Initialize COM. ------------------------------------------\n\n hres = CoInitializeEx(0, COINIT_MULTITHREADED);\n if (FAILED(hres))\n {\n cout << \"Failed to initialize COM library. Error code = 0x\"\n << hex << hres << endl;\n return 1; // Program has failed.\n }\n\n // Step 2: --------------------------------------------------\n // Set general COM security levels --------------------------\n\n hres = CoInitializeSecurity(\n NULL,\n -1, // COM authentication\n NULL, // Authentication services\n NULL, // Reserved\n RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication \n RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation \n NULL, // Authentication info\n EOAC_NONE, // Additional capabilities \n NULL // Reserved\n );\n\n\n if (FAILED(hres))\n {\n cout << \"Failed to initialize security. Error code = 0x\"\n << hex << hres << endl;\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n // Step 3: ---------------------------------------------------\n // Obtain the initial locator to WMI -------------------------\n\n IWbemLocator *pLoc = NULL;\n\n hres = CoCreateInstance(\n CLSID_WbemLocator,\n 0,\n CLSCTX_INPROC_SERVER,\n IID_IWbemLocator, (LPVOID *)&pLoc);\n\n if (FAILED(hres))\n {\n cout << \"Failed to create IWbemLocator object.\"\n << \" Err code = 0x\"\n << hex << hres << endl;\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n // Step 4: -----------------------------------------------------\n // Connect to WMI through the IWbemLocator::ConnectServer method\n\n IWbemServices *pSvc = NULL;\n\n // Connect to the root\\cimv2 namespace with\n // the current user and obtain pointer pSvc\n // to make IWbemServices calls.\n hres = pLoc->ConnectServer(\n _bstr_t(L\"ROOT\\\\CIMV2\"), // Object path of WMI namespace\n NULL, // User name. NULL = current user\n NULL, // User password. NULL = current\n 0, // Locale. NULL indicates current\n NULL, // Security flags.\n 0, // Authority (for example, Kerberos)\n 0, // Context object \n &pSvc // pointer to IWbemServices proxy\n );\n\n if (FAILED(hres))\n {\n cout << \"Could not connect. Error code = 0x\"\n << hex << hres << endl;\n pLoc->Release();\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n cout << \"Connected to ROOT\\\\CIMV2 WMI namespace\" << endl;\n\n\n // Step 5: --------------------------------------------------\n // Set security levels on the proxy -------------------------\n\n hres = CoSetProxyBlanket(\n pSvc, // Indicates the proxy to set\n RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx\n RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx\n NULL, // Server principal name \n RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx \n RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx\n NULL, // client identity\n EOAC_NONE // proxy capabilities \n );\n\n if (FAILED(hres))\n {\n cout << \"Could not set proxy blanket. Error code = 0x\"\n << hex << hres << endl;\n pSvc->Release();\n pLoc->Release();\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n // Step 6: --------------------------------------------------\n // Use the IWbemServices pointer to make requests of WMI ----\n\n // For example, get the name of the operating system\n IEnumWbemClassObject* pEnumerator = NULL;\n hres = pSvc->ExecQuery(\n bstr_t(\"WQL\"),\n bstr_t(L\"SELECT * FROM Win32_TemperatureProbe\"),\n WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,\n NULL,\n &pEnumerator);\n\n if (FAILED(hres))\n {\n cout << \"Query for operating system name failed.\"\n << \" Error code = 0x\"\n << hex << hres << endl;\n pSvc->Release();\n pLoc->Release();\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n // Step 7: -------------------------------------------------\n // Get the data from the query in step 6 -------------------\n\n IWbemClassObject *pclsObj = NULL;\n ULONG uReturn = 0;\n\n while (pEnumerator)\n {\n HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,\n &pclsObj, &uReturn);\n\n if (0 == uReturn)\n {\n break;\n }\n\n VARIANT vtProp;\n\n // Get the value of the Name property\n hr = pclsObj->Get(L\"SystemName\", 0, &vtProp, 0, 0);\n wcout << \" OS Name : \" << vtProp.bstrVal << endl;\n VariantClear(&vtProp);\n VARIANT vtProp1;\n VariantInit(&vtProp1);\n pclsObj->Get(L\"Caption\", 0, &vtProp1, 0, 0);\n wcout << \"Caption: \" << vtProp1.bstrVal << endl;\n VariantClear(&vtProp1);\n\n pclsObj->Release();\n }\n\n // Cleanup\n // ========\n\n pSvc->Release();\n pLoc->Release();\n pEnumerator->Release();\n CoUninitialize();\n\n return 0; // Program successfully completed.\n\n}\n"
},
{
"answer_id": 55015480,
"author": "AVX-42",
"author_id": 10669139,
"author_profile": "https://Stackoverflow.com/users/10669139",
"pm_score": 3,
"selected": false,
"text": "$ systemd-detect-virt none $ systemd-detect-virt\nkvm\n"
},
{
"answer_id": 66616314,
"author": "Gray Programmerz",
"author_id": 14919621,
"author_profile": "https://Stackoverflow.com/users/14919621",
"pm_score": 2,
"selected": false,
"text": "//asked at: https://stackoverflow.com/q/64846900/14919621\nwhat win32_portconnector is used for ? This question have 3 parts.\n1) What is the use case of win32_portconnector ? //https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-portconnector\n2) Can I get state of ports using it like Mouse cable, charger, HDMI cables etc ?\n3) Why VM have null results on this query : Get-WmiObject Win32_PortConnector ?\n PS C:\\Users\\Administrator> Get-WmiObject Win32_PortConnector\n PS C:\\Users\\Administrator> Get-WmiObject Win32_PortConnector\nTag : Port Connector 0\nConnectorType : {23, 3}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 2\n\nTag : Port Connector 1\nConnectorType : {21, 2}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 9\n\nTag : Port Connector 2\nConnectorType : {64}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 16\n\nTag : Port Connector 3\nConnectorType : {22, 3}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 28\n\nTag : Port Connector 4\nConnectorType : {54}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 17\n\nTag : Port Connector 5\nConnectorType : {38}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 30\n\nTag : Port Connector 6\nConnectorType : {39}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 31\n //@graysuit\n//https://graysuit.github.io\n//https://github.com/Back-X/anti-vm\nusing System;\nusing System.Windows.Forms;\n\npublic class Universal_VM_Detector\n{\n static void Main()\n {\n if((new System.Management.ManagementObjectSearcher(\"SELECT * FROM Win32_PortConnector\")).Get().Count == 0)\n {\n MessageBox.Show(\"VM detected !\");\n }\n else\n {\n MessageBox.Show(\"VM NOT detected !\");\n }\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4761/"
] |
154,179
|
<p>I'm refactoring some code currently implemented in stored procedures to use LinqToSql (for use in training). Is it possible to use SQL functions in a linqToSql Query?</p>
|
[
{
"answer_id": 16965126,
"author": "jpierson",
"author_id": 83658,
"author_profile": "https://Stackoverflow.com/users/83658",
"pm_score": 0,
"selected": false,
"text": " [Function(Name=\"SoundEx\", IsComposable = true)]\n public string SoundsLike(string input)\n {\n throw new NotImplementedException();\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
] |
154,185
|
<p>I have heard this concept used frequently, but I don't have a really good grasp of what it is.</p>
|
[
{
"answer_id": 154214,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 3,
"selected": false,
"text": "srcplayer = Player.new\n# marshal (store it as string)\nstr = Marshal.dump(srcplayer)\n#unmarshal (get it back)\ndestplayer = Marshal.load(str)\n"
},
{
"answer_id": 61426657,
"author": "Lewis Kelsey",
"author_id": 7194773,
"author_profile": "https://Stackoverflow.com/users/7194773",
"pm_score": 1,
"selected": false,
"text": "System.String MonoString MonoString MonoString* const wchar_t* System.String const wchar_t* MonoString* int System.Int32 gint32 int HTMLElement JSObject HTMLElement"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
154,204
|
<p>Is there any way to change the default tab size in a .NET RichTextBox?
It currently seems to be set to the equivalent of 8 spaces which is kinda large for my taste.</p>
<p>Edit: To clarify, I want to set the global default of "\t" displays as 4 spaces for the control. From what I can understand, the SelectionTabs property requires you to select all the text first and then the the tab widths via the array. I will do this if I have to, but I would rather just change the global default once, if possible, sot that I don't have to do that every time.</p>
|
[
{
"answer_id": 154255,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 6,
"selected": true,
"text": "private void Form1_Load(object sender, EventArgs e)\n{\n richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };\n}\n richTextBox1.Text = \"\\t1\\t2\\t3\\t4\";\nrichTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };\n richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };\nrichTextBox1.Text = \"\\t1\\t2\\t3\\t4\";\n"
},
{
"answer_id": 8787004,
"author": "Dan W",
"author_id": 848344,
"author_profile": "https://Stackoverflow.com/users/848344",
"pm_score": 3,
"selected": false,
"text": "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang2057\\deftab720{\\fonttbl{\\f0\\fnil\\fcharset0 Microsoft Sans Serif;}}\n\\viewkind4\\uc1\\pard\\f0\\fs41\n1\\tab 2\\tab 3\\tab 4\\tab 5\\par\n}\n int tabSize=720;\nGraphics g = this.CreateGraphics();\nint pixels = (int)Math.Round(((double)tabSize) / 1440.0 * g.DpiX);\ng.Dispose();\n"
},
{
"answer_id": 18399551,
"author": "Elmue",
"author_id": 1487529,
"author_profile": "https://Stackoverflow.com/users/1487529",
"pm_score": 1,
"selected": false,
"text": "OnKeyDown()"
},
{
"answer_id": 52122625,
"author": "Kir_Antipov",
"author_id": 7959772,
"author_profile": "https://Stackoverflow.com/users/7959772",
"pm_score": 2,
"selected": false,
"text": "RichTextBox public class TabRichTextBox : RichTextBox\n{\n [Browsable(true), Category(\"Settings\")]\n public int TabSize { get; set; } = 4;\n\n protected override bool ProcessCmdKey(ref Message Msg, Keys KeyData)\n {\n \n const int WM_KEYDOWN = 0x100; // https://learn.microsoft.com/en-us/windows/desktop/inputdev/wm-keydown\n const int WM_SYSKEYDOWN = 0x104; // https://learn.microsoft.com/en-us/windows/desktop/inputdev/wm-syskeydown\n // Tab has been pressed\n if ((Msg.Msg == WM_KEYDOWN || Msg.Msg == WM_SYSKEYDOWN) && KeyData.HasFlag(Keys.Tab))\n {\n // Let's create a string of spaces, which length == TabSize\n // And then assign it to the current position\n SelectedText += new string(' ', TabSize);\n\n // Tab processed\n return true;\n }\n return base.ProcessCmdKey(ref Msg, KeyData);\n }\n}\n \\t"
},
{
"answer_id": 58225802,
"author": "sɐunıɔןɐqɐp",
"author_id": 823321,
"author_profile": "https://Stackoverflow.com/users/823321",
"pm_score": 0,
"selected": false,
"text": "using System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace MyNamespace\n{\n public partial class MyRichTextBox : RichTextBox\n {\n public MyRichTextBox() : base() =>\n KeyDown += new KeyEventHandler(RichTextBox_KeyDown);\n\n [Browsable(true), Category(\"Settings\"), Description(\"Convert all tabs into spaces.\"), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]\n public bool ConvertTabToSpaces { get; set; } = false;\n\n [Browsable(true), Category(\"Settings\"), Description(\"The number os spaces used for replacing a tab character.\"), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]\n public int TabSize { get; set; } = 4;\n\n [Browsable(true), Category(\"Settings\"), Description(\"The text associated with the control.\"), Bindable(true), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]\n public new string Text\n {\n get => base.Text;\n set => base.Text = ConvertTabToSpaces ? value.Replace(\"\\t\", new string(' ', TabSize)) : value;\n }\n\n protected override bool ProcessCmdKey(ref Message Msg, Keys KeyData)\n {\n const int WM_KEYDOWN = 0x100; // https://learn.microsoft.com/en-us/windows/desktop/inputdev/wm-keydown\n const int WM_SYSKEYDOWN = 0x104; // https://learn.microsoft.com/en-us/windows/desktop/inputdev/wm-syskeydown\n\n if (ConvertTabToSpaces && KeyData == Keys.Tab && (Msg.Msg == WM_KEYDOWN || Msg.Msg == WM_SYSKEYDOWN))\n {\n SelectedText += new string(' ', TabSize);\n return true;\n }\n return base.ProcessCmdKey(ref Msg, KeyData);\n }\n\n public new void AppendText(string text)\n {\n if (ConvertTabToSpaces)\n text = text.Replace(\"\\t\", new string(' ', TabSize));\n base.AppendText(text);\n }\n\n private void RichTextBox_KeyDown(object sender, KeyEventArgs e)\n {\n if ((e.Shift && e.KeyCode == Keys.Insert) || (e.Control && e.KeyCode == Keys.V))\n {\n SuspendLayout();\n int start = SelectionStart;\n string end = Text.Substring(start);\n Text = Text.Substring(0, start);\n Text += (string)Clipboard.GetData(\"Text\") + end;\n SelectionStart = TextLength - end.Length;\n ResumeLayout();\n e.Handled = true;\n }\n }\n\n } // class\n} // namespace\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
154,206
|
<p>I am trying to use a DynamicResource in Storyboard contained within a ControlTemplate.</p>
<p>But, when I try to do this, I get a 'Cannot freeze this Storyboard timeline tree for use across threads' error.</p>
<p>What is going on here?</p>
|
[
{
"answer_id": 71658836,
"author": "SWSBB",
"author_id": 11776148,
"author_profile": "https://Stackoverflow.com/users/11776148",
"pm_score": 0,
"selected": false,
"text": "DynamicResource ControlTemplate StoryBoard Opacity Visibility ControlTemplate DynamicResources Visibility Opacity Storyboard"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22294/"
] |
154,245
|
<p>Ok, this is a bit of a cheeky question. I want to build a simple text editor (using my own text mode screen handling). I just want a good example of data structures that can be used to represent the text buffer, and some simple examples of char/text insertion/deletion. I can handle all the rest of the code myself (file i/o, console i/o etc). A link to a nice simple editor source would be great (C or C++).</p>
|
[
{
"answer_id": 154349,
"author": "Kluge",
"author_id": 8752,
"author_profile": "https://Stackoverflow.com/users/8752",
"pm_score": 2,
"selected": false,
"text": "while (editing) {\n GetCharacter();\n ProcessCharacter();\n UpdateDisplay();\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3685/"
] |
154,248
|
<p>I tried:</p>
<pre><code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Node mapNode = getMapNode(doc);
System.out.print("\r\n elementName "+ mapNode.getNodeName());//This works fine.
Element e = (Element) mapNode; //This is where the error occurs
//it seems to work on my machine, but not on the server.
e.setAttribute("objectId", "OBJ123");
</code></pre>
<p>But this throws a java.lang.ClassCastException error on the line that casts it to Element. <strong>mapNode is a valid node.</strong> I already have it printing out </p>
<p>I think maybe this code does not work in Java 1.4. What I really need is an alternative to using Element. I tried doing</p>
<pre><code>NamedNodeMap atts = mapNode.getAttributes();
Attr att = doc.createAttribute("objId");
att.setValue(docId);
atts.setNamedItem(att);
</code></pre>
<p>But getAttributes() returns null on the server. Even though its not and I am using the same document locally as on the server. And it can print out the getNodeName() its just that the getAttributes() does not work.</p>
|
[
{
"answer_id": 154297,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 0,
"selected": false,
"text": "System.out.println(doc.getFirstChild().getClass().getName());\n doc.getDocumentElement().getChildNodes();\n NodeList nodes = doc.getElementsByTagName(\"MyTag\");\n"
},
{
"answer_id": 154370,
"author": "Brandon DuRette",
"author_id": 17834,
"author_profile": "https://Stackoverflow.com/users/17834",
"pm_score": 0,
"selected": false,
"text": "ClassCastException setAttribute getFirstChild() DocumentType Element DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n\nDocumentBuilder db = dbf.newDocumentBuilder();\nDocument doc = db.parse(f);\n\nElement e = (Element) doc.getDocumentElement().getFirstChild();\ne.setAttribute(\"objectId\", \"OBJ123\");\n Node Element Element Node Node Element getMapNode() getMapNode() getElementsByTagName"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5653/"
] |
154,256
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/105372/c-how-to-enumerate-an-enum">C#: How to enumerate an enum?</a> </p>
</blockquote>
<p>The subject says all. I want to use that to add the values of an enum in a combobox.</p>
<p>Thanks</p>
<p>vIceBerg</p>
|
[
{
"answer_id": 154263,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 6,
"selected": true,
"text": "string[] names = Enum.GetNames (typeof(MyEnum));\n"
},
{
"answer_id": 154266,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "procedure TForm1.Button1Click(Sender: TObject);\ntype\n TEmployeeTypes = (etMin, etHourly, etSalary, etContractor, etMax);\nvar\n i : TEmployeeTypes;\nbegin\n for i := etMin to etMax do begin\n //do something\n end;\nend;\n"
},
{
"answer_id": 154269,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 3,
"selected": false,
"text": "public class GetNamesTest {\n enum Colors { Red, Green, Blue, Yellow };\n enum Styles { Plaid, Striped, Tartan, Corduroy };\n\n public static void Main() {\n\n Console.WriteLine(\"The values of the Colors Enum are:\");\n foreach(string s in Enum.GetNames(typeof(Colors)))\n Console.WriteLine(s);\n\n Console.WriteLine();\n\n Console.WriteLine(\"The values of the Styles Enum are:\");\n foreach(string s in Enum.GetNames(typeof(Styles)))\n Console.WriteLine(s);\n }\n}\n"
},
{
"answer_id": 154302,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "foreach (TestEnum en in Enum.GetValues(typeof(TestEnum)))\n{\n ...\n}\n"
},
{
"answer_id": 154306,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 3,
"selected": false,
"text": "foreach (TheEnum value in Enum.GetValues(typeof(TheEnum)))\n dropDown.Items.Add(new ListItem(\n value.ToString(), ((int)value).ToString()\n );\n"
},
{
"answer_id": 154335,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 5,
"selected": false,
"text": "public enum States\n{\n California,\n [Description(\"New Mexico\")]\n NewMexico,\n [Description(\"New York\")]\n NewYork,\n [Description(\"South Carolina\")]\n SouthCarolina,\n Tennessee,\n Washington\n}\n public static IEnumerable<T> EnumToList<T>()\n where T : struct\n{\n Type enumType = typeof(T);\n\n // Can't use generic type constraints on value types,\n // so have to do check like this\n if (enumType.BaseType != typeof(Enum))\n throw new ArgumentException(\"T must be of type System.Enum\");\n\n Array enumValArray = Enum.GetValues(enumType);\n List<T> enumValList = new List<T>();\n\n foreach (T val in enumValArray)\n {\n enumValList.Add(val.ToString());\n }\n\n return enumValList;\n}\n public static IEnumerable<T> EnumToList<T>()\n where T : struct\n{\n return Enum.GetValues(typeof(T)).Cast<T>();\n}\n\n// Using above method\nstatesComboBox.Items = EnumToList<States>();\n\n// Inline\nstatesComboBox.Items = Enum.GetValues(typeof(States)).Cast<States>();\n"
},
{
"answer_id": 154383,
"author": "Donny V.",
"author_id": 1231,
"author_profile": "https://Stackoverflow.com/users/1231",
"pm_score": 1,
"selected": false,
"text": "public enum eCarType\n{\n [StringValue(\"Saloon / Sedan\")] Saloon = 5,\n [StringValue(\"Coupe\")] Coupe = 4,\n [StringValue(\"Estate / Wagon\")] Estate = 6,\n [StringValue(\"Hatchback\")] Hatchback = 8,\n [StringValue(\"Utility\")] Ute = 1,\n}\n StringEnum CarTypes = new StringEnum(typeof(eCarTypes));\ncmbCarTypes.DataSource = CarTypes.GetGenericListValues();\n // Author: Donny V.\n// blog: http://donnyvblog.blogspot.com\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace xEnums\n{\n\n #region Class StringEnum\n\n /// <summary>\n /// Helper class for working with 'extended' enums using <see cref=\"StringValueAttribute\"/> attributes.\n /// </summary>\n public class StringEnum\n {\n #region Instance implementation\n\n private Type _enumType;\n private static Hashtable _stringValues = new Hashtable();\n\n /// <summary>\n /// Creates a new <see cref=\"StringEnum\"/> instance.\n /// </summary>\n /// <param name=\"enumType\">Enum type.</param>\n public StringEnum(Type enumType)\n {\n if (!enumType.IsEnum)\n throw new ArgumentException(String.Format(\"Supplied type must be an Enum. Type was {0}\", enumType.ToString()));\n\n _enumType = enumType;\n }\n\n /// <summary>\n /// Gets the string value associated with the given enum value.\n /// </summary>\n /// <param name=\"valueName\">Name of the enum value.</param>\n /// <returns>String Value</returns>\n public string GetStringValue(string valueName)\n {\n Enum enumType;\n string stringValue = null;\n try\n {\n enumType = (Enum) Enum.Parse(_enumType, valueName);\n stringValue = GetStringValue(enumType);\n }\n catch (Exception) { }//Swallow!\n\n return stringValue;\n }\n\n /// <summary>\n /// Gets the string values associated with the enum.\n /// </summary>\n /// <returns>String value array</returns>\n public Array GetStringValues()\n {\n ArrayList values = new ArrayList();\n //Look for our string value associated with fields in this enum\n foreach (FieldInfo fi in _enumType.GetFields())\n {\n //Check for our custom attribute\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n values.Add(attrs[0].Value);\n\n }\n\n return values.ToArray();\n }\n\n /// <summary>\n /// Gets the values as a 'bindable' list datasource.\n /// </summary>\n /// <returns>IList for data binding</returns>\n public IList GetListValues()\n {\n Type underlyingType = Enum.GetUnderlyingType(_enumType);\n ArrayList values = new ArrayList();\n //List<string> values = new List<string>();\n\n //Look for our string value associated with fields in this enum\n foreach (FieldInfo fi in _enumType.GetFields())\n {\n //Check for our custom attribute\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value));\n\n }\n\n return values;\n\n }\n\n /// <summary>\n /// Gets the values as a 'bindable' list<string> datasource.\n ///This is a newer version of 'GetListValues()'\n /// </summary>\n /// <returns>IList<string> for data binding</returns>\n public IList<string> GetGenericListValues()\n {\n Type underlyingType = Enum.GetUnderlyingType(_enumType);\n List<string> values = new List<string>();\n\n //Look for our string value associated with fields in this enum\n foreach (FieldInfo fi in _enumType.GetFields())\n {\n //Check for our custom attribute\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n values.Add(attrs[0].Value);\n }\n\n return values;\n\n }\n\n /// <summary>\n /// Return the existence of the given string value within the enum.\n /// </summary>\n /// <param name=\"stringValue\">String value.</param>\n /// <returns>Existence of the string value</returns>\n public bool IsStringDefined(string stringValue)\n {\n return Parse(_enumType, stringValue) != null;\n }\n\n /// <summary>\n /// Return the existence of the given string value within the enum.\n /// </summary>\n /// <param name=\"stringValue\">String value.</param>\n /// <param name=\"ignoreCase\">Denotes whether to conduct a case-insensitive match on the supplied string value</param>\n /// <returns>Existence of the string value</returns>\n public bool IsStringDefined(string stringValue, bool ignoreCase)\n {\n return Parse(_enumType, stringValue, ignoreCase) != null;\n }\n\n /// <summary>\n /// Gets the underlying enum type for this instance.\n /// </summary>\n /// <value></value>\n public Type EnumType\n {\n get { return _enumType; }\n }\n\n #endregion\n\n #region Static implementation\n\n /// <summary>\n /// Gets a string value for a particular enum value.\n /// </summary>\n /// <param name=\"value\">Value.</param>\n /// <returns>String Value associated via a <see cref=\"StringValueAttribute\"/> attribute, or null if not found.</returns>\n public static string GetStringValue(Enum value)\n {\n string output = null;\n Type type = value.GetType();\n\n if (_stringValues.ContainsKey(value))\n output = (_stringValues[value] as StringValueAttribute).Value;\n else \n {\n //Look for our 'StringValueAttribute' in the field's custom attributes\n FieldInfo fi = type.GetField(value.ToString());\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n {\n _stringValues.Add(value, attrs[0]);\n output = attrs[0].Value;\n }\n\n }\n return output;\n\n }\n\n /// <summary>\n /// Parses the supplied enum and string value to find an associated enum value (case sensitive).\n /// </summary>\n /// <param name=\"type\">Type.</param>\n /// <param name=\"stringValue\">String value.</param>\n /// <returns>Enum value associated with the string value, or null if not found.</returns>\n public static object Parse(Type type, string stringValue)\n {\n return Parse(type, stringValue, false);\n }\n\n /// <summary>\n /// Parses the supplied enum and string value to find an associated enum value.\n /// </summary>\n /// <param name=\"type\">Type.</param>\n /// <param name=\"stringValue\">String value.</param>\n /// <param name=\"ignoreCase\">Denotes whether to conduct a case-insensitive match on the supplied string value</param>\n /// <returns>Enum value associated with the string value, or null if not found.</returns>\n public static object Parse(Type type, string stringValue, bool ignoreCase)\n {\n object output = null;\n string enumStringValue = null;\n\n if (!type.IsEnum)\n throw new ArgumentException(String.Format(\"Supplied type must be an Enum. Type was {0}\", type.ToString()));\n\n //Look for our string value associated with fields in this enum\n foreach (FieldInfo fi in type.GetFields())\n {\n //Check for our custom attribute\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n enumStringValue = attrs[0].Value;\n\n //Check for equality then select actual enum value.\n if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)\n {\n output = Enum.Parse(type, fi.Name);\n break;\n }\n }\n\n return output;\n }\n\n /// <summary>\n /// Return the existence of the given string value within the enum.\n /// </summary>\n /// <param name=\"stringValue\">String value.</param>\n /// <param name=\"enumType\">Type of enum</param>\n /// <returns>Existence of the string value</returns>\n public static bool IsStringDefined(Type enumType, string stringValue)\n {\n return Parse(enumType, stringValue) != null;\n }\n\n /// <summary>\n /// Return the existence of the given string value within the enum.\n /// </summary>\n /// <param name=\"stringValue\">String value.</param>\n /// <param name=\"enumType\">Type of enum</param>\n /// <param name=\"ignoreCase\">Denotes whether to conduct a case-insensitive match on the supplied string value</param>\n /// <returns>Existence of the string value</returns>\n public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)\n {\n return Parse(enumType, stringValue, ignoreCase) != null;\n }\n\n #endregion\n }\n\n #endregion\n\n #region Class StringValueAttribute\n\n /// <summary>\n /// Simple attribute class for storing String Values\n /// </summary>\n public class StringValueAttribute : Attribute\n {\n private string _value;\n\n /// <summary>\n /// Creates a new <see cref=\"StringValueAttribute\"/> instance.\n /// </summary>\n /// <param name=\"value\">Value.</param>\n public StringValueAttribute(string value)\n {\n _value = value;\n }\n\n /// <summary>\n /// Gets the value.\n /// </summary>\n /// <value></value>\n public string Value\n {\n get { return _value; }\n }\n }\n\n #endregion\n}\n"
},
{
"answer_id": 154513,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 1,
"selected": false,
"text": "enum Color {Red, Green, Blue}\n Enum.GetValues(typeof(Color)).Cast<Color>()\n static IEnumerable<T> GetValues<T>() {\n return Enum.GetValues(typeof(T)).Cast<T>();\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17766/"
] |
154,261
|
<p>I frequently run into problems of this form and haven't found a good solution yet:</p>
<p>Assume we have two database tables representing an e-commerce system.</p>
<pre><code>userData (userId, name, ...)
orderData (orderId, userId, orderType, createDate, ...)
</code></pre>
<p>For all users in the system, select their user information, their most recent order information with type = '1', and their most recent order information with type = '2'. I want to do this in one query. Here is an example result:</p>
<pre><code>(userId, name, ..., orderId1, orderType1, createDate1, ..., orderId2, orderType2, createDate2, ...)
(101, 'Bob', ..., 472, '1', '4/25/2008', ..., 382, '2', '3/2/2008', ...)
</code></pre>
|
[
{
"answer_id": 154272,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM\n\"orderData\", \"userData\"\nWHERE\n\"userData\".\"userId\" =\"orderData\".\"userId\"\nAND \"orderData\".createDate >= current_date;\n SELECT * FROM\n\"orderData\", \"userData\"\nWHERE\n\"userData\".\"userId\" =\"orderData\".\"userId\"\nAND \"orderData\".type = '1'\nAND \"orderData\".\"orderId\" = (\nSELECT \"orderId\" FROM \"orderData\"\nWHERE \n\"orderType\" = '1'\nORDER \"orderId\" DESC\nLIMIT 1\n"
},
{
"answer_id": 154300,
"author": "Kevin Lamb",
"author_id": 3149,
"author_profile": "https://Stackoverflow.com/users/3149",
"pm_score": 0,
"selected": false,
"text": "SELECT orderId, orderType, createDate\nFROM orderData\nWHERE type=1 AND MAX(createDate)\nGROUP BY orderId, orderType, createDate\n\nUNION\n\nSELECT orderId, orderType, createDate\nFROM orderData\nWHERE type=2 AND MAX(createDate)\nGROUP BY orderId, orderType, createDate\n"
},
{
"answer_id": 154317,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "SELECT b.user_id, b.orderid, b.orderType, b.createDate, <etc>,\n a.name\nFROM orderData b, userData a\nWHERE a.userid = b.userid\nAND (b.userid, b.orderType, b.createDate) IN (\n SELECT userid, orderType, max(createDate) \n FROM orderData \n WHERE orderType IN (1,2)\n GROUP BY userid, orderType) \n"
},
{
"answer_id": 154334,
"author": "Bartek Szabat",
"author_id": 23774,
"author_profile": "https://Stackoverflow.com/users/23774",
"pm_score": 1,
"selected": false,
"text": "SELECT\n u.*\n , o1.*\n , o2.* \nFROM\n(\n SELECT\n , userData.*\n , (SELECT TOP 1 orderId.url FROM orderData WHERE orderData.userId=userData.userId AND orderType=1 ORDER BY createDate DESC)\n AS order1Id\n , (SELECT TOP 1 orderId.url FROM orderData WHERE orderData.userId=userData.userId AND orderType=2 ORDER BY createDate DESC)\n AS order2Id\n FROM userData\n) AS u\nLEFT JOIN orderData o1 ON (u.order1Id=o1.orderId)\nLEFT JOIN orderData o2 ON (u.order2Id=o2.orderId)\n"
},
{
"answer_id": 154336,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "SELECT\n u.*,\n SUBSTRING_INDEX( MAX( CONCAT( o1.createDate, '##', o1.otherfield)), '##', -1) as o2_orderfield,\n SUBSTRING_INDEX( MAX( CONCAT( o2.createDate, '##', o2.otherfield)), '##', -1) as o2_orderfield\nFROM\n userData as u\n LEFT JOIN orderData AS o1 ON (o1.userId=u.userId AND o1.orderType=1)\n LEFT JOIN orderData AS o2 ON (o1.userId=u.userId AND o2.orderType=2)\nGROUP BY u.userId\n select * from orderData where userId=XXX order by orderType, date desc group by orderType\n"
},
{
"answer_id": 154366,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "SELECT *\nFROM userData u\nINNER JOIN orderData o\n ON o.userId = u.userId\nINNER JOIN ( -- This subquery gives the last order of each type for each customer\n SELECT MAX(o2.orderId)\n --, o2.userId -- optional - include if joining for a particular customer\n --, o2.orderType -- optional - include if joining for a particular type\n FROM orderData o2\n GROUP BY o2.userId\n ,o2.orderType\n) AS LastOrders\n ON LastOrders.orderId = o.orderId -- expand join to include customer or type if desired\n"
},
{
"answer_id": 154433,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 3,
"selected": true,
"text": "select ud.name,\n order1.order_id,\n order1.order_type,\n order1.create_date,\n order2.order_id,\n order2.order_type,\n order2.create_date\n from user_data ud,\n order_data order1,\n order_data order2\n where ud.user_id = order1.user_id\n and ud.user_id = order2.user_id\n and order1.order_id = (select max(order_id)\n from order_data od1\n where od1.user_id = ud.user_id\n and od1.order_type = 'Type1')\n and order2.order_id = (select max(order_id)\n from order_data od2\n where od2.user_id = ud.user_id\n and od2.order_type = 'Type2')\n last_order_date"
},
{
"answer_id": 154450,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 0,
"selected": false,
"text": "SELECT\n a.name, ud1.*, ud2.*\nFROM\n userData a,\n (SELECT user_id, orderid, orderType, reateDate, <etc>,\n FROM orderData b\n WHERE (userid, orderType, createDate) IN (\n SELECT userid, orderType, max(createDate) \n FROM orderData \n WHERE orderType = 1\n GROUP BY userid, orderType) ud1,\n (SELECT user_id, orderid, orderType, createDate, <etc>,\n FROM orderData \n WHERE (userid, orderType, createDate) IN (\n SELECT userid, orderType, max(createDate) \n FROM orderData \n WHERE orderType = 2\n GROUP BY userid, orderType) ud2\n"
},
{
"answer_id": 154486,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "SELECT u.userId, u.name, o1.orderId, o1.orderType, o1.createDate,\n o2.orderId, o2.orderType, o2.createDate\nFROM userData AS u\n LEFT OUTER JOIN (\n SELECT o1a.orderId, o1a.userId, o1a.orderType, o1a.createDate\n FROM orderData AS o1a \n LEFT OUTER JOIN orderData AS o1b ON (o1a.userId = o1b.userId \n AND o1a.orderType = o1b.orderType AND o1a.createDate < o1b.createDate)\n WHERE o1a.orderType = 1 AND o1b.orderId IS NULL) AS o1 ON (u.userId = o1.userId)\n LEFT OUTER JOIN (\n SELECT o2a.orderId, o2a.userId, o2a.orderType, o2a.createDate\n FROM orderData AS o2a \n LEFT OUTER JOIN orderData AS o2b ON (o2a.userId = o2b.userId \n AND o2a.orderType = o2b.orderType AND o2a.createDate < o2b.createDate)\n WHERE o2a.orderType = 2 AND o2b.orderId IS NULL) o2 ON (u.userId = o2.userId);\n"
},
{
"answer_id": 154548,
"author": "JavadocMD",
"author_id": 9304,
"author_profile": "https://Stackoverflow.com/users/9304",
"pm_score": 0,
"selected": false,
"text": "select ud.name,\n order1.orderId,\n order1.orderType,\n order1.createDate,\n order2.orderId,\n order2.orderType,\n order2.createDate\n from userData ud\n left join orderData order1\n on order1.orderId = (select max(orderId)\n from orderData od1\n where od1.userId = ud.userId\n and od1.orderType = '1')\n left join orderData order2\n on order2.orderId = (select max(orderId)\n from orderData od2\n where od2.userId = ud.userId\n and od2.orderType = '2')\n where ...[some limiting factors on the selection of users]...;\n"
},
{
"answer_id": 155282,
"author": "Mario",
"author_id": 472,
"author_profile": "https://Stackoverflow.com/users/472",
"pm_score": 2,
"selected": false,
"text": "orderId createDate createDate select \n ud.userId, ud.fullname, \n od1.orderId as orderId1, od1.createDate as createDate1, od1.orderType as orderType1,\n od2.orderId as orderId2, od2.createDate as createDate2, od2.orderType as orderType2\n\nfrom userData ud\n inner join (\n select userId, [1] as typeOne, [2] as typeTwo\n from (select\n userId, orderType, orderId\n from orderData) as orders\n PIVOT\n (\n max(orderId)\n FOR orderType in ([1], [2])\n ) as LatestOrders) as LatestOrders on\n LatestOrders.userId = ud.userId \n inner join orderData od1 on\n od1.orderId = LatestOrders.typeOne\n inner join orderData od2 on\n od2.orderId = LatestOrders.typeTwo\n select \n ud.userId, ud.fullname, \n od1.orderId as orderId1, od1.createDate as createDate1, od1.orderType as orderType1,\n od2.orderId as orderId2, od2.createDate as createDate2, od2.orderType as orderType2\n\nfrom userData ud \n -- assuming not all users will have orders use outer join\n inner join (\n select \n od.userId,\n -- can be null if no orders for type\n max (case when orderType = 1 \n then ORDERID\n else null\n end) as maxTypeOneOrderId,\n\n -- can be null if no orders for type\n max (case when orderType = 2\n then ORDERID \n else null\n end) as maxTypeTwoOrderId\n from orderData od\n group by userId) as maxOrderKeys on\n maxOrderKeys.userId = ud.userId\n inner join orderData od1 on\n od1.ORDERID = maxTypeTwoOrderId\n inner join orderData od2 on\n OD2.ORDERID = maxTypeTwoOrderId\n select ud.userId,ud.fullname, \n order1.orderId, order1.orderType, order1.createDate, \n order2.orderId, order2.orderType, order2.createDate\n from userData ud,\n orderData order1,\n orderData order2\n where ud.userId = order1.userId\n and ud.userId = order2.userId\n and order1.orderId = (select max(orderId)\n from orderData od1\n where od1.userId = ud.userId\n and od1.orderType = 1)\n and order2.orderId = (select max(orderId)\n from orderData od2\n where od2.userId = ud.userId\n and od2.orderType = 2)\n CREATE TABLE [dbo].[orderData](\n [orderId] [int] IDENTITY(1,1) NOT NULL,\n [createDate] [datetime] NOT NULL,\n [orderType] [tinyint] NOT NULL, \n [userId] [int] NOT NULL\n) \n\nCREATE TABLE [dbo].[userData](\n [userId] [int] IDENTITY(1,1) NOT NULL,\n [fullname] [nvarchar](50) NOT NULL\n) \n\n-- Create 1000 users with 100 order each\ndeclare @userId int\ndeclare @usersAdded int\nset @usersAdded = 0\n\nwhile @usersAdded < 1000\nbegin\n insert into userData (fullname) values ('Mario' + ltrim(str(@usersAdded)))\n set @userId = @@identity\n\n declare @orderSetsAdded int\n set @orderSetsAdded = 0\n while @orderSetsAdded < 10\n begin\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-06-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-02-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-08-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-09-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-01-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-06-06', 2)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-02-02', 2)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-08-09', 2)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-09-01', 2)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-01-04', 2)\n\n set @orderSetsAdded = @orderSetsAdded + 1\n end\n set @usersAdded = @usersAdded + 1\nend\n -- Uncomment these to clear some caches\n--DBCC DROPCLEANBUFFERS\n--DBCC FREEPROCCACHE\n\nset statistics io on\nset statistics time on\n\n-- INSERT TEST QUERY HERE\n\nset statistics time off\nset statistics io off\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9304/"
] |
154,262
|
<p>It's very easy to mark an image file to become an embedded resource however how does one access the image thereafter. Please can I have some example code?</p>
|
[
{
"answer_id": 154276,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "YourProjectsBaseNamespace.Properties.Resources.YourImageResourceName\n"
},
{
"answer_id": 154278,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 3,
"selected": false,
"text": "System.Drawing.Bitmap bitmap1 = myProject.Properties.Resources.Image01; \n Assembly _assembly = Assembly.GetExecutingAssembly();\n\nStream _imageStream = \n _assembly.GetManifestResourceStream(\n \"ThumbnailPictureViewer.resources.Image1.bmp\");\nBitmap theDefaultImage = new Bitmap(_imageStream);\n"
},
{
"answer_id": 154285,
"author": "Leahn Novash",
"author_id": 5954,
"author_profile": "https://Stackoverflow.com/users/5954",
"pm_score": 0,
"selected": false,
"text": "//Get the names of the embedded resource files;\n\nList<string> resources = new List<string>(AssemblyBuilder.GetExecutingAssembly().GetManifestResourceNames());\n\n//Get the stream\n\nStreamReader sr = new StreamReader(\n AssemblyBuilder.GetExecutingAssembly().GetManifestResourceStream(\n resources.Find(target => target.ToLower().Contains(\"insert name here\"))\n"
},
{
"answer_id": 68335887,
"author": "Andrei15193",
"author_id": 2788501,
"author_profile": "https://Stackoverflow.com/users/2788501",
"pm_score": 0,
"selected": false,
"text": "Stream"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22284/"
] |
154,270
|
<p>It's been a while since I've programmed a GUI program, so this may end up being super simple, but I can't find the solution anywhere online. </p>
<p>Basically my problem is that when I maximize my program, all the things inside of the window (buttons, textboxes, etc.) stay in the same position in the window, which results in a large blank area near the bottom and right side. </p>
<p>Is there a way of making the the elements in the program to stretch to scale?</p>
|
[
{
"answer_id": 154359,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 0,
"selected": false,
"text": "FlowLayoutPanel TableLayoutPanel"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23875/"
] |
154,295
|
<p>In the latest MVC preview, I'm using this route for a legacy URL:</p>
<pre><code>routes.MapRoute(
"Legacy-Firefox", // Route name
"Firefox-Extension/", // URL with parameters
new { controller = "Home", action = "Firefox", id = "" } // Parameter defaults
);
</code></pre>
<p>The problem is that both of these URL's work:
<a href="http://example.com/Firefox-Extension" rel="nofollow noreferrer">http://example.com/Firefox-Extension</a>
<a href="http://example.com/Firefox-Extension/" rel="nofollow noreferrer">http://example.com/Firefox-Extension/</a></p>
<p>I only want the second to work (for SEO). Also, when I create a link to that page, the routing engine gives me back a URL without a trailing slash.</p>
<p>This is the code I'm using to generate the link:</p>
<pre><code><%= Html.ActionLink("Firefox Extension", "Firefox", "Home")%>
</code></pre>
<p>I believe can fix the first problem by using an HTTP handler to do a 301 redirect to the URL with the trailing slash. However, I want to link to the URL with the trailing slash, and I'm hoping to not have to hard-code the version with the slash.</p>
<p>Anyone know how to force the route to use a trailing slash?</p>
|
[
{
"answer_id": 955620,
"author": "Murad X",
"author_id": 68294,
"author_profile": "https://Stackoverflow.com/users/68294",
"pm_score": 2,
"selected": false,
"text": "public static string RouteLinkEx(this HtmlHelper helper,string text,string routeName,RouteValueDictionary rvd,object htmlAttributes)\n {\n\n UrlHelper uh = new UrlHelper(helper.ViewContext.RequestContext,helper.RouteCollection);\n // Add trailing slash to the url of the link\n string url = uh.RouteUrl(routeName,rvd) + \"/\";\n TagBuilder builder = new TagBuilder(\"a\")\n {\n InnerHtml = !string.IsNullOrEmpty(text) ? HttpUtility.HtmlEncode(text) : string.Empty\n };\n builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));\n builder.MergeAttribute(\"href\",url);\n return builder.ToString(TagRenderMode.Normal);\n //--- \n }\n"
},
{
"answer_id": 2174618,
"author": "Sky",
"author_id": 263223,
"author_profile": "https://Stackoverflow.com/users/263223",
"pm_score": 1,
"selected": false,
"text": " public static string RouteLinkEx(this HtmlHelper helper, string text, string routeName, object routeValues)\n {\n\n UrlHelper uh = new UrlHelper(helper.ViewContext.RequestContext);\n\n // Add trailing slash to the url of the link \n string url = uh.RouteUrl(routeName, routeValues) + \"/\";\n TagBuilder builder = new TagBuilder(\"a\")\n {\n InnerHtml = !string.IsNullOrEmpty(text) ? HttpUtility.HtmlEncode(text) : string.Empty\n };\n //builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));\n builder.MergeAttribute(\"href\", url);\n return builder.ToString(TagRenderMode.Normal);\n //--- \n }\n"
},
{
"answer_id": 3544941,
"author": "Sergey",
"author_id": 65214,
"author_profile": "https://Stackoverflow.com/users/65214",
"pm_score": 1,
"selected": false,
"text": " public static MvcHtmlString RouteLinkEx(this HtmlHelper helper, string text, RouteValueDictionary routeValues)\n {\n return RouteLinkEx(helper, text, null, routeValues, null);\n }\n\n public static MvcHtmlString RouteLinkEx(this HtmlHelper htmlHelper, string text, string routeName, RouteValueDictionary routeValues, object htmlAttributes)\n {\n string url = UrlHelper.GenerateUrl(routeName, null, null, null, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, false);\n\n var builder = new TagBuilder(\"a\")\n {\n InnerHtml = !string.IsNullOrEmpty(text) ? HttpUtility.HtmlEncode(text) : string.Empty\n };\n builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));\n // Add trailing slash to the url of the link\n builder.MergeAttribute(\"href\", url + \"/\");\n return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));\n }\n"
},
{
"answer_id": 31582416,
"author": "Muhammad Rehan Saeed",
"author_id": 1212017,
"author_profile": "https://Stackoverflow.com/users/1212017",
"pm_score": 2,
"selected": false,
"text": "public static class RouteConfig\n{\n public static void RegisterRoutes(RouteCollection routes)\n {\n // Imprive SEO by stopping duplicate URL's due to case or trailing slashes.\n routes.AppendTrailingSlash = true;\n routes.LowercaseUrls = true;\n\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\n routes.MapRoute(\n name: \"Default\",\n url: \"{controller}/{action}/{id}\",\n defaults: new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional });\n }\n}\n RedirectToCanonicalUrlAttribute /// <summary>\n/// To improve Search Engine Optimization SEO, there should only be a single URL for each resource. Case \n/// differences and/or URL's with/without trailing slashes are treated as different URL's by search engines. This \n/// filter redirects all non-canonical URL's based on the settings specified to their canonical equivalent. \n/// Note: Non-canonical URL's are not generated by this site template, it is usually external sites which are \n/// linking to your site but have changed the URL case or added/removed trailing slashes.\n/// (See Google's comments at http://googlewebmastercentral.blogspot.co.uk/2010/04/to-slash-or-not-to-slash.html\n/// and Bing's at http://blogs.bing.com/webmaster/2012/01/26/moving-content-think-301-not-relcanonical).\n/// </summary>\n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]\npublic class RedirectToCanonicalUrlAttribute : FilterAttribute, IAuthorizationFilter\n{\n private readonly bool appendTrailingSlash;\n private readonly bool lowercaseUrls;\n\n #region Constructors\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"RedirectToCanonicalUrlAttribute\" /> class.\n /// </summary>\n /// <param name=\"appendTrailingSlash\">If set to <c>true</c> append trailing slashes, otherwise strip trailing \n /// slashes.</param>\n /// <param name=\"lowercaseUrls\">If set to <c>true</c> lower-case all URL's.</param>\n public RedirectToCanonicalUrlAttribute(\n bool appendTrailingSlash, \n bool lowercaseUrls)\n {\n this.appendTrailingSlash = appendTrailingSlash;\n this.lowercaseUrls = lowercaseUrls;\n } \n\n #endregion\n\n #region Public Methods\n\n /// <summary>\n /// Determines whether the HTTP request contains a non-canonical URL using <see cref=\"TryGetCanonicalUrl\"/>, \n /// if it doesn't calls the <see cref=\"HandleNonCanonicalRequest\"/> method.\n /// </summary>\n /// <param name=\"filterContext\">An object that encapsulates information that is required in order to use the \n /// <see cref=\"RedirectToCanonicalUrlAttribute\"/> attribute.</param>\n /// <exception cref=\"ArgumentNullException\">The <paramref name=\"filterContext\"/> parameter is <c>null</c>.</exception>\n public virtual void OnAuthorization(AuthorizationContext filterContext)\n {\n if (filterContext == null)\n {\n throw new ArgumentNullException(\"filterContext\");\n }\n\n if (string.Equals(filterContext.HttpContext.Request.HttpMethod, \"GET\", StringComparison.Ordinal))\n {\n string canonicalUrl;\n if (!this.TryGetCanonicalUrl(filterContext, out canonicalUrl))\n {\n this.HandleNonCanonicalRequest(filterContext, canonicalUrl);\n }\n }\n }\n\n #endregion\n\n #region Protected Methods\n\n /// <summary>\n /// Determines whether the specified URl is canonical and if it is not, outputs the canonical URL.\n /// </summary>\n /// <param name=\"filterContext\">An object that encapsulates information that is required in order to use the \n /// <see cref=\"RedirectToCanonicalUrlAttribute\" /> attribute.</param>\n /// <param name=\"canonicalUrl\">The canonical URL.</param>\n /// <returns><c>true</c> if the URL is canonical, otherwise <c>false</c>.</returns>\n protected virtual bool TryGetCanonicalUrl(AuthorizationContext filterContext, out string canonicalUrl)\n {\n bool isCanonical = true;\n\n canonicalUrl = filterContext.HttpContext.Request.Url.ToString();\n int queryIndex = canonicalUrl.IndexOf(QueryCharacter);\n\n if (queryIndex == -1)\n {\n bool hasTrailingSlash = canonicalUrl[canonicalUrl.Length - 1] == SlashCharacter;\n\n if (this.appendTrailingSlash)\n {\n // Append a trailing slash to the end of the URL.\n if (!hasTrailingSlash)\n {\n canonicalUrl += SlashCharacter;\n isCanonical = false;\n }\n }\n else\n {\n // Trim a trailing slash from the end of the URL.\n if (hasTrailingSlash)\n {\n canonicalUrl = canonicalUrl.TrimEnd(SlashCharacter);\n isCanonical = false;\n }\n }\n }\n else\n {\n bool hasTrailingSlash = canonicalUrl[queryIndex - 1] == SlashCharacter;\n\n if (this.appendTrailingSlash)\n {\n // Append a trailing slash to the end of the URL but before the query string.\n if (!hasTrailingSlash)\n {\n canonicalUrl = canonicalUrl.Insert(queryIndex, SlashCharacter.ToString());\n isCanonical = false;\n }\n }\n else\n {\n // Trim a trailing slash to the end of the URL but before the query string.\n if (hasTrailingSlash)\n {\n canonicalUrl = canonicalUrl.Remove(queryIndex - 1, 1);\n isCanonical = false;\n }\n }\n }\n\n if (this.lowercaseUrls)\n {\n foreach (char character in canonicalUrl)\n {\n if (char.IsUpper(character))\n {\n canonicalUrl = canonicalUrl.ToLower();\n isCanonical = false;\n break;\n }\n }\n }\n\n return isCanonical;\n }\n\n /// <summary>\n /// Handles HTTP requests for URL's that are not canonical. Performs a 301 Permanent Redirect to the canonical URL.\n /// </summary>\n /// <param name=\"filterContext\">An object that encapsulates information that is required in order to use the \n /// <see cref=\"RedirectToCanonicalUrlAttribute\" /> attribute.</param>\n /// <param name=\"canonicalUrl\">The canonical URL.</param>\n protected virtual void HandleNonCanonicalRequest(AuthorizationContext filterContext, string canonicalUrl)\n {\n filterContext.Result = new RedirectResult(canonicalUrl, true);\n }\n\n #endregion\n}\n filters.Add(new RedirectToCanonicalUrlAttribute(\n RouteTable.Routes.AppendTrailingSlash, \n RouteTable.Routes.LowercaseUrls));\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23837/"
] |
154,299
|
<p>I am debugging a VB6 executable. The executable loads dlls and files from it's current directory, when running. When run in debugger, the current directory seems to be VB6's dir. </p>
<p>How do I set working directory for VB6?</p>
|
[
{
"answer_id": 154327,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "'Declaration\nPrivate Declare Function SetCurrentDirectory Lib \"kernel32\" _\nAlias \"SetCurrentDirectoryA\" (ByVal lpPathName As String) As Long\n\n'syntax to set current dir\nSetCurrentDirectory App.Path\n"
},
{
"answer_id": 154343,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 5,
"selected": true,
"text": "Public Sub ChangeDirToApp()\n#If MPDEBUG = 0 And MPRELEASE = 1 Then\n ' assume that in final release builds the current dir will be the location\n ' of where the .exe was installed; paths are relative to the install dir\n ChDrive App.path\n ChDir App.path\n#Else\n ' in all debug/IDE related builds, we need to switch to the \"bin\" dir\n ChDrive App.path\n ChDir App.path & BackSlash(App.path) & \"..\\bin\"\n#End If\nEnd Sub\n"
},
{
"answer_id": 154572,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 3,
"selected": false,
"text": "Sub Main Dim gISIDE as Boolean\n\nSub Main()\n If IsIDE Then\n ChDrive App.Path\n ChDir App.Path\n End If\n\n ' The rest of the code goes here...\n\nEnd Sub\n\nPublic Function IsIDE() As Boolean '\n IsIDE = False\n 'This line is only executed if running in the IDE and then returns True\n Debug.Assert CheckIDE \n If gISIDE Then \n IsIDE = True\n End If\nEnd Function\n\nPrivate Function CheckIDE() As Boolean ' this is a helper function for Public Function IsIDE() \n gISIDE = True 'set global flag \n CheckIDE = True \nEnd Function\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] |
154,305
|
<p>Given the following canvas:</p>
<pre><code><Canvas>
<Canvas.LayoutTransform>
<ScaleTransform ScaleX="1" ScaleY="1" CenterX=".5" CenterY=".5" />
</Canvas.LayoutTransform>
<Button x:Name="scaleButton" Content="Scale Me" Canvas.Top="10" Canvas.Left="10" />
<Button x:Name="dontScaleButton" Content="DON'T Scale Me" Canvas.Top="10" Canvas.Left="50" />
</Canvas>
</code></pre>
<p>Is it possible to scale 1 button, but not the other when ScaleX and ScaleY changes?</p>
|
[
{
"answer_id": 154500,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 2,
"selected": false,
"text": "Canvas Canvas <Canvas>\n <Canvas>\n <Canvas.LayoutTransform>\n <ScaleTransform ScaleX=\"1\" ScaleY=\"1\" CenterX=\".5\" CenterY=\".5\" />\n </Canvas.LayoutTransform>\n <Button x:Name=\"scaleButton\" Content=\"Scale Me\" Canvas.Top=\"10\" Canvas.Left=\"10\" />\n </Canvas>\n <Button x:Name=\"dontScaleButton\" Content=\"DON'T Scale Me\" Canvas.Top=\"10\" Canvas.Left=\"50\" />\n</Canvas>\n"
},
{
"answer_id": 5671474,
"author": "H.B.",
"author_id": 546730,
"author_profile": "https://Stackoverflow.com/users/546730",
"pm_score": 3,
"selected": false,
"text": "<Button x:Name=\"dontScaleButton\" Content=\"DON'T Scale Me\" Canvas.Top=\"10\" Canvas.Left=\"50\"\n LayoutTransform=\"{Binding LayoutTransform.Inverse,\n RelativeSource={RelativeSource AncestorType=Canvas}}\"/>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4580/"
] |
154,307
|
<p>I just saw this behaviour and I'm a bit surprised by it...</p>
<p>If I add 3 or 4 elements to a Dictionary, and then do a "For Each" to get all the keys, they appear in the same order I added them.</p>
<p>The reason this surprises me is that a Dictionary is supposed to be a HashTable internally, so I expected things to come out in ANY order (ordered by the hash of the key, right?)</p>
<p>What am I missing here?
Is this a behaviour I can count on?</p>
<p>EDIT: OK, I thought already of many of the reasons why this <em>might</em> happen (like the separate list to entries, whether this is a coincidence, etc).
My question is, does anyone <strong>know</strong> how this really works?</p>
|
[
{
"answer_id": 976871,
"author": "Dolphin",
"author_id": 110672,
"author_profile": "https://Stackoverflow.com/users/110672",
"pm_score": 6,
"selected": true,
"text": "add 1\nadd 2\nadd 3\nadd 4\nremove 2\nadd 5\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
154,309
|
<p>One of our programs is sometimes getting an <code>OutOfMemory</code> error on one user's machine, but of course not when I'm testing it. I just ran it with JProfiler (on a 10 day evaluation license because I've never used it before), and filtering on our code prefix, the biggest chunk both in total size and number of instances is 8000+ instances of a particular simple class. </p>
<p>I clicked the "Garbage Collect" button on JProfiler, and most instances of other classes of ours went away, but not these particular ones. I ran the test again, still in the same instance, and it created 4000+ more instances of the class, but when I clicked "Garbage Collect", those went away leaving the 8000+ original ones.</p>
<p>These instances do get stuck into various Collections at various stages. I assume that the fact that they're not garbage collected must mean that something is holding onto a reference to one of the collections so that's holding onto a reference to the objects.</p>
<p>Any suggestions how I can figure out what is holding onto the reference? I'm looking for suggestions of what to look for in the code, as well as ways to find this out in JProfiler if there are.</p>
|
[
{
"answer_id": 154454,
"author": "18Rabbit",
"author_id": 12662,
"author_profile": "https://Stackoverflow.com/users/12662",
"pm_score": 3,
"selected": false,
"text": "Map<String, Object> map = new HashMap<String, Object>(); // 1 Object\nString name = \"test\"; // 2 Objects\nObject o = new Object(); // 3 Objects\nmap.put(name, o); // 3 Objects, 2 of which have 2 references to them\n\no = null; // The objects are still being\nname = null; // referenced by the HashMap and won't be GC'd\n\nSystem.gc(); // Nothing is deleted.\n\nObject test = map.get(\"test\"); // Returns o\ntest = null;\n\nmap.remove(\"test\"); // Now we're down to just the HashMap in memory\n // o, name and test can all be GC'd\n"
},
{
"answer_id": 154570,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 5,
"selected": true,
"text": "C:\\dump>jmap -dump:format=b,file=heap.bin 3552\n\nC:\\dump>jhat heap.bin\nReading from heap.bin...\nDump file created Tue Sep 30 19:46:23 BST 2008\nSnapshot read, resolving...\nResolving 35484 objects...\nChasing references, expect 7 dots.......\nEliminating duplicate references.......\nSnapshot resolved.\nStarted HTTP server on port 7000\nServer is ready.\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333/"
] |
154,314
|
<p>I've found a couple of references (<a href="http://www.javapractices.com/topic/TopicAction.do?Id=23" rel="noreferrer">for example</a>) that suggest using <code>final</code> as much as possible and I'm wondering how important that is. This is mainly in the the context of method parameters and local variables, not final methods or classes. For constants, it makes obvious sense.</p>
<p>On one hand, the compiler can make some optimizations and it makes the programmer's intent clearer. On the other hand, it adds verbosity and the optimizations may be trivial.</p>
<p>Is it something I should make an effort to remember?</p>
|
[
{
"answer_id": 154510,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 9,
"selected": true,
"text": "if else"
},
{
"answer_id": 155881,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 3,
"selected": false,
"text": "final final"
},
{
"answer_id": 155916,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": false,
"text": " public int processSomethingCritical( final int x, final int y ){\n // hundreds of lines here \n // for loop here...\n int x2 = 0;\n x++; // bug aarrgg...\n // hundreds of lines there\n // if( x == 0 ) { ...\n\n }\n"
},
{
"answer_id": 17229101,
"author": "mel3kings",
"author_id": 2023728,
"author_profile": "https://Stackoverflow.com/users/2023728",
"pm_score": 2,
"selected": false,
"text": "final public static class CircleToolsBetter {\n public final static double PI = 3.141;\n public double getCircleArea(final double radius) {\n return (Math.pow(radius, 2) * PI);\n }\n }\n public static String someMethod(final String environmentKey) {\n final String key = \"env.\" + environmentKey;\n System.out.println(\"Key is: \" + key);\n return (System.getProperty(key));\n\n }\n\n}\n public class FinalVariables {\n\n\n public final static void main(final String[] args) {\n System.out.println(\"Note how the key variable is changed.\");\n someMethod(\"JAVA_HOME\");\n someMethod(\"ANT_HOME\");\n }\n}\n public double equation2Better(final double inputValue) {\n final double K = 1.414;\n final double X = 45.0;\n\ndouble result = (((Math.pow(inputValue, 3.0d) * K) + X) * M);\ndouble powInputValue = 0; \nif (result > 360) {\n powInputValue = X * Math.sin(result); \n} else {\n inputValue = K * Math.sin(result); // <= Compiler error \n}\n public final static Set VALID_COLORS; \n static {\n Set temp = new HashSet( );\n temp.add(Color.red);\n temp.add(Color.orange);\n temp.add(Color.yellow);\n temp.add(Color.green);\n temp.add(Color.blue);\n temp.add(Color.decode(\"#4B0082\")); // indigo\n temp.add(Color.decode(\"#8A2BE2\")); // violet\n VALID_COLORS = Collections.unmodifiableSet(temp);\n }\n Set colors = Rainbow.VALID_COLORS;\ncolors.add(Color.black); // <= logic error but allowed by compiler\n public final class SomeClass {\n // . . . Class contents\n}\n public class SomeClass {\n public final static SOME_INSTANCE = new SomeClass(5);\n private SomeClass(final int value) {\n }\n public class Test{\n private Test(Class beanClass, Class stopClass, int flags)\n throws Exception{\n // . . . snip . . . \n }\n}\n"
},
{
"answer_id": 17518942,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "final int CM_PER_INCH = 2.54;\n final String helloworld = \"Hello World\";\nhelloworld = \"A String\"; //helloworld still equals \"Hello World\"\n local variable is accessed from inner class, must be declared final\n final String[] helloworld = new String[1];\nhelloworld[0] = \"Hello World!\";\nSystem.out.println(helloworld[0]);\nhelloworld[0] = \"A String\";\nSystem.out.println(helloworld[0]);\n Hello World!\nA String\n"
},
{
"answer_id": 18856192,
"author": "Adam Gent",
"author_id": 318174,
"author_profile": "https://Stackoverflow.com/users/318174",
"pm_score": 4,
"selected": false,
"text": "final if,else,switch final String name;\n switch(pluginType) {\n case CANDIDATE_EXPORT:\n name = \"Candidate Stuff\";\n break;\n case JOB_POSTING_IMPORT:\n name = \"Blah\";\n break;\n default:\n throw new IllegalStateException();\n }\n case name let String name final break final String name;\n switch(pluginType) {\n case CANDIDATE_EXPORT:\n name = \"Candidate Stuff\";\n //break; whoops forgot break.. \n //this will cause a compile error for final ;P @Recurse\n case JOB_POSTING_IMPORT:\n name = \"Blah\";\n break;\n }\n // code, code, code\n // Below is not possible with final\n name = \"Whoops bug\";\n break String name;\n switch(pluginType) {\n case CANDIDATE_EXPORT:\n name = \"Candidate Stuff\";\n break;\n //should have handled all the cases for pluginType\n }\n // code, code, code\n // Below is not possible with final\n name = \"Whoops bug\";\n type plugin = CandidateExport | JobPostingImport\n\nlet p = CandidateExport\n\nlet name = match p with\n | CandidateExport -> \"Candidate Stuff\"\n | JobPostingImport -> \"Blah\" ;;\n match ... with ... (define name \n (match b\n ['CandidateExport \"Candidate Stuff\"]\n ['JobPostingImport \"Blah\"]))\n"
},
{
"answer_id": 33971921,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 1,
"selected": false,
"text": "final immutable effectively final variable"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23669/"
] |
154,332
|
<p>I'm using <strong>mysqldump</strong> to replicate a database between accounts on a particular machine. Everything works just great, except when we get to our defined views. Because the dump includes a line like the following ...</p>
<pre><code>/*!50013 DEFINER=`user_a`@`localhost` SQL SECURITY DEFINER */
</code></pre>
<p>... when loading the dump into mysql on user_b we receive an error: </p>
<pre><code>ERROR 1227 (42000) at line 657: Access denied; you need the SUPER privilege for this operation
</code></pre>
<p>Needless to say, I don't have SUPER privilege on this mysql instance. Is there a way to convince <strong>mysqldump</strong> to dump the views in a user-agnostic way? I can't find anything in the manual on this point. Do I have to actually parse the dumpfile to replace the usernames? Or am I missing something?</p>
|
[
{
"answer_id": 313854,
"author": "user40237",
"author_id": 40237,
"author_profile": "https://Stackoverflow.com/users/40237",
"pm_score": 6,
"selected": true,
"text": "mysqldump -uuser1 -ppassword1 database1 > backup.sql\n\nsed '/^\\/\\*\\!50013 DEFINER/d' backup.sql > backup_without_50013.sql\n\nmysql -u user2 -ppassword2 -D database2 < backup_without_50013.sql\n"
},
{
"answer_id": 1751162,
"author": "Sander",
"author_id": 213184,
"author_profile": "https://Stackoverflow.com/users/213184",
"pm_score": 0,
"selected": false,
"text": "mysqldump \"--skip-triggers\""
},
{
"answer_id": 1931022,
"author": "johnk",
"author_id": 234870,
"author_profile": "https://Stackoverflow.com/users/234870",
"pm_score": 4,
"selected": false,
"text": "user_a localhost"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] |
154,365
|
<p>I need to find occurrences of ~ 25 000 words within a text. What is the most suitable algorithm/library for this purpose?</p>
<p>target language is C++</p>
|
[
{
"answer_id": 154381,
"author": "Justin R.",
"author_id": 4593,
"author_profile": "https://Stackoverflow.com/users/4593",
"pm_score": 4,
"selected": false,
"text": "int capacity = 2000000; // the number of items you expect to add to the filter\nFilter<string> filter = new Filter<string>(capacity);\nfilter.Add(\"Lorem\");\nfilter.Add(\"Ipsum\");\nif (filter.Contains(\"Lorem\"))\n Console.WriteLine(\"Match!\");\n"
},
{
"answer_id": 154410,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "stdext::hash_map std::tr1::unordered_map #ifndef FINDER_HPP\n#define FINDER_HPP\n\n#include <string>\n\nnamespace thru { namespace matching {\n\nclass Finder {\npublic:\n virtual bool find() = 0;\n\n virtual std::size_t position() const = 0;\n\n virtual ~Finder() = 0;\n\nprotected:\n static size_t code_from_chr(char c) {\n return static_cast<size_t>(static_cast<unsigned char>(c));\n }\n};\n\ninline Finder::~Finder() { }\n\n} } // namespace thru::matching\n\n#endif // !defined(FINDER_HPP)\n #include <vector>\n#include <hash_map>\n\n#include \"finder.hpp\"\n\n#ifndef WUMANBER_HPP\n#define WUMANBER_HPP\n\nnamespace thru { namespace matching {\n\nclass WuManberFinder : public Finder {\npublic:\n\n WuManberFinder(std::string const& text, std::vector<std::string> const& patterns);\n\n bool find();\n\n std::size_t position() const;\n\n std::size_t pattern_index() const;\n\nprivate:\n\n template <typename K, typename V>\n struct HashMap {\n typedef stdext::hash_map<K, V> Type;\n };\n\n typedef HashMap<std::string, std::size_t>::Type shift_type;\n typedef HashMap<std::string, std::vector<std::size_t> >::Type hash_type;\n\n std::string const& m_text;\n std::vector<std::string> const& m_patterns;\n shift_type m_shift;\n hash_type m_hash;\n std::size_t m_pos;\n std::size_t m_find_pos;\n std::size_t m_find_pattern_index;\n std::size_t m_lmin;\n std::size_t m_lmax;\n std::size_t m_B;\n};\n\n} } // namespace thru::matching\n\n#endif // !defined(WUMANBER_HPP)\n #include <cmath>\n#include <iostream>\n\n#include \"wumanber.hpp\"\n\nusing namespace std;\n\nnamespace thru { namespace matching {\n\nWuManberFinder::WuManberFinder(string const& text, vector<string> const& patterns)\n : m_text(text)\n , m_patterns(patterns)\n , m_shift()\n , m_hash()\n , m_pos()\n , m_find_pos(0)\n , m_find_pattern_index(0)\n , m_lmin(m_patterns[0].size())\n , m_lmax(m_patterns[0].size())\n , m_B()\n{\n for (size_t i = 0; i < m_patterns.size(); ++i) {\n if (m_patterns[i].size() < m_lmin)\n m_lmin = m_patterns[i].size();\n else if (m_patterns[i].size() > m_lmax)\n m_lmax = m_patterns[i].size();\n }\n\n m_pos = m_lmin;\n m_B = static_cast<size_t>(ceil(log(2.0 * m_lmin * m_patterns.size()) / log(256.0)));\n\n for (size_t i = 0; i < m_patterns.size(); ++i)\n m_hash[m_patterns[i].substr(m_patterns[i].size() - m_B)].push_back(i);\n\n for (size_t i = 0; i < m_patterns.size(); ++i) {\n for (size_t j = 0; j < m_patterns[i].size() - m_B + 1; ++j) {\n string bgram = m_patterns[i].substr(j, m_B);\n size_t pos = m_patterns[i].size() - j - m_B;\n\n shift_type::iterator old = m_shift.find(bgram);\n if (old == m_shift.end())\n m_shift[bgram] = pos;\n else\n old->second = min(old->second, pos);\n }\n }\n}\n\nbool WuManberFinder::find() {\n while (m_pos <= m_text.size()) {\n string bgram = m_text.substr(m_pos - m_B, m_B);\n shift_type::iterator i = m_shift.find(bgram);\n if (i == m_shift.end())\n m_pos += m_lmin - m_B + 1;\n else {\n if (i->second == 0) {\n vector<size_t>& list = m_hash[bgram];\n // Verify all patterns in list against the text.\n ++m_pos;\n for (size_t j = 0; j < list.size(); ++j) {\n string const& str = m_patterns[list[j]];\n m_find_pos = m_pos - str.size() - 1;\n size_t k = 0;\n\n for (; k < str.size(); ++k)\n if (str[k] != m_text[m_find_pos + k])\n break;\n\n if (k == str.size()) {\n m_find_pattern_index = list[j];\n return true;\n }\n }\n }\n else\n m_pos += i->second;\n }\n }\n\n return false;\n}\n\nsize_t WuManberFinder::position() const {\n return m_find_pos;\n}\n\nsize_t WuManberFinder::pattern_index() const {\n return m_find_pattern_index;\n}\n\n} } // namespace thru::matching\n vector<string> patterns;\npatterns.push_back(\"announce\");\npatterns.push_back(\"annual\");\npatterns.push_back(\"annually\");\n\nWuManberFinder wmf(\"CPM_annual_conference_announce\", patterns);\n\nwhile (wmf.find())\n cout << \"Pattern \\\"\" << patterns[wmf.pattern_index()] <<\n \"\\\" found at position \" << wmf.position() << endl;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127878/"
] |
154,372
|
<p>How do I get a list of all the tables defined for the database when using active record?</p>
|
[
{
"answer_id": 155524,
"author": "Jay Stramel",
"author_id": 3547,
"author_profile": "https://Stackoverflow.com/users/3547",
"pm_score": 2,
"selected": false,
"text": "Dir[\"app/models/*.rb\"].each do |file_path|\n require file_path # Make sure that the model has been loaded.\n\n basename = File.basename(file_path, File.extname(file_path))\n clazz = basename.camelize.constantize\n\n clazz.find(:all).each do |rec|\n # Important code here...\n end\nend\n"
},
{
"answer_id": 155723,
"author": "François Beausoleil",
"author_id": 7355,
"author_profile": "https://Stackoverflow.com/users/7355",
"pm_score": 9,
"selected": true,
"text": "ActiveRecord::ConnectionAdapters::SchemaStatements#tables >> ActiveRecord::Base.connection.tables\n=> [\"accounts\", \"assets\", ...]\n activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb:21 activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:412 activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb:615 activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb:176"
},
{
"answer_id": 14276740,
"author": "Thomas E",
"author_id": 1208895,
"author_profile": "https://Stackoverflow.com/users/1208895",
"pm_score": 4,
"selected": false,
"text": "ActiveRecord::Base.connection.tables.each do |table|\n next if table.match(/\\Aschema_migrations\\Z/)\n klass = table.singularize.camelize.constantize \n puts \"#{klass.name} has #{klass.count} records\"\nend\n"
},
{
"answer_id": 50990734,
"author": "Horacio",
"author_id": 3043906,
"author_profile": "https://Stackoverflow.com/users/3043906",
"pm_score": 4,
"selected": false,
"text": "ApplicationRecord Array ar_internal_metadata schema_migrations ApplicationRecord.connection.tables\n ar_internal_metadata schema_migrations ApplicationRecord.connection.tables - %w[ar_internal_metadata schema_migrations]\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3547/"
] |
154,387
|
<p>I'm trying to get something very subtle to work, it looks pretty awful right now. I'm trying to paint the background of a TGroupBox which I have overloaded the paint function of so that the corners are show through to their parent object. I've got a bunch of nested group boxes that look very decent without XPThemes. </p>
<p>Is there a way to paint part of a background transparent at runtime. I'm programming the form generator, not using Delphi design view.</p>
|
[
{
"answer_id": 154470,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": true,
"text": " object GroupBox1: TGroupBox\n Left = 64\n Top = 56\n Width = 481\n Height = 361\n Margins.Left = 10\n Caption = 'GroupBox1'\n ParentBackground = False\n TabOrder = 0\n object GroupBox2: TGroupBox\n Left = 2\n Top = 254\n Width = 477\n Height = 105\n Align = alBottom\n Caption = 'GroupBox2'\n TabOrder = 0\n end\n object GroupBox3: TGroupBox\n Left = 2\n Top = 15\n Width = 477\n Height = 239\n Align = alClient\n Caption = 'GroupBox3'\n TabOrder = 1\n end\n end\n"
},
{
"answer_id": 154855,
"author": "X-Ray",
"author_id": 14031,
"author_profile": "https://Stackoverflow.com/users/14031",
"pm_score": 2,
"selected": false,
"text": "procedure TfraNewRTMDisplay.pbPaint(Sender: TObject);\nconst\n icMarginPixels=0;\n icCornerElipsisDiameterPixels=10;\nbegin\n pb.Canvas.Pen.Color:=clDkGray;\n pb.Canvas.Pen.Width:=1;\n pb.Canvas.Pen.Style:=psSolid;\n pb.Canvas.Brush.Color:=m_iDisplayColor;\n pb.Canvas.Brush.Style:=bsSolid;\n pb.Canvas.RoundRect(icMarginPixels,\n icMarginPixels,\n pb.Width-icMarginPixels*2,\n pb.Height-icMarginPixels*2,\n icCornerElipsisDiameterPixels,\n icCornerElipsisDiameterPixels);\nend;\n"
},
{
"answer_id": 162545,
"author": "Peter Turner",
"author_id": 1765,
"author_profile": "https://Stackoverflow.com/users/1765",
"pm_score": 1,
"selected": false,
"text": "ParentBackground := false"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] |
154,411
|
<p>I am having trouble getting Team Build to execute my MbUnit unit tests. I have tried to edit TFSBuild.proj and added the following parts:</p>
<pre><code><Project ...>
<UsingTask TaskName="MbUnit.MSBuild.Tasks.MbUnit" AssemblyFile="path_to_MbUnit.MSBuild.Tasks.dll" />
...
...
<ItemGroup>
<TestAssemblies Include="$(OutDir)\Project1.dll" />
<TestAssemblies Include="$(OutDir)\Project2.dll" />
</ItemGroup>
<Target Name="Tests">
<MbUnit
Assemblies="@(TestAssemblies)"
ReportTypes="html"
ReportFileNameFormat="buildreport{0}{1}"
ReportOutputDirectory="." />
</Target>
...
</Project>
</code></pre>
<p>But I have yet to get the tests to run.</p>
|
[
{
"answer_id": 154807,
"author": "Martin Woodward",
"author_id": 6438,
"author_profile": "https://Stackoverflow.com/users/6438",
"pm_score": 0,
"selected": false,
"text": " <PropertyGroup>\n <TestDependsOn>\n $(TestDependsOn);\n CallMbUnitTests;\n </TestDependsOn>\n </PropertyGroup>\n\n <Target Name=\"CallMbUnitTests\">\n <MSBuild Projects=\"$(MSBuildProjectFile)\"\n Properties=\"BuildAgentName=$(BuildAgentName);BuildAgentUri=$(BuildAgentUri);BuildDefinitionName=$(BuildDefinitionName);BuildDefinitionUri=$(BuildDefinitionUri);\n BuildDirectory=$(BuildDirectory);BuildNumber=$(BuildNumber);CompilationStatus=$(CompilationStatus);CompilationSuccess=$(CompilationSuccess);\n ConfigurationFolderUri=$(ConfigurationFolderUri);DropLocation=$(DropLocation);\n FullLabelName=$(FullLabelName);LastChangedBy=$(LastChangedBy);LastChangedOn=$(LastChangedOn);LogLocation=$(LogLocation);\n MachineName=$(MachineName);MaxProcesses=$(MaxProcesses);Port=$(Port);Quality=$(Quality);Reason=$(Reason);RequestedBy=$(RequestedBy);RequestedFor=$(RequestedFor);\n SourceGetVersion=$(SourceGetVersion);StartTime=$(StartTime);Status=$(Status);TeamProject=$(TeamProject);TestStatus=$(TestStatus);\n TestSuccess=$(TestSuccess);WorkspaceName=$(WorkspaceName);WorkspaceOwner=$(WorkspaceOwner);\n SolutionRoot=$(SolutionRoot);BinariesRoot=$(BinariesRoot);TestResultsRoot=$(TestResultsRoot)\"\n Targets=\"RunMbUnitTests\"/>\n </Target>\n\n <ItemGroup>\n <TestAssemblies Include=\"$(OutDir)\\Project1.dll\" />\n <TestAssemblies Include=\"$(OutDir)\\Project2.dll\" />\n </ItemGroup>\n <Target Name=\"RunMbUnitTests\">\n <MbUnit\n Assemblies=\"@(TestAssemblies)\"\n ReportTypes=\"html\"\n ReportFileNameFormat=\"buildreport{0}{1}\"\n ReportOutputDirectory=\".\" />\n </Target>\n"
},
{
"answer_id": 157129,
"author": "Geir-Tore Lindsve",
"author_id": 4582,
"author_profile": "https://Stackoverflow.com/users/4582",
"pm_score": 2,
"selected": true,
"text": "<Project ...>\n <UsingTask TaskName=\"MbUnit.MSBuild.Tasks.MbUnit\" AssemblyFile=\"path_to_MbUnit.MSBuild.Tasks.dll\" />\n ...\n ...\n <Target Name=\"AfterCompile\">\n <ItemGroup>\n <TestAssemblies Include=\"$(OutDir)\\Project1.dll\" />\n <TestAssemblies Include=\"$(OutDir)\\Project2.dll\" />\n </ItemGroup>\n\n <BuildStep\n TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Message=\"Running tests (cross your fingers)...\">\n <Output TaskParameter=\"Id\" PropertyName=\"StepId\" />\n </BuildStep>\n\n <MbUnit\n Assemblies=\"@(TestAssemblies)\"\n ReportTypes=\"html\"\n ReportFileNameFormat=\"buildreport{0}{1}\"\n ReportOutputDirectory=\".\" />\n\n <BuildStep\n TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Id=\"$(StepId)\"\n Message=\"Yay! All tests succeded!\"\n Status=\"Succeeded\" />\n <OnError ExecuteTargets=\"MarkBuildStepAsFailed\" />\n </Target>\n\n <Target Name=\"MarkBuildStepAsFailed\">\n <BuildStep\n TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Id=\"$(StepId)\"\n Message=\"Oh no! Some tests have failed. See test report in drop folder for details.\"\n Status=\"Failed\" />\n </Target>\n ...\n</Project>\n"
},
{
"answer_id": 707951,
"author": "Erling Paulsen",
"author_id": 85925,
"author_profile": "https://Stackoverflow.com/users/85925",
"pm_score": 1,
"selected": false,
"text": "<Target Name=\"AfterCompile\">\n<CreateItem Include=\"$(OutDir)\\*.Test.dll\">\n <Output\n TaskParameter=\"Include\"\n ItemName=\"TestBinaries\"/>\n</CreateItem>\n</Target><!--Test run happens in a later target in our case, we use MSTest -->\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4582/"
] |
154,427
|
<p>What's the object type returned by Datepicker?
Supposing I have the following:</p>
<pre><code>$("#txtbox").datepicker({
onClose: function(date){
//something
}
});
</code></pre>
<p>What is <code>date</code>? I'm interested in reading the date object from another Datepicker for comparison, something like:</p>
<pre><code> function(date){
oDate = $("#oDP").datepicker("getDate");
if(oDate == date)
//do one
else if(oDate > date)
//do two
}
</code></pre>
<p>However, this kind of comparison is not working. I'm guessing there is some sort of comparison method for Date object, but I don't know. I also tried comparing the String representation of the dates like <code>oDate.toString() > date.toString()</code> to no avail.</p>
|
[
{
"answer_id": 157441,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "Date datePicker var myDate=new Date();\nmyDate.setFullYear(2010,0,14);\nvar today = new Date();\n\nif (myDate>today)\n{\n alert(\"Today is before 14th January 2010\");\n}\n oDate oDate = $(\"#oDP\").datepicker(\"getDate\");\n datePicker #oDP oDate date Date tDate"
},
{
"answer_id": 234380,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 4,
"selected": true,
"text": "if (oDate.getTime() > date.getTime()) {\n ...\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024/"
] |
154,430
|
<p>I need to store encrypted data (few small strings) between application runs. I do not want the user to provide a passphrase every time (s)he launches the application. I.e. after all it goes down to storing securely the encryption key(s).</p>
<p>I was looking into RSACryptoServiceProvider and using PersistentKeyInCsp, but I'm not sure how it works. Is the key container persistent between application runs or machine restarts? If yes, is it user specific, or machine specific. I.e. if I store my encrypted data in user's roaming profile, can I decrypt the data if the user logs on a different machine?</p>
<p>If the above does not work, what are my options (I need to deal with roaming profiles).</p>
|
[
{
"answer_id": 154687,
"author": "Michael Petrotta",
"author_id": 23897,
"author_profile": "https://Stackoverflow.com/users/23897",
"pm_score": 6,
"selected": true,
"text": "byte[] plaintextBytes = GetDataToProtect();\nbyte[] encodedBytes = ProtectedData.Protect(plaintextBytes, null, DataProtectionScope.CurrentUser);\n byte[] encodedBytes = GetDataToUnprotect();\nbyte[] plaintextBytes = ProtectedData.Unprotect(encodedBytes, null, DataProtectionScope.CurrentUser);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8220/"
] |
154,434
|
<p>How do you get spreadsheet data in Excel to recalculate itself from within VBA, without the kluge of just changing a cell value?</p>
|
[
{
"answer_id": 154439,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 7,
"selected": true,
"text": "ActiveSheet.EnableCalculation = False \nActiveSheet.EnableCalculation = True \n .Calculate() .CalculateFull()"
},
{
"answer_id": 154562,
"author": "Graham",
"author_id": 1826,
"author_profile": "https://Stackoverflow.com/users/1826",
"pm_score": 4,
"selected": false,
"text": "'recalculate all open workbooks\nApplication.Calculate\n\n'recalculate a specific worksheet\nWorksheets(1).Calculate\n\n' recalculate a specific range\nWorksheets(1).Columns(1).Calculate\n"
},
{
"answer_id": 154679,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 3,
"selected": false,
"text": "Application.CalculateFull\n Application.CalculateFullRebuild\n CalculateFullRebuild"
},
{
"answer_id": 18621896,
"author": "kambeeks",
"author_id": 2748213,
"author_profile": "https://Stackoverflow.com/users/2748213",
"pm_score": 3,
"selected": false,
"text": "ActiveSheet.EnableCalculation = True\n Cells(RowA,ColB).Formula = Cells(RowA,ColB).Formula\n"
},
{
"answer_id": 27255401,
"author": "AjV Jsy",
"author_id": 2078245,
"author_profile": "https://Stackoverflow.com/users/2078245",
"pm_score": 2,
"selected": false,
"text": "Sheets(1).PageSetup.CenterHeader = \"\" ActiveSheet.EnableCalculation Application.ScreenUpdating = True"
},
{
"answer_id": 56744685,
"author": "pghcpa",
"author_id": 149572,
"author_profile": "https://Stackoverflow.com/users/149572",
"pm_score": 1,
"selected": false,
"text": "Sheets(\"mysheet\").Columns(\"D\").Calculate\n Application.Calculation = xlManual\nDoEvents\nFor Each mycell In Sheets(\"mysheet\").Range(\"D9:D750\").Cells\n mycell.Formula = mycell.Formula\nNext\nDoEvents\nApplication.Calculation = xlAutomatic\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295/"
] |
154,441
|
<p>I need to test some HTTP interaction with a client I'd rather not modify. What I need to test is the behavior of the server when the client's requests include a certain, static header.</p>
<p>I'm thinking the easiest way to run this test is to set up an HTTP proxy that inserts the header on every request. What would be the simplest way to set this up?</p>
|
[
{
"answer_id": 154641,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 7,
"selected": true,
"text": "NameVirtualHost *\n<VirtualHost *>\n <Proxy http://127.0.0.1:8080/*>\n Allow from all\n </Proxy>\n <LocationMatch \"/myapp\">\n ProxyPass http://127.0.0.1:8080/myapp\n ProxyPassReverse http://127.0.0.1:8080/myapp\n Header add myheader \"myvalue\"\n RequestHeader set myheader \"myvalue\" \n </LocationMatch>\n</VirtualHost>\n"
},
{
"answer_id": 157775,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 4,
"selected": false,
"text": "OnBeforeRequest oSession.oRequest.headers.Add(\"MyHeader\", \"MyValue\");\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3518/"
] |
154,443
|
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
|
[
{
"answer_id": 154617,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 9,
"selected": true,
"text": "sys.dont_write_bytecode python -B prog.py .pyc __pycache__ PYTHONDONTWRITEBYTECODE=1"
},
{
"answer_id": 154640,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 5,
"selected": false,
"text": "$ unzip -l /tmp/example.zip\n Archive: /tmp/example.zip\n Length Date Time Name\n -------- ---- ---- ----\n 8467 11-26-02 22:30 jwzthreading.py\n -------- -------\n 8467 1 file\n$ ./python\nPython 2.3 (#1, Aug 1 2003, 19:54:32) \n>>> import sys\n>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path\n>>> import jwzthreading\n>>> jwzthreading.__file__\n'/tmp/example.zip/jwzthreading.py'\n"
},
{
"answer_id": 9562273,
"author": "te wilson",
"author_id": 1249153,
"author_profile": "https://Stackoverflow.com/users/1249153",
"pm_score": 7,
"selected": false,
"text": "import sys\n\nsys.dont_write_bytecode = True\n"
},
{
"answer_id": 39925524,
"author": "Ravil Asadov",
"author_id": 6815329,
"author_profile": "https://Stackoverflow.com/users/6815329",
"pm_score": 2,
"selected": false,
"text": "python LoginSuite.py\n python -B LoginSuite.py\n"
},
{
"answer_id": 44560785,
"author": "Elwyne",
"author_id": 8164421,
"author_profile": "https://Stackoverflow.com/users/8164421",
"pm_score": 3,
"selected": false,
"text": "sys.dont_write_bytecode = True python somefile.py somefile.pyc setup.py entry_points= sys.dont_write_bytecode -B python -B somefile.py\n somefile.pyc .pyc myutil PYTHONDONTWRITEBYTECODE PYTHONDONTWRITEBYTECODE=x myutil\n"
},
{
"answer_id": 48728321,
"author": "alpha_989",
"author_id": 4752883,
"author_profile": "https://Stackoverflow.com/users/4752883",
"pm_score": 2,
"selected": false,
"text": "ipython 6.2.1 using python 3.5.2 Ipython %env PYTHONDONTWRITEBYTECODE =1 ipython ~/.ipython/profile-default/startup/00-startup.ipy ~.ipython/profile-default/startup/00-startup.py import sys\nsys.dont_write_bytecode=True\n"
},
{
"answer_id": 57414078,
"author": "Rotareti",
"author_id": 1612318,
"author_profile": "https://Stackoverflow.com/users/1612318",
"pm_score": 4,
"selected": false,
"text": "PYTHONPYCACHEPREFIX ./profile export PYTHONPYCACHEPREFIX=\"$HOME/.cache/cpython/\"\n __pycache__ ~/.cache/cpython/"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1476/"
] |
154,446
|
<p>I am trying to save data to a database on a button push, but the variables seem to be private by the nature of where they are defined. I have tried to move where they are defined, but this seems to produce other errors.</p>
<p>Given a fix, why was it fixed that way?</p>
<p>The code follows.</p>
<pre><code>namespace enable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.123.5\\Share\\Matt\\BugTypes.mdb");
string strSQL = "SELECT CategoryName, Show " + "FROM [Categories] WHERE Show = 'Yes' " + "ORDER BY CategoryName";
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, favouriteConnection);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(adapter);
DataTable dTable = new DataTable();
adapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView1.DataSource = bSource;
adapter.Update(dTable);
}
private void button1_Click(object sender, EventArgs e)
{
adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.
}
}
}
</code></pre>
|
[
{
"answer_id": 154458,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 0,
"selected": false,
"text": "namespace enable\n{ \n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\\\\\192.168.123.5\\\\Share\\\\Matt\\\\BugTypes.mdb\");\n string strSQL = \"SELECT CategoryName, Show \" + \"FROM [Categories] WHERE Show = 'Yes' \" + \"ORDER BY CategoryName\";\n m_Adapter = new OleDbDataAdapter(strSQL, favouriteConnection)l\n OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(m_Adapter);\n dTable = new DataTable();\n m_Adapter.Fill(dTable);\n BindingSource bSource = new BindingSource();\n bSource.DataSource = dTable;\n dataGridView1.DataSource = bSource;\n m_Adapter.Update(dTable); \n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n m_Adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.\n }\n\n OleDbDataAdapter m_Adapter;\n DataTable dTable;\n }\n}\n"
},
{
"answer_id": 154461,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 4,
"selected": true,
"text": "dTable adapter public partial class Form1 : Form\n{\n private DataTable dTable;\n private OleDbDataAdapter adapter;\n\n Public Form1()\n {\n ... your setup here ...\n dTable = new DataTable();\n ... etc ...\n }\n}\n"
},
{
"answer_id": 154464,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 2,
"selected": false,
"text": "namespace enable\n{ \n public partial class Form1 : Form\n {\n\n OleDbDataAdapter adapter;\n DataTable dTable = new DataTable();\n\n public Form1()\n {\n InitializeComponent();\n OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\\\\\192.168.123.5\\\\Share\\\\Matt\\\\BugTypes.mdb\");\n string strSQL = \"SELECT CategoryName, Show \" + \"FROM [Categories] WHERE Show = 'Yes' \" + \"ORDER BY CategoryName\";\n adapter = new OleDbDataAdapter(strSQL, favouriteConnection);\n OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(adapter);\n adapter.Fill(dTable);\n BindingSource bSource = new BindingSource();\n bSource.DataSource = dTable;\n dataGridView1.DataSource = bSource;\n adapter.Update(dTable); \n }\n private void button1_Click(object sender, EventArgs e)\n {\n adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.\n }\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19802/"
] |
154,463
|
<p>I'm using SharpZipLib version 0.85.5 to unzip files. My code has been working nicely for a couple of months until I found a ZIP file that it doesn't like.</p>
<pre><code>ICSharpCode.SharpZipLib.Zip.ZipException: End of extra data
at ICSharpCode.SharpZipLib.Zip.ZipExtraData.ReadCheck(Int32 length) in C:\C#\SharpZLib\Zip\ZipExtraData.cs:line 933
at ICSharpCode.SharpZipLib.Zip.ZipExtraData.Skip(Int32 amount) in C:\C#\SharpZLib\Zip\ZipExtraData.cs:line 921
at ICSharpCode.SharpZipLib.Zip.ZipEntry.ProcessExtraData(Boolean localHeader) in C:\C#\SharpZLib\Zip\ZipEntry.cs:line 925
at ICSharpCode.SharpZipLib.Zip.ZipInputStream.GetNextEntry() in C:\C#\SharpZLib\Zip\ZipInputStream.cs:line 269
at Constellation.Utils.Tools.UnzipFile(String sourcePath, String targetDirectory) in C:\C#\Constellation2\Utils\Tools.cs:line 90
--- End of inner exception stack trace ---
</code></pre>
<p>Here is my unzip method:</p>
<pre><code> public static void UnzipFile(string sourcePath, string targetDirectory)
{
try
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
//string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (targetDirectory.Length > 0)
{
Directory.CreateDirectory(targetDirectory);
}
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(targetDirectory + fileName))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
}
}
</code></pre>
<p>The file unzips fine using XP's built-in ZIP support, WinZIP, and 7-Zip. The exception is being thrown at <code>s.GetNextEntry()</code>. </p>
|
[
{
"answer_id": 155204,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 0,
"selected": false,
"text": "public static void UnzipFile(string sourcePath, string targetDirectory)\n{\n try\n {\n FastZip fastZip = new FastZip();\n fastZip.CreateEmptyDirectories = false;\n fastZip.ExtractZip(sourcePath, targetDirectory,\"\");\n }\n catch(Exception ex)\n {\n throw new Exception(\"Error unzipping file \\\"\" + sourcePath + \"\\\"\", ex);\n }\n}\n"
},
{
"answer_id": 30934297,
"author": "Barmaley A",
"author_id": 5027568,
"author_profile": "https://Stackoverflow.com/users/5027568",
"pm_score": 0,
"selected": false,
"text": "SharpZipLib entry.IsZip64Forced() if ( entry.CentralHeaderRequiresZip64 ) {\n ed.StartNewEntry();\n\n if ((entry.Size >= 0xffffffff) || (useZip64_ == UseZip64.On) || entry.IsZip64Forced())\n {\n ed.AddLeLong(entry.Size);\n }\n\n if ((entry.CompressedSize >= 0xffffffff) || (useZip64_ == UseZip64.On) || entry.IsZip64Forced())\n {\n ed.AddLeLong(entry.CompressedSize);\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.