qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence |
---|---|---|---|---|
2,775 | <p>Here's what I use:</p>
<pre><code>SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME)
</code></pre>
<p>I'm thinking there may be a better and more elegant way.</p>
<p>Requirements:</p>
<ul>
<li>It has to be as fast as possible (the less casting, the better).</li>
<li>The final result has to be a <code>datetime</code> type, not a string.</li>
</ul>
| [
{
"answer_id": 2781,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": false,
"text": "CAST FLOOR CAST Select Convert(varchar(11), getdate(),101)"
},
{
"answer_id": 3130,
"author": "Marek Grzenkowicz",
"author_id": 95,
"author_profile": "https://Stackoverflow.com/users/95",
"pm_score": 5,
"selected": false,
"text": "SELECT CAST(CAST(GETDATE() AS date) AS datetime)\n"
},
{
"answer_id": 3154,
"author": "Marek Grzenkowicz",
"author_id": 95,
"author_profile": "https://Stackoverflow.com/users/95",
"pm_score": 4,
"selected": false,
"text": "SELECT CAST(CONVERT(char(8), GETDATE(), 112) AS datetime)\n\nSELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)\n\nSELECT CAST(CAST(GETDATE() - 0.50000004 AS int) AS datetime)\n"
},
{
"answer_id": 3696991,
"author": "ErikE",
"author_id": 57611,
"author_profile": "https://Stackoverflow.com/users/57611",
"pm_score": 8,
"selected": true,
"text": "Convert(date, @date) datetime datetime2 datetime float declare @d datetime;\nset @d = '2010-09-12 00:00:00.003';\nselect Convert(datetime, Convert(float, @d));\n-- result: 2010-09-12 00:00:00.000 -- oops\n create table AllDay (Tm datetime NOT NULL CONSTRAINT PK_AllDay PRIMARY KEY CLUSTERED);\ndeclare @d datetime;\nset @d = DateDiff(Day, 0, GetDate());\ninsert AllDay select @d;\nwhile @@ROWCOUNT != 0\n insert AllDay\n select * from (\n select Tm =\n DateAdd(ms, (select Max(DateDiff(ms, @d, Tm)) from AllDay) + 3, Tm)\n from AllDay\n ) X\n where Tm < DateAdd(Day, 1, @d);\nexec sp_spaceused AllDay; -- 25,920,000 rows\n set statistics time on;\n-- (All queries are the same on io: logical reads 54712)\nGO\ndeclare\n @dd date,\n @d datetime,\n @di int,\n @df float,\n @dv varchar(10);\n\n-- Round trip back to datetime\nselect @d = CONVERT(date, Tm) from AllDay; -- CPU time = 21234 ms, elapsed time = 22301 ms.\nselect @d = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 23031 ms, elapsed = 24091 ms.\nselect @d = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23782 ms, elapsed = 24818 ms.\nselect @d = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 36891 ms, elapsed = 38414 ms.\nselect @d = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 102984 ms, elapsed = 109897 ms.\nselect @d = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 103390 ms, elapsed = 108236 ms.\nselect @d = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 123375 ms, elapsed = 135179 ms.\n\n-- Only to another type but not back\nselect @dd = Tm from AllDay; -- CPU time = 19891 ms, elapsed time = 20937 ms.\nselect @di = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 21453 ms, elapsed = 23079 ms.\nselect @di = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23218 ms, elapsed = 24700 ms\nselect @df = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 29312 ms, elapsed = 31101 ms.\nselect @dv = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 64016 ms, elapsed = 67815 ms.\nselect @dv = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 64297 ms, elapsed = 67987 ms.\nselect @dv = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 65609 ms, elapsed = 68173 ms.\nGO\nset statistics time off;\n datetime select Convert(datetime, DateDiff(dd, 0, Tm))\nfrom (select '2010-09-12 00:00:00.003') X (Tm)\ngroup by DateDiff(dd, 0, Tm)\n datetime varchar Convert(, 112) Convert(, 101) varchar date varchar Convert(, 112) method round single base\n----------- ------ ------ -----\n date 21324 19891 18458\n int 23031 21453 19875\n datediff 23782 23218 22654\n float 36891 29312 21733\nvarchar-112 102984 64016 25048\nvarchar-101 123375 65609 7843\n datetime single single - (round - single) datetime Convert(date) datetime varchar DateDiff DateAdd 0.50000004 0.50000004 '12:00:00.003' datetime"
},
{
"answer_id": 17378887,
"author": "srihari",
"author_id": 2518677,
"author_profile": "https://Stackoverflow.com/users/2518677",
"pm_score": 2,
"selected": false,
"text": "SELECT CONVERT(VARCHAR(10),[YOUR COLUMN NAME],105) [YOURTABLENAME]\n"
},
{
"answer_id": 26749689,
"author": "user4217069",
"author_id": 4217069,
"author_profile": "https://Stackoverflow.com/users/4217069",
"pm_score": 1,
"selected": false,
"text": "select cast(DATEDIFF(DAY, 0, datetimefield) as datetime)\n select DATEADD(DAY, DATEDIFF(DAY, 0, datetimefield), 0)\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434/"
] |
2,780 | <p>Let's say that we have an ARGB color:</p>
<pre><code>Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
</code></pre>
<p>When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is <code>Color.FromARGB(255, 162, 133, 255);</code></p>
<p>The solution should work like this:</p>
<pre><code>Color blend = Color.White;
Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255);
</code></pre>
<p>What is <code>ToRGB</code>'s implementation? </p>
| [
{
"answer_id": 2789,
"author": "Louis Brandy",
"author_id": 2089740,
"author_profile": "https://Stackoverflow.com/users/2089740",
"pm_score": 5,
"selected": true,
"text": "alpha=argb.alpha()\nr = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()\ng = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()\nb = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()\n"
},
{
"answer_id": 17318104,
"author": "Paul Ishak",
"author_id": 1532865,
"author_profile": "https://Stackoverflow.com/users/1532865",
"pm_score": 2,
"selected": false,
"text": "Public Shared Function AlphaBlend(ByVal ForeGround As Color, ByVal BackGround As Color) As Color\n If ForeGround.A = 0 Then Return BackGround\n If BackGround.A = 0 Then Return ForeGround\n If ForeGround.A = 255 Then Return ForeGround\n Dim Alpha As Integer = CInt(ForeGround.A) + 1\n Dim B As Integer = Alpha * ForeGround.B + (255 - Alpha) * BackGround.B >> 8\n Dim G As Integer = Alpha * ForeGround.G + (255 - Alpha) * BackGround.G >> 8\n Dim R As Integer = Alpha * ForeGround.R + (255 - Alpha) * BackGround.R >> 8\n Dim A As Integer = ForeGround.A\n\n If BackGround.A = 255 Then A = 255\n If A > 255 Then A = 255\n If R > 255 Then R = 255\n If G > 255 Then G = 255\n If B > 255 Then B = 255\n\n Return Color.FromArgb(Math.Abs(A), Math.Abs(R), Math.Abs(G), Math.Abs(B))\nEnd Function\n\npublic static Color AlphaBlend(Color ForeGround, Color BackGround)\n{\n if (ForeGround.A == 0)\n return BackGround;\n if (BackGround.A == 0)\n return ForeGround;\n if (ForeGround.A == 255)\n return ForeGround;\n\n int Alpha = Convert.ToInt32(ForeGround.A) + 1;\n int B = Alpha * ForeGround.B + (255 - Alpha) * BackGround.B >> 8;\n int G = Alpha * ForeGround.G + (255 - Alpha) * BackGround.G >> 8;\n int R = Alpha * ForeGround.R + (255 - Alpha) * BackGround.R >> 8;\n int A = ForeGround.A;\n\n if (BackGround.A == 255)\n A = 255;\n if (A > 255)\n A = 255;\n if (R > 255)\n R = 255;\n if (G > 255)\n G = 255;\n if (B > 255)\n B = 255;\n\n return Color.FromArgb(Math.Abs(A), Math.Abs(R), Math.Abs(G), Math.Abs(B));\n}\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45/"
] |
2,785 | <p>Should you set all the objects to <code>null</code> (<code>Nothing</code> in VB.NET) once you have finished with them? </p>
<p>I understand that in .NET it is essential to dispose of any instances of objects that implement the <code>IDisposable</code> interface to release some resources although the object can still be something after it is disposed (hence the <code>isDisposed</code> property in forms), so I assume it can still reside in memory or at least in part?</p>
<p>I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time).</p>
<p>So with this in mind will setting it to <code>null</code> speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects?</p>
<p>MSDN articles never do this in examples and currently I do this as I cannot
see the harm. However I have come across a mixture of opinions so any comments are useful.</p>
| [
{
"answer_id": 2794,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": ".dispose()"
},
{
"answer_id": 2813,
"author": "Steve T",
"author_id": 415,
"author_profile": "https://Stackoverflow.com/users/415",
"pm_score": 3,
"selected": false,
"text": "using(SomeObject object = new SomeObject()) \n{\n // do stuff with the object\n}\n// the object will be disposed of\n"
},
{
"answer_id": 2839,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 7,
"selected": true,
"text": "IDisposable IDisposable.Dispose() try finally using() Dispose() Dispose()"
},
{
"answer_id": 6728,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 3,
"selected": false,
"text": "this.myField.Dispose();\n// ... at some later time\nthis.myField.DoSomething();\n"
},
{
"answer_id": 6739,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 3,
"selected": false,
"text": "null using(SomeObject object = new SomeObject()) \n{\n // do stuff with the object\n}\n// the object will be disposed of\n {\n // Declare the variable and use it\n SomeObject object = new SomeObject()\n}\n// The variable is no longer available\n"
},
{
"answer_id": 12301,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 5,
"selected": false,
"text": "void foo()\n{\n var someType = new SomeType();\n someType.DoSomething();\n // someType is now eligible for garbage collection \n\n // ... rest of method not using 'someType' ...\n}\n void foo()\n{\n var someType = new SomeType();\n someType.DoSomething();\n // someType is NOT eligible for garbage collection yet\n // because that variable is used at the end of the method \n\n // ... rest of method not using 'someType' ...\n someType = null;\n}\n"
},
{
"answer_id": 10098611,
"author": "KenF",
"author_id": 337868,
"author_profile": "https://Stackoverflow.com/users/337868",
"pm_score": 2,
"selected": false,
"text": ".Dispose() .Close() ObjA class A Class A PropB class B PropB _B PropB.Get() _PropB B _PropB _PropB _PropB A _PropB _PropB.Dispose() Dispose() Dispose() _PropB ObjA PropB _PropB Dispose()"
},
{
"answer_id": 10188102,
"author": "Munish Goyal",
"author_id": 520348,
"author_profile": "https://Stackoverflow.com/users/520348",
"pm_score": 3,
"selected": false,
"text": "private void Reset()\n{\n if(_dataset != null)\n {\n _dataset.Dispose();\n _dataset = null;\n }\n //..More such member variables like oracle connection etc. _oraConnection\n }\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33/"
] |
2,798 | <p>I've always been intrigued by Map Routing, but I've never found any good introductory (or even advanced!) level tutorials on it. Does anybody have any pointers, hints, etc?</p>
<p><strong>Update:</strong> I'm primarily looking for pointers as to how a map system is implemented (data structures, algorithms, etc).</p>
| [
{
"answer_id": 139714,
"author": "Guillermo Phillips",
"author_id": 441661,
"author_profile": "https://Stackoverflow.com/users/441661",
"pm_score": 2,
"selected": false,
"text": "nodes edges nodes route cost distance time NextNode node cost cost"
},
{
"answer_id": 7464631,
"author": "Geof",
"author_id": 951678,
"author_profile": "https://Stackoverflow.com/users/951678",
"pm_score": 1,
"selected": false,
"text": "Quickest"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
2,804 | <p>I have an application that displays an image inside of a Windows Forms <code>PictureBox</code> control. The <code>SizeMode</code> of the control is set to <code>Zoom</code> so that the image contained in the <code>PictureBox</code> will be displayed in an aspect-correct way regardless of the dimensions of the <code>PictureBox</code>.</p>
<p>This is great for the visual appearance of the application because you can size the window however you want and the image will always be displayed using its best fit. Unfortunately, I also need to handle mouse click events on the picture box and need to be able to translate from screen-space coordinates to image-space coordinates.</p>
<p>It looks like it's easy to translate from screen space to control space, but I don't see any obvious way to translate from control space to image space (i.e. the pixel coordinate in the source image that has been scaled in the picture box).</p>
<p>Is there an easy way to do this, or should I just duplicate the scaling math that they're using internally to position the image and do the translation myself?</p>
| [
{
"answer_id": 3078,
"author": "fastcall",
"author_id": 328,
"author_profile": "https://Stackoverflow.com/users/328",
"pm_score": 3,
"selected": false,
"text": "// Recompute the image scaling the zoom mode uses to fit the image on screen\nimageScale ::= min(pictureBox.width / image.width, pictureBox.height / image.height)\n\nscaledWidth ::= image.width * imageScale\nscaledHeight ::= image.height * imageScale\n\n// Compute the offset of the image to center it in the picture box\nimageX ::= (pictureBox.width - scaledWidth) / 2\nimageY ::= (pictureBox.height - scaledHeight) / 2\n\n// Test the coordinate in the picture box against the image bounds\nif pos.x < imageX or imageX + scaledWidth < pos.x then return null\nif pos.y < imageY or imageY + scaledHeight < pos.y then return null\n\n// Compute the normalized (0..1) coordinates in image space\nu ::= (pos.x - imageX) / imageScale\nv ::= (pos.y - imageY) / imageScale\nreturn (u, v)\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/328/"
] |
2,811 | <p>I have a table with a structure like the following:</p>
<hr />
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>LocationID</th>
<th>AccountNumber</th>
</tr>
</thead>
<tbody>
<tr>
<td>long-guid-here</td>
<td>12345</td>
</tr>
<tr>
<td>long-guid-here</td>
<td>54321</td>
</tr>
</tbody>
</table>
</div>
<p>To pass into another stored procedure, I need the XML to look like this:</p>
<pre><code><root>
<clientID>12345</clientID>
<clientID>54321</clientID>
</root>
</code></pre>
<p>The best I've been able to do so far was getting it like this:</p>
<pre><code><root clientID="10705"/>
</code></pre>
<p>I'm using this SQL statement:</p>
<pre><code>SELECT
1 as tag,
null as parent,
AccountNumber as 'root!1!clientID'
FROM
Location.LocationMDAccount
WHERE
locationid = 'long-guid-here'
FOR XML EXPLICIT
</code></pre>
<p>So far, I've looked at the documentation on <a href="http://msdn.microsoft.com/en-us/library/ms345137.aspx" rel="nofollow noreferrer">the MSDN page</a>, but I've not come out with the desired results.</p>
<hr />
<p>@KG,</p>
<p>Yours gave me this output actually:</p>
<pre><code><root>
<Location.LocationMDAccount>
<clientId>10705</clientId>
</Location.LocationMDAccount>
</root>
</code></pre>
<p>I'm going to stick with the <code>FOR XML EXPLICIT</code> from Chris Leon for now.</p>
| [
{
"answer_id": 2825,
"author": "Chris Leon",
"author_id": 289,
"author_profile": "https://Stackoverflow.com/users/289",
"pm_score": 3,
"selected": true,
"text": "SELECT\n 1 AS Tag,\n 0 AS Parent,\n AccountNumber AS [Root!1!AccountNumber!element]\nFROM\n Location.LocationMDAccount\nWHERE\n LocationID = 'long-guid-here'\nFOR XML EXPLICIT\n"
},
{
"answer_id": 2832,
"author": "karlgrz",
"author_id": 318,
"author_profile": "https://Stackoverflow.com/users/318",
"pm_score": 0,
"selected": false,
"text": "SELECT\n AccountNumber as [clientId]\nFROM\n Location.Location root\nWHERE\n LocationId = 'long-guid-here'\nFOR\n XML AUTO, ELEMENTS\n"
},
{
"answer_id": 2834,
"author": "Chris Benard",
"author_id": 448,
"author_profile": "https://Stackoverflow.com/users/448",
"pm_score": 0,
"selected": false,
"text": "select\n1 as tag,\nnull as parent,\nAccountNumber as 'root!1!clientID!element'\nfrom\nLocation.LocationMDAccount\nwhere\nlocationid = 'long-guid-here'\nfor xml explicit\n"
},
{
"answer_id": 13536,
"author": "jeffreypriebe",
"author_id": 1592,
"author_profile": "https://Stackoverflow.com/users/1592",
"pm_score": 0,
"selected": false,
"text": "SELECT AccountNumber as \"clientID\"\nFROM Location.LocationMDAccount\nWHERE locationid = 'long-guid-here'\nFOR XML PATH (''), Root ('root');\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/448/"
] |
2,815 | <p>I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc.</p>
<p>Unfortunately, I couldn't get the right set of cookies, etc, to make this work. Any ideas?</p>
<p>Also, when the beta is finished, will my status page be accessible without logging in?</p>
| [
{
"answer_id": 2818,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 2,
"selected": false,
"text": "--load-cookies (filename)\n"
},
{
"answer_id": 2819,
"author": "Grant",
"author_id": 30,
"author_profile": "https://Stackoverflow.com/users/30",
"pm_score": 4,
"selected": true,
"text": "wget --no-cookies --header \"Cookie: soba=(LookItUpYourself)\" https://stackoverflow.com/users/30/myProfile.html\n"
},
{
"answer_id": 2878,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "curl -s --cookie soba=. http://stackoverflow.com/users\n"
},
{
"answer_id": 2920,
"author": "Grant",
"author_id": 30,
"author_profile": "https://Stackoverflow.com/users/30",
"pm_score": 3,
"selected": false,
"text": "wget --no-cookies --header \"Cookie: soba=(LookItUpYourself)\" https://stackoverflow.com/users/30/myProfile.html\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
2,840 | <p>How do I page results in SQL Server 2005?</p>
<p>I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method?</p>
<p>What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.</p>
<p>Any help would be much appreciated.</p>
| [
{
"answer_id": 2843,
"author": "Pat",
"author_id": 36,
"author_profile": "https://Stackoverflow.com/users/36",
"pm_score": 6,
"selected": true,
"text": "the Row_Number() SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName\nFROM Users\n RowID SELECT * \nFROM \n ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName\n FROM Users \n ) As RowResults\nWHERE RowID Between 5 AND 10\n"
},
{
"answer_id": 11352,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 4,
"selected": false,
"text": "SELECT rn, total_rows, x.OWNER, x.object_name, x.object_type\nFROM (SELECT COUNT (*) OVER (PARTITION BY owner) AS TOTAL_ROWS,\n ROW_NUMBER () OVER (ORDER BY 1) AS rn, uo.*\n FROM all_objects uo\n WHERE owner = 'CSEIS') x\nWHERE rn BETWEEN 6 AND 10\n RN TOTAL_ROWS OWNER OBJECT_NAME OBJECT_TYPE\n6 1262 CSEIS CG$BDS_MODIFICATION_TYPES TRIGGER\n7 1262 CSEIS CG$AUS_MODIFICATION_TYPES TRIGGER\n8 1262 CSEIS CG$BDR_MODIFICATION_TYPES TRIGGER\n9 1262 CSEIS CG$ADS_MODIFICATION_TYPES TRIGGER\n10 1262 CSEIS CG$BIS_LANGUAGES TRIGGER\n"
},
{
"answer_id": 74129,
"author": "Andrew Burgess",
"author_id": 12096,
"author_profile": "https://Stackoverflow.com/users/12096",
"pm_score": 2,
"selected": false,
"text": "--Declaration--\n\n--Variables\n@StartIndex INT,\n@PageSize INT,\n@SortColumn VARCHAR(50),\n@SortDirection CHAR(3),\n@Results INT OUTPUT\n\n--Statements--\nSELECT @Results = COUNT(ID) FROM Customers\nWHERE FirstName LIKE '%a%'\n\nSET @StartIndex = @StartIndex - 1 --Either do this here or in code, but be consistent\nCREATE TABLE #Page(ROW INT IDENTITY(1,1) NOT NULL, id INT, sorting_1 SQL_VARIANT, sorting_2 SQL_VARIANT)\nINSERT INTO #Page(ID, sorting_1, sorting_2)\nSELECT TOP (@StartIndex + @PageSize)\n ID,\n CASE\n WHEN @SortColumn='FirstName' AND @SortDirection='ASC' THEN CAST(FirstName AS SQL_VARIANT)\n WHEN @SortColumn='LastName' AND @SortDirection='ASC' THEN CAST(LastName AS SQL_VARIANT)\n ELSE NULL\n END AS sort_1,\n CASE\n WHEN @SortColumn='FirstName' AND @SortDirection='DES' THEN CAST(FirstName AS SQL_VARIANT)\n WHEN @SortColumn='LastName' AND @SortDirection='DES' THEN CAST(LastName AS SQL_VARIANT)\n ELSE NULL\n END AS sort_2\nFROM (\n SELECT\n CustomerId AS ID,\n FirstName,\n LastName\n FROM Customers\n WHERE\n FirstName LIKE '%a%'\n) C\nORDER BY sort_1 ASC, sort_2 DESC, ID ASC;\n\nSELECT\n ID,\n Customers.FirstName,\n Customers.LastName\nFROM #Page\nINNER JOIN Customers ON\n ID = Customers.CustomerId\nWHERE ROW > @StartIndex AND ROW <= (@StartIndex + @PageSize)\nORDER BY ROW ASC\n\nDROP TABLE #Page\n"
},
{
"answer_id": 752940,
"author": "Beska",
"author_id": 57120,
"author_profile": "https://Stackoverflow.com/users/57120",
"pm_score": 3,
"selected": false,
"text": "SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName\nFROM Users\nWHERE RowID Between 0 AND 9\n SELECT * \nFROM\n (SELECT\n Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName\n FROM Users\n ) innerSelect\nWHERE RowID Between 0 AND 9\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
2,844 | <pre><code>#include <stdio.h>
int main() {
unsigned long long int num = 285212672; //FYI: fits in 29 bits
int normalInt = 5;
printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt);
return 0;
}
</code></pre>
<p>Output:</p>
<pre><code>My number is 8 bytes wide and its value is 285212672l. A normal number is 0.
</code></pre>
<p>I assume this unexpected result is from printing the <code>unsigned long long int</code>. How do you <code>printf()</code> an <code>unsigned long long int</code>?</p>
| [
{
"answer_id": 2850,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 10,
"selected": true,
"text": "printf(\"%llu\", 285212672);\n"
},
{
"answer_id": 2851,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 1,
"selected": false,
"text": "L ll q ll"
},
{
"answer_id": 2895,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 0,
"selected": false,
"text": "int normalInt = 5; \nunsigned long long int num=285212672;\nprintf(\n \"My number is %d bytes wide and its value is %ul. \n A normal number is %d \\n\", \n sizeof(num), \n num, \n normalInt);\n int normalInt = 5; \nunsigned __int64 num=285212672;\nprintf(\n \"My number is %d bytes wide and its value is %I64u. \n A normal number is %d\", \n sizeof(num),\n num, normalInt);\n"
},
{
"answer_id": 8679,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 7,
"selected": false,
"text": "int32_t int64_t uint64_t #include <inttypes.h>\n\nuint64_t x;\nuint32_t y;\n\nprintf(\"x: %\"PRIu64\", y: %\"PRIu32\"\\n\", x, y);\n long unsigned long long"
},
{
"answer_id": 51366,
"author": "Paul Hargreaves",
"author_id": 5330,
"author_profile": "https://Stackoverflow.com/users/5330",
"pm_score": 5,
"selected": false,
"text": "#include <stdio.h>\n#include <inttypes.h>\n\nint main() {\n unsigned long long int num = 285212672; //FYI: fits in 29 bits\n int normalInt = 5;\n /* NOTE: PRIu64 is a preprocessor macro and thus should go outside the quoted string. */\n printf(\"My number is %d bytes wide and its value is %\" PRIu64 \". A normal number is %d.\\n\", sizeof(num), num, normalInt);\n return 0;\n}\n My number is 8 bytes wide and its value is 285212672. A normal number is 5.\n"
},
{
"answer_id": 55586,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 4,
"selected": false,
"text": "%llu %I64u"
},
{
"answer_id": 1385786,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "__int64 a;\ntime_t b;\n...\nfprintf(outFile,\"%I64d,%I64d\\n\",a,b); //I is capital i\n"
},
{
"answer_id": 30221946,
"author": "Shivam Chauhan",
"author_id": 4080247,
"author_profile": "https://Stackoverflow.com/users/4080247",
"pm_score": 7,
"selected": false,
"text": "%d int %u unsigned int %ld long int long %lu unsigned long int long unsigned int unsigned long %lld long long int long long %llu unsigned long long int unsigned long long"
},
{
"answer_id": 31635676,
"author": "kungfooman",
"author_id": 1952626,
"author_profile": "https://Stackoverflow.com/users/1952626",
"pm_score": 0,
"selected": false,
"text": "printf(\"64bit: %llp\", 0xffffffffffffffff);\n 64bit: FFFFFFFFFFFFFFFF\n"
},
{
"answer_id": 34838293,
"author": "Bernd Elkemann",
"author_id": 618598,
"author_profile": "https://Stackoverflow.com/users/618598",
"pm_score": 2,
"selected": false,
"text": "main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=] printf(\"%llu\\n\", k); -std=c99"
},
{
"answer_id": 55306337,
"author": "7vujy0f0hy",
"author_id": 6314667,
"author_profile": "https://Stackoverflow.com/users/6314667",
"pm_score": 3,
"selected": false,
"text": "lltoa() #include <stdlib.h> /* lltoa() */\n// ...\nchar dummy[255];\nprintf(\"Over 4 bytes: %s\\n\", lltoa(5555555555, dummy, 10));\nprintf(\"Another one: %s\\n\", lltoa(15555555555, dummy, 10));\n #include <stdio.h>\n#include <stdlib.h> /* lltoa() */\n\nint main() {\n unsigned long long int num = 285212672; // fits in 29 bits\n char dummy[255];\n int normalInt = 5;\n printf(\"My number is %d bytes wide and its value is %s. \"\n \"A normal number is %d.\\n\", \n sizeof(num), lltoa(num, dummy, 10), normalInt);\n return 0;\n}\n %lld _ui64toa() lltoa()"
},
{
"answer_id": 66028620,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 3,
"selected": false,
"text": "unsigned long long int printf \"ll\" o,u,x,X unsigned long long num = 285212672;\nprintf(\"Base 10: %llu\\n\", num);\nnum += 0xFFF; // For more interesting hex/octal output.\nprintf(\"Base 16: %llX\\n\", num); // Use uppercase A-F\nprintf(\"Base 16: %llx\\n\", num); // Use lowercase a-f\nprintf(\"Base 8: %llo\\n\", num);\nputs(\"or 0x,0X prefix\");\nprintf(\"Base 16: %#llX %#llX\\n\", num, 0ull); // When non-zero, print leading 0X\nprintf(\"Base 16: %#llx %#llx\\n\", num, 0ull); // When non-zero, print leading 0x\nprintf(\"Base 16: 0x%llX\\n\", num); // My hex fave: lower case prefix, with A-F\n Base 10: 285212672\nBase 16: 11000FFF\nBase 16: 11000fff\nBase 8: 2100007777\nor 0x,0X prefix\nBase 16: 0X11000FFF 0\nBase 16: 0x11000fff 0\nBase 16: 0x11000FFF\n"
},
{
"answer_id": 73709670,
"author": "ad absurdum",
"author_id": 6879826,
"author_profile": "https://Stackoverflow.com/users/6879826",
"pm_score": 1,
"selected": false,
"text": "unsigned long long uintmax_t stdint.h uintmax_t intmax_t uintmax_t uintmax_t %ju intmax_t %jd uintmax_t uintmax_t #include <stdio.h>\n#include <stdint.h>\n\nint main(void) {\n unsigned long long num = 285212672;\n printf(\"%ju\\n\", (uintmax_t)num);\n\n return 0;\n}\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] |
2,871 | <p>What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty):</p>
<pre><code>typedef OldStuff {
CHAR Name[8];
UInt32 User;
CHAR Location[8];
UInt32 TimeStamp;
UInt32 Sequence;
CHAR Tracking[16];
CHAR Filler[12];
}
</code></pre>
<p>And would fill something like this:</p>
<pre><code>[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
public struct NewStuff
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
[FieldOffset(0)]
public string Name;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(8)]
public uint User;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
[FieldOffset(12)]
public string Location;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(20)]
public uint TimeStamp;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(24)]
public uint Sequence;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
[FieldOffset(28)]
public string Tracking;
}
</code></pre>
<p>What is best way to copy <code>OldStuff</code> to <code>NewStuff</code>, if <code>OldStuff</code> was passed as byte[] array?</p>
<p>I'm currently doing something like the following, but it feels kind of clunky.</p>
<pre><code>GCHandle handle;
NewStuff MyStuff;
int BufferSize = Marshal.SizeOf(typeof(NewStuff));
byte[] buff = new byte[BufferSize];
Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);
handle = GCHandle.Alloc(buff, GCHandleType.Pinned);
MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));
handle.Free();
</code></pre>
<p>Is there better way to accomplish this?</p>
<hr>
<p>Would using the <code>BinaryReader</code> class offer any performance gains over pinning the memory and using <code>Marshal.PtrStructure</code>?</p>
| [
{
"answer_id": 2887,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 8,
"selected": true,
"text": "SomeByteArray SomeByteArray IntPtr PtrToStructure NewStuff ByteArrayToNewStuff(byte[] bytes)\n{\n GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n try\n {\n NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));\n }\n finally\n {\n handle.Free();\n }\n return stuff;\n}\n T ByteArrayToStructure<T>(byte[] bytes) where T: struct \n{\n T stuff;\n GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n try\n {\n stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\n }\n finally\n {\n handle.Free();\n }\n return stuff;\n}\n unsafe unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct\n{\n fixed (byte* ptr = &bytes[0])\n {\n return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T));\n }\n}\n"
},
{
"answer_id": 8463705,
"author": "Dushyant",
"author_id": 1092176,
"author_profile": "https://Stackoverflow.com/users/1092176",
"pm_score": 2,
"selected": false,
"text": "object ByteArrayToStructure(byte[] bytearray, object structureObj, int position)\n{\n int length = Marshal.SizeOf(structureObj);\n IntPtr ptr = Marshal.AllocHGlobal(length);\n Marshal.Copy(bytearray, 0, ptr, length);\n structureObj = Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(bytearray, position), structureObj.GetType());\n Marshal.FreeHGlobal(ptr);\n return structureObj;\n} \n"
},
{
"answer_id": 41836532,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 4,
"selected": false,
"text": "public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct\n{\n var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n try {\n return (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\n }\n finally {\n handle.Free();\n }\n}\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/206/"
] |
2,873 | <p>I'm working on a project where I'm coding in C in a UNIX environment. I've been using the lint tool to check my source code. Lint has been around a long time (since 1979), can anyone suggest a more recent code analysis tool I could use ? Preferably a tool that is free.</p>
| [
{
"answer_id": 2927,
"author": "svec",
"author_id": 103,
"author_profile": "https://Stackoverflow.com/users/103",
"pm_score": 6,
"selected": true,
"text": "-Werror -Wall valgrind"
},
{
"answer_id": 31055169,
"author": "Nicolas Jean",
"author_id": 4830306,
"author_profile": "https://Stackoverflow.com/users/4830306",
"pm_score": 3,
"selected": false,
"text": "cppcheck --enable=all ."
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] |
2,874 | <p>I have a control that is modelled on a <strong>ComboBox</strong>. I want to render the control so that the control <strong>border</strong> looks like that of a standard <strong>Windows ComboBox</strong>. Specifically, I have followed the MSDN documentation and all the rendering of the control is correct except for rendering when the control is disabled.</p>
<p>Just to be clear, this is for a system with <strong>Visual Styles</strong> enabled. Also, all parts of the control render properly except the border around a disabled control, which does not match the disabled <strong>ComboBox border</strong> colour.</p>
<p>I am using the <strong>VisualStyleRenderer</strong> class. MSDN suggests using the <code>VisualStyleElement.TextBox</code> element for the <strong>TextBox</strong> part of the <strong>ComboBox</strong> control but a standard disabled <strong>TextBox</strong> and a standard disabled <strong>ComboBox</strong> draw slightly differently (one has a light grey border, the other a light blue border).</p>
<p>How can I get correct rendering of the control in a disabled state?</p>
| [
{
"answer_id": 13372,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 4,
"selected": false,
"text": "// Create the renderer.\nif (VisualStyleInformation.IsSupportedByOS \n && VisualStyleInformation.IsEnabledByUser) \n{\n renderer = new VisualStyleRenderer(\n VisualStyleElement.ComboBox.DropDownButton.Disabled);\n}\n if(renderer != null)\n{\n // Use visual style renderer.\n}\nelse\n{\n // Use ControlPaint renderer.\n}\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441/"
] |
2,898 | <p>Let me preface this question by saying I use TextMate on Mac OSX for my text needs and I am in love with it. Anything comparable on the Linux platform? I'll mostly use it for coding python/ruby.</p>
<p>Doing a google search yielded outdated answers.</p>
<p>Edit: Since there has been some concern about the 'merit' of this question. I am about to start a new Ruby Programming Project in Linux and before I got started I wanted to make sure I had the right tools to do the job.</p>
<p>Edit #2: I use VIM on a daily basis -- all . the . time. I enjoy using it. I was just looking for some alternatives.</p>
| [
{
"answer_id": 2066166,
"author": "Wayne Conrad",
"author_id": 238886,
"author_profile": "https://Stackoverflow.com/users/238886",
"pm_score": 1,
"selected": false,
"text": "# Local Variables:\n# tab-width: 2\n# ruby-indent-level: 2\n# indent-tabs-mode: nil\n# End:\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] |
2,900 | <p>I am getting the following error:</p>
<blockquote>
<p>Access denied for user 'apache'@'localhost' (using password: NO)</p>
</blockquote>
<p>When using the following code:</p>
<pre><code><?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
echo "<h1>Delete Story</h1>";
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)){
echo '<b>'.$row[1].'</b><span align="right"><a href="../process/delete_story.php?id='.$row[0].'">Delete</a></span>';
echo '<br /><i>'.$row[2].'</i>';
}
}
else {
echo "No stories available.";
}
?>
</code></pre>
<p>The <code>connect.php</code> file contains my MySQL connect calls that are working fine with my <code>INSERT</code> queries in another portion of the software. If I comment out the <code>$result = mysql_query</code> line, then it goes through to the else statement. So, it is that line or the content in the if.</p>
<p>I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.</p>
| [
{
"answer_id": 2908,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 1,
"selected": false,
"text": "<?php\ninclude(\"../includes/connect.php\");\n\n$query = \"SELECT * from story\";\n$result = mysql_query($query) or die(mysql_error());\n"
},
{
"answer_id": 2911,
"author": "Justin Bennett",
"author_id": 271,
"author_profile": "https://Stackoverflow.com/users/271",
"pm_score": 1,
"selected": false,
"text": "GRANT ALL PRIVILEGES ON `*databasename*`.* to 'apache'@'localhost';\n"
},
{
"answer_id": 2915,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 1,
"selected": false,
"text": "GRANT SELECT ON myDatabase.myTable TO 'apache'@'localhost';\n"
},
{
"answer_id": 2943,
"author": "Mesidin",
"author_id": 454,
"author_profile": "https://Stackoverflow.com/users/454",
"pm_score": 1,
"selected": false,
"text": "$conn = mysql_connect(\"localhost\", ******, ******) or die(\"Could not connect\");\nmysql_select_db(\"adbay_com_-_cms\") or die(\"Could not select database\");\n"
},
{
"answer_id": 1024750,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "mysql_connect"
},
{
"answer_id": 18892554,
"author": "MoonJoose",
"author_id": 2795056,
"author_profile": "https://Stackoverflow.com/users/2795056",
"pm_score": 1,
"selected": false,
"text": "flush privileges;\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/454/"
] |
2,913 | <p>Does anyone have some good hints for writing test code for database-backend development where there is a heavy dependency on state?</p>
<p>Specifically, I want to write tests for code that retrieve records from the database, but the answers will depend on the data in the database (which may change over time).</p>
<p>Do people usually make a separate development system with a 'frozen' database so that any given function should always return the exact same result set?</p>
<p>I am quite sure this is not a new issue, so I would be very interested to learn from other people's experience.</p>
<p>Are there good articles out there that discuss this issue of web-based development in general?</p>
<p>I usually write PHP code, but I would expect all of these issues are largely language and framework agnostic.</p>
| [
{
"answer_id": 16710,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 1,
"selected": false,
"text": "DELETE * FROM table"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] |
2,914 | <p>Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening.</p>
<p>What methods can the calling window use to make sure the new window launched properly?</p>
| [
{
"answer_id": 2917,
"author": "omar",
"author_id": 453,
"author_profile": "https://Stackoverflow.com/users/453",
"pm_score": 9,
"selected": true,
"text": "var newWin = window.open(url); \n\nif(!newWin || newWin.closed || typeof newWin.closed=='undefined') \n{ \n //POPUP BLOCKED\n}\n"
},
{
"answer_id": 13652829,
"author": "Kevin B",
"author_id": 886103,
"author_profile": "https://Stackoverflow.com/users/886103",
"pm_score": 5,
"selected": false,
"text": " // open after 3 seconds\nsetTimeout(() => window.open('http://google.com'), 3000);\n // open after 1 seconds\nsetTimeout(() => window.open('http://google.com'), 1000);\n var popupBlockerChecker = {\n check: function(popup_window){\n var scope = this;\n if (popup_window) {\n if(/chrome/.test(navigator.userAgent.toLowerCase())){\n setTimeout(function () {\n scope.is_popup_blocked(scope, popup_window);\n },200);\n }else{\n popup_window.onload = function () {\n scope.is_popup_blocked(scope, popup_window);\n };\n }\n } else {\n scope.displayError();\n }\n },\n is_popup_blocked: function(scope, popup_window){\n if ((popup_window.innerHeight > 0)==false){ \n scope.displayError();\n }\n },\n displayError: function(){\n alert(\"Popup Blocker is enabled! Please add this site to your exception list.\");\n }\n};\n var popup = window.open(\"http://www.google.ca\", '_blank');\npopupBlockerChecker.check(popup);\n"
},
{
"answer_id": 27725432,
"author": "DanielB",
"author_id": 4409047,
"author_profile": "https://Stackoverflow.com/users/4409047",
"pm_score": 6,
"selected": false,
"text": "openPopUp: function(urlToOpen) {\n var popup_window=window.open(urlToOpen,\"myWindow\",\"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=400, height=400\"); \n try {\n popup_window.focus(); \n } catch (e) {\n alert(\"Pop-up Blocker is enabled! Please add this site to your exception list.\");\n }\n}\n"
},
{
"answer_id": 48521529,
"author": "Michael Giovanni Pumo",
"author_id": 695749,
"author_profile": "https://Stackoverflow.com/users/695749",
"pm_score": 1,
"selected": false,
"text": "function popup (url, width, height) {\n const left = (window.screen.width / 2) - (width / 2)\n const top = (window.screen.height / 2) - (height / 2)\n let opener = window.open(url, '', `menubar=no, toolbar=no, status=no, resizable=yes, scrollbars=yes, width=${width},height=${height},top=${top},left=${left}`)\n\n window.setTimeout(() => {\n if (!opener || opener.closed || typeof opener.closed === 'undefined') {\n console.log('Not allowed...') // Do something here.\n }\n }, 1000)\n}\n"
},
{
"answer_id": 50587436,
"author": "Yash Bora",
"author_id": 9194867,
"author_profile": "https://Stackoverflow.com/users/9194867",
"pm_score": -1,
"selected": false,
"text": " function popup()\n {\n var chk=false;\n var win1=window.open();\n win1.onbeforeunload=()=>{\n var win2=window.open();\n win2.onbeforeunload=()=>{\n chk=true;\n };\n win2.close();\n };\n win1.close();\n return chk;\n }\n"
},
{
"answer_id": 54898902,
"author": "wonsuc",
"author_id": 4729203,
"author_profile": "https://Stackoverflow.com/users/4729203",
"pm_score": 1,
"selected": false,
"text": "var isPopupBlockerActivated = function(popupWindow) {\n if (popupWindow) {\n if (/chrome/.test(navigator.userAgent.toLowerCase())) {\n try {\n popupWindow.focus();\n } catch (e) {\n return true;\n }\n } else {\n popupWindow.onload = function() {\n return (popupWindow.innerHeight > 0) === false;\n };\n }\n } else {\n return true;\n }\n return false;\n};\n var popup = window.open('https://www.google.com', '_blank');\nif (isPopupBlockerActivated(popup)) {\n // Do what you want.\n}\n"
},
{
"answer_id": 59999198,
"author": "Lalit Umbarkar",
"author_id": 3983039,
"author_profile": "https://Stackoverflow.com/users/3983039",
"pm_score": 1,
"selected": false,
"text": " <script>\n var magicNumber = 49;\n </script>\n // Create the window with login URL.\n let openedWindow = window.open(URL_HERE);\n\n // Check this magic number after some time, if it exists then your window exists\n setTimeout(() => {\n if (openedWindow[\"magicNumber\"] !== 32) {\n console.error(\"Window open was blocked\");\n }\n }, 1500);\n\n undefined"
},
{
"answer_id": 73744911,
"author": "vladanPro",
"author_id": 617934,
"author_profile": "https://Stackoverflow.com/users/617934",
"pm_score": 0,
"selected": false,
"text": "try {\n const newWindow = window.open(url, '_blank');\n if (!newWindow || newWindow.closed || typeof newWindow.closed == 'undefined') {\n return null;\n }\n\n (newWindow as Window).window.focus();\n newWindow.addEventListener('load', function () {\n console.info('Please allow popups for this website')\n })\n return newWindow;\n } catch (e) {\n return null;\n }"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434/"
] |
2,933 | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p>
| [
{
"answer_id": 2937,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 9,
"selected": true,
"text": "PyQt"
},
{
"answer_id": 41966334,
"author": "PythonProgrammi",
"author_id": 6464947,
"author_profile": "https://Stackoverflow.com/users/6464947",
"pm_score": 2,
"selected": false,
"text": "# I'd use tkinter for python 3\n\nimport tkinter\n\ntk = tkinter.Tk()\ntk.geometry(\"400x300+500+300\")\nl = Label(tk,text=\"\")\nl.pack()\ne = Entry(tk)\ne.pack()\n\ndef click():\n e['text'] = 'You clicked the button'\n\nb = Button(tk,text=\"Click me\",command=click)\nb.pack()\n\ntk.mainloop()\n\n# After this I would you py2exe\n# search for the use of this module on stakoverflow\n# otherwise I could edit this to let you know how to do it\n from distutils.core import setup\nimport py2exe\n\nsetup(console=['l4h.py'])\n"
},
{
"answer_id": 44433045,
"author": "shahar_m",
"author_id": 662770,
"author_profile": "https://Stackoverflow.com/users/662770",
"pm_score": 1,
"selected": false,
"text": "appJar from appJar import gui\n\nnum=1\n\ndef myfcn(btnName): \n global num\n num +=1\n win.setLabel(\"mylabel\", num)\n\nwin = gui('Test')\n\nwin.addButtons([\"Set\"], [myfcn])\nwin.addLabel(\"mylabel\", \"Press the Button\")\n\nwin.go()\n pip install appjar"
},
{
"answer_id": 52721116,
"author": "Mike from PSG",
"author_id": 8743099,
"author_profile": "https://Stackoverflow.com/users/8743099",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env python\nimport sys\nif sys.version_info[0] >= 3:\n import PySimpleGUI as sg\nelse:\n import PySimpleGUI27 as sg\n\nlayout = [[ sg.Text('My Window') ],\n [ sg.Button('OK')]]\n\nwindow = sg.Window('My window').Layout(layout)\nbutton, value = window.Read()\n"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
2,968 | <p>For parsing player commands, I've most often used the <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29" rel="noreferrer">split</a> method to split a string by delimiters and then to then just figure out the rest by a series of <code>if</code>s or <code>switch</code>es. What are some different ways of parsing strings in Java?</p>
| [
{
"answer_id": 2971,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "String command = \"kick person\";\nStringTokenizer tokens = new StringTokenizer(command);\nString action = null;\n\nif (tokens.hasMoreTokens()) {\n action = tokens.nextToken();\n}\n\nif (action != null) {\n doCommand(action, tokens);\n}\n"
},
{
"answer_id": 3539,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 2,
"selected": false,
"text": "public static boolean simpleNLP(String inputline, String keywords[]) {\n if (inputline.length() < 1)\n return false;\n\n List<String> lexed = new ArrayList<String>(); \n for (String ele : inputline.split(\" \")) {\n lexed.add(ele);\n }\n\n\n boolean status = false;\n to = 0;\n for (i = 0; i < lexed.size(); i++) {\n String s = (String) lexed.get(i);\n if (s.equalsIgnoreCase(keywords[to])) {\n to++;\n if (to >= keywords.length) {\n status = true;\n break;\n }\n }\n }\n return status;\n}\n"
},
{
"answer_id": 13539884,
"author": "Pratik",
"author_id": 513340,
"author_profile": "https://Stackoverflow.com/users/513340",
"pm_score": 1,
"selected": false,
"text": "split regular expressions"
},
{
"answer_id": 23633702,
"author": "shouyu",
"author_id": 2899548,
"author_profile": "https://Stackoverflow.com/users/2899548",
"pm_score": 1,
"selected": false,
"text": "regex String regex String regex, int limit String regex StringTokenizer"
}
] | 2008/08/05 | [
"https://Stackoverflow.com/questions/2968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362/"
] |
2,993 | <p>I'm in an environment with a lot of computers that haven't been
properly inventoried. Basically, no one knows which IP goes with which
mac address and which hostname. So I wrote the following:</p>
<pre><code># This script goes down the entire IP range and attempts to
# retrieve the Hostname and mac address and outputs them
# into a file. Yay!
require "socket"
TwoOctets = "10.26"
def computer_exists?(computerip)
system("ping -c 1 -W 1 #{computerip}")
end
def append_to_file(line)
file = File.open("output.txt", "a")
file.puts(line)
file.close
end
def getInfo(current_ip)
begin
if computer_exists?(current_ip)
arp_output = `arp -v #{current_ip}`
mac_addr = arp_output.to_s.match(/..:..:..:..:..:../)
host_name = Socket.gethostbyname(current_ip)
append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n")
end
rescue SocketError => mySocketError
append_to_file("unknown - #{current_ip} - #{mac_addr}")
end
end
(6..8).each do |i|
case i
when 6
for j in (1..190)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 7
for j in (1..255)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 8
for j in (1..52)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
end
end
</code></pre>
<p>Everything works except it does not find a Reverse DNS.</p>
<p>Sample output that I'm getting is this:</p>
<pre><code>10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F
10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3
10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2
</code></pre>
<p>If I do <code>nslookup 10.26.6.12</code> then I get the correct reverse DNS so
that shows that my machine is seeing the DNS server.</p>
<p>I have tried <code>Socket.gethostbyname</code>, <code>gethostbyaddr</code>, but it doesn't work.</p>
<p>Any guidance will be much appreciated.</p>
| [
{
"answer_id": 3012,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 3,
"selected": false,
"text": "getaddrinfo host_name = Socket.gethostbyname(current_ip)\n host_name = Socket.getaddrinfo(current_ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][1]\n getaddrinfo"
},
{
"answer_id": 3306,
"author": "garg",
"author_id": 155,
"author_profile": "https://Stackoverflow.com/users/155",
"pm_score": 2,
"selected": false,
"text": "host_name = Socket.getaddrinfo(current_ip,nil)\nappend_to_file(\"#{host_name[0][2]} - #{current_ip} - #{mac_addr}\\n\")\n gethostbyaddr"
},
{
"answer_id": 5544777,
"author": "gertas",
"author_id": 446210,
"author_profile": "https://Stackoverflow.com/users/446210",
"pm_score": 6,
"selected": true,
"text": "require 'resolv'\nhost_name = Resolv.getname(ip_address_here)\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/2993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155/"
] |
3,017 | <p>By "generate", I mean auto-generation of the code necessary for a particular selected (set of) variable(s).</p>
<p>But any more explicit explication or comment on good practice is welcome.</p>
| [
{
"answer_id": 3023,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 5,
"selected": false,
"text": "public PropertyType PropertyName { get; set; }\n private PropertyType _property;\n\npublic PropertyType PropertyName\n{\n get\n {\n //logic here \n return _property;\n }\n set\n {\n //logic here\n _property = value;\n }\n }\n"
},
{
"answer_id": 3029,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 9,
"selected": true,
"text": "prop"
},
{
"answer_id": 26029899,
"author": "avinash kadu",
"author_id": 4070190,
"author_profile": "https://Stackoverflow.com/users/4070190",
"pm_score": 2,
"selected": false,
"text": "propfull propfull private data_type var_name;\n\npublic data_type var_name1{ get;set;}\n"
},
{
"answer_id": 29265520,
"author": "bsayegh",
"author_id": 2872338,
"author_profile": "https://Stackoverflow.com/users/2872338",
"pm_score": 2,
"selected": false,
"text": "{get; set;} prop <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<CodeSnippets\n xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n <CodeSnippet Format=\"1.0.0\">\n <Header>\n <Title>get set</Title>\n <Shortcut>get</Shortcut>\n </Header>\n <Snippet>\n <Code Language=\"CSharp\">\n <![CDATA[{get; set;}]]>\n </Code>\n </Snippet>\n </CodeSnippet>\n</CodeSnippets>\n get"
},
{
"answer_id": 29917170,
"author": "James Grey",
"author_id": 3728901,
"author_profile": "https://Stackoverflow.com/users/3728901",
"pm_score": 6,
"selected": false,
"text": "private int productID;\n\npublic int ProductID\n{\n get { return productID; }\n set { productID = value; }\n}\n public int ProductID { get; set; }\n"
},
{
"answer_id": 59482593,
"author": "Adil Malik",
"author_id": 1182823,
"author_profile": "https://Stackoverflow.com/users/1182823",
"pm_score": 4,
"selected": false,
"text": "Ctrl+r Ctrl+e OK"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391/"
] |
3,021 | <p>One of the topics that seems to come up regularly on mailing lists and online discussions is the merits (or lack thereof) of doing a Computer Science Degree. An argument that seems to come up time and again for the negative party is that they have been coding for some number of years and they have never used recursion.</p>
<p>So the question is:</p>
<ol>
<li>What is recursion?</li>
<li>When would I use recursion?</li>
<li>Why don't people use recursion?</li>
</ol>
| [
{
"answer_id": 3025,
"author": "Louis Brandy",
"author_id": 2089740,
"author_profile": "https://Stackoverflow.com/users/2089740",
"pm_score": 3,
"selected": false,
"text": "int fact(int a) \n{\n if(a==1)\n return 1;\n\n return a*fact(a-1);\n}\n"
},
{
"answer_id": 3030,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 3,
"selected": false,
"text": "function cmdCheckAllClick {\n checkRecursively(TreeView1.RootNode);\n}\n\nfunction checkRecursively(Node n) {\n n.Checked = True;\n foreach ( n.Children as child ) {\n checkRecursively(child);\n }\n}\n"
},
{
"answer_id": 3035,
"author": "Mike Minutillo",
"author_id": 358,
"author_profile": "https://Stackoverflow.com/users/358",
"pm_score": 5,
"selected": false,
"text": "public int Fact(int n)\n{\n int fact = 1;\n\n for( int i = 2; i <= n; i++)\n {\n fact = fact * i;\n }\n\n return fact;\n}\n public int FactRec(int n)\n{\n if( n < 2 )\n {\n return 1;\n }\n\n return n * FactRec( n - 1 );\n}\n // In FactRec(5)\nreturn 5 * FactRec( 5 - 1 );\n\n// which is\nreturn 5 * FactRec(4);\n // In FactRec(4)\nreturn 4 * FactRec(3);\n // In FactRec(5)\nreturn 5 * (4 * FactRec(3));\n return 5 * (4 * FactRec(3));\nreturn 5 * (4 * (3 * FactRec(2)));\nreturn 5 * (4 * (3 * (2 * FactRec(1))));\nreturn 5 * (4 * (3 * (2 * (1))));\n"
},
{
"answer_id": 3037,
"author": "Mario Marinato",
"author_id": 431,
"author_profile": "https://Stackoverflow.com/users/431",
"pm_score": 0,
"selected": false,
"text": "String ArrangeString(TStringList* items, int position, String separator)\n{\n String result;\n\n result = items->Strings[position];\n\n if (position <= items->Count)\n result += separator + ArrangeString(items, position + 1, separator);\n\n return result;\n}\n String columnsList;\ncolumnsList = ArrangeString(columns, 0, \", \");\n ArrangeString(fields, 0, \", \");\n ArrangeString(fields, 1, \", \");\n"
},
{
"answer_id": 3043,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "count of [x x x] = 1 + count of [x x]\n = 1 + (1 + count of [x])\n = 1 + (1 + (1 + count of []))\n = 1 + (1 + (1 + 0)))\n = 1 + (1 + (1))\n = 1 + (2)\n = 3\n numberOfItems(set)\n if set is empty\n return 0\n else\n remove 1 item from set\n return 1 + numberOfItems(set)\n"
},
{
"answer_id": 3050,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 0,
"selected": false,
"text": "String ArrangeString(TStringList* items, String separator)\n{\n String result = items->Strings[0];\n\n for (int position=1; position < items->count; position++) {\n result += separator + items->Strings[position];\n }\n\n return result;\n}\n"
},
{
"answer_id": 19918,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 0,
"selected": false,
"text": "int factorial_accumulate(int n, int accum) {\n return (n < 2 ? accum : factorial_accumulate(n - 1, n * accum));\n}\n\nint factorial(int n) {\n return factorial_accumulate(n, 1);\n}\n"
},
{
"answer_id": 2764802,
"author": "Andreas Brinck",
"author_id": 125672,
"author_profile": "https://Stackoverflow.com/users/125672",
"pm_score": 6,
"selected": false,
"text": "struct Node {\n Node* next;\n};\n int length(const Node* list) {\n if (!list->next) {\n return 1;\n } else {\n return 1 + length(list->next);\n }\n}\n"
},
{
"answer_id": 2764809,
"author": "Amber",
"author_id": 148870,
"author_profile": "https://Stackoverflow.com/users/148870",
"pm_score": 3,
"selected": false,
"text": "X X times the factorial of X-1 X-1 X X-1 X-2 X 1 0! = 1! = 1"
},
{
"answer_id": 2764836,
"author": "RationalGeek",
"author_id": 123468,
"author_profile": "https://Stackoverflow.com/users/123468",
"pm_score": 4,
"selected": false,
"text": "public int Factorial(int n)\n{\n if (n <= 1)\n return 1;\n\n return n * Factorial(n - 1);\n}\n"
},
{
"answer_id": 2765055,
"author": "kacalapy",
"author_id": 352157,
"author_profile": "https://Stackoverflow.com/users/352157",
"pm_score": 1,
"selected": false,
"text": "private void findlinks(string URL, int reccursiveCycleNumb) {\n if (reccursiveCycleNumb == 0)\n {\n return;\n }\n\n //recursive action here\n foreach (LinkItem i in LinkFinder.Find(URL))\n {\n //see what links are being caught...\n lblResults.Text += i.Href + \"<BR>\";\n\n findlinks(i.Href, reccursiveCycleNumb - 1);\n }\n\n reccursiveCycleNumb -= reccursiveCycleNumb;\n}\n"
},
{
"answer_id": 2765346,
"author": "Indigo Praveen",
"author_id": 317536,
"author_profile": "https://Stackoverflow.com/users/317536",
"pm_score": 1,
"selected": false,
"text": "public int fact(int n)\n{\n if (n==0) return 1;\n else return n*fact(n-1)\n}\n"
},
{
"answer_id": 2765519,
"author": "Bastiaan Linders",
"author_id": 255657,
"author_profile": "https://Stackoverflow.com/users/255657",
"pm_score": 2,
"selected": false,
"text": "start\n Is the table empty?\n yes: Count the tally marks and cheer like it's your birthday!\n no: Take 1 apple and put it aside\n Write down a tally mark\n goto start\n"
},
{
"answer_id": 2765695,
"author": "Gregory Brown",
"author_id": 289274,
"author_profile": "https://Stackoverflow.com/users/289274",
"pm_score": 2,
"selected": false,
"text": "factorial(6) = 6*5*4*3*2*1\n 6 * factorial(5) = 6*(5*4*3*2*1).\n factorial(n) = n*factorial(n-1)\n factorial(6) = 6*factorial(5)\n = 6*5*factorial(4)\n = 6*5*4*factorial(3) = 6*5*4*3*factorial(2) = 6*5*4*3*2*factorial(1) = 6*5*4*3*2*1\n factorial(n) = n*factorial(n-1) factorial(1) = 1"
},
{
"answer_id": 2765712,
"author": "Steve Wortham",
"author_id": 102896,
"author_profile": "https://Stackoverflow.com/users/102896",
"pm_score": 6,
"selected": false,
"text": "int FloorByTen(int num)\n{\n if (num % 10 == 0)\n return num;\n else\n return FloorByTen(num-1);\n}\n private void BuildVertices(double x, double y, double len)\n{\n if (len > 0.002)\n {\n mesh.Positions.Add(new Point3D(x, y + len, -len));\n mesh.Positions.Add(new Point3D(x - len, y - len, -len));\n mesh.Positions.Add(new Point3D(x + len, y - len, -len));\n len *= 0.5;\n BuildVertices(x, y + len, len);\n BuildVertices(x - len, y - len, len);\n BuildVertices(x + len, y - len, len);\n }\n}\n"
},
{
"answer_id": 2765870,
"author": "mfx",
"author_id": 8015,
"author_profile": "https://Stackoverflow.com/users/8015",
"pm_score": 1,
"selected": false,
"text": " tree = null \n | leaf(value:integer) \n | node(left: tree, right:tree)\n function computeSomething(x : tree) =\n if x is null: base case\n if x is leaf: do something with x.value\n if x is node: do something with x.left,\n do something with x.right,\n combine the results\n integer = 0 | succ(integer)\n function computeSomething(x : integer) =\n if x is 0 : base case\n if x is succ(prev) : do something with prev\n"
},
{
"answer_id": 2765912,
"author": "Greg Bacon",
"author_id": 123109,
"author_profile": "https://Stackoverflow.com/users/123109",
"pm_score": 3,
"selected": false,
"text": "sum l =\n if empty(l)\n return 0\n else\n return head(l) + sum(tail(l))\n head tail sum max l =\n if empty(l)\n error\n elsif length(l) = 1\n return head(l)\n else\n tailmax = max(tail(l))\n if head(l) > tailmax\n return head(l)\n else\n return tailmax\n a * b =\n if b = 0\n return 0\n else\n return a + (a * (b - 1))\n sort(l) =\n if empty(l) or length(l) = 1\n return l\n else\n (left,right) = split l\n return merge(sort(left), sort(right))\n"
},
{
"answer_id": 2766028,
"author": "Don Mackenzie",
"author_id": 100347,
"author_profile": "https://Stackoverflow.com/users/100347",
"pm_score": 1,
"selected": false,
"text": "def qsort: List[Int] => List[Int] = {\n case Nil => Nil\n case pivot :: tail =>\n val (smaller, rest) = tail.partition(_ < pivot)\n qsort(smaller) ::: pivot :: qsort(rest)\n}\n"
},
{
"answer_id": 2766604,
"author": "J.K.Aery",
"author_id": 283163,
"author_profile": "https://Stackoverflow.com/users/283163",
"pm_score": 1,
"selected": false,
"text": "n! = n(n-1)(n-2)(n-3)...........*3*2*1\n n! = n(n-1)! for n>=1\n"
},
{
"answer_id": 2766661,
"author": "Donal Fellows",
"author_id": 301832,
"author_profile": "https://Stackoverflow.com/users/301832",
"pm_score": 1,
"selected": false,
"text": "struct Tree {\n int leaf;\n Tree *leftBranch;\n Tree *rightBranch;\n};\n function printTreeInOrder(Tree *tree) {\n if (tree->leftBranch) {\n printTreeInOrder(tree->leftBranch);\n }\n print(tree->leaf);\n if (tree->rightBranch) {\n printTreeInOrder(tree->rightBranch);\n }\n}\n"
},
{
"answer_id": 2767157,
"author": "DMin",
"author_id": 237351,
"author_profile": "https://Stackoverflow.com/users/237351",
"pm_score": 6,
"selected": false,
"text": "A child couldn't sleep, so her mother told her a story about a little frog,\n who couldn't sleep, so the frog's mother told her a story about a little bear,\n who couldn't sleep, so the bear's mother told her a story about a little weasel... \n who fell asleep.\n ...and the little bear fell asleep;\n ...and the little frog fell asleep;\n...and the child fell asleep.\n"
},
{
"answer_id": 22321942,
"author": "AlienOnEarth",
"author_id": 2041115,
"author_profile": "https://Stackoverflow.com/users/2041115",
"pm_score": 2,
"selected": false,
"text": "void f() {\n ... f() ... \n}\n void f() {\n ... g() ...\n}\n\nvoid g() {\n ... f() ...\n}\n Q: Does using recursion usually make your code faster? \nA: No.\nQ: Does using recursion usually use less memory? \nA: No.\nQ: Then why use recursion? \nA: It sometimes makes your code much simpler!\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/358/"
] |
3,033 | <p>If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using <code>each</code> may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way?</p>
<pre><code># Method 1
while (my ($key, $value) = each(%hash)) {
# Something
}
# Method 2
foreach my $key (keys(%hash)) {
# Something
}
</code></pre>
| [
{
"answer_id": 3360,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 9,
"selected": true,
"text": "foreach my $key (keys %hash) { ... }\n foreach my $val (values %hash) { ... }\n keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop\nwhile(my($k, $v) = each %hash) { ... }\n %h = (a => 1, b => 2);\n\nforeach my $k (keys %h)\n{\n $h{uc $k} = $h{$k} * 2;\n}\n (a => 1, A => 2, b => 2, B => 4)\n %h = (a => 1, b => 2);\n\nkeys %h;\nwhile(my($k, $v) = each %h)\n{\n $h{uc $k} = $h{$k} * 2; # BAD IDEA!\n}\n (a => 1, A => 2, b => 2, B => 8)\n keys %h;\nwhile(my($k, $v) = each %h)\n{\n if(...)\n {\n delete $h{$k}; # This is safe\n }\n}\n % perldoc -f keys\n% perldoc -f each\n"
},
{
"answer_id": 22669,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 2,
"selected": false,
"text": "keys each map map { print \"$_ => $hash{$_}\\n\" } keys %hash;\n"
},
{
"answer_id": 67239,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "values each keys each keys"
},
{
"answer_id": 67970,
"author": "8jean",
"author_id": 10011,
"author_profile": "https://Stackoverflow.com/users/10011",
"pm_score": 5,
"selected": false,
"text": "each each last return while ... each each my %hash = ( foo => 1, bar => 2, baz => 3, quux => 4 );\n\n# find key 'baz'\nwhile ( my ($k, $v) = each %hash ) {\n print \"found key $k\\n\";\n last if $k eq 'baz'; # found it!\n}\n\n# later ...\n\nprint \"the hash contains:\\n\";\n\n# iterate over all keys:\nwhile ( my ($k, $v) = each %hash ) {\n print \"$k => $v\\n\";\n}\n found key bar\nfound key baz\nthe hash contains:\nquux => 4\nfoo => 1\n each"
},
{
"answer_id": 73004,
"author": "Darren Meyer",
"author_id": 7826,
"author_profile": "https://Stackoverflow.com/users/7826",
"pm_score": 4,
"selected": false,
"text": "each while ( my ($key,$val) = each %a_hash ) {\n print \"$key => $val\\n\";\n last if $val; #exits loop when $val is true\n}\n\n# but \"each\" hasn't reset!!\nwhile ( my ($key,$val) = each %a_hash ) {\n # continues where the last loop left off\n print \"$key => $val\\n\";\n}\n each keys values"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219/"
] |
3,058 | <p>Inversion of Control (IoC) can be quite confusing when it is first encountered.</p>
<ol>
<li>What is it?</li>
<li>Which problem does it solve?</li>
<li>When is it appropriate to use and when not?</li>
</ol>
| [
{
"answer_id": 3108,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 10,
"selected": false,
"text": "print \"enter your name\"\nread name\nprint \"enter your address\"\nread address\netc...\nstore in database\n when the user types in field a, store it in NAME\nwhen the user types in field b, store it in ADDRESS\nwhen the user clicks the save button, call StoreInDatabase\n"
},
{
"answer_id": 3140,
"author": "urini",
"author_id": 373,
"author_profile": "https://Stackoverflow.com/users/373",
"pm_score": 12,
"selected": true,
"text": "Inversion-of-Control callback Dependency-Injection DI IoC IoC public class TextEditor {\n\n private SpellChecker checker;\n\n public TextEditor() {\n this.checker = new SpellChecker();\n }\n}\n TextEditor SpellChecker public class TextEditor {\n\n private IocSpellChecker checker;\n\n public TextEditor(IocSpellChecker checker) {\n this.checker = checker;\n }\n}\n SpellChecker this.checker = new SpellChecker(); TextEditor SpellChecker SpellChecker TextEditor SpellChecker sc = new SpellChecker(); // dependency\nTextEditor textEditor = new TextEditor(sc);\n TextEditor SpellChecker TextEditor"
},
{
"answer_id": 99760,
"author": "ferventcoder",
"author_id": 18475,
"author_profile": "https://Stackoverflow.com/users/18475",
"pm_score": 2,
"selected": false,
"text": "public class MessagePublisher<RECORD,MESSAGE>\n{\n public MessagePublisher(IMapper<RECORD,MESSAGE> mapper,IRemoteEndpoint endPointToSendTo)\n {\n //setup\n }\n}\n"
},
{
"answer_id": 12607591,
"author": "Jainendra",
"author_id": 1341006,
"author_profile": "https://Stackoverflow.com/users/1341006",
"pm_score": 5,
"selected": false,
"text": "public class MeetingMember {\n\n private GlassOfWater glassOfWater;\n\n ...\n\n public void setGlassOfWater(GlassOfWater glassOfWater){\n this.glassOfWater = glassOfWater;\n }\n //your glassOfWater object initialized and ready to use...\n //spring IoC called setGlassOfWater method itself in order to\n //offer to meetingMember glassOfWater instance\n\n}\n"
},
{
"answer_id": 26839777,
"author": "VeKe",
"author_id": 1878022,
"author_profile": "https://Stackoverflow.com/users/1878022",
"pm_score": 5,
"selected": false,
"text": "For quick understanding just read examples*\n Quick Example:EMPLOYEE OBJECT WHEN CREATED,\n IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT\n (if address is defines as dependency by Employee object)\n QUICK EXAMPLE:Inversion of Control is about getting freedom, more flexibility, and less dependency. When you are using a desktop computer, you are slaved (or say, controlled). You have to sit before a screen and look at it. Using keyboard to type and using mouse to navigate. And a bad written software can slave you even more. If you replaced your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of computer controlling it"
},
{
"answer_id": 29729645,
"author": "magallanes",
"author_id": 202705,
"author_profile": "https://Stackoverflow.com/users/202705",
"pm_score": 4,
"selected": false,
"text": "trainDays() trainDays() trainDays()"
},
{
"answer_id": 47111262,
"author": "Raghavendra N",
"author_id": 3965675,
"author_profile": "https://Stackoverflow.com/users/3965675",
"pm_score": 4,
"selected": false,
"text": "class SomeController\n{\n private $storage;\n\n function __construct(StorageServiceInterface $storage)\n {\n $this->storage = $storage;\n }\n\n public function myFunction () \n {\n return $this->storage->getFile($fileName);\n }\n}\n\nclass GoogleDriveService implements StorageServiceInterface\n{\n public function authenticate($user) {}\n public function putFile($file) {}\n public function getFile($file) {}\n}\n new class SomeController\n{\n private $storage;\n\n function __construct()\n {\n $this->storage = new GoogleDriveService();\n }\n\n public function myFunction () \n {\n return $this->storage->getFile($fileName);\n }\n}\n new"
},
{
"answer_id": 47838081,
"author": "Sergiy Ostrovsky",
"author_id": 2084960,
"author_profile": "https://Stackoverflow.com/users/2084960",
"pm_score": 4,
"selected": false,
"text": "getProductList() doShopping()"
},
{
"answer_id": 54700451,
"author": "Toseef Zafar",
"author_id": 1386990,
"author_profile": "https://Stackoverflow.com/users/1386990",
"pm_score": 2,
"selected": false,
"text": "TextEditor SpellChecker SpellChecker TextEditor TextEditor ISpeallChecker SpellChecker"
},
{
"answer_id": 56050702,
"author": "Hearen",
"author_id": 2361308,
"author_profile": "https://Stackoverflow.com/users/2361308",
"pm_score": 2,
"selected": false,
"text": "<<Clean Code: A Handbook of Agile Software Craftsmanship>> <<Refactoring: Improving the Design of Existing Code>>"
},
{
"answer_id": 59695363,
"author": "Daniel W.",
"author_id": 1948292,
"author_profile": "https://Stackoverflow.com/users/1948292",
"pm_score": 0,
"selected": false,
"text": "function isVarHello($var) {\n return ($var === \"Hello\");\n}\n\n// Responsibility is within the caller\n$word = \"Hello\";\nif (isVarHello($word)) {\n $word = \"World\";\n}\n function changeHelloToWorld(&$var) {\n // Responsibility has been shifted to the dependency\n if ($var === \"Hello\") {\n $var = \"World\";\n }\n}\n\n$word = \"Hello\";\nchangeHelloToWorld($word);\n <?php\n\nclass Human {\n private $hp = 0.5;\n\n function consume(Eatable $chunk) {\n // $this->chew($chunk);\n $chunk->unfoldEffectOn($this);\n }\n\n function incrementHealth() {\n $this->hp++;\n }\n function isHealthy() {}\n function getHungry() {}\n // ...\n}\n\ninterface Eatable {\n public function unfoldEffectOn($body);\n}\n\nclass Medicine implements Eatable {\n function unfoldEffectOn($human) {\n // The dependency is now in charge of the human.\n $human->incrementHealth();\n $this->depleted = true;\n }\n}\n\n$human = new Human();\n$medicine = new Medicine();\nif (!$human->isHealthy()) {\n $human->consume($medicine); \n}\n\nvar_dump($medicine);\nvar_dump($human);\n"
},
{
"answer_id": 71012995,
"author": "Ryan Deschamps",
"author_id": 3050664,
"author_profile": "https://Stackoverflow.com/users/3050664",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\ndf = new DataFrame()\n# Now do things with the dataframe.\n map filter"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/358/"
] |
3,061 | <p>How do I call a function, using a string with the function's name? For example:</p>
<pre><code>import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
</code></pre>
| [
{
"answer_id": 3071,
"author": "Patrick Johnmeyer",
"author_id": 363,
"author_profile": "https://Stackoverflow.com/users/363",
"pm_score": 12,
"selected": true,
"text": "foo bar import foo\nbar = getattr(foo, 'bar')\nresult = bar()\n getattr"
},
{
"answer_id": 4605,
"author": "HS.",
"author_id": 618,
"author_profile": "https://Stackoverflow.com/users/618",
"pm_score": 9,
"selected": false,
"text": "module = __import__('foo')\nfunc = getattr(module, 'bar')\nfunc()\n"
},
{
"answer_id": 834451,
"author": "sastanin",
"author_id": 25450,
"author_profile": "https://Stackoverflow.com/users/25450",
"pm_score": 10,
"selected": false,
"text": "locals() locals()[\"myfunction\"]()\n globals() globals()[\"myfunction\"]()\n"
},
{
"answer_id": 9272378,
"author": "trubliphone",
"author_id": 1060339,
"author_profile": "https://Stackoverflow.com/users/1060339",
"pm_score": 5,
"selected": false,
"text": "myFnName = \"MyFn\"\nmyAppName = \"MyApp\"\napp = sys.modules[myAppName]\nfn = getattr(app,myFnName)\n"
},
{
"answer_id": 12025554,
"author": "Sourcegeek",
"author_id": 1609832,
"author_profile": "https://Stackoverflow.com/users/1609832",
"pm_score": 7,
"selected": false,
"text": "# Get class from globals and create an instance\nm = globals()['our_class']()\n\n# Get the function (from the instance) that we need to call\nfunc = getattr(m, 'function_name')\n\n# Call it\nfunc()\n class A:\n def __init__(self):\n pass\n\n def sampleFunc(self, arg):\n print('you called sampleFunc({})'.format(arg))\n\nm = globals()['A']()\nfunc = getattr(m, 'sampleFunc')\nfunc('sample arg')\n\n# Sample, all on one line\ngetattr(globals()['A'](), 'sampleFunc')('sample arg')\n def sampleFunc(arg):\n print('you called sampleFunc({})'.format(arg))\n\nglobals()['sampleFunc']('sample arg')\n"
},
{
"answer_id": 14072943,
"author": "Natdrip",
"author_id": 1112523,
"author_profile": "https://Stackoverflow.com/users/1112523",
"pm_score": 4,
"selected": false,
"text": "<object>.__getattribute__(<string name>)(<params>)\n"
},
{
"answer_id": 19393328,
"author": "ferrouswheel",
"author_id": 272238,
"author_profile": "https://Stackoverflow.com/users/272238",
"pm_score": 7,
"selected": false,
"text": "import importlib\nfunction_string = 'mypackage.mymodule.myfunc'\nmod_name, func_name = function_string.rsplit('.',1)\nmod = importlib.import_module(mod_name)\nfunc = getattr(mod, func_name)\nresult = func()\n"
},
{
"answer_id": 22959509,
"author": "00500005",
"author_id": 1356953,
"author_profile": "https://Stackoverflow.com/users/1356953",
"pm_score": 6,
"selected": false,
"text": "getattr(locals().get(\"foo\") or globals().get(\"foo\"), \"bar\")()\n getattr(\n locals().get(\"foo\") or \n globals().get(\"foo\") or\n __import__(\"foo\"), \n\"bar\")()\n getattr(next((x for x in (f(\"foo\") for f in \n [locals().get, globals().get, \n self.__dict__.get, __import__]) \n if x)),\n\"bar\")()\n getattr(next((x for x in (f(\"foo\") for f in \n ([locals().get, globals().get, self.__dict__.get] +\n [d.get for d in (list(dd.values()) for dd in \n [locals(),globals(),self.__dict__]\n if isinstance(dd,dict))\n if isinstance(d,dict)] + \n [__import__])) \n if x)),\n\"bar\")()\n"
},
{
"answer_id": 40219576,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "functions = {'myfoo': foo.bar}\n\nmystring = 'myfoo'\nif mystring in functions:\n functions[mystring]()\n"
},
{
"answer_id": 41024742,
"author": "tvt173",
"author_id": 701803,
"author_profile": "https://Stackoverflow.com/users/701803",
"pm_score": 5,
"selected": false,
"text": "def say_hello(name):\n print 'Hello {}!'.format(name)\n\n# get the function by name\nmethod_name = 'say_hello'\nmethod = eval(method_name)\n\n# call it like a regular function later\nargs = ['friend']\nkwargs = {}\nmethod(*args, **kwargs)\n"
},
{
"answer_id": 55363812,
"author": "Serjik",
"author_id": 546822,
"author_profile": "https://Stackoverflow.com/users/546822",
"pm_score": 4,
"selected": false,
"text": "class MyClass:\n def __init__(self, i):\n self.i = i\n\n def get(self):\n func = getattr(MyClass, 'function{}'.format(self.i))\n func(self, 12) # This one will work\n # self.func(12) # But this does NOT work.\n\n\n def function1(self, p1):\n print('function1: {}'.format(p1))\n # do other stuff\n\n def function2(self, p1):\n print('function2: {}'.format(p1))\n # do other stuff\n\n\nif __name__ == \"__main__\":\n class1 = MyClass(1)\n class1.get()\n class2 = MyClass(2)\n class2.get()\n"
},
{
"answer_id": 57696855,
"author": "Number File",
"author_id": 11530007,
"author_profile": "https://Stackoverflow.com/users/11530007",
"pm_score": -1,
"selected": false,
"text": "clear cls eval(\"os.system(\\\"clear\\\")\")\nexec(\"os.system(\\\"clear\\\")\")\n"
},
{
"answer_id": 62672406,
"author": "정도유",
"author_id": 5532667,
"author_profile": "https://Stackoverflow.com/users/5532667",
"pm_score": 3,
"selected": false,
"text": "getattr super(self.__class__, self) class Base:\n def call_base(func):\n \"\"\"This does not work\"\"\"\n def new_func(self, *args, **kwargs):\n name = func.__name__\n getattr(super(self.__class__, self), name)(*args, **kwargs)\n return new_func\n\n def f(self, *args):\n print(f\"BASE method invoked.\")\n\n def g(self, *args):\n print(f\"BASE method invoked.\")\n\nclass Inherit(Base):\n @Base.call_base\n def f(self, *args):\n \"\"\"function body will be ignored by the decorator.\"\"\"\n pass\n\n @Base.call_base\n def g(self, *args):\n \"\"\"function body will be ignored by the decorator.\"\"\"\n pass\n\nInherit().f() # The goal is to print \"BASE method invoked.\"\n"
},
{
"answer_id": 62937980,
"author": "Lukas",
"author_id": 10257810,
"author_profile": "https://Stackoverflow.com/users/10257810",
"pm_score": 4,
"selected": false,
"text": "x = eval('foo.bar')() # import module, call module function, pass parameters and print retured value with eval():\nimport random\nbar = 'random.randint'\nrandint = eval(bar)(0,100)\nprint(randint) # will print random int from <0;100)\n\n# also class method returning (or not) value(s) can be used with eval: \nclass Say:\n def say(something='nothing'):\n return something\n\nbar = 'Say.say'\nprint(eval(bar)('nice to meet you too')) # will print 'nice to meet you' \n # try/except block can be used to catch both errors\ntry:\n eval('Say.talk')() # raises AttributeError because function does not exist\n eval('Says.say')() # raises NameError because the class does not exist\n # or the same with getattr:\n getattr(Say, 'talk')() # raises AttributeError\n getattr(Says, 'say')() # raises NameError\nexcept AttributeError:\n # do domething or just...\n print('Function does not exist')\nexcept NameError:\n # do domething or just...\n print('Module does not exist')\n"
},
{
"answer_id": 67982516,
"author": "Bowen 404",
"author_id": 7266363,
"author_profile": "https://Stackoverflow.com/users/7266363",
"pm_score": 2,
"selected": false,
"text": "eval() ast.literal_eval() \"foo.bar\" x x() str_to_convert = \"foo.bar\"\nexec(f\"x = {str_to_convert}\")\nx()\n foo . {} str_to_convert = \"bar\"\nexec(f\"x = foo.{str_to_convert}\")\nx()\n eval() exec() eval() exec() eval() exec()"
},
{
"answer_id": 68283436,
"author": "Aliakbar Ahmadi",
"author_id": 4879852,
"author_profile": "https://Stackoverflow.com/users/4879852",
"pm_score": 4,
"selected": false,
"text": "__getattribute__ func_name = 'reverse'\n\nl = [1, 2, 3, 4]\nprint(l)\n>> [1, 2, 3, 4]\n\nl.__getattribute__(func_name)()\nprint(l)\n>> [4, 3, 2, 1]\n"
},
{
"answer_id": 69249811,
"author": "U12-Forward",
"author_id": 8708364,
"author_profile": "https://Stackoverflow.com/users/8708364",
"pm_score": 3,
"selected": false,
"text": "operator.attrgetter >>> from operator import attrgetter\n>>> l = [1, 2, 3]\n>>> attrgetter('reverse')(l)()\n>>> l\n[3, 2, 1]\n>>> \n"
},
{
"answer_id": 70526558,
"author": "Franz Kurt",
"author_id": 7327114,
"author_profile": "https://Stackoverflow.com/users/7327114",
"pm_score": -1,
"selected": false,
"text": "import foo\nmethod = foo.bar\nexecuted = method(parameter)\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121/"
] |
3,088 | <p><strong>Original Question</strong></p>
<p>I am currently engaged in teaching my brother to program. He is a total beginner, but very smart. (And he actually wants to learn). I've noticed that some of our sessions have gotten bogged down in minor details, and I don't feel I've been very organized. (<em>But the answers to this post have helped a lot.</em>)</p>
<p>What can I do better to teach him effectively? Is there a logical order that I can use to run through concept by concept? Are there complexities I should avoid till later?</p>
<p>The language we are working with is <a href="http://www.python.org" rel="noreferrer">Python</a>, but advice in any language is welcome.</p>
<hr>
<p><strong>How to Help</strong></p>
<p>If you have good ones please add the following in your answer:</p>
<ul>
<li>Beginner Exercises and Project Ideas</li>
<li>Resources for teaching beginners</li>
<li>Screencasts / blog posts / free e-books</li>
<li>Print books that are good for beginners</li>
</ul>
<p>Please describe the resource <em>with a link to it</em> so I can take a look. I want everyone to know that I have definitely been using some of these ideas. Your submissions will be aggregated in this post.</p>
<hr>
<p><strong>Online Resources</strong> for teaching beginners:</p>
<ul>
<li><a href="http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-189January--IAP--2008/CourseHome/" rel="noreferrer">A Gentle Introduction to Programming Using Python</a></li>
<li><a href="http://openbookproject.net/thinkcs/python/english2e/index.html" rel="noreferrer">How to Think Like a Computer Scientist</a></li>
<li><a href="http://www.alice.org/" rel="noreferrer">Alice: a 3d program for beginners</a></li>
<li><a href="http://scratch.mit.edu/" rel="noreferrer">Scratch (A system to develop programming skills)</a></li>
<li><a href="http://www.htdp.org/" rel="noreferrer">How To Design Programs</a></li>
<li><a href="http://mitpress.mit.edu/sicp/full-text/book/book.html" rel="noreferrer">Structure and Interpretation of Computer Programs</a></li>
<li><a href="http://pine.fm/LearnToProgram/" rel="noreferrer">Learn To Program</a></li>
<li><a href="http://samizdat.mines.edu/howto/HowToBeAProgrammer.html" rel="noreferrer">Robert Read's How To Be a Programmer</a></li>
<li><a href="http://creators.xna.com/" rel="noreferrer">Microsoft XNA</a></li>
<li><a href="http://vodpod.com/watch/914464-inspirational-oscon-keynote" rel="noreferrer">Spawning the Next Generation of Hackers</a></li>
<li><a href="http://deimos3.apple.com/WebObjects/Core.woa/Browse/unsw.edu.au.1504975442.01504975444" rel="noreferrer"><em>COMP1917 Higher Computing</em> lectures by Richard Buckland</a> (requires iTunes)</li>
<li><a href="http://diveintopython.net/" rel="noreferrer">Dive into Python</a></li>
<li><a href="http://en.wikibooks.org/wiki/Programming:Python" rel="noreferrer">Python Wikibook</a></li>
<li><a href="http://projecteuler.net/" rel="noreferrer">Project Euler</a> - sample problems (mostly mathematical)</li>
<li><a href="http://www.pygame.org/" rel="noreferrer">pygame</a> - an easy python library for creating games</li>
<li><a href="http://inventwithpython.com/IYOCGwP_book1.pdf" rel="noreferrer">Invent Your Own Computer Games With Python</a></li>
<li><a href="http://codebetter.com/blogs/karlseguin/archive/2008/06/24/foundations-of-programming-ebook.aspx" rel="noreferrer">Foundations of Programming</a> for a next step beyond basics.</li>
<li><a href="http://www.iam.unibe.ch/~scg/SBE/" rel="noreferrer">Squeak by Example</a> </li>
<li><a href="http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/" rel="noreferrer">Snake Wrangling For Kids</a> (It's not just for kids!)</li>
</ul>
<hr>
<p><strong>Recommended Print Books</strong> for teaching beginners</p>
<ul>
<li><a href="http://www.acceleratedcpp.com/" rel="noreferrer">Accelerated C++</a></li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/1598631128" rel="noreferrer" rel="nofollow noreferrer">Python Programming for the Absolute Beginner</a></li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0735611319" rel="noreferrer" rel="nofollow noreferrer">Code by Charles Petzold</a></li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/1590282418" rel="noreferrer" rel="nofollow noreferrer">Python Programming: An Introduction to Computer Science 2nd Edition</a></li>
</ul>
| [
{
"answer_id": 12928,
"author": "Wing",
"author_id": 958,
"author_profile": "https://Stackoverflow.com/users/958",
"pm_score": 1,
"selected": false,
"text": "if :\n if () \n{\n\n}\n If () Then\nBegin\n\nEnd\n"
},
{
"answer_id": 22042,
"author": "pkchukiss",
"author_id": 2504504,
"author_profile": "https://Stackoverflow.com/users/2504504",
"pm_score": 0,
"selected": false,
"text": "int a = 5;\n\nfor (int i = 0; i < a; i++) {\n System.out.println(\"i is now \" + i);\n}\n"
},
{
"answer_id": 50351,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": "from visual import *\n\nfloor = box (pos=(0,0,0), length=4, height=0.5, width=4, color=color.blue)\nball = sphere (pos=(0,4,0), radius=1, color=color.red)\nball.velocity = vector(0,-1,0)\ndt = 0.01\n\nwhile 1:\n rate (100)\n ball.pos = ball.pos + ball.velocity*dt\n if ball.y < ball.radius:\n ball.velocity.y = -ball.velocity.y\n else:\n ball.velocity.y = ball.velocity.y - 9.8*dt\n"
},
{
"answer_id": 587826,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": ">>> from turtle import *\n>>> setup()\n>>> title(\"turtle test\")\n>>> clear()\n>>>\n>>> #DRAW A SQUARE\n>>> down() #pen down\n>>> forward(50) #move forward 50 units\n>>> right(90) #turn right 90 degrees\n>>> forward(50)\n>>> right(90)\n>>> forward(50)\n>>> right(90)\n>>> forward(50)\n>>>\n>>> #INTRODUCE ITERATION TO SIMPLIFY SQUARE CODE\n>>> clear()\n>>> for i in range(4):\n forward(50)\n right(90)\n>>>\n>>> #INTRODUCE PROCEDURES \n>>> def square(length):\n down()\n for i in range(4):\n forward(length)\n right(90)\n>>>\n>>> #HAVE STUDENTS PREDICT WHAT THIS WILL DRAW\n>>> for i in range(50):\n up()\n left(90)\n forward(25)\n square(i)\n>>>\n>>> #NOW HAVE THE STUDENTS WRITE CODE TO DRAW\n>>> #A SQUARE 'TUNNEL' (I.E. CONCENTRIC SQUARES\n>>> #GETTING SMALLER AND SMALLER).\n>>>\n>>> #AFTER THAT, MAKE THE TUNNEL ROTATE BY HAVING\n>>> #EACH SUCCESSIVE SQUARE TILTED\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92/"
] |
3,106 | <p>I'm developing some cross platform software targeting Mono under Visual Studio and would like to be able to build the installers for Windows and Linux (Ubuntu specifically) with a single button click. I figure I could do it by calling cygwin from a post-build event, but I was hoping for at best a Visual Studio plugin or at worst a more Windows-native way of doing it. It seems like the package format is fairly simple and this must be a common need.</p>
<p>edit: Re-asked question under other account due to duplicate login issue.</p>
| [
{
"answer_id": 74257,
"author": "apenwarr",
"author_id": 42219,
"author_profile": "https://Stackoverflow.com/users/42219",
"pm_score": 3,
"selected": false,
"text": "$ ar xv asciidoc_8.2.1-2_all.deb \nx - debian-binary\nx - control.tar.gz\nx - data.tar.gz\n\n$ tar -tzf control.tar.gz \n./\n./conffiles\n./md5sums\n./control\n"
},
{
"answer_id": 52202616,
"author": "Frederik Carlier",
"author_id": 4463242,
"author_profile": "https://Stackoverflow.com/users/4463242",
"pm_score": 3,
"selected": false,
"text": "dotnet deb -c Release -f netcoreapp2.1 -r ubuntu.16.04-x64 .deb"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
3,112 | <p>I have a perl variable <code>$results</code> that gets returned from a service. The value is supposed to be an array, and <code>$results</code> should be an array reference. However, when the array has only one item in it, <code>$results</code> will be set to that value, and not a referenced array that contains that one item.</p>
<p>I want to do a <code>foreach</code> loop on the expected array. Without checking <code>ref($results) eq 'ARRAY'</code>, is there any way to have something equivalent to the following:</p>
<pre><code>foreach my $result (@$results) {
# Process $result
}
</code></pre>
<p>That particular code sample will work for the reference, but will complain for the simple scalar.</p>
<p>EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value.</p>
| [
{
"answer_id": 3126,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": -1,
"selected": false,
"text": "#!/usr/bin/perl -w\nuse strict;\n\nsub testit {\n\n my @ret = ();\n if (shift){\n push @ret,1;\n push @ret,2;\n push @ret,3;\n}else{\n push @ret,\"oneonly\";\n}\n\nreturn \\@ret;\n}\n\nforeach my $r (@{testit(1)}){\n print $r.\" test1\\n\";\n}\nforeach my $r (@{testit()}){\n print $r.\" test2\\n\";\n}\n"
},
{
"answer_id": 3134,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 6,
"selected": true,
"text": "$result = [ $result ] if ref($result) ne 'ARRAY'; \nforeach .....\n"
},
{
"answer_id": 11722,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "if( ref $results eq 'ARRAY' ){\n my_sub($result) for my $result (@$results);\n}else{\n my_sub($results);\n}\n"
},
{
"answer_id": 16243,
"author": "user1917",
"author_id": 1917,
"author_profile": "https://Stackoverflow.com/users/1917",
"pm_score": 4,
"selected": false,
"text": "sub call_to_service\n{\n my $returnValue = service::call();\n\n if (ref($returnValue) eq \"ARRAY\")\n {\n return($returnValue);\n }\n else\n {\n return( [$returnValue] );\n }\n}\n foreach my $item (@{call_to_service()})\n{\n ...\n}\n"
},
{
"answer_id": 196099,
"author": "draegtun",
"author_id": 12195,
"author_profile": "https://Stackoverflow.com/users/12195",
"pm_score": 2,
"selected": false,
"text": "for my $result ( ref $results eq 'ARRAY' ? @$results : $results ) {\n # Process result\n}\n for my $result ( ! ref $results ? $results : @$results ) {\n # Process result\n}\n for my $result ( eval { @$results }, eval $results ) {\n # Process result\n}\n for my $result ( eval { $results->[0] } || $results, eval { @$results[1 .. $#{ $results }] } ) {\n # Process result\n}\n"
},
{
"answer_id": 40756797,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "my @some_array\npush (@some_array, results);\nforeach my $elt(@some_array){\n #do something\n}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219/"
] |
3,136 | <p>How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs?</p>
<p>Right now my crontab looks something like this</p>
<pre><code>@daily /path/to/script.sh
</code></pre>
| [
{
"answer_id": 3139,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": true,
"text": "59 23 * * * /usr/sbin/myscript > /dev/null\n"
},
{
"answer_id": 3145,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 3,
"selected": false,
"text": "... 2>&1 ....\n"
},
{
"answer_id": 7080,
"author": "Dominic Cooney",
"author_id": 878,
"author_profile": "https://Stackoverflow.com/users/878",
"pm_score": 3,
"selected": false,
"text": "59 23 * * * /usr/sbin/myscript > /dev/null 2>&1\n 59 23 * * * /usr/sbin/myscript 2>&1 > /dev/null\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87/"
] |
3,143 | <p>I'm compiling a NAnt project on linux with TeamCity Continuous Integration server. I have been able to generate a test report by running NAnt on mono thru a Command Line Runner but don't have the options of using the report like a NAnt Runner. I'm also using MBUnit for the testing framework.</p>
<p>How can I merge in the test report and display "Tests failed: 1 (1 new), passed: 3049" for the build?</p>
<p><strong>Update:</strong> take a look at MBUnitTask its a NAnt task that uses sends messages that TeamCity expects from NUnit so it lets you use all of TeamCity's features for tests.</p>
<p><a href="http://code.google.com/p/nant-extensions/wiki/MbUnitTask" rel="noreferrer">MBUnitTask</a></p>
<p><strong>Update:</strong> Galio has better support so you just have to reference the Galio MBUnit 3.5 dlls instead of the MBUnit 3.5 dlls and switch to the galio runner to make it work.</p>
| [
{
"answer_id": 4144,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 2,
"selected": false,
"text": "##teamcity[testSuiteStarted name='Test1']\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n <xsl:template match=\"/\">\n\n <xsl:apply-templates/>\n\n </xsl:template>\n\n <xsl:template match=\"assemblies/assembly\">\n##teamcity[testSuiteStarted name='<xsl:value-of select=\"@name\" />']\n\n <xsl:apply-templates select=\"//run\" />\n\n##teamcity[testSuiteFinished name='<xsl:value-of select=\"@name\" />']\n </xsl:template>\n\n <xsl:template match=\"run\">\n\n <xsl:choose>\n <xsl:when test=\"@result='ignore' or @result='skip'\">\n ##teamcity[testIgnored name='<xsl:value-of select=\"@name\" />' message='Test Ignored']\n </xsl:when>\n <xsl:otherwise>\n ##teamcity[testStarted name='<xsl:value-of select=\"@name\" />']\n </xsl:otherwise>\n </xsl:choose>\n\n\n <xsl:if test=\"@result='failure'\">\n ##teamcity[testFailed name='<xsl:value-of select=\"@name\" />' message='<xsl:value-of select=\"child::node()/message\"/>' details='<xsl:value-of select=\"normalize-space(child::node()/stack-trace)\"/>']\n </xsl:if>\n\n\n <xsl:if test=\"@result!='ignore' and @result!='skip'\">\n ##teamcity[testFinished name='<xsl:value-of select=\"@name\" />']\n </xsl:if>\n\n </xsl:template>\n\n</xsl:stylesheet>\n"
},
{
"answer_id": 30235,
"author": "Scott Cowan",
"author_id": 253,
"author_profile": "https://Stackoverflow.com/users/253",
"pm_score": 2,
"selected": false,
"text": "/rt:Xml /rt:Html /rnf:mbunit /rf:..\\reports\n build\\reports\\* => Reports\n <report-tab title=\"Tests\" basePath=\"Reports\" startPage=\"mbunit.html\" />\n <style style=\"includes\\teamcity-info.xsl\" in=\"reports\\mbunit.xml\" out=\"..\\teamcity-info.xml\" />\n <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n\n<xsl:stylesheet version=\"1.0\"\nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n<xsl:param name=\"cbl\" select=\"'{'\"/>\n<xsl:param name=\"cbr\" select=\"'}'\"/>\n<xsl:template match=\"/\">\n<xsl:for-each select=\"report-result/counter\">\n\n<build number=\"1.0.{concat($cbl,'build.number',$cbr)}\">\n <xsl:if test=\"@failure-count > 0\">\n <statusInfo status=\"FAILURE\"> \n <text action=\"append\"> Tests failed: <xsl:value-of select=\"@failure-count\"/>, passed: <xsl:value-of select=\"@success-count\"/></text>\n </statusInfo>\n </xsl:if>\n <xsl:if test=\"@failure-count = 0\">\n <statusInfo status=\"SUCCESS\">\n <text action=\"append\"> Tests passed: <xsl:value-of select=\"@success-count\"/></text>\n </statusInfo>\n </xsl:if>\n\n</build>\n</xsl:for-each>\n\n</xsl:template>\n</xsl:stylesheet>\n <build number=\"1.0.{build.number}\">\n <statusInfo status=\"FAILURE\">\n <text action=\"append\">Tests failed: 16, passed: 88</text>\n </statusInfo>\n</build>\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253/"
] |
3,147 | <p>I have seen these being used every which way, and have been accused of using them the wrong way (though in that case, I was using them that way to demonstrate a <a href="http://blog.gadodia.net/extension-methods-in-vbnet-and-c/" rel="noreferrer">point</a>).</p>
<p>So, what do you think are the best practices for employing Extension Methods?</p>
<p>Should development teams create a library of extension methods and deploy them across various projects?</p>
<p>Should there be a collection of common extension methods in the form of an open source project?</p>
<p><em>Update: have decided to create an organization wide extension methods library</em></p>
| [
{
"answer_id": 3155,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 2,
"selected": false,
"text": "Core.Extensions.Base64Encode(str);\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] |
3,150 | <p>I'm having trouble figuring out how to get the testing framework set up and usable in <strong>Visual Studio 2008</strong> for <code>C++</code> presumably with the built-in unit testing suite.</p>
<p>Any links or tutorials would be appreciated.</p>
| [
{
"answer_id": 16548,
"author": "Lehane",
"author_id": 142,
"author_profile": "https://Stackoverflow.com/users/142",
"pm_score": 1,
"selected": false,
"text": "#include <cppunit/extensions/HelperMacros.h>"
},
{
"answer_id": 1829212,
"author": "aracntido",
"author_id": 191417,
"author_profile": "https://Stackoverflow.com/users/191417",
"pm_score": 3,
"selected": false,
"text": "// Example\n#include \"stdafx.h\"\n#include \"mstest.h\"\n\n// Following code is native code.\n#pragma unmanaged\nvoid AddTwoNumbersTest() {\n // Arrange\n Adder yourNativeObject;\n int expected = 3;\n int actual;\n // Act\n actual = yourNativeObject.Add(1, 2);\n // Assert\n Assert::AreEqual(expected, actual, L\"1 + 2 != 3\");\n}\n\n// Following code is C++/CLI (Managed)\n#pragma managed\nusing namespace Microsoft::VisualStudio::TestTools::UnitTesting;\n[TestClass]\npublic ref class TestShim {\npublic:\n [TestMethod]\n void AddTwoNumbersTest() {\n // Just jump to C++ native code (above)\n ::AddTwoNumbersTest();\n }\n};\n // Example\n#pragma once\n#pragma managed(push, on)\nusing namespace System;\nclass Assert {\npublic:\n static void AreEqual(int expected, int actual) {\n Microsoft::VisualStudio::TestTools::UnitTesting::Assert::AreEqual(expected, actual);\n }\n\n static void AreEqual(int expected, int actual, PCWSTR pszMessage) {\n Microsoft::VisualStudio::TestTools::UnitTesting::Assert::AreEqual(expected, actual, gcnew String(pszMe\nssage));\n }\n\n template<typename T>\n static void AreEqual(T expected, T actual) {\n Microsoft::VisualStudio::TestTools::UnitTesting::Assert::AreEqual(expected, actual);\n }\n\n // Etcetera, other overloads...\n}\n#pragma managed(pop)\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370/"
] |
3,157 | <p>In an application that heavily relies on <code>.htaccess</code> RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? That is:</p>
<pre><code>/appRoot/.htaccess
app/
static/
</code></pre>
<p>By default every request to <code>/appRoot/*</code> is being rewritten to be picked up by <code>app/webroot/index.php</code>, where it's being analysed and corresponding controller actions are being invoked. This is done by these directives in <code>.htaccess</code>:</p>
<pre><code>RewriteBase /appRoot
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
</code></pre>
<p>I now want to exclude a few directories like static/ from this rewriting. I tried with this <em>before</em> the Cake RewriteRules:</p>
<pre><code>RewriteCond $1 ^(static|otherDir).*$ [NC]
RewriteRule (.*) - [L]
</code></pre>
<p>It works in so far that requests are no longer rewritten, but now <strong>all</strong> requests are being skipped, even legitimate Cake requests which should not match <code>^(static|otherDir).*$</code>.</p>
<p>I tried several variations of these rules but can't get it to work the way I want.</p>
| [
{
"answer_id": 3159,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 1,
"selected": false,
"text": "RewriteBase /appRoot\n\nRewriteRule ^$ app/webroot/ \nRewriteRule (.*) app/webroot/$1\n"
},
{
"answer_id": 3161,
"author": "Lauren",
"author_id": 265,
"author_profile": "https://Stackoverflow.com/users/265",
"pm_score": 1,
"selected": false,
"text": "RewriteCond $1 !^(static|otherDir).*$ [NC]\nRewriteRule ^$ app/webroot/ [L]\n\nRewriteCond $1 !^(static|otherDir).*$ [NC]\nRewriteRule ^$ app/webroot/$1 [L]\n"
},
{
"answer_id": 4449,
"author": "deceze",
"author_id": 476,
"author_profile": "https://Stackoverflow.com/users/476",
"pm_score": 4,
"selected": true,
"text": "RewriteRule ^(a|bunch|of|old|directories).* - [NC,L]\n\n# all other requests will be forwarded to Cake\nRewriteRule ^$ app/webroot/ [L]\nRewriteRule (.*) app/webroot/$1 [L]\n /appRoot/app/views/pages/home.ctp\n RewriteCond $1 !^(a|bunch|of|old|directories).*$ [NC]\nRewriteRule ^(.*)$ app/webroot/$1 [L]\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/476/"
] |
3,163 | <p>I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings.</p>
<p>Does anyone know any faster ways of doing this or tips to speed up the methods?</p>
<pre><code>castMethod1 takes 3673 ms
castMethod2 takes 3812 ms
castMethod3 takes 3931 ms
</code></pre>
<p>Code:</p>
<pre><code>private function castMethod1(dateString:String):Date {
if ( dateString == null ) {
return null;
}
var year:int = int(dateString.substr(0,4));
var month:int = int(dateString.substr(5,2))-1;
var day:int = int(dateString.substr(8,2));
if ( year == 0 && month == 0 && day == 0 ) {
return null;
}
if ( dateString.length == 10 ) {
return new Date(year, month, day);
}
var hour:int = int(dateString.substr(11,2));
var minute:int = int(dateString.substr(14,2));
var second:int = int(dateString.substr(17,2));
return new Date(year, month, day, hour, minute, second);
}
</code></pre>
<p>-</p>
<pre><code>private function castMethod2(dateString:String):Date {
if ( dateString == null ) {
return null;
}
if ( dateString.indexOf("0000-00-00") != -1 ) {
return null;
}
dateString = dateString.split("-").join("/");
return new Date(Date.parse( dateString ));
}
</code></pre>
<p>-</p>
<pre><code>private function castMethod3(dateString:String):Date {
if ( dateString == null ) {
return null;
}
var mainParts:Array = dateString.split(" ");
var dateParts:Array = mainParts[0].split("-");
if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) {
return null;
}
return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) );
}
</code></pre>
<hr>
<p>No, Date.parse will not handle dashes by default. And I need to return null for date time strings like <code>"0000-00-00"</code>.</p>
| [
{
"answer_id": 3194,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 1,
"selected": false,
"text": "private function castMethod2(dateString:String):Date {\n if ( dateString == null ) {\n return null;\n }\n\n if ( dateString.indexOf(\"0000-00-00\") != -1 ) {\n return null;\n }\n\n dateString = dateString.split(\"-\").join(\"/\");\n\n return new Date(Date.parse( dateString ));\n}\n"
},
{
"answer_id": 9904,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 3,
"selected": false,
"text": "private function castMethod4(dateString:String):Date { \n if ( dateString == null ) \n return null; \n if ( dateString.length != 10 && dateString.length != 19) \n return null;\n\n dateString = dateString.replace(\"-\", \"/\");\n dateString = dateString.replace(\"-\", \"/\");\n\n return new Date(Date.parse( dateString ));\n}\n"
},
{
"answer_id": 10030,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 5,
"selected": true,
"text": "private function parseUTCDate( str : String ) : Date {\n var matches : Array = str.match(/(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d)Z/);\n\n var d : Date = new Date();\n\n d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3]));\n d.setUTCHours(int(matches[4]), int(matches[5]), int(matches[6]), 0);\n\n return d;\n}\n private function parseDate( str : String ) : Date {\n var matches : Array = str.match(/(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)/);\n\n var d : Date = new Date();\n\n d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3]));\n\n return d;\n}\n"
},
{
"answer_id": 3016172,
"author": "JabbyPanda",
"author_id": 193063,
"author_profile": "https://Stackoverflow.com/users/193063",
"pm_score": 1,
"selected": false,
"text": "// English formatter\nvar stringValue = \"2010.10.06\"\nvar dateCommonFormatter : DateFormatter = new DateFormatter();\ndateCommonFormatter.formatString = \"YYYY/MM/DD\";\n\nvar formattedStringValue : String = dateCommonFormatter.format(stringValue); \nvar dateFromString : Date = new Date(Date.parse(formattedStringValue));\n"
},
{
"answer_id": 6972550,
"author": "Abhinav Mehta",
"author_id": 882693,
"author_profile": "https://Stackoverflow.com/users/882693",
"pm_score": 0,
"selected": false,
"text": "public static function dateToUtcTime(date:Date):String {\n var tmp:Array = new Array();\n var char:String;\n var output:String = '';\n\n // create format YYMMDDhhmmssZ\n // ensure 2 digits are used for each format entry, so 0x00 suffuxed at each byte\n\n tmp.push(date.secondsUTC);\n tmp.push(date.minutesUTC);\n tmp.push(date.hoursUTC);\n tmp.push(date.getUTCDate());\n tmp.push(date.getUTCMonth() + 1); // months 0-11\n tmp.push(date.getUTCFullYear() % 100);\n\n\n for(var i:int=0; i < 6/* 7 items pushed*/; ++i) {\n char = String(tmp.pop());\n trace(\"char: \" + char);\n if(char.length < 2)\n output += \"0\";\n output += char;\n }\n\n output += 'Z';\n\n return output;\n}\n"
},
{
"answer_id": 20170012,
"author": "Romeo",
"author_id": 3026302,
"author_profile": "https://Stackoverflow.com/users/3026302",
"pm_score": 1,
"selected": false,
"text": "var strDate:String = \"2013-01-24 01:02:40\";\n\nfunction dateParser(s:String):Date{\n var regexp:RegExp = /(\\d{4})\\-(\\d{1,2})\\-(\\d{1,2}) (\\d{2})\\:(\\d{2})\\:(\\d{2})/;\n var _result:Object = regexp.exec(s);\n\n return new Date(\n parseInt(_result[1]),\n parseInt(_result[2])-1,\n parseInt(_result[3]),\n parseInt(_result[4]),\n parseInt(_result[5]),\n parseInt(_result[6])\n );\n}\n\nvar myDate:Date = dateParser(strDate);\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22/"
] |
3,164 | <p>If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the <strong>fastest</strong> way to convert that absolute path back into a relative web path?</p>
| [
{
"answer_id": 3218,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 7,
"selected": true,
"text": "String RelativePath = AbsolutePath.Replace(Request.ServerVariables[\"APPL_PHYSICAL_PATH\"], String.Empty);\n"
},
{
"answer_id": 5222928,
"author": "Canoas",
"author_id": 358580,
"author_profile": "https://Stackoverflow.com/users/358580",
"pm_score": 5,
"selected": false,
"text": "public static class ExtensionMethods\n{\n public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)\n {\n return path.Replace(context.ServerVariables[\"APPL_PHYSICAL_PATH\"], \"~/\").Replace(@\"\\\", \"/\");\n }\n}\n Server.RelativePath(path, Request);\n"
},
{
"answer_id": 10462610,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 4,
"selected": false,
"text": "static string RelativeFromAbsolutePath(string path)\n{\n if(HttpContext.Current != null)\n {\n var request = HttpContext.Current.Request;\n var applicationPath = request.PhysicalApplicationPath;\n var virtualDir = request.ApplicationPath;\n virtualDir = virtualDir == \"/\" ? virtualDir : (virtualDir + \"/\");\n return path.Replace(applicationPath, virtualDir).Replace(@\"\\\", \"/\");\n }\n\n throw new InvalidOperationException(\"We can only map an absolute back to a relative path if an HttpContext is available.\");\n}\n"
},
{
"answer_id": 31021328,
"author": "Pierre Chavaroche",
"author_id": 1928513,
"author_profile": "https://Stackoverflow.com/users/1928513",
"pm_score": 3,
"selected": false,
"text": "public static string RelativePath(this HttpServerUtility srv, string path)\n{\n return path.Replace(HttpContext.Current.Server.MapPath(\"~/\"), \"~/\").Replace(@\"\\\", \"/\");\n}\n"
},
{
"answer_id": 53850472,
"author": "Lapenkov Vladimir",
"author_id": 4404269,
"author_profile": "https://Stackoverflow.com/users/4404269",
"pm_score": 0,
"selected": false,
"text": "public class FilePathHelper\n{\n private readonly IHostingEnvironment _env;\n public FilePathHelper(IHostingEnvironment env)\n {\n _env = env;\n }\n public string GetVirtualPath(string physicalPath)\n {\n if (physicalPath == null) throw new ArgumentException(\"physicalPath is null\");\n if (!File.Exists(physicalPath)) throw new FileNotFoundException(physicalPath + \" doesn't exists\");\n var lastWord = _env.WebRootPath.Split(\"\\\\\").Last();\n int relativePathIndex = physicalPath.IndexOf(lastWord) + lastWord.Length;\n var relativePath = physicalPath.Substring(relativePathIndex);\n return $\"/{ relativePath.TrimStart('\\\\').Replace('\\\\', '/')}\";\n }\n public string GetPhysicalPath(string relativepath)\n {\n if (relativepath == null) throw new ArgumentException(\"relativepath is null\");\n var fileInfo = _env.WebRootFileProvider.GetFileInfo(relativepath);\n if (fileInfo.Exists) return fileInfo.PhysicalPath;\n else throw new FileNotFoundException(\"file doesn't exists\");\n }\n var physicalPath = _fp.GetPhysicalPath(\"/img/banners/abro.png\");\n var virtualPath = _fp.GetVirtualPath(physicalPath);\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
3,196 | <p>If I have data like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Key</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Dan</td>
</tr>
<tr>
<td>2</td>
<td>Tom</td>
</tr>
<tr>
<td>3</td>
<td>Jon</td>
</tr>
<tr>
<td>4</td>
<td>Tom</td>
</tr>
<tr>
<td>5</td>
<td>Sam</td>
</tr>
<tr>
<td>6</td>
<td>Dan</td>
</tr>
</tbody>
</table>
</div>
<p>What is the SQL query to bring back the records where <code>Name</code> is repeated 2 or more times?</p>
<p>So the result I would want is</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Tom</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dan</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 3197,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 6,
"selected": true,
"text": "Select Name, Count(Name) As Count \n From Table\n Group By Name\n Having Count(Name) > 1\n Order By Count(Name) Desc\n Delete From Table\nWhere Key In (\n Select Max(Key)\n From Table\n Group By Name\n Having Count(Name) > 1\n )\n"
},
{
"answer_id": 6986,
"author": "Dag Haavi Finstad",
"author_id": 687,
"author_profile": "https://Stackoverflow.com/users/687",
"pm_score": 2,
"selected": false,
"text": "SELECT DISTINCT t1.name\nFROM tbl t1\n INNER JOIN tbl t2\n ON t1.name = t2.name\nWHERE t1.key != t2.key;\n"
},
{
"answer_id": 13512,
"author": "Ryan",
"author_id": 1545,
"author_profile": "https://Stackoverflow.com/users/1545",
"pm_score": 2,
"selected": false,
"text": "select name from table group by name having count(name) > 1\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
3,213 | <p>Is there an efficient method of converting an integer into the written numbers, for example:</p>
<pre><code>string Written = IntegerToWritten(21);
</code></pre>
<p>would return "Twenty One".</p>
<p>Is there any way of doing this that doesn't involve a massive look-up table?</p>
| [
{
"answer_id": 3215,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 2,
"selected": false,
"text": "string GetWrittenInteger(int n)\n{\n string[] a = new string[] {\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\" }\n string[] b = new string[] { \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\" }\n string[] c = new string[] {\"Twenty\", \"Thirty\", \"Forty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"};\n string[] d = new string[] {\"Hundred\", \"Thousand\", \"Million\"}\n string s = n.ToString();\n\n for (int i = 0; i < s.Length; i++)\n {\n // logic (too lazy but you get the idea)\n }\n}\n"
},
{
"answer_id": 3228,
"author": "Nick Masao",
"author_id": 487,
"author_profile": "https://Stackoverflow.com/users/487",
"pm_score": 3,
"selected": false,
"text": "Function NumberToText(ByVal n As Integer) As String\n\n Select Case n\nCase 0\n Return \"\"\n\nCase 1 To 19\n Dim arr() As String = {\"One\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\", _\n \"Eight\",\"Nine\",\"Ten\",\"Eleven\",\"Twelve\",\"Thirteen\",\"Fourteen\", _\n \"Fifteen\",\"Sixteen\",\"Seventeen\",\"Eighteen\",\"Nineteen\"}\n Return arr(n-1) & \" \"\n\nCase 20 to 99\n Dim arr() as String = {\"Twenty\",\"Thirty\",\"Forty\",\"Fifty\",\"Sixty\",\"Seventy\",\"Eighty\",\"Ninety\"}\n Return arr(n\\10 -2) & \" \" & NumberToText(n Mod 10)\n\nCase 100 to 199\n Return \"One Hundred \" & NumberToText(n Mod 100)\n\nCase 200 to 999\n Return NumberToText(n\\100) & \"Hundreds \" & NumberToText(n mod 100)\n\nCase 1000 to 1999\n Return \"One Thousand \" & NumberToText(n Mod 1000)\n\nCase 2000 to 999999\n Return NumberToText(n\\1000) & \"Thousands \" & NumberToText(n Mod 1000)\n\nCase 1000000 to 1999999\n Return \"One Million \" & NumberToText(n Mod 1000000)\n\nCase 1000000 to 999999999\n Return NumberToText(n\\1000000) & \"Millions \" & NumberToText(n Mod 1000000)\n\nCase 1000000000 to 1999999999\n Return \"One Billion \" & NumberTotext(n Mod 1000000000)\n\nCase Else\n Return NumberToText(n\\1000000000) & \"Billion \" _\n & NumberToText(n mod 1000000000)\nEnd Select\nEnd Function\n public static string AmountInWords(double amount)\n{\n var n = (int)amount;\n\n if (n == 0)\n return \"\";\n else if (n > 0 && n <= 19)\n {\n var arr = new string[] { \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\" };\n return arr[n - 1] + \" \";\n }\n else if (n >= 20 && n <= 99)\n {\n var arr = new string[] { \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\" };\n return arr[n / 10 - 2] + \" \" + AmountInWords(n % 10);\n }\n else if (n >= 100 && n <= 199)\n {\n return \"One Hundred \" + AmountInWords(n % 100);\n }\n else if (n >= 200 && n <= 999)\n {\n return AmountInWords(n / 100) + \"Hundred \" + AmountInWords(n % 100);\n }\n else if (n >= 1000 && n <= 1999)\n {\n return \"One Thousand \" + AmountInWords(n % 1000);\n }\n else if (n >= 2000 && n <= 999999)\n {\n return AmountInWords(n / 1000) + \"Thousand \" + AmountInWords(n % 1000);\n }\n else if (n >= 1000000 && n <= 1999999)\n {\n return \"One Million \" + AmountInWords(n % 1000000);\n }\n else if (n >= 1000000 && n <= 999999999)\n {\n return AmountInWords(n / 1000000) + \"Million \" + AmountInWords(n % 1000000);\n }\n else if (n >= 1000000000 && n <= 1999999999)\n {\n return \"One Billion \" + AmountInWords(n % 1000000000);\n }\n else\n {\n return AmountInWords(n / 1000000000) + \"Billion \" + AmountInWords(n % 1000000000);\n }\n }\n"
},
{
"answer_id": 3267,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 7,
"selected": true,
"text": "public static class HumanFriendlyInteger\n{\n static string[] ones = new string[] { \"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\" };\n static string[] teens = new string[] { \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\" };\n static string[] tens = new string[] { \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\" };\n static string[] thousandsGroups = { \"\", \" Thousand\", \" Million\", \" Billion\" };\n\n private static string FriendlyInteger(int n, string leftDigits, int thousands)\n {\n if (n == 0)\n {\n return leftDigits;\n }\n\n string friendlyInt = leftDigits;\n\n if (friendlyInt.Length > 0)\n {\n friendlyInt += \" \";\n }\n\n if (n < 10)\n {\n friendlyInt += ones[n];\n }\n else if (n < 20)\n {\n friendlyInt += teens[n - 10];\n }\n else if (n < 100)\n {\n friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);\n }\n else if (n < 1000)\n {\n friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + \" Hundred\"), 0);\n }\n else\n {\n friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, \"\", thousands+1), 0);\n if (n % 1000 == 0)\n {\n return friendlyInt;\n }\n }\n\n return friendlyInt + thousandsGroups[thousands];\n }\n\n public static string IntegerToWritten(int n)\n {\n if (n == 0)\n {\n return \"Zero\";\n }\n else if (n < 0)\n {\n return \"Negative \" + IntegerToWritten(-n);\n }\n\n return FriendlyInteger(n, \"\", 0);\n }\n}\n"
},
{
"answer_id": 8377509,
"author": "Karthik",
"author_id": 1080359,
"author_profile": "https://Stackoverflow.com/users/1080359",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \n\nnamespace tryingstartfror4digits \n{ \n class Program \n { \n static void Main(string[] args)\n {\n Program pg = new Program();\n Console.WriteLine(\"Enter ur number\");\n int num = Convert.ToInt32(Console.ReadLine());\n\n if (num <= 19)\n {\n string g = pg.first(num);\n Console.WriteLine(\"The number is \" + g);\n }\n else if ((num >= 20) && (num <= 99))\n {\n if (num % 10 == 0)\n {\n string g = pg.second(num / 10);\n Console.WriteLine(\"The number is \" + g);\n }\n else\n {\n string g = pg.second(num / 10) + pg.first(num % 10);\n Console.WriteLine(\"The number is \" + g);\n }\n }\n else if ((num >= 100) && (num <= 999))\n {\n int k = num % 100;\n string g = pg.first(num / 100) +pg.third(0) + pg.second(k / 10)+pg.first(k%10);\n Console.WriteLine(\"The number is \" + g);\n }\n else if ((num >= 1000) && (num <= 19999))\n {\n int h = num % 1000;\n int k = h % 100;\n string g = pg.first(num / 1000) + \"Thousand \" + pg.first(h/ 100) + pg.third(k) + pg.second(k / 10) + pg.first(k % 10);\n Console.WriteLine(\"The number is \" + g);\n }\n\n Console.ReadLine();\n }\n\n public string first(int num)\n {\n string name;\n\n if (num == 0)\n {\n name = \" \";\n }\n else\n {\n string[] arr1 = new string[] { \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\" , \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"};\n name = arr1[num - 1];\n }\n\n return name;\n }\n\n public string second(int num)\n {\n string name;\n\n if ((num == 0)||(num==1))\n {\n name = \" \";\n }\n else\n {\n string[] arr1 = new string[] { \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\" };\n name = arr1[num - 2];\n }\n\n return name;\n }\n\n public string third(int num)\n {\n string name ;\n\n if (num == 0)\n {\n name = \"\";\n }\n else\n {\n string[] arr1 = new string[] { \"Hundred\" };\n name = arr1[0];\n }\n\n return name;\n }\n }\n}\n"
},
{
"answer_id": 27958953,
"author": "Emre Guldogan",
"author_id": 197652,
"author_profile": "https://Stackoverflow.com/users/197652",
"pm_score": 1,
"selected": false,
"text": "public static class HumanFriendlyInteger\n{\n static string[] ones = new string[] { \"\", \"Bir\", \"İki\", \"Üç\", \"Dört\", \"Beş\", \"Altı\", \"Yedi\", \"Sekiz\", \"Dokuz\" };\n static string[] teens = new string[] { \"On\", \"On Bir\", \"On İki\", \"On Üç\", \"On Dört\", \"On Beş\", \"On Altı\", \"On Yedi\", \"On Sekiz\", \"On Dokuz\" };\n static string[] tens = new string[] { \"Yirmi\", \"Otuz\", \"Kırk\", \"Elli\", \"Altmış\", \"Yetmiş\", \"Seksen\", \"Doksan\" };\n static string[] thousandsGroups = { \"\", \" Bin\", \" Milyon\", \" Milyar\" };\n\n private static string FriendlyInteger(int n, string leftDigits, int thousands)\n {\n if (n == 0)\n {\n return leftDigits;\n }\n\n string friendlyInt = leftDigits;\n\n if (friendlyInt.Length > 0)\n {\n friendlyInt += \" \";\n }\n\n if (n < 10)\n friendlyInt += ones[n];\n else if (n < 20)\n friendlyInt += teens[n - 10];\n else if (n < 100)\n friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);\n else if (n < 1000)\n friendlyInt += FriendlyInteger(n % 100, ((n / 100 == 1 ? \"\" : ones[n / 100] + \" \") + \"Yüz\"), 0); // Yüz 1 ile başlangıçta \"Bir\" kelimesini Türkçe'de almaz.\n else\n friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, \"\", thousands + 1), 0);\n\n return friendlyInt + thousandsGroups[thousands];\n }\n\n public static string IntegerToWritten(int n)\n {\n if (n == 0)\n return \"Sıfır\";\n else if (n < 0)\n return \"Eksi \" + IntegerToWritten(-n);\n\n return FriendlyInteger(n, \"\", 0);\n }\n"
},
{
"answer_id": 30468102,
"author": "CleverPatrick",
"author_id": 22399,
"author_profile": "https://Stackoverflow.com/users/22399",
"pm_score": 2,
"selected": false,
"text": "for (int i = int.MinValue+1; i < int.MaxValue; i++)\n{\n Console.WriteLine(ToWords(i));\n}\n private static readonly string[] Ones = {\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\"};\n\nprivate static readonly string[] Teens =\n{\n \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\",\n \"Seventeen\", \"Eighteen\", \"Nineteen\"\n};\n\nprivate static readonly string[] Tens =\n{\n \"\", \"\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\",\n \"Ninety\"\n};\n\npublic static string ToWords(int number)\n{\n if (number == 0)\n return \"Zero\";\n\n var wordsList = new List<string>();\n\n if (number < 0)\n {\n wordsList.Add(\"Negative\");\n number = Math.Abs(number);\n }\n\n if (number >= 1000000000 && number <= int.MaxValue) //billions\n {\n int billionsValue = number / 1000000000;\n GetValuesUnder1000(billionsValue, wordsList);\n wordsList.Add(\"Billion\");\n number -= billionsValue * 1000000000;\n\n if (number > 0 && number < 10)\n wordsList.Add(\"and\");\n }\n\n if (number >= 1000000 && number < 1000000000) //millions\n {\n int millionsValue = number / 1000000;\n GetValuesUnder1000(millionsValue, wordsList);\n wordsList.Add(\"Million\");\n number -= millionsValue * 1000000;\n\n if (number > 0 && number < 10)\n wordsList.Add(\"and\");\n }\n\n if (number >= 1000 && number < 1000000) //thousands\n {\n int thousandsValue = number/1000;\n GetValuesUnder1000(thousandsValue, wordsList);\n wordsList.Add(\"Thousand\");\n number -= thousandsValue * 1000;\n\n if (number > 0 && number < 10)\n wordsList.Add(\"and\");\n }\n\n GetValuesUnder1000(number, wordsList);\n\n return string.Join(\" \", wordsList);\n}\n\nprivate static void GetValuesUnder1000(int number, List<string> wordsList)\n{\n while (number != 0)\n {\n if (number < 10)\n {\n wordsList.Add(Ones[number]);\n number -= number;\n }\n else if (number < 20)\n {\n wordsList.Add(Teens[number - 10]);\n number -= number;\n }\n else if (number < 100)\n {\n int tensValue = ((int) (number/10))*10;\n int onesValue = number - tensValue;\n\n if (onesValue == 0)\n {\n wordsList.Add(Tens[tensValue/10]);\n }\n else\n {\n wordsList.Add(Tens[tensValue/10] + \"-\" + Ones[onesValue]);\n }\n\n number -= tensValue;\n number -= onesValue;\n }\n else if (number < 1000)\n {\n int hundredsValue = ((int) (number/100))*100;\n wordsList.Add(Ones[hundredsValue/100]);\n wordsList.Add(\"Hundred\");\n number -= hundredsValue;\n\n if (number > 0)\n wordsList.Add(\"and\");\n }\n }\n}\n"
},
{
"answer_id": 31827074,
"author": "Dhiraj D B",
"author_id": 3877940,
"author_profile": "https://Stackoverflow.com/users/3877940",
"pm_score": 1,
"selected": false,
"text": "string s = txtNumber.Text.Tostring();\nint i = Convert.ToInt32(s.Tostring());\n"
},
{
"answer_id": 34197484,
"author": "SArifin",
"author_id": 5035041,
"author_profile": "https://Stackoverflow.com/users/5035041",
"pm_score": 1,
"selected": false,
"text": "string number = \"২২৮৯\";\nnumber = number.Replace(\"০\", \"0\").Replace(\"১\", \"1\").Replace(\"২\", \"2\").Replace(\"৩\", \"3\").Replace(\"৪\", \"4\").Replace(\"৫\", \"5\").Replace(\"৬\", \"6\").Replace(\"৭\", \"7\").Replace(\"৮\", \"8\").Replace(\"৯\", \"9\");\ndouble vtempdbl = Convert.ToDouble(number);\nstring amount = AmountInWords(vtempdbl);\n\nprivate static string AmountInWords(double amount)\n {\n var n = (int)amount;\n\n if (n == 0)\n return \" \";\n else if (n > 0 && n <= 99)\n {\n var arr = new string[] { \"এক\", \"দুই\", \"তিন\", \"চার\", \"পাঁচ\", \"ছয়\", \"সাত\", \"আট\", \"নয়\", \"দশ\", \"এগার\", \"বারো\", \"তের\", \"চৌদ্দ\", \"পনের\", \"ষোল\", \"সতের\", \"আঠার\", \"ঊনিশ\", \"বিশ\", \"একুশ\", \"বাইস\", \"তেইশ\", \"চব্বিশ\", \"পঁচিশ\", \"ছাব্বিশ\", \"সাতাশ\", \"আঠাশ\", \"ঊনত্রিশ\", \"ত্রিশ\", \"একত্রিস\", \"বত্রিশ\", \"তেত্রিশ\", \"চৌত্রিশ\", \"পঁয়ত্রিশ\", \"ছত্রিশ\", \"সাঁইত্রিশ\", \"আটত্রিশ\", \"ঊনচল্লিশ\", \"চল্লিশ\", \"একচল্লিশ\", \"বিয়াল্লিশ\", \"তেতাল্লিশ\", \"চুয়াল্লিশ\", \"পয়তাল্লিশ\", \"ছিচল্লিশ\", \"সাতচল্লিশ\", \"আতচল্লিশ\", \"উনপঞ্চাশ\", \"পঞ্চাশ\", \"একান্ন\", \"বায়ান্ন\", \"তিপ্পান্ন\", \"চুয়ান্ন\", \"পঞ্চান্ন\", \"ছাপ্পান্ন\", \"সাতান্ন\", \"আটান্ন\", \"উনষাট\", \"ষাট\", \"একষট্টি\", \"বাষট্টি\", \"তেষট্টি\", \"চৌষট্টি\", \"পয়ষট্টি\", \"ছিষট্টি\", \" সাতষট্টি\", \"আটষট্টি\", \"ঊনসত্তর \", \"সত্তর\", \"একাত্তর \", \"বাহাত্তর\", \"তেহাত্তর\", \"চুয়াত্তর\", \"পঁচাত্তর\", \"ছিয়াত্তর\", \"সাতাত্তর\", \"আটাত্তর\", \"ঊনাশি\", \"আশি\", \"একাশি\", \"বিরাশি\", \"তিরাশি\", \"চুরাশি\", \"পঁচাশি\", \"ছিয়াশি\", \"সাতাশি\", \"আটাশি\", \"উননব্বই\", \"নব্বই\", \"একানব্বই\", \"বিরানব্বই\", \"তিরানব্বই\", \"চুরানব্বই\", \"পঁচানব্বই \", \"ছিয়ানব্বই \", \"সাতানব্বই\", \"আটানব্বই\", \"নিরানব্বই\" };\n return arr[n - 1] + \" \";\n }\n else if (n >= 100 && n <= 199)\n {\n return AmountInWords(n / 100) + \"এক শত \" + AmountInWords(n % 100);\n }\n\n else if (n >= 100 && n <= 999)\n {\n return AmountInWords(n / 100) + \"শত \" + AmountInWords(n % 100);\n }\n else if (n >= 1000 && n <= 1999)\n {\n return \"এক হাজার \" + AmountInWords(n % 1000);\n }\n else if (n >= 1000 && n <= 99999)\n {\n return AmountInWords(n / 1000) + \"হাজার \" + AmountInWords(n % 1000);\n }\n else if (n >= 100000 && n <= 199999)\n {\n return \"এক লাখ \" + AmountInWords(n % 100000);\n }\n else if (n >= 100000 && n <= 9999999)\n {\n return AmountInWords(n / 100000) + \"লাখ \" + AmountInWords(n % 100000);\n }\n else if (n >= 10000000 && n <= 19999999)\n {\n return \"এক কোটি \" + AmountInWords(n % 10000000);\n }\n else\n {\n return AmountInWords(n / 10000000) + \"কোটি \" + AmountInWords(n % 10000000);\n }\n }\n"
},
{
"answer_id": 39917660,
"author": "Mari Faleiros",
"author_id": 6093407,
"author_profile": "https://Stackoverflow.com/users/6093407",
"pm_score": 4,
"selected": false,
"text": "int someNumber = 543;\nvar culture = System.Globalization.CultureInfo(\"en-US\");\nvar result = someNumber.ToWords(culture); // 543 -> five hundred forty-three\n"
},
{
"answer_id": 44401667,
"author": "Santhosh",
"author_id": 6851131,
"author_profile": "https://Stackoverflow.com/users/6851131",
"pm_score": 1,
"selected": false,
"text": " namespace ConsoleApplication2\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text.RegularExpressions;\n class Program\n {\n static void Main(string[] args)\n {\n bool repeat = true;\n while (repeat)\n {\n string inputMonetaryValueInNumberic = string.Empty;\n string centPart = string.Empty;\n string dollarPart = string.Empty;\n Console.Write(\"\\nEnter the monetary value : \");\n inputMonetaryValueInNumberic = Console.ReadLine();\n inputMonetaryValueInNumberic = inputMonetaryValueInNumberic.TrimStart('0');\n\n if (ValidateInput(inputMonetaryValueInNumberic))\n {\n\n if (inputMonetaryValueInNumberic.Contains('.'))\n {\n centPart = ProcessCents(inputMonetaryValueInNumberic.Substring(inputMonetaryValueInNumberic.IndexOf(\".\") + 1));\n dollarPart = ProcessDollar(inputMonetaryValueInNumberic.Substring(0, inputMonetaryValueInNumberic.IndexOf(\".\")));\n }\n else\n {\n dollarPart = ProcessDollar(inputMonetaryValueInNumberic);\n }\n centPart = string.IsNullOrWhiteSpace(centPart) ? string.Empty : \" and \" + centPart;\n Console.WriteLine(string.Format(\"\\n\\n{0}{1}\", dollarPart, centPart));\n }\n else\n {\n Console.WriteLine(\"Invalid Input..\");\n }\n\n Console.WriteLine(\"\\n\\nPress any key to continue or Escape of close : \");\n var loop = Console.ReadKey();\n repeat = !loop.Key.ToString().Contains(\"Escape\");\n Console.Clear();\n }\n\n }\n\n private static string ProcessCents(string cents)\n {\n string english = string.Empty;\n string dig3 = Process3Digit(cents);\n if (!string.IsNullOrWhiteSpace(dig3))\n {\n dig3 = string.Format(\"{0} {1}\", dig3, GetSections(0));\n }\n english = dig3 + english;\n return english;\n }\n private static string ProcessDollar(string dollar)\n {\n string english = string.Empty;\n foreach (var item in Get3DigitList(dollar))\n {\n string dig3 = Process3Digit(item.Value);\n if (!string.IsNullOrWhiteSpace(dig3))\n {\n dig3 = string.Format(\"{0} {1}\", dig3, GetSections(item.Key));\n }\n english = dig3 + english;\n }\n return english;\n }\n private static string Process3Digit(string digit3)\n {\n string result = string.Empty;\n if (Convert.ToInt32(digit3) != 0)\n {\n int place = 0;\n Stack<string> monetaryValue = new Stack<string>();\n for (int i = digit3.Length - 1; i >= 0; i--)\n {\n place += 1;\n string stringValue = string.Empty;\n switch (place)\n {\n case 1:\n stringValue = GetOnes(digit3[i].ToString());\n break;\n case 2:\n int tens = Convert.ToInt32(digit3[i]);\n if (tens == 1)\n {\n if (monetaryValue.Count > 0)\n {\n monetaryValue.Pop();\n }\n stringValue = GetTens((digit3[i].ToString() + digit3[i + 1].ToString()));\n }\n else\n {\n stringValue = GetTens(digit3[i].ToString());\n }\n break;\n case 3:\n stringValue = GetOnes(digit3[i].ToString());\n if (!string.IsNullOrWhiteSpace(stringValue))\n {\n string postFixWith = \" Hundred\";\n if (monetaryValue.Count > 0)\n {\n postFixWith = postFixWith + \" And\";\n }\n stringValue += postFixWith;\n }\n break;\n }\n if (!string.IsNullOrWhiteSpace(stringValue))\n monetaryValue.Push(stringValue);\n }\n while (monetaryValue.Count > 0)\n {\n result += \" \" + monetaryValue.Pop().ToString().Trim();\n }\n }\n return result;\n }\n private static Dictionary<int, string> Get3DigitList(string monetaryValueInNumberic)\n {\n Dictionary<int, string> hundredsStack = new Dictionary<int, string>();\n int counter = 0;\n while (monetaryValueInNumberic.Length >= 3)\n {\n string digit3 = monetaryValueInNumberic.Substring(monetaryValueInNumberic.Length - 3, 3);\n monetaryValueInNumberic = monetaryValueInNumberic.Substring(0, monetaryValueInNumberic.Length - 3);\n hundredsStack.Add(++counter, digit3);\n }\n if (monetaryValueInNumberic.Length != 0)\n hundredsStack.Add(++counter, monetaryValueInNumberic);\n return hundredsStack;\n }\n private static string GetTens(string tensPlaceValue)\n {\n string englishEquvalent = string.Empty;\n int value = Convert.ToInt32(tensPlaceValue);\n Dictionary<int, string> tens = new Dictionary<int, string>();\n tens.Add(2, \"Twenty\");\n tens.Add(3, \"Thirty\");\n tens.Add(4, \"Forty\");\n tens.Add(5, \"Fifty\");\n tens.Add(6, \"Sixty\");\n tens.Add(7, \"Seventy\");\n tens.Add(8, \"Eighty\");\n tens.Add(9, \"Ninty\");\n tens.Add(10, \"Ten\");\n tens.Add(11, \"Eleven\");\n tens.Add(12, \"Twelve\");\n tens.Add(13, \"Thrteen\");\n tens.Add(14, \"Fourteen\");\n tens.Add(15, \"Fifteen\");\n tens.Add(16, \"Sixteen\");\n tens.Add(17, \"Seventeen\");\n tens.Add(18, \"Eighteen\");\n tens.Add(19, \"Ninteen\");\n if (tens.ContainsKey(value))\n {\n englishEquvalent = tens[value];\n }\n\n return englishEquvalent;\n\n }\n private static string GetOnes(string onesPlaceValue)\n {\n int value = Convert.ToInt32(onesPlaceValue);\n string englishEquvalent = string.Empty;\n Dictionary<int, string> ones = new Dictionary<int, string>();\n ones.Add(1, \" One\");\n ones.Add(2, \" Two\");\n ones.Add(3, \" Three\");\n ones.Add(4, \" Four\");\n ones.Add(5, \" Five\");\n ones.Add(6, \" Six\");\n ones.Add(7, \" Seven\");\n ones.Add(8, \" Eight\");\n ones.Add(9, \" Nine\");\n\n if (ones.ContainsKey(value))\n {\n englishEquvalent = ones[value];\n }\n\n return englishEquvalent;\n }\n private static string GetSections(int section)\n {\n string sectionName = string.Empty;\n switch (section)\n {\n case 0:\n sectionName = \"Cents\";\n break;\n case 1:\n sectionName = \"Dollars\";\n break;\n case 2:\n sectionName = \"Thousand\";\n break;\n case 3:\n sectionName = \"Million\";\n break;\n case 4:\n sectionName = \"Billion\";\n break;\n case 5:\n sectionName = \"Trillion\";\n break;\n case 6:\n sectionName = \"Zillion\";\n break;\n }\n return sectionName;\n }\n private static bool ValidateInput(string input)\n {\n return Regex.IsMatch(input, \"[0-9]{1,18}(\\\\.[0-9]{1,2})?\"))\n }\n }\n}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
3,224 | <p>CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.</p>
<hr />
<blockquote>
<p>Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.</p>
<p>Could use the SVN revision number to automate this for you: <a href="https://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number">ASP.NET Display SVN Revision Number</a></p>
</blockquote>
<p>Can you specify how you include the <a href="http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html" rel="noreferrer">Revision</a> variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file.</p>
<p>In the <a href="http://svnbook.red-bean.com" rel="noreferrer">Subversion book</a> it says about Revision: "This keyword describes the last known revision in which this file changed in the repository".</p>
<blockquote>
<p>Firefox also allows pressing <kbd>CTRL</kbd>+<kbd>R</kbd> to reload everything on a particular page.</p>
</blockquote>
<p>To clarify I am looking for solutions that don't require the user to do anything on their part.</p>
| [
{
"answer_id": 3225,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 6,
"selected": true,
"text": "function urlmtime($url) {\n $parsed_url = parse_url($url);\n $path = $parsed_url['path'];\n\n if ($path[0] == \"/\") {\n $filename = $_SERVER['DOCUMENT_ROOT'] . \"/\" . $path;\n } else {\n $filename = $path;\n }\n\n if (!file_exists($filename)) {\n // If not a file then use the current time\n $lastModified = date('YmdHis');\n } else {\n $lastModified = date('YmdHis', filemtime($filename));\n }\n\n if (strpos($url, '?') === false) {\n $url .= '?ts=' . $lastModified;\n } else {\n $url .= '&ts=' . $lastModified;\n }\n\n return $url;\n}\n\nfunction include_css($css_url, $media='all') {\n // According to Yahoo, using link allows for progressive \n // rendering in IE where as @import url($css_url) does not\n echo '<link rel=\"stylesheet\" type=\"text/css\" media=\"' .\n $media . '\" href=\"' . urlmtime($css_url) . '\">'.\"\\n\";\n}\n\nfunction include_javascript($javascript_url) {\n echo '<script type=\"text/javascript\" src=\"' . urlmtime($javascript_url) .\n '\"></script>'.\"\\n\";\n}\n"
},
{
"answer_id": 3233,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"funkycode.js?v1\">\n"
},
{
"answer_id": 4026,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 3,
"selected": false,
"text": "myscript.1.2.3.js"
},
{
"answer_id": 60686,
"author": "Michelle",
"author_id": 4058,
"author_profile": "https://Stackoverflow.com/users/4058",
"pm_score": 3,
"selected": false,
"text": "<?php \n include ('grom_file.php');\n // timestamp on the filename has to be updated manually\n include_css('_stylesheets/style.css?ts=20080912162813', 'all');\n?>\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] |
3,234 | <p>How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request.</p>
<p>This would allow people to hit a url to the type <a href="http://www.foo.com?Image=test.jpg" rel="noreferrer">http://www.foo.com?Image=test.jpg</a> and have the image display in their browser. So as you may know this revolves around the use of Response.ContentType.</p>
<p>By using </p>
<pre><code>Response.ContentType = "application/octet-stream";
</code></pre>
<p>I am able to display images of type gif/jpeg/png (all i have tested so far), bit trying to display .swf or .ico files gives me a nice little error.</p>
<p>using</p>
<pre><code>Response.ContentType = "application/x-shockwave-flash";
</code></pre>
<p>I can get flash files to play, but then the images are messed.</p>
<p>So how do i <strong>easily</strong> choose the contenttype?</p>
| [
{
"answer_id": 3240,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "// Clear the response buffer incase there is anything already in it.\nResponse.Clear();\nResponse.Buffer = true;\n\n// Read the original file from disk\nFileStream myFileStream = new FileStream(sPath, FileMode.Open);\nlong FileSize = myFileStream.Length;\nbyte[] Buffer = new byte[(int)FileSize];\nmyFileStream.Read(Buffer, 0, (int)FileSize);\nmyFileStream.Close();\n\n// Tell the browse stuff about the file\nResponse.AddHeader(\"Content-Length\", FileSize.ToString());\nResponse.AddHeader(\"Content-Disposition\", \"inline; filename=\" + sFilename.Replace(\" \",\"_\"));\nResponse.ContentType = getMimeType(sExtention, oConnection);\n\n// Send the data to the browser\nResponse.BinaryWrite(Buffer);\nResponse.End();\n"
},
{
"answer_id": 14496,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": true,
"text": "switch ( fileExtension )\n{\n case \"pdf\": Response.ContentType = \"application/pdf\"; break; \n case \"swf\": Response.ContentType = \"application/x-shockwave-flash\"; break; \n\n case \"gif\": Response.ContentType = \"image/gif\"; break; \n case \"jpeg\": Response.ContentType = \"image/jpg\"; break; \n case \"jpg\": Response.ContentType = \"image/jpg\"; break; \n case \"png\": Response.ContentType = \"image/png\"; break; \n\n case \"mp4\": Response.ContentType = \"video/mp4\"; break; \n case \"mpeg\": Response.ContentType = \"video/mpeg\"; break; \n case \"mov\": Response.ContentType = \"video/quicktime\"; break; \n case \"wmv\":\n case \"avi\": Response.ContentType = \"video/x-ms-wmv\"; break; \n\n //and so on \n\n default: Response.ContentType = \"application/octet-stream\"; break; \n}\n"
},
{
"answer_id": 46413068,
"author": "shurik",
"author_id": 1159723,
"author_profile": "https://Stackoverflow.com/users/1159723",
"pm_score": 0,
"selected": false,
"text": "MimeMapping.GetMimeMapping\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] |
3,255 | <p>Most people with a degree in CS will certainly know what <a href="http://www.nist.gov/dads/HTML/bigOnotation.html" rel="noreferrer">Big O stands for</a>.
It helps us to measure how well an algorithm scales. </p>
<p>But I'm curious, how do <em>you</em> calculate or approximate the complexity of your algorithms?</p>
| [
{
"answer_id": 3368,
"author": "DShook",
"author_id": 370,
"author_profile": "https://Stackoverflow.com/users/370",
"pm_score": 8,
"selected": false,
"text": "int array[n];\n x = array[0];\n for(int i = 0; i < n; i++){\n if(array[i] == numToFind){ return i; }\n}\n for(int i = 0; i < n; i++){\n for(int j = i; j < n; j++){\n array[j] += 2;\n }\n}\n"
},
{
"answer_id": 4515,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 5,
"selected": false,
"text": "(define (fac n)\n (if (= n 0)\n 1\n (* n (fac (- n 1)))))\n"
},
{
"answer_id": 5943,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "a=0;\nb=1;\nfor (i = 0; i <n; i++) {\n tmp = b;\n b = a + b;\n a = tmp;\n}\n"
},
{
"answer_id": 24582,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 5,
"selected": false,
"text": "big O premature optimisation is the root of all evil"
},
{
"answer_id": 46502,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 2,
"selected": false,
"text": "int nCmp = 0;\nSystem.Random rnd = new System.Random();\n\n// measure the time required to sort a list of n integers\nvoid DoTest(int n)\n{\n List<int> lst = new List<int>(n);\n for( int i=0; i<n; i++ )\n lst[i] = rnd.Next(0,1000);\n\n // as we sort, keep track of the number of comparisons performed!\n nCmp = 0;\n lst.Sort( delegate( int a, int b ) { nCmp++; return (a<b)?-1:((a>b)?1:0)); }\n\n System.Console.Writeline( \"{0},{1}\", n, nCmp );\n}\n\n\n// Perform measurement for a variety of sample sizes.\n// It would be prudent to check multiple random samples of each size, but this is OK for a quick sanity check\nfor( int n = 0; n<1000; n++ )\n DoTest(n);\n"
},
{
"answer_id": 630142,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 5,
"selected": false,
"text": "if"
},
{
"answer_id": 4852098,
"author": "Emmanuel",
"author_id": 579731,
"author_profile": "https://Stackoverflow.com/users/579731",
"pm_score": 3,
"selected": false,
"text": "n-i i 0 n-1 n-i n*(n + 1) / 2 O(n²/2) = O(n²) i 0 n j n"
},
{
"answer_id": 4852666,
"author": "vz0",
"author_id": 209629,
"author_profile": "https://Stackoverflow.com/users/209629",
"pm_score": 12,
"selected": true,
"text": "int sum(int* data, int N) {\n int result = 0; // 1\n\n for (int i = 0; i < N; i++) { // 2\n result += data[i]; // 3\n }\n\n return result; // 4\n}\n Number_Of_Steps = f(N)\n f(N) Number_Of_Steps = f(data.length)\n N data.length f() C data f(N) = C + ??? + C\n for for N C N f(N) = C + (C + C + ... + C) + C = C + N * C + C\n for for C f() standard form N infinity f() f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1\n C f(N) = 1 + N ^ 1\n f() sum() O(N)\n for (i = 0; i < 2*n; i += 2) { // 1\n for (j=n; j > i; j--) { // 2\n foo(); // 3\n }\n}\n foo() O(1) O(1) C N for 2 * N for N f(N) = Summation(i from 1 to 2 * N / 2)( ... ) = \n = Summation(i from 1 to N)( ... )\n i for for f(N) = Summation(i from 1 to N)( Summation(j = ???)( ) )\n f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) )\n foo() O(1) C i N / 2 + 1 i N / 2 + 1 f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C )\n i > N / 2 for w f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C )\n\nf(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C )\n\nf(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C )\n\n=> Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i )\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C )\n\n=> (N / 2 - 1) * (N / 2 - 1 + 1) / 2 = \n\n (N / 2 - 1) * (N / 2) / 2 = \n\n ((N ^ 2 / 4) - (N / 2)) / 2 = \n\n (N ^ 2 / 8) - (N / 4)\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C )\n\nf(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2)\n\nf(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2)\n\nf(N) = C * ( N ^ 2 / 4 ) + C * N\n\nf(N) = C * 1/4 * N ^ 2 + C * N\n O(N²)\n"
},
{
"answer_id": 4855527,
"author": "laynece",
"author_id": 534263,
"author_profile": "https://Stackoverflow.com/users/534263",
"pm_score": 2,
"selected": false,
"text": "n+1 n n-2 0+2+..+(n-2)+n= (0+n)(n+1)/2= O(n²)"
},
{
"answer_id": 21512377,
"author": "ajknzhol",
"author_id": 1112163,
"author_profile": "https://Stackoverflow.com/users/1112163",
"pm_score": 5,
"selected": false,
"text": "O(1) O(1) for (i = 0; i < n-1; i++) \n{\n small = i;\n for (j = i+1; j < n; j++)\n if (A[j] < A[small])\n small = j;\n temp = A[small];\n A[small] = A[i];\n A[i] = temp;\n}\n ((n − 1) − 0)/1 = n − 1 times (1) for (j = 0; j < n; j++)\n(2) A[i][j] = 0;\n O(1) O(n) (2) for (i = 0; i < n; i++)\n(3) for (j = 0; j < n; j++)\n(4) A[i][j] = 0;\n O(n^2)"
},
{
"answer_id": 68223915,
"author": "Top-Master",
"author_id": 8740349,
"author_profile": "https://Stackoverflow.com/users/8740349",
"pm_score": 2,
"selected": false,
"text": "function f(text) {\n var n = text.length;\n for (var i = 0; i < n; i++) {\n f(text.slice(0, n-1))\n }\n // ... other JS logic here, which we can ignore ...\n}\n number operation for (i = 0; i < 2*n; i += 2) { // line 123\n for (j=n; j > i; j--) { // line 124\n foo(); // line 125\n }\n}\n 2*n i += 2 f(n) = O( n j j=n n ( n + n f(n) = O( n( n ) )\n n( n )"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46/"
] |
3,260 | <p>We use a data acquisition card to take readings from a device that increases its signal to a peak and then falls back to near the original value. To find the peak value we currently search the array for the highest reading and use the index to determine the timing of the peak value which is used in our calculations.</p>
<p>This works well if the highest value is the peak we are looking for but if the device is not working correctly we can see a second peak which can be higher than the initial peak. We take 10 readings a second from 16 devices over a 90 second period.</p>
<p>My initial thoughts are to cycle through the readings checking to see if the previous and next points are less than the current to find a peak and construct an array of peaks. Maybe we should be looking at a average of a number of points either side of the current position to allow for noise in the system. Is this the best way to proceed or are there better techniques?</p>
<hr>
<p>We do use LabVIEW and I have checked the <a href="http://forums.lavag.org/Peak-Detection-t8499.html" rel="noreferrer">LAVA forums</a> and there are a number of interesting examples. This is part of our test software and we are trying to avoid using too many non-standard VI libraries so I was hoping for feedback on the process/algorithms involved rather than specific code. </p>
| [
{
"answer_id": 24259,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 3,
"selected": false,
"text": "TSpectrum*"
},
{
"answer_id": 44357,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 6,
"selected": false,
"text": "(x(0), y(0)) (x(n), y(n)) y(i + 1) - y(i) 0 <= i < n T R y(n) - y(0) + k k T/R > 1 x0 < x1 < x2, y1 > 0.5 * (y0 + y2) D((x0, y0), (x1, y1)) + D((x1, y1), (x2, y2)) > D((x0, y0),(x2, y2))"
},
{
"answer_id": 33509689,
"author": "Jean-Paul",
"author_id": 2431885,
"author_profile": "https://Stackoverflow.com/users/2431885",
"pm_score": 3,
"selected": false,
"text": "lag = the lag of the moving window threshold = the z-score at which the algorithm signals influence = the influence (between 0 and 1) of new signals on the mean and standard deviation lag threshold influence influence # Let y be a vector of timeseries data of at least length lag+2\n# Let mean() be a function that calculates the mean\n# Let std() be a function that calculates the standard deviaton\n# Let absolute() be the absolute value function\n\n# Settings (the ones below are examples: choose what is best for your data)\nset lag to 5; # lag 5 for the smoothing functions\nset threshold to 3.5; # 3.5 standard deviations for signal\nset influence to 0.5; # between 0 and 1, where 1 is normal influence, 0.5 is half\n\n# Initialise variables\nset signals to vector 0,...,0 of length of y; # Initialise signal results\nset filteredY to y(1,...,lag) # Initialise filtered series\nset avgFilter to null; # Initialise average filter\nset stdFilter to null; # Initialise std. filter\nset avgFilter(lag) to mean(y(1,...,lag)); # Initialise first value\nset stdFilter(lag) to std(y(1,...,lag)); # Initialise first value\n\nfor i=lag+1,...,t do\n if absolute(y(i) - avgFilter(i-1)) > threshold*stdFilter(i-1) then\n if y(i) > avgFilter(i-1)\n set signals(i) to +1; # Positive signal\n else\n set signals(i) to -1; # Negative signal\n end\n # Adjust the filters\n set filteredY(i) to influence*y(i) + (1-influence)*filteredY(i-1);\n set avgFilter(i) to mean(filteredY(i-lag,i),lag);\n set stdFilter(i) to std(filteredY(i-lag,i),lag);\n else\n set signals(i) to 0; # No signal\n # Adjust the filters\n set filteredY(i) to y(i);\n set avgFilter(i) to mean(filteredY(i-lag,i),lag);\n set stdFilter(i) to std(filteredY(i-lag,i),lag);\n end\nend\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186/"
] |
3,281 | <p>I'm wondering if there's a way to do what I can do below with Python, in Ruby:</p>
<pre><code>sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))
</code></pre>
<p>I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.</p>
| [
{
"answer_id": 3314,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "weights = [1, 2, 3]\ndata = [4, 5, 6]\nresult = Array.new\na.zip(b) { |x, y| result << x * y } # For just the one operation\n\nsum = 0\na.zip(b) { |x, y| sum += x * y } # For both operations\n"
},
{
"answer_id": 3318,
"author": "Joey deVilla",
"author_id": 216,
"author_profile": "https://Stackoverflow.com/users/216",
"pm_score": 1,
"selected": false,
"text": "map collect Enumerable numbers numbers.map{|x| x + 5}\n map(lambda x: x + 5, numbers)\n"
},
{
"answer_id": 4263,
"author": "Michiel de Mare",
"author_id": 136,
"author_profile": "https://Stackoverflow.com/users/136",
"pm_score": 3,
"selected": false,
"text": "weights.zip(data).map{|a,b| a*b}.reduce(:+)\n weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }\n"
},
{
"answer_id": 4270,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 5,
"selected": true,
"text": "weights.zip(data).map(:*).reduce(:+)\n weights.zip(data).map(&:*).reduce(&:+)\n"
},
{
"answer_id": 5124209,
"author": "Chris Turner",
"author_id": 635050,
"author_profile": "https://Stackoverflow.com/users/635050",
"pm_score": 0,
"selected": false,
"text": "def dot(*arrays)\n arrays.transpose.map {|vals| yield vals}\nend\n\ndot(weights,data) {|a,b| a*b} \n\n# OR, if you have a third array\n\ndot(weights,data,offsets) {|a,b,c| (a*b)+c}\n class Array\n def dot\n self.transpose.map{|vals| yield vals}\n end\nend\n\n[weights,data].dot {|a,b| a*b}\n\n#OR\n\n[weights,data,offsets].dot {|a,b,c| (a*b)+c}\n"
},
{
"answer_id": 21015028,
"author": "Cary Swoveland",
"author_id": 256970,
"author_profile": "https://Stackoverflow.com/users/256970",
"pm_score": 0,
"selected": false,
"text": "weights = [1,2,3]\ndata = [10,50,30]\n\nrequire 'matrix'\nVector[*weights].inner_product Vector[*data] # => 200 \n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484/"
] |
3,284 | <p>I've been working with <a href="http://msdn.microsoft.com/en-us/library/aa479030.aspx" rel="noreferrer">providers</a> a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?</p>
| [
{
"answer_id": 3291,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 6,
"selected": false,
"text": "public static class Base\n{\n public static virtual int GetNumber() { return 5; }\n}\n\npublic static class Child1 : Base\n{\n public static override int GetNumber() { return 1; }\n}\n\npublic static class Child2 : Base\n{\n public static override int GetNumber() { return 2; }\n}\n"
},
{
"answer_id": 3294,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 8,
"selected": true,
"text": "public class A\n{\n public static void Test()\n {\n }\n}\n\npublic class B : A\n{\n}\n class Program\n{\n static void Main(string[] args)\n {\n B.Test();\n }\n}\n .entrypoint\n.maxstack 8\nL0000: nop \nL0001: call void ConsoleApplication1.A::Test()\nL0006: nop \nL0007: ret \n"
},
{
"answer_id": 6674,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 4,
"selected": false,
"text": "static"
},
{
"answer_id": 15090,
"author": "Fabio Gomes",
"author_id": 727,
"author_profile": "https://Stackoverflow.com/users/727",
"pm_score": 3,
"selected": false,
"text": "class function AvailableObjects: string; override;\nbegin\n Result := 'Object1, Object2';\nend; \n"
},
{
"answer_id": 2286540,
"author": "user275801",
"author_id": 275801,
"author_profile": "https://Stackoverflow.com/users/275801",
"pm_score": 4,
"selected": false,
"text": "abstract class Animal\n{\n protected static string[] legs;\n\n static Animal() {\n legs=new string[0];\n }\n\n public static void printLegs()\n {\n foreach (string leg in legs) {\n print(leg);\n }\n }\n}\n\n\nclass Human: Animal\n{\n static Human() {\n legs=new string[] {\"left leg\", \"right leg\"};\n }\n}\n\n\nclass Dog: Animal\n{\n static Dog() {\n legs=new string[] {\"left foreleg\", \"right foreleg\", \"left hindleg\", \"right hindleg\"};\n }\n}\n\n\npublic static void main() {\n Dog.printLegs();\n Human.printLegs();\n}\n\n\n//what is the output?\n//does each subclass get its own copy of the array \"legs\"?\n"
},
{
"answer_id": 66070907,
"author": "Burakumin",
"author_id": 6053778,
"author_profile": "https://Stackoverflow.com/users/6053778",
"pm_score": 3,
"selected": false,
"text": "void Catch<TAnimal>() where TAnimal : Animal\n{\n string scientificName = TAnimal.ScientificName; // abstract static property\n Console.WriteLine($\"Let's catch some {scientificName}\");\n …\n}\n SpeciesFor<TAnimal> Animal public abstract class SpeciesFor<TAnimal> where TAnimal : Animal\n{\n public static SpeciesFor<TAnimal> Instance { get { … } }\n\n // abstract \"static\" members\n\n public abstract string ScientificName { get; }\n \n …\n}\n\npublic abstract class Animal { … }\n void Catch<TAnimal>() where TAnimal : Animal\n{\n string scientificName = SpeciesFor<TAnimal>.Instance.ScientificName;\n Console.WriteLine($\"Let's catch some {scientificName}\");\n …\n}\n Animal SpeciesFor<TAnimal> SpeciesFor<TAnimal>.Instance public abstract class Animal<TSelf> where TSelf : Animal<TSelf>\n{\n private Animal(…) {}\n \n public abstract class OfSpecies<TSpecies> : Animal<TSelf>\n where TSpecies : SpeciesFor<TSelf>, new()\n {\n protected OfSpecies(…) : base(…) { }\n }\n \n …\n}\n Animal<TSelf> Animal<TSelf>.OfSpecies<TSpecies> TSpecies new() public abstract class SpeciesFor<TAnimal> where TAnimal : Animal<TAnimal>\n{\n private static SpeciesFor<TAnimal> _instance;\n\n public static SpeciesFor<TAnimal> Instance => _instance ??= MakeInstance();\n\n private static SpeciesFor<TAnimal> MakeInstance()\n {\n Type t = typeof(TAnimal);\n while (true)\n {\n if (t.IsConstructedGenericType\n && t.GetGenericTypeDefinition() == typeof(Animal<>.OfSpecies<>))\n return (SpeciesFor<TAnimal>)Activator.CreateInstance(t.GenericTypeArguments[1]);\n t = t.BaseType;\n if (t == null)\n throw new InvalidProgramException();\n }\n }\n\n // abstract \"static\" members\n\n public abstract string ScientificName { get; }\n \n …\n}\n MakeInstance() Animal<TSelf> Animal<TSelf>.OfSpecies<TSpecies> TSpecies : new() Animal<Something> where TAnimal : Animal<TAnimal> SpeciesFor<Animal<Something>>.Instance Animal<Something> Animal<Animal<Something>> public class CatSpecies : SpeciesFor<Cat>\n{\n // overriden \"static\" members\n\n public override string ScientificName => \"Felis catus\";\n public override Cat CreateInVivoFromDnaTrappedInAmber() { … }\n public override Cat Clone(Cat a) { … }\n public override Cat Breed(Cat a1, Cat a2) { … }\n}\n\npublic class Cat : Animal<Cat>.OfSpecies<CatSpecies>\n{\n // overriden members\n\n public override string CuteName { get { … } }\n}\n\npublic class DogSpecies : SpeciesFor<Dog>\n{\n // overriden \"static\" members\n\n public override string ScientificName => \"Canis lupus familiaris\";\n public override Dog CreateInVivoFromDnaTrappedInAmber() { … }\n public override Dog Clone(Dog a) { … }\n public override Dog Breed(Dog a1, Dog a2) { … }\n}\n\npublic class Dog : Animal<Dog>.OfSpecies<DogSpecies>\n{\n // overriden members\n\n public override string CuteName { get { … } }\n}\n\npublic class Program\n{\n public static void Main()\n {\n ConductCrazyScientificExperimentsWith<Cat>();\n ConductCrazyScientificExperimentsWith<Dog>();\n ConductCrazyScientificExperimentsWith<Tyranosaurus>();\n ConductCrazyScientificExperimentsWith<Wyvern>();\n }\n \n public static void ConductCrazyScientificExperimentsWith<TAnimal>()\n where TAnimal : Animal<TAnimal>\n {\n // Look Ma! No animal instance polymorphism!\n \n TAnimal a2039 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();\n TAnimal a2988 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();\n TAnimal a0400 = SpeciesFor<TAnimal>.Instance.Clone(a2988);\n TAnimal a9477 = SpeciesFor<TAnimal>.Instance.Breed(a0400, a2039);\n TAnimal a9404 = SpeciesFor<TAnimal>.Instance.Breed(a2988, a9477);\n \n Console.WriteLine(\n \"The confederation of mad scientists is happy to announce the birth \" +\n $\"of {a9404.CuteName}, our new {SpeciesFor<TAnimal>.Instance.ScientificName}.\");\n }\n}\n Mammal MammalClass"
},
{
"answer_id": 69666855,
"author": "0BLU",
"author_id": 3338196,
"author_profile": "https://Stackoverflow.com/users/3338196",
"pm_score": 4,
"selected": false,
"text": ".NET 6 C# 10/next/preview using System;\n\nnamespace StaticAbstractTesting\n{\n public interface ISomeAbstractInterface\n {\n public abstract static string CallMe();\n }\n\n public class MyClassA : ISomeAbstractInterface\n {\n static string ISomeAbstractInterface.CallMe()\n {\n return \"You called ClassA\";\n }\n }\n\n public class MyClassB : ISomeAbstractInterface\n {\n static string ISomeAbstractInterface.CallMe()\n {\n return \"You called ClassB\";\n }\n }\n\n public class Program\n {\n\n public static void Main(string[] args)\n {\n UseStaticClassMethod<MyClassA>();\n UseStaticClassMethod<MyClassB>();\n }\n\n public static void UseStaticClassMethod<T>() where T : ISomeAbstractInterface\n {\n Console.WriteLine($\"{typeof(T).Name}.CallMe() result: {T.CallMe()}\");\n }\n }\n}\n\n public static void UseStaticClassMethodSimple<T>() where T : ISomeAbstractInterface {\nIL_0000: constrained. !!T\nIL_0006: call string StaticAbstractTesting.ISomeAbstractInterface::CallMe()\nIL_000b: call void [System.Console]System.Console::WriteLine(string)\nIL_0010: ret\n}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] |
3,315 | <p>I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this:</p>
<pre><code>private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)
{
foreach (Control control in rootControl.Controls)
{
if (control.Controls.Count > 0)
{
// Recursively search for any TextBoxes within each child control
foreach (TextBox textBox in FindTextBoxes(control))
{
yield return textBox;
}
}
TextBox textBox2 = control as TextBox;
if (textBox2 != null)
{
yield return textBox2;
}
}
}
</code></pre>
<p>Using it like this:</p>
<pre><code>foreach(TextBox textBox in FindTextBoxes(this))
{
textBox.Height = height;
}
</code></pre>
<p>But of course the compiler spits its dummy, because <em>foreach</em> expects an <strong>IEnumerable</strong> rather than an <strong>IEnumerator</strong>.</p>
<p>Is there a way to do this without having to create a separate class with a <strong>GetEnumerator()</strong> method?</p>
| [
{
"answer_id": 3323,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 1,
"selected": false,
"text": "// Generic function that gets all child controls of a certain type, \n// returned in a List collection\nprivate static List<T> GetChildTextBoxes<T>(Control ctrl) where T : Control{\n List<T> tbs = new List<T>();\n foreach (Control c in ctrl.Controls) {\n // If c is of type T, add it to the collection\n if (c is T) { \n tbs.Add((T)c);\n }\n }\n return tbs;\n}\n\nprivate static void SetChildTextBoxesHeight(Control ctrl, int height) {\n foreach (TextBox t in GetChildTextBoxes<TextBox>(ctrl)) {\n t.Height = height;\n }\n}\n"
},
{
"answer_id": 6472,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)\n private static IEnumerable<TextBox> FindTextBoxes(Control rootControl)\n"
},
{
"answer_id": 6698655,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "toEnumerable GetEnumerator foreach IEnumerator<> IEnumerable<T> GetEnumerator"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/503/"
] |
3,319 | <p>How can I set the background color of an HTML element using css in JavaScript?</p>
| [
{
"answer_id": 3320,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 5,
"selected": false,
"text": "var element = document.getElementById('element');\nelement.style.background = '#FF00AA';\n"
},
{
"answer_id": 3321,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 8,
"selected": true,
"text": "background-color backgroundColor function setColor(element, color)\n{\n element.style.backgroundColor = color;\n}\n\n// where el is the concerned element\nvar el = document.getElementById('elementId');\nsetColor(el, 'green');\n"
},
{
"answer_id": 3361,
"author": "Wally Lawless",
"author_id": 37,
"author_profile": "https://Stackoverflow.com/users/37",
"pm_score": 4,
"selected": false,
"text": "$('#fieldID').css('background-color', '#FF6600');\n"
},
{
"answer_id": 16037,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 5,
"selected": false,
"text": ".highlight {\n background:#ff00aa;\n}\n element.className = element.className === 'highlight' ? '' : 'highlight';\n"
},
{
"answer_id": 5186696,
"author": "james.garriss",
"author_id": 584674,
"author_profile": "https://Stackoverflow.com/users/584674",
"pm_score": 3,
"selected": false,
"text": "<body>\n <script type=\"text/javascript\">\n document.body.style.backgroundColor = \"#AAAAAA\";\n </script>\n</body>\n"
},
{
"answer_id": 15168927,
"author": "Zardiw",
"author_id": 1723600,
"author_profile": "https://Stackoverflow.com/users/1723600",
"pm_score": 2,
"selected": false,
"text": "document.getElementById('element').style.background = '#DD00DD';\n"
},
{
"answer_id": 20933776,
"author": "Saeed",
"author_id": 1726377,
"author_profile": "https://Stackoverflow.com/users/1726377",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\n Window.body.style.backgroundColor = \"#5a5a5a\";\n</script>\n"
},
{
"answer_id": 21683642,
"author": "bluelog",
"author_id": 3293861,
"author_profile": "https://Stackoverflow.com/users/3293861",
"pm_score": 2,
"selected": false,
"text": "$(\".class\").css(\"background\",\"yellow\");\n"
},
{
"answer_id": 23002017,
"author": "hamed",
"author_id": 3521734,
"author_profile": "https://Stackoverflow.com/users/3521734",
"pm_score": 1,
"selected": false,
"text": "$('#elementID').css('background-color', '#C0C0C0');\n"
},
{
"answer_id": 29704278,
"author": "Roger Causto",
"author_id": 4292292,
"author_profile": "https://Stackoverflow.com/users/4292292",
"pm_score": 3,
"selected": false,
"text": "var element = document.getElementById('element');\n\nelement.onclick = function() {\n element.classList.add('backGroundColor');\n \n setTimeout(function() {\n element.classList.remove('backGroundColor');\n }, 2000);\n}; .backGroundColor {\n background-color: green;\n} <div id=\"element\">Click Me</div>"
},
{
"answer_id": 32375473,
"author": "Ajay Gupta",
"author_id": 2663073,
"author_profile": "https://Stackoverflow.com/users/2663073",
"pm_score": 3,
"selected": false,
"text": "var element = document.getElementById('element_id');\nelement.style.backgroundColor = \"color or color_code\";\n var element = document.getElementById('firstname');\nelement.style.backgroundColor = \"green\";//Or #ff55ff\n"
},
{
"answer_id": 33646923,
"author": "LemonPie",
"author_id": 1500076,
"author_profile": "https://Stackoverflow.com/users/1500076",
"pm_score": -1,
"selected": false,
"text": "$(\".class\")[0].style.background = \"blue\";\n"
},
{
"answer_id": 42773184,
"author": "Srikrushna",
"author_id": 5852550,
"author_profile": "https://Stackoverflow.com/users/5852550",
"pm_score": 2,
"selected": false,
"text": "$(\"body\").css(\"background\",\"green\"); //jQuery\n\ndocument.body.style.backgroundColor = \"green\"; //javascript\n"
},
{
"answer_id": 44718510,
"author": "pragadeesh mahendran",
"author_id": 8203775,
"author_profile": "https://Stackoverflow.com/users/8203775",
"pm_score": 2,
"selected": false,
"text": "$('#ID / .Class').css('background-color', '#FF6600');\n"
},
{
"answer_id": 44718647,
"author": "Mr.Pandya",
"author_id": 6554624,
"author_profile": "https://Stackoverflow.com/users/6554624",
"pm_score": 0,
"selected": false,
"text": "document.getElementById(\"ID\").style.background = \"colorName\"; //JS ID\n\ndocument.getElementsByClassName(\"ClassName\")[0].style.background = \"colorName\"; //JS Class\n $('#ID/.className').css(\"background\",\"colorName\") // One style\n\n$('#ID/.className').css({\"background\":\"colorName\",\"color\":\"colorname\"}); //Multiple style\n"
},
{
"answer_id": 50749215,
"author": "Ivan",
"author_id": 6331369,
"author_profile": "https://Stackoverflow.com/users/6331369",
"pm_score": 1,
"selected": false,
"text": "HTMLElement document.querySelector(<selector>).style[<property>] = <new style>\n <selector> <property> <new style> String background-color backgroundColor #container documentquerySelector('#container').style.background = 'red'\n colors = ['rosybrown', 'cornflowerblue', 'pink', 'lightblue', 'lemonchiffon', 'lightgrey', 'lightcoral', 'blueviolet', 'firebrick', 'fuchsia', 'lightgreen', 'red', 'purple', 'cyan']\n\nlet i = 0\nsetInterval(() => {\n const random = Math.floor(Math.random()*colors.length)\n document.querySelector('.box').style.background = colors[random];\n}, 500) .box {\n width: 100px;\n height: 100px;\n} <div class=\"box\"></div> HTMLElement box lightgreen .querySelectorAll Array const elements = [...document.querySelectorAll('.box')]\n .forEach elements.forEach(element => element.style.background = 'lightgreen')\n const elements = [...document.querySelectorAll('.box')]\nelements.forEach(element => element.style.background = 'lightgreen') .box {\n height: 100px;\n width: 100px;\n display: inline-block;\n margin: 10px;\n} <div class=\"box\"></div>\n<div class=\"box\"></div>\n<div class=\"box\"></div>\n<div class=\"box\"></div> classList toggle document.querySelector('.box').classList.toggle('orange') .box {\n width: 100px;\n height: 100px;\n}\n\n.orange {\n background: orange;\n} <div class='box'></div> alignContent\nalignItems\nalignSelf\nanimation\nanimationDelay\nanimationDirection\nanimationDuration\nanimationFillMode\nanimationIterationCount\nanimationName\nanimationTimingFunction\nanimationPlayState\nbackground\nbackgroundAttachment\nbackgroundColor\nbackgroundImage\nbackgroundPosition\nbackgroundRepeat\nbackgroundClip\nbackgroundOrigin\nbackgroundSize</a></td>\nbackfaceVisibility\nborderBottom\nborderBottomColor\nborderBottomLeftRadius\nborderBottomRightRadius\nborderBottomStyle\nborderBottomWidth\nborderCollapse\nborderColor\nborderImage\nborderImageOutset\nborderImageRepeat\nborderImageSlice\nborderImageSource \nborderImageWidth\nborderLeft\nborderLeftColor\nborderLeftStyle\nborderLeftWidth\nborderRadius\nborderRight\nborderRightColor\nborderRightStyle\nborderRightWidth\nborderSpacing\nborderStyle\nborderTop\nborderTopColor\nborderTopLeftRadius\nborderTopRightRadius\nborderTopStyle\nborderTopWidth\nborderWidth\nbottom\nboxShadow\nboxSizing\ncaptionSide\nclear\nclip\ncolor\ncolumnCount\ncolumnFill\ncolumnGap\ncolumnRule\ncolumnRuleColor\ncolumnRuleStyle\ncolumnRuleWidth\ncolumns\ncolumnSpan\ncolumnWidth\ncounterIncrement\ncounterReset\ncursor\ndirection\ndisplay\nemptyCells\nfilter\nflex\nflexBasis\nflexDirection\nflexFlow\nflexGrow\nflexShrink\nflexWrap\ncontent\nfontStretch\nhangingPunctuation\nheight\nhyphens\nicon\nimageOrientation\nnavDown\nnavIndex\nnavLeft\nnavRight\nnavUp>\ncssFloat\nfont\nfontFamily\nfontSize\nfontStyle\nfontVariant\nfontWeight\nfontSizeAdjust\njustifyContent\nleft\nletterSpacing\nlineHeight\nlistStyle\nlistStyleImage\nlistStylePosition\nlistStyleType\nmargin\nmarginBottom\nmarginLeft\nmarginRight\nmarginTop\nmaxHeight\nmaxWidth\nminHeight\nminWidth\nopacity\norder\norphans\noutline\noutlineColor\noutlineOffset\noutlineStyle\noutlineWidth\noverflow\noverflowX\noverflowY\npadding\npaddingBottom\npaddingLeft\npaddingRight\npaddingTop\npageBreakAfter\npageBreakBefore\npageBreakInside\nperspective\nperspectiveOrigin\nposition\nquotes\nresize\nright\ntableLayout\ntabSize\ntextAlign\ntextAlignLast\ntextDecoration\ntextDecorationColor\ntextDecorationLine\ntextDecorationStyle\ntextIndent\ntextOverflow\ntextShadow\ntextTransform\ntextJustify\ntop\ntransform\ntransformOrigin\ntransformStyle\ntransition\ntransitionProperty\ntransitionDuration\ntransitionTimingFunction\ntransitionDelay\nunicodeBidi\nuserSelect\nverticalAlign\nvisibility\nvoiceBalance\nvoiceDuration\nvoicePitch\nvoicePitchRange\nvoiceRate\nvoiceStress\nvoiceVolume\nwhiteSpace\nwidth\nwordBreak\nwordSpacing\nwordWrap\nwidows\nwritingMode\nzIndex\n"
},
{
"answer_id": 59819524,
"author": "Mehadi Hassan",
"author_id": 9569557,
"author_profile": "https://Stackoverflow.com/users/9569557",
"pm_score": 0,
"selected": false,
"text": "document.getElementById(\"idName\").style.background = \"blue\";\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
3,362 | <p>I would like to be able to use the <kbd>Tab</kbd> key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input.</p>
<p>Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI?</p>
<p>I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like <kbd>Shift</kbd>+<kbd>Tab</kbd>, or <kbd>Ctrl</kbd>+<kbd>Q</kbd>?</p>
| [
{
"answer_id": 3370,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 4,
"selected": false,
"text": "document.onkeydown = TabExample;\n\nfunction TabExample(evt) {\n var evt = (evt) ? evt : ((event) ? event : null);\n var tabKey = 9;\n if(evt.keyCode == tabKey) {\n // do work\n }\n}\n"
},
{
"answer_id": 13130,
"author": "ScottKoon",
"author_id": 1538,
"author_profile": "https://Stackoverflow.com/users/1538",
"pm_score": 8,
"selected": true,
"text": "keydown keyup preventDefault() preventDefault <body>\n<input type=\"text\" id=\"myInput\">\n<script type=\"text/javascript\">\n var myInput = document.getElementById(\"myInput\");\n if(myInput.addEventListener ) {\n myInput.addEventListener('keydown',this.keyHandler,false);\n } else if(myInput.attachEvent ) {\n myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */\n }\n\n function keyHandler(e) {\n var TABKEY = 9;\n if(e.keyCode == TABKEY) {\n this.value += \" \";\n if(e.preventDefault) {\n e.preventDefault();\n }\n return false;\n }\n }\n</script>\n</body>\n"
},
{
"answer_id": 2280003,
"author": "Paul D. Waite",
"author_id": 20578,
"author_profile": "https://Stackoverflow.com/users/20578",
"pm_score": 2,
"selected": false,
"text": "<textarea>"
},
{
"answer_id": 3674216,
"author": "chintan123",
"author_id": 443119,
"author_profile": "https://Stackoverflow.com/users/443119",
"pm_score": 2,
"selected": false,
"text": "} else if(el.attachEvent ) {\n myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */\n}\n } else if(myInput.attachEvent ) {\n myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */\n}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] |
3,385 | <p>I know that we can get the MAC address of a user via IE (ActiveX objects).</p>
<p>Is there a way to obtain a user's MAC address using JavaScript?</p>
| [
{
"answer_id": 48112607,
"author": "Ad Kahn",
"author_id": 2855519,
"author_profile": "https://Stackoverflow.com/users/2855519",
"pm_score": 3,
"selected": false,
"text": "function showMacAddress() {\n var obj = new ActiveXObject(\"WbemScripting.SWbemLocator\");\n var s = obj.ConnectServer(\".\");\n var properties = s.ExecQuery(\"SELECT * FROM Win32_NetworkAdapterConfiguration\");\n var e = new Enumerator(properties);\n var output;\n output = '<table border=\"0\" cellPadding=\"5px\" cellSpacing=\"1px\" bgColor=\"#CCCCCC\">';\n output = output + '<tr bgColor=\"#EAEAEA\"><td>Caption</td><td>MACAddress</td></tr>';\n while (!e.atEnd()) {\n e.moveNext();\n var p = e.item();\n if (!p) continue;\n output = output + '<tr bgColor=\"#FFFFFF\">';\n output = output + '<td>' + p.Caption; +'</td>';\n output = output + '<td>' + p.MACAddress + '</td>';\n output = output + '</tr>';\n }\n output = output + '</table>';\n document.getElementById(\"box\").innerHTML = output;\n}\n\nshowMacAddress(); <div id='box'></div>"
},
{
"answer_id": 73131819,
"author": "hasherfer",
"author_id": 5339177,
"author_profile": "https://Stackoverflow.com/users/5339177",
"pm_score": 0,
"selected": false,
"text": " function genrandstr($length=NULL) {\n if($length == NULL){ $length = 30; }\n $characters = \n '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n $charactersLength = strlen($characters);\n $randomString = '';\n for ($i = 0; $i < $length; $i++) {\n $randomString .= $characters[rand(0, $charactersLength - 1)];\n }\n return $randomString;\n }\n\n localStorage.setItem('id', id) to add to localStorage\n (let) or (var) id = localStorage.getItem('id') to read from localStorage\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384/"
] |
3,400 | <p><strong>Note:</strong> I <em>am</em> using SQL's Full-text search capabilities, CONTAINS clauses and all - the * is the wildcard in full-text, % is for LIKE clauses only.</p>
<p>I've read in several places now that "leading wildcard" searches (e.g. using "*overflow" to match "stackoverflow") is not supported in MS SQL. I'm considering using a <a href="http://blogs.msdn.com/sqlclr/archive/2005/06/29/regex.aspx" rel="noreferrer" title="SQL CLR Blog">CLR function to add regex matching</a>, but I'm curious to see what other solutions people might have.</p>
<p><strong>More Info</strong>: <a href="http://msdn.microsoft.com/en-us/library/ms552152.aspx" rel="noreferrer" title="MSDN">You can add the asterisk only at the end of the word or phrase.</a> - along with my empirical experience: When matching "myvalue", "my*" works, but "(asterisk)value" returns no match, when doing a query as simple as:</p>
<pre><code>SELECT * FROM TABLENAME WHERE CONTAINS(TextColumn, '"*searchterm"');
</code></pre>
<p>Thus, my need for a workaround. I'm only using search in my site on an actual search page - so it needs to work basically the same way that Google works (in the eyes on a Joe Sixpack-type user). Not nearly as complicated, but this sort of match really shouldn't fail.</p>
| [
{
"answer_id": 3405,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "CONTAINS % % _"
},
{
"answer_id": 3521,
"author": "Otto",
"author_id": 519,
"author_profile": "https://Stackoverflow.com/users/519",
"pm_score": -1,
"selected": false,
"text": "Example: \"*ildcar\" will look for a single word as long as it ends with \"ildcar\".\n\nExample: \"*ildcar*\" will look for a single word with \"ildcar\" in the middle, which means it will match \"wildcard\". [Just noticed that Markdown removed the wildcard characters from the beginning and ending of my quoted string here.]\n"
},
{
"answer_id": 124502,
"author": "xnagyg",
"author_id": 2622295,
"author_profile": "https://Stackoverflow.com/users/2622295",
"pm_score": 5,
"selected": false,
"text": "SELECT * \nFROM TABLENAME \nWHERE CONTAINS(TextColumnREV, '\"mrethcraes*\"');\n"
},
{
"answer_id": 320132,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "SELECT * FROM SomeTable WHERE CONTAINS(ColumnName, '\"datab*\"')\n SELECT * FROM SomeTable WHERE CONTAINS(ColumnName, '\"*abase\"')\n"
},
{
"answer_id": 34602059,
"author": "ASP Force",
"author_id": 3464788,
"author_profile": "https://Stackoverflow.com/users/3464788",
"pm_score": 1,
"selected": false,
"text": "ALTER procedure [dbo].[uspLkp_DrugProductSelectAllByName]\n(\n @PROPRIETARY_NAME varchar(10)\n)\nas\n set nocount on\n declare @PROPRIETARY_NAME2 varchar(10) = '\"' + @PROPRIETARY_NAME + '*\"'\n\n select ldp.*, lkp.DRUG_PKG_ID\n from Lkp_DrugProduct ldp\n left outer join Lkp_DrugPackage lkp on ldp.DRUG_PROD_ID = lkp.DRUG_PROD_ID\n where contains(ldp.PROPRIETARY_NAME, @PROPRIETARY_NAME2)\n"
},
{
"answer_id": 51138309,
"author": "Hans",
"author_id": 9989507,
"author_profile": "https://Stackoverflow.com/users/9989507",
"pm_score": 0,
"selected": false,
"text": " pie\n applepie\n spies\n cherrypie\n dog\n cat\n to-match <- SELECT word FROM words WHERE word LIKE '%pie%'\n matcher = \"\"\n a = \"\"\n foreach(m, to-match) {\n matcher += a\n matcher += m\n a = \" OR \"\n }\n SELECT text FROM full_text WHERE text MATCH matcher\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35/"
] |
3,408 | <p>What do you think is the best set-up for RoR in a Win Vista environment? I've tried the radrails eclipse plug-in, and it just seemed too bulky for me, I've also started to just use Textpad and the command line, but I'm used to having somewhat of an IDE to work with.</p>
| [
{
"answer_id": 8381,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "rubygems"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/514/"
] |
3,432 | <p>I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?</p>
<p>Edit:
For example I have the following</p>
<pre><code>Name id Col1 Col2
Row1 1 6 1
Row2 2 2 3
Row3 3 9 5
Row4 4 16 8
</code></pre>
<p>I want to combine all the following Updates into one query</p>
<pre><code>UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;
</code></pre>
| [
{
"answer_id": 3439,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 3,
"selected": false,
"text": "UPDATE table1, table2 SET table1.col1='value', table2.col1='value' WHERE table1.col3='567' AND table2.col6='567'\n"
},
{
"answer_id": 3444,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": "Update Table Set\nColumn1 = 'New Value'\n Update Table Set\nColumn1 = 'New Value'\nWhere\nColumn2 > 5\n UPDATE table1, table2 SET\ntable1.col1 = 'value',\ntable2.col1 = 'value'\nWHERE\ntable1.col3 = '567'\nAND table2.col6='567'\n"
},
{
"answer_id": 3445,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 2,
"selected": false,
"text": "Update someTable Set someValue = 4 From someTable s Inner Join anotherTable a on s.id = a.id Where a.id = 4\n-- Only updates someValue in someTable who has a foreign key on anotherTable with a value of 4.\n"
},
{
"answer_id": 3449,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": -1,
"selected": false,
"text": "UPDATE tableName SET col1='000' WHERE id='3' OR id='5'\n"
},
{
"answer_id": 3466,
"author": "Michiel de Mare",
"author_id": 136,
"author_profile": "https://Stackoverflow.com/users/136",
"pm_score": 10,
"selected": true,
"text": "INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12)\nON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);\n"
},
{
"answer_id": 5213557,
"author": "Brooks",
"author_id": 126001,
"author_profile": "https://Stackoverflow.com/users/126001",
"pm_score": 2,
"selected": false,
"text": "$con = new mysqli('localhost','user1','password','my_database');\n$query = \"Update MyTable SET col1='some value' WHERE id=1 LIMIT 1;\";\n$query .= \"UPDATE MyTable SET col1='other value' WHERE id=2 LIMIT 1;\";\n//etc\n$con->multi_query($query);\n$con->close();\n"
},
{
"answer_id": 5577503,
"author": "Laymain",
"author_id": 696291,
"author_profile": "https://Stackoverflow.com/users/696291",
"pm_score": 3,
"selected": false,
"text": "// Reorder items\nfunction update_items_tempdb(&$items)\n{\n shuffle($items);\n $table_name = uniqid('tmp_test_');\n $sql = \"CREATE TEMPORARY TABLE `$table_name` (\"\n .\" `id` int(10) unsigned NOT NULL AUTO_INCREMENT\"\n .\", `position` int(10) unsigned NOT NULL\"\n .\", PRIMARY KEY (`id`)\"\n .\") ENGINE = MEMORY\";\n query($sql);\n $i = 0;\n $sql = '';\n foreach ($items as &$item)\n {\n $item->position = $i++;\n $sql .= ($sql ? ', ' : '').\"({$item->id}, {$item->position})\";\n }\n if ($sql)\n {\n query(\"INSERT INTO `$table_name` (id, position) VALUES $sql\");\n $sql = \"UPDATE `test`, `$table_name` SET `test`.position = `$table_name`.position\"\n .\" WHERE `$table_name`.id = `test`.id\";\n query($sql);\n }\n query(\"DROP TABLE `$table_name`\");\n}\n"
},
{
"answer_id": 14128210,
"author": "eggmatters",
"author_id": 1010444,
"author_profile": "https://Stackoverflow.com/users/1010444",
"pm_score": 2,
"selected": false,
"text": "UPDATE table1 tab1, table1 tab2 -- alias references the same table\nSET \ncol1 = 1\n,col2 = 2\n. . . \nWHERE \ntab1.id = tab2.id;\n"
},
{
"answer_id": 17284265,
"author": "Roman Imankulov",
"author_id": 848010,
"author_profile": "https://Stackoverflow.com/users/848010",
"pm_score": 7,
"selected": false,
"text": "INSERT ... ON DUPLICATE KEY UPDATE \"Field 'fieldname' doesn't have a default value\" INSERT ... ON DUPLICATE KEY UPDATE"
},
{
"answer_id": 18492422,
"author": "user2082581",
"author_id": 2082581,
"author_profile": "https://Stackoverflow.com/users/2082581",
"pm_score": -1,
"selected": false,
"text": "UPDATE `your_table` SET \n\n`something` = IF(`id`=\"1\",\"new_value1\",`something`), `smth2` = IF(`id`=\"1\", \"nv1\",`smth2`),\n`something` = IF(`id`=\"2\",\"new_value2\",`something`), `smth2` = IF(`id`=\"2\", \"nv2\",`smth2`),\n`something` = IF(`id`=\"4\",\"new_value3\",`something`), `smth2` = IF(`id`=\"4\", \"nv3\",`smth2`),\n`something` = IF(`id`=\"6\",\"new_value4\",`something`), `smth2` = IF(`id`=\"6\", \"nv4\",`smth2`),\n`something` = IF(`id`=\"3\",\"new_value5\",`something`), `smth2` = IF(`id`=\"3\", \"nv5\",`smth2`),\n`something` = IF(`id`=\"5\",\"new_value6\",`something`), `smth2` = IF(`id`=\"5\", \"nv6\",`smth2`) \n $q = 'UPDATE `your_table` SET ';\n\nforeach($data as $dat){\n\n $q .= '\n\n `something` = IF(`id`=\"'.$dat->id.'\",\"'.$dat->value.'\",`something`), \n `smth2` = IF(`id`=\"'.$dat->id.'\", \"'.$dat->value2.'\",`smth2`),';\n\n}\n\n$q = substr($q,0,-1);\n"
},
{
"answer_id": 19033152,
"author": "newtover",
"author_id": 68998,
"author_profile": "https://Stackoverflow.com/users/68998",
"pm_score": 6,
"selected": false,
"text": "UPDATE my_table m\nJOIN (\n SELECT 1 as id, 10 as _col1, 20 as _col2\n UNION ALL\n SELECT 2, 5, 10\n UNION ALL\n SELECT 3, 15, 30\n) vals ON m.id = vals.id\nSET col1 = _col1, col2 = _col2;\n"
},
{
"answer_id": 36017552,
"author": "Justin Levene",
"author_id": 1938802,
"author_profile": "https://Stackoverflow.com/users/1938802",
"pm_score": 0,
"selected": false,
"text": "REPLACE INTO`table` VALUES (`id`,`col1`,`col2`) VALUES\n(1,6,1),(2,2,3),(3,9,5),(4,16,8);\n"
},
{
"answer_id": 39831043,
"author": "Dakusan",
"author_id": 698632,
"author_profile": "https://Stackoverflow.com/users/698632",
"pm_score": 6,
"selected": false,
"text": "SET SESSION sql_mode=REPLACE(REPLACE(@@SESSION.sql_mode,\"STRICT_TRANS_TABLES\",\"\"),\"STRICT_ALL_TABLES\",\"\") sql_mode <?php\n//Variables\n$NumRows=30000;\n\n//These 2 functions need to be filled in\nfunction InitSQL()\n{\n\n}\nfunction RunSQLQuery($Q)\n{\n\n}\n\n//Run the 3 tests\nInitSQL();\nfor($i=0;$i<3;$i++)\n RunTest($i, $NumRows);\n\nfunction RunTest($TestNum, $NumRows)\n{\n $TheQueries=Array();\n $DoQuery=function($Query) use (&$TheQueries)\n {\n RunSQLQuery($Query);\n $TheQueries[]=$Query;\n };\n\n $TableName='Test';\n $DoQuery('DROP TABLE IF EXISTS '.$TableName);\n $DoQuery('CREATE TABLE '.$TableName.' (i1 int NOT NULL AUTO_INCREMENT, i2 int NOT NULL, primary key (i1)) ENGINE=InnoDB');\n $DoQuery('INSERT INTO '.$TableName.' (i2) VALUES ('.implode('), (', range(2, $NumRows+1)).')');\n\n if($TestNum==0)\n {\n $TestName='Transaction';\n $Start=microtime(true);\n $DoQuery('START TRANSACTION');\n for($i=1;$i<=$NumRows;$i++)\n $DoQuery('UPDATE '.$TableName.' SET i2='.(($i+5)*1000).' WHERE i1='.$i);\n $DoQuery('COMMIT');\n }\n \n if($TestNum==1)\n {\n $TestName='Insert';\n $Query=Array();\n for($i=1;$i<=$NumRows;$i++)\n $Query[]=sprintf(\"(%d,%d)\", $i, (($i+5)*1000));\n $Start=microtime(true);\n $DoQuery('INSERT INTO '.$TableName.' VALUES '.implode(', ', $Query).' ON DUPLICATE KEY UPDATE i2=VALUES(i2)');\n }\n \n if($TestNum==2)\n {\n $TestName='Case';\n $Query=Array();\n for($i=1;$i<=$NumRows;$i++)\n $Query[]=sprintf('WHEN %d THEN %d', $i, (($i+5)*1000));\n $Start=microtime(true);\n $DoQuery(\"UPDATE $TableName SET i2=CASE i1\\n\".implode(\"\\n\", $Query).\"\\nEND\\nWHERE i1 IN (\".implode(',', range(1, $NumRows)).')');\n }\n \n print \"$TestName: \".(microtime(true)-$Start).\"<br>\\n\";\n\n file_put_contents(\"./$TestName.sql\", implode(\";\\n\", $TheQueries).';');\n}\n"
},
{
"answer_id": 44931466,
"author": "mononoke",
"author_id": 6088837,
"author_profile": "https://Stackoverflow.com/users/6088837",
"pm_score": 3,
"selected": false,
"text": "multi_query PHP Warning: Error while sending SET_OPTION packet\n max_allowed_packet /etc/mysql/my.cnf"
},
{
"answer_id": 61643990,
"author": "Stan Sokolov",
"author_id": 1610778,
"author_profile": "https://Stackoverflow.com/users/1610778",
"pm_score": 1,
"selected": false,
"text": "update my_table m, -- let create a temp table with populated values\n (select 1 as id, 20 as value union -- this part will be generated\n select 2 as id, 30 as value union -- using a backend code\n -- for loop \n select N as id, X as value\n ) t\nset m.value = t.value where t.id=m.id -- now update by join - quick\n"
},
{
"answer_id": 65950733,
"author": "Liam",
"author_id": 3714181,
"author_profile": "https://Stackoverflow.com/users/3714181",
"pm_score": 0,
"selected": false,
"text": "drop table if exists `test`;\ncreate table `test` (\n `Id` int,\n `Number` int,\n PRIMARY KEY (`Id`)\n);\ninsert into test (Id, Number) values (1, 1), (2, 2);\n\nDROP procedure IF EXISTS `Test`;\nDELIMITER $$\nCREATE PROCEDURE `Test`(\n p_json json\n)\nBEGIN\n update test s\n join json_table(p_json, '$[*]' columns(`id` int path '$.id', `number` int path '$.number')) v \n on s.Id=v.id set s.Number=v.number;\nEND$$\nDELIMITER ;\n\ncall `Test`('[{\"id\": 1, \"number\": 10}, {\"id\": 2, \"number\": 20}]');\nselect * from test;\n\ndrop table if exists `test`;\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
3,437 | <p>We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively?</p>
<blockquote>
<p><a href="http://code.google.com/support/bin/answer.py?answer=65301&topic=10945" rel="noreferrer">Will the Maps API work over SSL (HTTPS)?</a></p>
<p>At this time, the Maps API is not
available over a secure (SSL)
connection. If you are running the
Maps API on a secure site, the browser
may warn the user about non-secure
objects on the screen.</p>
</blockquote>
<p>We have considered the following options</p>
<ol>
<li>Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map.</li>
<li>Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL.</li>
<li>Playing tricks with IFRAMEs. Sounds kludgy.</li>
<li>Proxying the calls to Google. Sounds like a lot of overhead.</li>
</ol>
<p>Are there other options, or does anyone have insight into the options that we have considered?</p>
| [
{
"answer_id": 20612,
"author": "Gary",
"author_id": 2330,
"author_profile": "https://Stackoverflow.com/users/2330",
"pm_score": 5,
"selected": true,
"text": "<script src=\"http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1\" type=\"text/javascript\"></script>\n <script src=\"https://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1&s=1\" type=\"text/javascript\"></script>\n"
},
{
"answer_id": 11800462,
"author": "Bhupendra",
"author_id": 1574777,
"author_profile": "https://Stackoverflow.com/users/1574777",
"pm_score": 1,
"selected": false,
"text": "<script src=\"https://maps.google.com/maps?file=api&v=2&hl=en&tab=wl&z=6&sensor=true&key=<?php echo $key;?>\n\" type=\"text/javascript\"></script>\n <script src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE\"\n type=\"text/javascript\"></script>\n"
},
{
"answer_id": 44341756,
"author": "Panayiotis Hiripis",
"author_id": 3342967,
"author_profile": "https://Stackoverflow.com/users/3342967",
"pm_score": 0,
"selected": false,
"text": "<script src=\"http://maps.google.com/maps/api/js?sensor=true\" type=\"text/javascript\"></script>\n <script src=\"//maps.google.com/maps/api/js?sensor=true\" type=\"text/javascript\"></script>\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/308/"
] |
3,470 | <p>I have a very simple problem which requires a very quick and simple solution in SQL Server 2005.</p>
<p>I have a table with x Columns. I want to be able to select one row from the table and then transform the columns into rows.</p>
<pre><code>TableA
Column1, Column2, Column3
</code></pre>
<p>SQL Statement to ruturn</p>
<pre><code>ResultA
Value of Column1
Value of Column2
Value of Column3
</code></pre>
<hr>
<p><strong>@Kevin:</strong> I've had a google search on the topic but alot of the example where overly complex for my example, <strong>are you able to help further?</strong></p>
<p>@Mario: The solution I am creating has 10 columns which stores the values 0 to 6 and I must work out how many columns have the value 3 or more. So I thought about creating a query to turn that into rows and then using the generated table in a subquery to say count the number of rows with Column >= 3</p>
| [
{
"answer_id": 3475,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 0,
"selected": false,
"text": "SELECT Column1 FROM table WHERE idColumn = 1\nUNION ALL\nSELECT Column2 FROM table WHERE idColumn = 1\nUNION ALL\nSELECT Column3 FROM table WHERE idColumn = 1\n"
},
{
"answer_id": 3478,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "(SELECT Column1 AS ResultA FROM TableA) as R1"
},
{
"answer_id": 3513,
"author": "Mat",
"author_id": 48,
"author_profile": "https://Stackoverflow.com/users/48",
"pm_score": 0,
"selected": false,
"text": "SELECT IDColumn, ( IF( Column1 >= 3, 1, 0 ) + IF( Column2 >= 3, 1, 0 ) + IF( Column3 >= 3, 1, 0 ) + ... [snip ] )\n AS NumberOfColumnsGreaterThanThree\nFROM TableA;\n CASE IF"
},
{
"answer_id": 3533,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 1,
"selected": false,
"text": " ''' <summary>\n ''' Pivots a data table from rows to columns\n ''' </summary>\n ''' <param name=\"dtOriginal\">The data table to be transformed</param>\n ''' <param name=\"strKeyColumn\">The name of the column that identifies each row</param>\n ''' <param name=\"strNameColumn\">The name of the column with the values to be transformed from rows to columns</param>\n ''' <param name=\"strValueColumn\">The name of the column with the values to pivot into the new columns</param>\n ''' <returns>The transformed data table</returns>\n ''' <remarks></remarks>\n Public Shared Function PivotTable(ByVal dtOriginal As DataTable, ByVal strKeyColumn As String, ByVal strNameColumn As String, ByVal strValueColumn As String) As DataTable\n Dim dtReturn As DataTable\n Dim drReturn As DataRow\n Dim strLastKey As String = String.Empty\n Dim blnFirstRow As Boolean = True\n\n ' copy the original data table and remove the name and value columns\n dtReturn = dtOriginal.Clone\n dtReturn.Columns.Remove(strNameColumn)\n dtReturn.Columns.Remove(strValueColumn)\n\n ' create a new row for the new data table\n drReturn = dtReturn.NewRow\n\n ' Fill the new data table with data from the original table\n For Each drOriginal As DataRow In dtOriginal.Rows\n\n ' Determine if a new row needs to be started\n If drOriginal(strKeyColumn).ToString <> strLastKey Then\n\n ' If this is not the first row, the previous row needs to be added to the new data table\n If Not blnFirstRow Then\n dtReturn.Rows.Add(drReturn)\n End If\n\n blnFirstRow = False\n drReturn = dtReturn.NewRow\n\n ' Add all non-pivot column values to the new row\n For Each dcOriginal As DataColumn In dtOriginal.Columns\n If dcOriginal.ColumnName <> strNameColumn AndAlso dcOriginal.ColumnName <> strValueColumn Then\n drReturn(dcOriginal.ColumnName.ToLower) = drOriginal(dcOriginal.ColumnName.ToLower)\n End If\n Next\n strLastKey = drOriginal(strKeyColumn).ToString\n End If\n\n ' Add new columns if needed and then assign the pivot values to the proper column\n If Not dtReturn.Columns.Contains(drOriginal(strNameColumn).ToString) Then\n dtReturn.Columns.Add(drOriginal(strNameColumn).ToString, drOriginal(strValueColumn).GetType)\n End If\n drReturn(drOriginal(strNameColumn).ToString) = drOriginal(strValueColumn)\n Next\n\n ' Add the final row to the new data table\n dtReturn.Rows.Add(drReturn)\n\n ' Return the transformed data table\n Return dtReturn\n End Function\n"
},
{
"answer_id": 142124,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "SELECT IDColumn, \n NumberOfColumnsGreaterThanThree = (CASE WHEN Column1 >= 3 THEN 1 ELSE 0 END) + \n (CASE WHEN Column2 >= 3 THEN 1 ELSE 0 END) + \n (Case WHEN Column3 >= 3 THEN 1 ELSE 0 END) \nFROM TableA;\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
3,486 | <p>I have control over the HttpServer but not over the ApplicationServer or the Java Applications sitting there but I need to block direct access to certain pages on those applications. Precisely, I don't want users automating access to forms issuing direct GET/POST HTTP requests to the appropriate servlet. </p>
<p>So, I decided to block users based on the value of <code>HTTP_REFERER</code>. After all, if the user is navigating inside the site, it will have an appropriate <code>HTTP_REFERER</code>. Well, that was what I thought. </p>
<p>I implemented a rewrite rule in the .htaccess file that says: </p>
<pre><code>RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC]
RewriteRule (servlet1|servlet2)/.+\?.+ - [F]
</code></pre>
<p>I expected to forbid access to users that didn't navigate the site but issue direct GET requests to the "servlet1" or "servlet2" servlets using querystrings. But my expectations ended abruptly because the regular expression <code>(servlet1|servlet2)/.+\?.+</code> didn't worked at all. </p>
<p>I was really disappointed when I changed that expression to <code>(servlet1|servlet2)/.+</code> and it worked so well that my users were blocked no matter if they navigated the site or not. </p>
<p>So, my question is: How do I can accomplish this thing of not allowing "robots" with direct access to certain pages if I have no access/privileges/time to modify the application?</p>
| [
{
"answer_id": 3827,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 3,
"selected": true,
"text": "RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC]\nRewriteCond %{QUERY_STRING} ^.+$\nRewriteRule ^(script1|script2)\\.cgi - [F]\n RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC]\nRewriteCond %{QUERY_STRING} ^.+$ [OR]\nRewriteCond %{REQUEST_METHOD} ^POST$ [OR]\nRewriteCond %{PATH_INFO} ^.+$\nRewriteRule ^(script1|script2)\\.cgi - [F]\n RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC]\nRewriteCond %{QUERY_STRING} ^.+$ [OR]\nRewriteCond %{REQUEST_METHOD} ^POST$ [OR]\nRewriteCond %{PATH_INFO} ^.+$\nRewriteRule (servlet1|servlet2)\\b - [F]\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527/"
] |
3,510 | <p>What is BODMAS and why is it useful in programming?</p>
| [
{
"answer_id": 3511,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 5,
"selected": true,
"text": "result = (((i + 4) - (a + b)) * MAGIC_NUMBER) - ANOTHER_MAGIC_NUMBER;\n result = (i + 4 - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER;\n"
},
{
"answer_id": 3518,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 3,
"selected": false,
"text": "foo * (bar + baz^2 / foo) \n"
},
{
"answer_id": 10557,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 3,
"selected": false,
"text": "(i + 4) - (a + b)\n (i + 4 - a + b)\n ((i + 4) - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER;\n (i + 4 - a - b) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER;\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
3,512 | <p>I'm using MSVE, and I have my own tiles I'm displaying in layers on top. Problem is, there's a ton of them, and they're on a network server. In certain directories, there are something on the order of 30,000+ files. Initially I called Directory.GetFiles, but once I started testing in a pseudo-real environment, it timed out.</p>
<p>What's the best way to programatically list, and iterate through, this many files?</p>
<p>Edit: My coworker suggested using the MS indexing service. Has anyone tried this approach, and (how) has it worked?</p>
| [
{
"answer_id": 3583,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 1,
"selected": false,
"text": "DIR /s/b > Files.txt\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517/"
] |
3,530 | <p>I have a <code>Rakefile</code> with a Rake task that I would normally call from the command line:</p>
<pre><code>rake blog:post Title
</code></pre>
<p>I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or <code>system</code>.</p>
<p>What's the right way to do this?</p>
| [
{
"answer_id": 3543,
"author": "titanous",
"author_id": 399,
"author_profile": "https://Stackoverflow.com/users/399",
"pm_score": 7,
"selected": true,
"text": "require 'rake'\n\ndef capture_stdout\n s = StringIO.new\n oldstdout = $stdout\n $stdout = s\n yield\n s.string\nensure\n $stdout = oldstdout\nend\n\nRake.application.rake_require 'metric_fetcher', ['../../lib/tasks']\nresults = capture_stdout {Rake.application['metric_fetcher'].invoke}\n"
},
{
"answer_id": 11520262,
"author": "knut",
"author_id": 676874,
"author_profile": "https://Stackoverflow.com/users/676874",
"pm_score": 4,
"selected": false,
"text": "invoke reenable rake blog:post Title invoke require 'rake'\ntask 'mytask', :title do |tsk, args|\n p \"called #{tsk} (#{args[:title]})\"\nend\n\n\n\nRake.application['mytask'].invoke('one')\nRake.application['mytask'].reenable\nRake.application['mytask'].invoke('two')\n mytask blog:post require reenable require 'rake'\ntask 'mytask', :title do |tsk, args|\n p \"called #{tsk} (#{args[:title]})\"\n tsk.reenable #<-- HERE\nend\n\nRake.application['mytask'].invoke('one')\nRake.application['mytask'].invoke('two')\n \"called mytask (one)\"\n\"called mytask (two)\"\n"
},
{
"answer_id": 15259172,
"author": "Kelvin",
"author_id": 498594,
"author_profile": "https://Stackoverflow.com/users/498594",
"pm_score": 5,
"selected": false,
"text": "require 'rake'\napp = Rake.application\napp.init\n# do this as many times as needed\napp.add_import 'some/other/file.rake'\n# this loads the Rakefile and other imports\napp.load_rakefile\n\napp['sometask'].invoke\n reenable"
},
{
"answer_id": 41839883,
"author": "Dorian",
"author_id": 407213,
"author_profile": "https://Stackoverflow.com/users/407213",
"pm_score": 2,
"selected": false,
"text": "rails runner script.rb def rake(*tasks)\n tasks.each do |task|\n Rake.application[task].tap(&:invoke).tap(&:reenable)\n end\nend\n\nrake('db:migrate', 'cache:clear', 'cache:warmup')\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1388162/"
] |
3,567 | <p>In SQL Server how do you query a database to bring back all the tables that have a field of a specific name?</p>
| [
{
"answer_id": 3574,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "SELECT Table_Name\nFROM Information_Schema.Columns\nWHERE Column_Name = 'YourFieldName'\n"
},
{
"answer_id": 3575,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT object_name(id)\nFROM syscolumns\nWHERE name = 'FIELDNAME'\n"
},
{
"answer_id": 3578,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 4,
"selected": true,
"text": "Column_Name SELECT Table_Name\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE Column_Name = 'Desired_Column_Name'\nGROUP BY Table_Name\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
3,585 | <p>I want to create my Rails application with MySQL, because I like it so much. How can I do that in the latest version of Rails instead of the default SQLite?</p>
| [
{
"answer_id": 3586,
"author": "Daniel Broekman",
"author_id": 124,
"author_profile": "https://Stackoverflow.com/users/124",
"pm_score": 8,
"selected": false,
"text": "rails ProjectName\n rails new ProjectName -d mysql\n"
},
{
"answer_id": 3588,
"author": "James Avery",
"author_id": 537,
"author_profile": "https://Stackoverflow.com/users/537",
"pm_score": 3,
"selected": false,
"text": "rails -d mysql myapp\n"
},
{
"answer_id": 3601,
"author": "Michiel de Mare",
"author_id": 136,
"author_profile": "https://Stackoverflow.com/users/136",
"pm_score": 8,
"selected": true,
"text": "config/database.yml mysql development:\n adapter: mysql2\n database: db_name_dev\n username: koploper\n password:\n host: localhost\n socket: /tmp/mysql.sock\n"
},
{
"answer_id": 792421,
"author": "huacnlee",
"author_id": 83558,
"author_profile": "https://Stackoverflow.com/users/83558",
"pm_score": 4,
"selected": false,
"text": "rails -d mysql ProjectName\n"
},
{
"answer_id": 4438499,
"author": "Robbie Done",
"author_id": 541839,
"author_profile": "https://Stackoverflow.com/users/541839",
"pm_score": 6,
"selected": false,
"text": "$ rails new projectname -d mysql\n"
},
{
"answer_id": 6046965,
"author": "andy318",
"author_id": 204180,
"author_profile": "https://Stackoverflow.com/users/204180",
"pm_score": 3,
"selected": false,
"text": "$rails new projectname --database=mysql\n"
},
{
"answer_id": 6936105,
"author": "Coder",
"author_id": 876011,
"author_profile": "https://Stackoverflow.com/users/876011",
"pm_score": 4,
"selected": false,
"text": "rails new your_project_name -d mysql\n rails new -d mysql your_project_name\n rails -v\n"
},
{
"answer_id": 8183962,
"author": "George Bellos",
"author_id": 89724,
"author_profile": "https://Stackoverflow.com/users/89724",
"pm_score": 3,
"selected": false,
"text": "$ rails --help \n $ rails new APP_PATH[options]\n $ rails new project_name -d mysql\n $ rails new project_name -d postgresql\n"
},
{
"answer_id": 9921786,
"author": "Marthinus A. Botha",
"author_id": 1300257,
"author_profile": "https://Stackoverflow.com/users/1300257",
"pm_score": 3,
"selected": false,
"text": " rails -D mysql project_name (less than version 3)\n\n rails new project_name -D mysql (version 3 and up)\n --database"
},
{
"answer_id": 11138212,
"author": "vijay chouhan",
"author_id": 2079997,
"author_profile": "https://Stackoverflow.com/users/2079997",
"pm_score": 4,
"selected": false,
"text": "rails new <project_name> -d mysql\n rails new projectname\n development:\n adapter: mysql2\n database: db_name_name\n username: root\n password:\n host: localhost\n socket: /tmp/mysql.sock\n"
},
{
"answer_id": 14438074,
"author": "Abhinav",
"author_id": 1996835,
"author_profile": "https://Stackoverflow.com/users/1996835",
"pm_score": 5,
"selected": false,
"text": "rails new <project_name> -d mysql\n"
},
{
"answer_id": 14440100,
"author": "Dipali Nagrale",
"author_id": 1645570,
"author_profile": "https://Stackoverflow.com/users/1645570",
"pm_score": 4,
"selected": false,
"text": "rails new AppName -d mysql\n"
},
{
"answer_id": 24365127,
"author": "Drake Mandin",
"author_id": 3767282,
"author_profile": "https://Stackoverflow.com/users/3767282",
"pm_score": 5,
"selected": false,
"text": "$rails new <your_app_name> -d mysql"
},
{
"answer_id": 42243150,
"author": "Amarpreet Jethra",
"author_id": 6375692,
"author_profile": "https://Stackoverflow.com/users/6375692",
"pm_score": 3,
"selected": false,
"text": "rails new YOURAPPNAME -d mysql\n"
},
{
"answer_id": 46322499,
"author": "Shabbir",
"author_id": 8572496,
"author_profile": "https://Stackoverflow.com/users/8572496",
"pm_score": 2,
"selected": false,
"text": "gem install mysql2\n rails new app-name -d mysql\n"
},
{
"answer_id": 48695295,
"author": "Riccardo",
"author_id": 362420,
"author_profile": "https://Stackoverflow.com/users/362420",
"pm_score": 2,
"selected": false,
"text": "rails new your_new_project_name -d mysql\n # On Gemfile:\ngem 'mysql2', '>= 0.3.18', '< 0.5' # copied from a new project for rails 5.1 :)\ngem 'activerecord-mysql-adapter' # needed for mysql..\n\n# On Dockerfile or on CLI:\nsudo apt-get install -y mysql-client libmysqlclient-dev \n"
},
{
"answer_id": 52131248,
"author": "Dinesh Vaitage",
"author_id": 5710925,
"author_profile": "https://Stackoverflow.com/users/5710925",
"pm_score": 0,
"selected": false,
"text": "rails new <appname> --api -d mysql\n\n\n adapter: mysql2\n encoding: utf8\n pool: 5\n username: root\n password: \n socket: /var/run/mysqld/mysqld.sock\n"
},
{
"answer_id": 54820357,
"author": "artamonovdev",
"author_id": 5754223,
"author_profile": "https://Stackoverflow.com/users/5754223",
"pm_score": 0,
"selected": false,
"text": "# MySQL. Versions 5.1.10 and up are supported.\n#\n# Install the MySQL driver\n# gem install mysql2\n#\n# Ensure the MySQL gem is defined in your Gemfile\n# gem 'mysql2'\n#\n# And be sure to use new-style password hashing:\n# https://dev.mysql.com/doc/refman/5.7/en/password-hashing.html\n#\ndefault: &default\n adapter: mysql2\n encoding: utf8\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n host: localhost\n database: database_name\n username: username\n password: secret\n\ndevelopment:\n <<: *default\n\n# Warning: The database defined as \"test\" will be erased and\n# re-generated from your development database when you run \"rake\".\n# Do not set this db to the same as development or production.\ntest:\n <<: *default\n\n# As with config/secrets.yml, you never want to store sensitive information,\n# like your database password, in your source code. If your source code is\n# ever seen by anyone, they now have access to your database.\n#\n# Instead, provide the password as a unix environment variable when you boot\n# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database\n# for a full rundown on how to provide these environment variables in a\n# production deployment.\n#\n# On Heroku and other platform providers, you may have a full connection URL\n# available as an environment variable. For example:\n#\n# DATABASE_URL=\"mysql2://myuser:mypass@localhost/somedatabase\"\n#\n# You can use this database configuration with:\n#\n# production:\n# url: <%= ENV['DATABASE_URL'] %>\n#\nproduction:\n <<: *default\n # Use mysql as the database for Active Record\ngem 'mysql2', '>= 0.4.4', '< 0.6.0'\n"
},
{
"answer_id": 61106989,
"author": "Muhammad Elbadawy",
"author_id": 8111491,
"author_profile": "https://Stackoverflow.com/users/8111491",
"pm_score": 0,
"selected": false,
"text": "sudo apt-get install mysql-client libmysqlclient-dev\n gem 'mysql2', '~> 0.3.16'\n bundle install\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124/"
] |
3,589 | <p>I need to create a backup of a SQL Server 2005 Database that's only the structure...no records, just the schema. Is there any way to do this?</p>
<p>EDIT: I'm trying to create a backup file to use with old processes, so a script wouldn't work for my purposes, sorry</p>
| [
{
"answer_id": 73465453,
"author": "Daniel Brink",
"author_id": 141443,
"author_profile": "https://Stackoverflow.com/users/141443",
"pm_score": 0,
"selected": false,
"text": "dbcc clonedatabase(Demo, Demo_Clone) with verify_clonedb;\nalter database [Demo_Clone] set read_write;\nbackup database [Demo_Clone] to disk = N'C:\\temp\\Demo_SchemaOnly_20220821.bak';\ndrop database [Demo_Clone];\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44/"
] |
3,607 | <p>I've got TotroiseSVN installed and have a majority of my repositories checking in and out from C:\subversion\ <em>and a couple checking in and out from a network share (I forgot about this when I originally posted this question)</em>.</p>
<p>This means that I don't have a "subversion" server per-se.</p>
<p>How do I integrate TortoiseSVN and Fogbugz?</p>
<p><em>Edit: inserted italics</em></p>
| [
{
"answer_id": 370131,
"author": "Andy Madge",
"author_id": 46433,
"author_profile": "https://Stackoverflow.com/users/46433",
"pm_score": 5,
"selected": true,
"text": "svnlook.exe svnlook.exe bugtraq:label BugzID:\nbugtraq:message BugzID: %BUGID%\nbugtraq:number true\nbugtraq:url http://[your fogbugz URL here]/default.asp?%BUGID%\nbugtraq:warnifnoissue false\n <repository-path> <revision>\n <affected-files> <depth> <messagefile> <revision> <error> <working-copy-path>\n rem @echo off\nrem SubVersion -> FogBugz post-commit hook file\nrem Put this into the Hooks directory in your subversion repository\nrem along with the logBugDataSVN.vbs file\n\nrem TSVN calls this with args <PATH> <DEPTH> <MESSAGEFILE> <REVISION> <ERROR> <CWD>\nrem The ones we're interested in are <REVISION> and <CWD> which are %4 and %6\n\nrem YOU NEED TO EDIT THE LINE WHICH SETS RepoRoot TO POINT AT THE DIRECTORY \nrem THAT CONTAINS YOUR REPOSITORIES AND ALSO YOU MUST SET THE HOOKS DIRECTORY\n\nsetlocal\n\nrem debugging\nrem echo %1 %2 %3 %4 %5 %6 > c:\\temp\\test.txt\n\nrem Set Hooks directory location (no trailing slash)\nset HooksDir=\\\\myserver\\svn\\hooks\n\nrem Set Repo Root location (ie. the directory containing all the repos)\nrem (no trailing slash)\nset RepoRoot=\\\\myserver\\svn\n\nrem Build full repo location\nset Repo=%RepoRoot%\\%~n6\n\nrem debugging\nrem echo %Repo% >> c:\\temp\\test.txt\n\nrem Grab the last two digits of the revision number\nrem and append them to the log of svn changes\nrem to avoid simultaneous commit scenarios causing overwrites\nset ChangeFileSuffix=%~4\nset LogSvnChangeFile=svn%ChangeFileSuffix:~-2,2%.txt\n\nset LogBugDataScript=logBugDataSVN.vbs\nset ScriptCommand=cscript\n\nrem Could remove the need for svnlook on the client since TSVN \nrem provides as parameters the info we need to call the script.\nrem However, it's in a slightly different format than the script is expecting\nrem for parsing, therefore we would have to amend the script too, so I won't bother.\nrem @echo on\nsvnlook changed -r %4 %Repo% > %temp%\\%LogSvnChangeFile%\nsvnlook log -r %4 %Repo% | %ScriptCommand% %HooksDir%\\%LogBugDataScript% %4 %temp%\\%LogSvnChangeFile% %~n6\n\ndel %temp%\\%LogSvnChangeFile%\nendlocal\n \\\\myserver\\svn\\ \\\\myserver\\svn\\hooks\\ .safe post-commit-tsvn.bat C:\\Projects \\\\myserver\\svn\\hooks\\post-commit-tsvn.bat"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] |
3,611 | <p>I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have:</p>
<pre><code><?php
if ( !empty($_FILES['file']['tmp_name']) ) {
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
header('Location: http://www.mywebsite.com/dump/');
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Dump Upload</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000000" />
Select the File:<br /><input type="file" name="file" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
</code></pre>
<p>I'm getting these errors:</p>
<blockquote>
<p>Warning: move_uploaded_file(./test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3</p>
<p>Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './test.txt' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3</p>
<p>Warning: Cannot modify header information - headers already sent by (output started at E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php:3) in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 4</p>
</blockquote>
<p>PHP version 4.4.7
Running IIS on a Windows box. This particular file/folder has 777 permissions.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 3618,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": true,
"text": "E:\\inetpub\\vhosts\\mywebsite.com\\httpdocs\\dump\\\nC:\\WINDOWS\\Temp\\\n"
},
{
"answer_id": 4618,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 2,
"selected": false,
"text": "<?php\n\nif ( !empty($_FILES['file']) ) {\n $from = $_FILES['file']['tmp_name'];\n $to = dirname(__FILE__).'/'.$_FILES['file']['name'];\n\n if( move_uploaded_file($from, $to) ){\n echo 'Success'; \n } else {\n echo 'Failure'; \n }\n\n header('Location: http://www.mywebsite.com/dump/');\n exit;\n}\n?>\n"
},
{
"answer_id": 365455,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 4,
"selected": false,
"text": "move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);\n $_FILES['file']['name'] ../../../../boot.ini basename($_FILES['file']['name'])"
},
{
"answer_id": 13416957,
"author": "Soumya Roy",
"author_id": 1829575,
"author_profile": "https://Stackoverflow.com/users/1829575",
"pm_score": 0,
"selected": false,
"text": "777 <?php\n move_uploaded_file($_FILES['file']['tmp_name'],\"image/\".$_FILES['file']['name']);\n?>\n"
},
{
"answer_id": 59200854,
"author": "Rod Fuller",
"author_id": 12487347,
"author_profile": "https://Stackoverflow.com/users/12487347",
"pm_score": 0,
"selected": false,
"text": "{['DOCUMENT_ROOT'] + 'path to folder'"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402/"
] |
3,625 | <p>I can't seem to find Developer Express' version of the <code>LinkButton</code>. (The Windows Forms linkbutton, not the <code>ASP.NET</code> linkbutton.) <code>HyperLinkEdit</code> doesn't seem to be what I'm looking for since it looks like a TextEdit/TextBox.</p>
<p>Anyone know what their version of it is? I'm using the latest DevX controls: 8.2.1.</p>
| [
{
"answer_id": 102129,
"author": "Josh Kodroff",
"author_id": 549,
"author_profile": "https://Stackoverflow.com/users/549",
"pm_score": 3,
"selected": true,
"text": " control.BorderStyle = BorderStyles.NoBorder;\n control.Properties.Appearance.BackColor = Color.Transparent;\n control.Properties.AppearanceFocused.BackColor = Color.Transparent;\n control.Properties.ReadOnly = true;\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] |
3,654 | <p>When developing a new web based application which version of html should you aim for?</p>
<p>EDIT:</p>
<p>cool I was just attempting to get a feel from others I tend to use XHTML 1.0 Strict in my own work and Transitional when others are involved in the content creation.</p>
<p>I marked the first XHTML 1.0 Transitional post as the 'correct answer' but believe strongly that all the answers given at that point where equally valid.</p>
| [
{
"answer_id": 20487,
"author": "Chris",
"author_id": 2134,
"author_profile": "https://Stackoverflow.com/users/2134",
"pm_score": 2,
"selected": false,
"text": "Content-type: application/xhtml+xml Content-type: text/html"
},
{
"answer_id": 194049,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "text/html <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"> <!DOCTYPE html>\n"
},
{
"answer_id": 194117,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\"/>\n <title></title>\n </head>\n <body>\n <p>Line1<br/>Line2</p>\n <p><img src=\"\" alt=\"blank\"/></p>\n <p><input type=\"text\"/></p>\n <p><embed type=\"application/x-something\" src=\"\"/></p>\n </body>\n</html>\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269/"
] |
3,682 | <p>I have a MySQL table with approximately 3000 rows per user. One of the columns is a datetime field, which is mutable, so the rows aren't in chronological order.</p>
<p>I'd like to visualize the time distribution in a chart, so I need a number of individual datapoints. 20 datapoints would be enough.</p>
<p>I could do this:</p>
<pre><code>select timefield from entries where uid = ? order by timefield;
</code></pre>
<p>and look at every 150th row.</p>
<p>Or I could do 20 separate queries and use <code>limit 1</code> and <code>offset</code>. </p>
<p>But there must be a more efficient solution...</p>
| [
{
"answer_id": 3691,
"author": "Michal Sznajder",
"author_id": 501,
"author_profile": "https://Stackoverflow.com/users/501",
"pm_score": 1,
"selected": false,
"text": "select @rownum:=@rownum+1 rownum, entries.* \nfrom (select @rownum:=0) r, entries \nwhere uid = ? and rownum % 150 = 0\n"
},
{
"answer_id": 3775,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 0,
"selected": false,
"text": "select timefield from entries\nwhere uid = ? and id % 150 = 0 order by timefield;\n"
},
{
"answer_id": 30600,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 0,
"selected": false,
"text": "select timefield\nfrom entries\nwhere rand() = .01 --will return 1% of rows adjust as needed.\n"
},
{
"answer_id": 155901,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "SELECT * FROM (\n SELECT @rownum:=@rownum+1 AS rownum, e.*\n FROM (SELECT @rownum := 0) r, entries e) AS e2\nWHERE uid = ? AND rownum % 150 = 0;\n"
},
{
"answer_id": 155951,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "SELECT DATEADD(day, DATEDIFF(day, 0, timefield), 0) AS bucket -- choose an appropriate granularity (days used here)\n ,COUNT(*)\nFROM entries\nWHERE uid = ?\nGROUP BY DATEADD(day, DATEDIFF(day, 0, timefield), 0)\nORDER BY DATEADD(day, DATEDIFF(day, 0, timefield), 0)\n SELECT uid\n ,bucket\n ,COUNT(*) AS measure\nFROM (\n SELECT uid\n ,DATEADD(day, DATEDIFF(day, 0, timefield), 0) AS bucket\n FROM entries\n) AS buckets\nGROUP BY uid\n ,bucket\nORDER BY uid\n ,bucket\n"
},
{
"answer_id": 22067305,
"author": "Michiel de Mare",
"author_id": 136,
"author_profile": "https://Stackoverflow.com/users/136",
"pm_score": 0,
"selected": false,
"text": "SELECT percentile_disc(0.95) \nWITHIN GROUP (ORDER BY response_time) \nFROM pageviews;\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136/"
] |
3,713 | <p>I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.</p>
<p>Is it possible to call a method I created in ASP with JavaScript's click event?</p>
| [
{
"answer_id": 3752,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 4,
"selected": false,
"text": "Ajax.Utility.RegisterTypeForAjax(GetType(YOURPAGECLASSNAME))\n <Ajax.AjaxMethod()> _\nPublic Function Get5() AS Integer\n Return 5\nEnd Function\n PageClassName.Get5(javascriptCallbackFunction);\n"
},
{
"answer_id": 3777,
"author": "Adhip Gupta",
"author_id": 384,
"author_profile": "https://Stackoverflow.com/users/384",
"pm_score": 8,
"selected": true,
"text": "public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}\n public void RaisePostBackEvent(string eventArgument) { }\n var pageId = '<%= Page.ClientID %>';\n__doPostBack(pageId, argumentString);\n"
},
{
"answer_id": 8096,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 6,
"selected": false,
"text": "__doPostBack() <div style=\"display: none;\">\n <asp:Button runat=\"server\" ... OnClick=\"ButtonClickHandlerMethod\" />\n</div>\n var button = document.getElementById(/* button client id */);\n\nbutton.click();\n"
},
{
"answer_id": 2802366,
"author": "Ananda",
"author_id": 328911,
"author_profile": "https://Stackoverflow.com/users/328911",
"pm_score": -1,
"selected": false,
"text": "<div style=\"display: none;\"> \n <asp:Button runat=\"server\" ... OnClick=\"ButtonClickHandlerMethod\" /> \n</div> \n var button = document.getElementByID(/* button client id */); \n\nbutton.Click(); \n"
},
{
"answer_id": 3577148,
"author": "Ricardo stands with Ukraine",
"author_id": 364568,
"author_profile": "https://Stackoverflow.com/users/364568",
"pm_score": 1,
"selected": false,
"text": "<asp:Button ID=\"btnJavascript\" runat=\"server\" UseSubmitBehavior=\"false\" />\n"
},
{
"answer_id": 4977299,
"author": "David",
"author_id": 365789,
"author_profile": "https://Stackoverflow.com/users/365789",
"pm_score": 0,
"selected": false,
"text": "ClientScript.GetPostBackEventReference(this, \"\");\n"
},
{
"answer_id": 6354219,
"author": "kakani santosh",
"author_id": 799094,
"author_profile": "https://Stackoverflow.com/users/799094",
"pm_score": 0,
"selected": false,
"text": "PageMethods.Your C# method Name"
},
{
"answer_id": 7040311,
"author": "Behnam Esmaili",
"author_id": 891794,
"author_profile": "https://Stackoverflow.com/users/891794",
"pm_score": 2,
"selected": false,
"text": "//<![CDATA[\nvar theForm = document.forms['form1'];\nif (!theForm) {\n theForm = document.form1;\n}\nfunction __doPostBack(eventTarget, eventArgument) {\n if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\n theForm.__EVENTTARGET.value = eventTarget;\n theForm.__EVENTARGUMENT.value = eventArgument;\n theForm.submit();\n }\n}\n//]]>\n"
},
{
"answer_id": 11013093,
"author": "Despertar",
"author_id": 1160036,
"author_profile": "https://Stackoverflow.com/users/1160036",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\nvar xmlhttp = new XMLHttpRequest(); // Create object that will make the request\nxmlhttp.open(\"GET\", \"http://example.org/api/service\", \"true\"); // configure object (method, URL, async)\nxmlhttp.send(); // Send request\n\nxmlhttp.onstatereadychange = function() { // Register a function to run when the state changes, if the request has finished and the stats code is 200 (OK). Write result to <p>\n if (xmlhttp.readyState == 4 && xmlhttp.statsCode == 200) {\n document.getElementById(\"resultText\").innerHTML = xmlhttp.responseText;\n }\n};\n</script>\n public class DataController : ApiController\n{\n public HttpResponseMessage<string[]> Get()\n {\n HttpResponseMessage<string[]> response = new HttpResponseMessage<string[]>(\n Repository.Get(true),\n new MediaTypeHeaderValue(\"application/json\")\n );\n\n return response;\n }\n}\n void Application_Start(object sender, EventArgs e)\n{\n RouteTable.Routes.MapHttpRoute(\"Service\", \"api/{controller}/{id}\");\n}\n"
},
{
"answer_id": 15403629,
"author": "Robin",
"author_id": 2042366,
"author_profile": "https://Stackoverflow.com/users/2042366",
"pm_score": 0,
"selected": false,
"text": "if(!ClientScript.IsStartupScriptRegistered(\"window\"))\n{\n Page.ClientScript.RegisterStartupScript(this.GetType(), \"window\", \"pop();\", true);\n}\n Response.Write(\"<script>alert('Hello World');</script>\");\n"
},
{
"answer_id": 19113786,
"author": "The Hungry Dictator",
"author_id": 2763709,
"author_profile": "https://Stackoverflow.com/users/2763709",
"pm_score": 0,
"selected": false,
"text": "document.getElementById('<%=btnName.ClientID%>').click()\n"
},
{
"answer_id": 19939808,
"author": "davrob01",
"author_id": 1839956,
"author_profile": "https://Stackoverflow.com/users/1839956",
"pm_score": 2,
"selected": false,
"text": "public void RaisePostBackEvent(string _arg)\n{\n UserControlID.RaisePostBackEvent(_arg);\n}\n public void RaisePostBackEvent(string _arg)\n{\n UserControlID.method1();\n UserControlID.method2();\n}\n"
},
{
"answer_id": 23781882,
"author": "SRV",
"author_id": 3660574,
"author_profile": "https://Stackoverflow.com/users/3660574",
"pm_score": 3,
"selected": false,
"text": "<script src=\"http://code.jquery.com/jquery-3.3.1.js\" />\n<script language=\"javascript\" type=\"text/javascript\">\n\n function GetCompanies() {\n $(\"#UpdatePanel\").html(\"<div style='text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>\");\n $.ajax({\n type: \"POST\",\n url: \"Default.aspx/GetCompanies\",\n data: \"{}\",\n dataType: \"json\",\n contentType: \"application/json; charset=utf-8\",\n success: OnSuccess,\n error: OnError\n });\n }\n\n function OnSuccess(data) {\n var TableContent = \"<table border='0'>\" +\n \"<tr>\" +\n \"<td>Rank</td>\" +\n \"<td>Company Name</td>\" +\n \"<td>Revenue</td>\" +\n \"<td>Industry</td>\" +\n \"</tr>\";\n for (var i = 0; i < data.d.length; i++) {\n TableContent += \"<tr>\" +\n \"<td>\"+ data.d[i].Rank +\"</td>\" +\n \"<td>\"+data.d[i].CompanyName+\"</td>\" +\n \"<td>\"+data.d[i].Revenue+\"</td>\" +\n \"<td>\"+data.d[i].Industry+\"</td>\" +\n \"</tr>\";\n }\n TableContent += \"</table>\";\n\n $(\"#UpdatePanel\").html(TableContent);\n }\n\n function OnError(data) {\n\n }\n</script>\n [WebMethod]\n[ScriptMethod(ResponseFormat= ResponseFormat.Json)]\npublic static List<TopCompany> GetCompanies()\n{\n System.Threading.Thread.Sleep(5000);\n List<TopCompany> allCompany = new List<TopCompany>();\n using (MyDatabaseEntities dc = new MyDatabaseEntities())\n {\n allCompany = dc.TopCompanies.ToList();\n }\n return allCompany;\n}\n"
},
{
"answer_id": 27164392,
"author": "KDJ",
"author_id": 3889892,
"author_profile": "https://Stackoverflow.com/users/3889892",
"pm_score": 1,
"selected": false,
"text": "var button = document.getElementById(/* Button client id */);\n\nbutton.click();\n var button = document.getElementById('<%=formID.ClientID%>');\n"
},
{
"answer_id": 35812420,
"author": "Sumit Kumar",
"author_id": 6021773,
"author_profile": "https://Stackoverflow.com/users/6021773",
"pm_score": 0,
"selected": false,
"text": "<%= Page.ClientScript.GetPostBackEventReference(ddlVoucherType, String.Empty) %>;\n"
},
{
"answer_id": 40970986,
"author": "6134548",
"author_id": 6134548,
"author_profile": "https://Stackoverflow.com/users/6134548",
"pm_score": 0,
"selected": false,
"text": "onmouseup() onclick() OnClick()"
},
{
"answer_id": 42817465,
"author": "Bengi Besçeli",
"author_id": 1136253,
"author_profile": "https://Stackoverflow.com/users/1136253",
"pm_score": 0,
"selected": false,
"text": "window.location = \"Page.aspx?key=1\";\n protected void Page_Load(object sender, EventArgs e)\n{\n if (Request.QueryString[\"key\"] != null)\n {\n string key= Request.QueryString[\"key\"];\n if (key==\"1\")\n {\n // Some code\n }\n }\n}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557/"
] |
3,725 | <p>I'm writing an application that is basically just a preferences dialog, much like the tree-view preferences dialog that Visual Studio itself uses. The function of the application is simply a pass-through for data from a serial device to a file. It performs many, many transformations on the data before writing it to the file, so the GUI for the application is simply all the settings that dictate what those transformations should be.</p>
<p>What's the best way to go about designing/coding a tree-view preferences dialog? The way I've been going about it is building the main window with a docked tree control on the left. Then I have been creating container controls that correspond to each node of the tree. When a node is selected, the app brings that node's corresponding container control to the front, moves it to the right position, and maximizes it in the main window. This seems really, really clunky while designing it. It basically means I have tons of container controls beyond the edge of the main window during design time that I have to keep scrolling the main window over to in order to work with them. I don't know if this totally makes sense the way I'm writing this, but maybe this visual for what I'm talking about will make more sense:</p>
<p><img src="https://i.stack.imgur.com/bVRJB.png" alt="form design"></p>
<p>Basically I have to work with this huge form, with container controls all over the place, and then do a bunch of run-time reformatting to make it all work. This seems like a <em>lot</em> of extra work. Am I doing this in a totally stupid way? Is there some "obvious" easier way of doing this that I'm missing?</p>
| [
{
"answer_id": 3776,
"author": "xyz",
"author_id": 82,
"author_profile": "https://Stackoverflow.com/users/82",
"pm_score": 5,
"selected": true,
"text": "this.TopLevel = false;\nthis.FormBorderStyle = FormBorderStyle.None;\nthis.Dock = DockStyle.Fill;\n SplitContainer TreeView Hide/Show BringToFront/SendToBack SeparateForm f = new SeparateForm(); \nMainFormSplitContainer.Panel2.Controls.Add(f); \nf.Show();\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/551/"
] |
3,739 | <p>I have an unusual situation in which I need a SharePoint timer job to both have local administrator windows privileges and to have <code>SHAREPOINT\System</code> SharePoint privileges.</p>
<p>I can get the windows privileges by simply configuring the timer service to use an account which is a member of local administrators. I understand that this is not a good solution since it gives SharePoint timer service more rights then it is supposed to have. But it at least allows my SharePoint timer job to run <code>stsadm</code>.</p>
<p>Another problem with running the timer service under local administrator is that this user won't necessarily have <code>SHAREPOINT\System</code> SharePoint privileges which I also need for this SharePoint job. It turns out that <code>SPSecurity.RunWithElevatedPrivileges</code> won't work in this case. Reflector shows that <code>RunWithElevatedPrivileges</code> checks if the current process is <code>owstimer</code> (the service process which runs SharePoint jobs) and performs no elevation this is the case (the rational here, I guess, is that the timer service is supposed to run under <code>NT AUTHORITY\NetworkService</code> windows account which which has <code>SHAREPOINT\System</code> SharePoint privileges, and thus there's no need to elevate privileges for a timer job).</p>
<p>The only possible solution here seems to be to run the timer service under its usual NetworkService windows account and to run stsadm as a local administrator by storing the administrator credentials somewhere and passing them to System.Diagnostics.Process.Run() trough the StarInfo's Username, domain and password.</p>
<p>It seems everything should work now, but here is another problem I'm stuck with at the moment. Stsamd is failing with the following error popup (!) (Winternals filemon shows that stsadm is running under the administrator in this case):</p>
<p><code>The application failed to initialize properly (0x0c0000142).</code> <br />
<code>Click OK to terminate the application.</code></p>
<p>Event Viewer registers nothing except the popup.</p>
<p>The local administrator user is my account and when I just run <code>stsadm</code> interactively under this account everything is ok. It also works fine when I configure the timer service to run under this account.</p>
<p>Any suggestions are appreciated :)</p>
| [
{
"answer_id": 3741,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 1,
"selected": false,
"text": "SPUserToken sut = thisSite.RootWeb.AllUsers[\"SHAREPOINT\\SYSTEM\"].UserToken;\n\nusing (SPSite syssite = new SPSite(thisSite.Url,sut)\n{\n // Do what you have to do\n}\n"
},
{
"answer_id": 4566,
"author": "axk",
"author_id": 578,
"author_profile": "https://Stackoverflow.com/users/578",
"pm_score": 0,
"selected": false,
"text": "internal class ExternalProcess\n{\n public static void run(String executablePath, String workingDirectory, String programArguments, String domain, String userName,\n String password, out Int32 exitCode, out String output)\n {\n Process process = new Process();\n\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.RedirectStandardOutput = true;\n\n StringBuilder outputString = new StringBuilder();\n Object synchObj = new object();\n\n DataReceivedEventHandler outputAppender =\n delegate(Object sender, DataReceivedEventArgs args)\n {\n lock (synchObj)\n {\n outputString.AppendLine(args.Data);\n }\n };\n\n process.OutputDataReceived += outputAppender;\n process.ErrorDataReceived += outputAppender;\n\n process.StartInfo.FileName = @\"C:\\AppRunner.exe\";\n process.StartInfo.WorkingDirectory = workingDirectory;\n process.StartInfo.Arguments = @\"\"\"\" + executablePath + @\"\"\" \" + programArguments;\n\n process.StartInfo.UserName = userName;\n process.StartInfo.Domain = domain; \n SecureString passwordString = new SecureString();\n\n foreach (Char c in password)\n {\n passwordString.AppendChar(c);\n }\n\n process.StartInfo.Password = passwordString;\n\n process.Start();\n\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n process.WaitForExit();\n\n exitCode = process.ExitCode;\n output = outputString.ToString();\n }\n}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
3,793 | <p>What's the best way to get the contents of the mixed <code>body</code> element in the code below? The element might contain either XHTML or text, but I just want its contents in string form. The <code>XmlElement</code> type has the <code>InnerXml</code> property which is exactly what I'm after.</p>
<p>The code as written <em>almost</em> does what I want, but includes the surrounding <code><body></code>...<code></body></code> element, which I don't want.</p>
<pre class="lang-js prettyprint-override"><code>XDocument doc = XDocument.Load(new StreamReader(s));
var templates = from t in doc.Descendants("template")
where t.Attribute("name").Value == templateName
select new
{
Subject = t.Element("subject").Value,
Body = t.Element("body").ToString()
};
</code></pre>
| [
{
"answer_id": 3896,
"author": "Mike Powell",
"author_id": 205,
"author_profile": "https://Stackoverflow.com/users/205",
"pm_score": 3,
"selected": false,
"text": "Body = t.Element(\"body\").Nodes().Aggregate(\"\", (b, node) => b += node.ToString());\n"
},
{
"answer_id": 16882,
"author": "Vin",
"author_id": 1747,
"author_profile": "https://Stackoverflow.com/users/1747",
"pm_score": 4,
"selected": false,
"text": "public static string InnerXml(this XElement element)\n{\n StringBuilder innerXml = new StringBuilder();\n\n foreach (XNode node in element.Nodes())\n {\n // append node's xml string to innerXml\n innerXml.Append(node.ToString());\n }\n\n return innerXml.ToString();\n}\n public static string InnerXml(this XElement element)\n{\n StringBuilder innerXml = new StringBuilder();\n doc.Nodes().ToList().ForEach( node => innerXml.Append(node.ToString()));\n\n return innerXml.ToString();\n}\n element.Nodes() element.Elements() element.Nodes() XText XAttribute XElement"
},
{
"answer_id": 659159,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "t.Element( \"body\" ).Nodes()\n .Aggregate( \"\", ( b, node ) => b + node.ToString() );\n string.Join( \"\", t.Element.Nodes()\n .Select( n => n.ToString() ).ToArray() );\n"
},
{
"answer_id": 659264,
"author": "Instance Hunter",
"author_id": 65393,
"author_profile": "https://Stackoverflow.com/users/65393",
"pm_score": 6,
"selected": false,
"text": "Dim xReader = x.CreateReader\nxReader.MoveToContent\nxReader.ReadInnerXml\n"
},
{
"answer_id": 1655006,
"author": "Marcin Kosieradzki",
"author_id": 200228,
"author_profile": "https://Stackoverflow.com/users/200228",
"pm_score": 3,
"selected": false,
"text": "String.Concat(node.Nodes().Select(x => x.ToString()).ToArray())\n"
},
{
"answer_id": 1704579,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "<hint>\n <strong>Thinking of using a fake address?</strong>\n <br />\n Please don't. If we can't verify your address we might just\n have to reject your application.\n</hint>\n XmlDocument XDocument XElement var reader = parent.CreateReader();\nreader.MoveToContent();\n\nreturn reader.ReadInnerXml();\n return parent.Nodes().Aggregate(\"\", (b, node) => b += node.ToString());\n StringBuilder sb = new StringBuilder();\n\nforeach(var node in parent.Nodes()) {\n sb.Append(node.ToString());\n}\n\nreturn sb.ToString();\n return String.Join(\"\", parent.Nodes().Select(x => x.ToString()).ToArray());\n return String.Concat(parent.Nodes().Select(x => x.ToString()).ToArray());\n CreateReader StringBuilder CreateReader Join Concat"
},
{
"answer_id": 2460802,
"author": "Martin R-L",
"author_id": 46343,
"author_profile": "https://Stackoverflow.com/users/46343",
"pm_score": 2,
"selected": false,
"text": "InnerXml public static string InnerXml(this XElement thiz)\n{\n return thiz.Nodes().Aggregate( string.Empty, ( element, node ) => element += node.ToString() );\n}\n var innerXml = myXElement.InnerXml();\n"
},
{
"answer_id": 3474630,
"author": "Shivraj",
"author_id": 419273,
"author_profile": "https://Stackoverflow.com/users/419273",
"pm_score": -1,
"selected": false,
"text": "public static string InnerXml(this XElement xElement)\n{\n //remove start tag\n string innerXml = xElement.ToString().Trim().Replace(string.Format(\"<{0}>\", xElement.Name), \"\");\n ////remove end tag\n innerXml = innerXml.Trim().Replace(string.Format(\"</{0}>\", xElement.Name), \"\");\n return innerXml.Trim();\n}\n"
},
{
"answer_id": 14164352,
"author": "Todd Menier",
"author_id": 62600,
"author_profile": "https://Stackoverflow.com/users/62600",
"pm_score": 4,
"selected": false,
"text": "public static string InnerXml(this XNode node) {\n using (var reader = node.CreateReader()) {\n reader.MoveToContent();\n return reader.ReadInnerXml();\n }\n}\n"
},
{
"answer_id": 21642095,
"author": "user950851",
"author_id": 950851,
"author_profile": "https://Stackoverflow.com/users/950851",
"pm_score": 1,
"selected": false,
"text": "var content = element.ToString();\nvar matchBegin = Regex.Match(content, @\"<.+?>\");\ncontent = content.Substring(matchBegin.Index + matchBegin.Length); \nvar matchEnd = Regex.Match(content, @\"</.+?>\", RegexOptions.RightToLeft);\ncontent = content.Substring(0, matchEnd.Index);\n"
},
{
"answer_id": 52996448,
"author": "Vinod Srivastav",
"author_id": 3057246,
"author_profile": "https://Stackoverflow.com/users/3057246",
"pm_score": 0,
"selected": false,
"text": "var innerXmlAsText= XElement.Parse(xmlContent)\n .Descendants()\n .Where(n => n.Name.LocalName == \"template\")\n .Elements()\n .Single()\n .ToString();\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205/"
] |
3,798 | <p>Currently I have two Linux servers running MySQL, one sitting on a rack right next to me under a 10 Mbit/s upload pipe (main server) and another some couple of miles away on a 3 Mbit/s upload pipe (mirror).</p>
<p>I want to be able to replicate data on both servers continuously, but have run into several roadblocks. One of them being, under MySQL master/slave configurations, every now and then, some statements drop (!), meaning; some people logging on to the mirror URL don't see data that I know is on the main server and vice versa. Let's say this happens on a meaningful block of data once every month, so I can live with it and assume it's a "lost packet" issue (i.e., god knows, but we'll compensate).</p>
<p>The other most important (and annoying) recurring issue is that, when for some reason we do a major upload or update (or reboot) on one end and have to <a href="http://en.wiktionary.org/wiki/sever" rel="noreferrer">sever</a> the link, then LOAD DATA FROM MASTER doesn't work and I have to manually dump on one end and upload on the other, quite a task nowadays moving some .5 TB worth of data.</p>
<p>Is there software for this? I know MySQL (the "corporation") offers this as a VERY expensive service (full database replication). What do people out there do? The way it's structured, we run an automatic failover where if one server is not up, then the main URL just resolves to the other server. </p>
| [
{
"answer_id": 2303995,
"author": "serbaut",
"author_id": 84760,
"author_profile": "https://Stackoverflow.com/users/84760",
"pm_score": 0,
"selected": false,
"text": " Network timeouts between the master and the slave could result\n in corruption of the relay log.\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] |
3,802 | <p>What is the best way to typeset a function with arguments for readibility, brevity, and accuracy? I tend to put empty parentheses after the function name like <code>func()</code>, even if there are actually arguments for the function. I have trouble including the arguments and still feeling like the paragraph is readable.</p>
<p>Any thoughts on best practices for this?</p>
| [
{
"answer_id": 3874,
"author": "MojoFilter",
"author_id": 93,
"author_profile": "https://Stackoverflow.com/users/93",
"pm_score": 3,
"selected": true,
"text": "myFunction(...)"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59/"
] |
3,839 | <p>I'm trying out the following query:</p>
<pre><code>SELECT A,B,C FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query%'
GROUP BY B ORDER BY B ASC LIMIT 5
</code></pre>
<p>That's three queries stuck together, kinda sorta. However, the result set that comes back reflects results from query #3 before the results from query #1 which is undesired.</p>
<p>Is there any way to prioritize these so that results come as all for query #1, then all for query #2 then all for query #3? I don't want to do this in PHP just yet (not to mention having to control for results that showed up in the first query not to show in the second and so forth).</p>
| [
{
"answer_id": 3852,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM (\n SELECT A,B,C FROM table WHERE field LIKE 'query%'\n UNION\n SELECT A,B,C FROM table WHERE field LIKE '%query'\n UNION\n SELECT A,B,C FROM table WHERE field LIKE '%query%'\n) ORDER BY B ASC LIMIT 5\n"
},
{
"answer_id": 3854,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 3,
"selected": false,
"text": "SELECT A,B,C,1 as [order] FROM table WHERE field LIKE 'query%'\nUNION\nSELECT A,B,C,2 as [order] FROM table WHERE field LIKE '%query'\nUNION\nSELECT A,B,C,3 as [order] FROM table WHERE field LIKE '%query%'\nGROUP BY B ORDER BY [order] ASC, B ASC LIMIT 5\n"
},
{
"answer_id": 3860,
"author": "Mario Marinato",
"author_id": 431,
"author_profile": "https://Stackoverflow.com/users/431",
"pm_score": 5,
"selected": true,
"text": "SELECT A,B,C, \"query 1\" as origin FROM table WHERE field LIKE 'query%'\nUNION\nSELECT A,B,C, \"query 2\" as origin FROM table WHERE field LIKE '%query'\nUNION\nSELECT A,B,C, \"query 3\" as origin FROM table WHERE field LIKE '%query%'\nGROUP BY origin, B ORDER BY origin, B ASC LIMIT 5\n"
},
{
"answer_id": 3876,
"author": "mauriciopastrana",
"author_id": 547,
"author_profile": "https://Stackoverflow.com/users/547",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM \n (SELECT A, B, C, \"1\" FROM table WHERE B LIKE 'query%' LIMIT 3\n UNION\n SELECT A, B, C, \"2\" FROM table WHERE B LIKE '%query%' LIMIT 5)\nAS RS\nGROUP BY B\nORDER BY 1 DESC\n"
},
{
"answer_id": 3902,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 1,
"selected": false,
"text": "GROUP BY B ORDER BY B ASC LIMIT 5\n"
},
{
"answer_id": 84974,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "'UNION' and 'UNION ALL'\n SELECT DISTINCT"
},
{
"answer_id": 56214651,
"author": "harsha reddy",
"author_id": 11315515,
"author_profile": "https://Stackoverflow.com/users/11315515",
"pm_score": 0,
"selected": false,
"text": "SELECT A, B, C \nFROM table \nWHERE field LIKE 'query%' \n OR field LIKE '%query' \n OR field LIKE '%query%'\nGROUP BY B \nORDER BY B ASC LIMIT 5\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] |
3,856 | <p>I wrote a component that displays a filename, a thumbnail and has a button to load/play the file. The component is databound to a repeater. How can I make it so that the button event fires to the main application and tells it which file to play?</p>
| [
{
"answer_id": 3852,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM (\n SELECT A,B,C FROM table WHERE field LIKE 'query%'\n UNION\n SELECT A,B,C FROM table WHERE field LIKE '%query'\n UNION\n SELECT A,B,C FROM table WHERE field LIKE '%query%'\n) ORDER BY B ASC LIMIT 5\n"
},
{
"answer_id": 3854,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 3,
"selected": false,
"text": "SELECT A,B,C,1 as [order] FROM table WHERE field LIKE 'query%'\nUNION\nSELECT A,B,C,2 as [order] FROM table WHERE field LIKE '%query'\nUNION\nSELECT A,B,C,3 as [order] FROM table WHERE field LIKE '%query%'\nGROUP BY B ORDER BY [order] ASC, B ASC LIMIT 5\n"
},
{
"answer_id": 3860,
"author": "Mario Marinato",
"author_id": 431,
"author_profile": "https://Stackoverflow.com/users/431",
"pm_score": 5,
"selected": true,
"text": "SELECT A,B,C, \"query 1\" as origin FROM table WHERE field LIKE 'query%'\nUNION\nSELECT A,B,C, \"query 2\" as origin FROM table WHERE field LIKE '%query'\nUNION\nSELECT A,B,C, \"query 3\" as origin FROM table WHERE field LIKE '%query%'\nGROUP BY origin, B ORDER BY origin, B ASC LIMIT 5\n"
},
{
"answer_id": 3876,
"author": "mauriciopastrana",
"author_id": 547,
"author_profile": "https://Stackoverflow.com/users/547",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM \n (SELECT A, B, C, \"1\" FROM table WHERE B LIKE 'query%' LIMIT 3\n UNION\n SELECT A, B, C, \"2\" FROM table WHERE B LIKE '%query%' LIMIT 5)\nAS RS\nGROUP BY B\nORDER BY 1 DESC\n"
},
{
"answer_id": 3902,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 1,
"selected": false,
"text": "GROUP BY B ORDER BY B ASC LIMIT 5\n"
},
{
"answer_id": 84974,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "'UNION' and 'UNION ALL'\n SELECT DISTINCT"
},
{
"answer_id": 56214651,
"author": "harsha reddy",
"author_id": 11315515,
"author_profile": "https://Stackoverflow.com/users/11315515",
"pm_score": 0,
"selected": false,
"text": "SELECT A, B, C \nFROM table \nWHERE field LIKE 'query%' \n OR field LIKE '%query' \n OR field LIKE '%query%'\nGROUP BY B \nORDER BY B ASC LIMIT 5\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] |
3,868 | <p>I'm downloading a web page (tag soup HTML) with XMLHttpRequest and I want to take the output and turn it into a DOM object that I can then run XPATH queries on. How do I convert from a string into DOM object?</p>
<p>It appears that the general solution is to create a hidden iframe and throw the contents of the string into that. There has been <a href="http://starkravingfinkle.org/blog/2007/03/how-to-parse-html-in-mozilla/" rel="nofollow noreferrer">talk</a> of updating <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMParser" rel="nofollow noreferrer">DOMParser</a> to support text/html but as of Firefox 3.0.1 you still get an <code>NS_ERROR_NOT_IMPLEMENTED</code> if you try.</p>
<p>Is there any option besides using the hidden iframe trick? And if not, what is the best way to do the iframe trick so that your code works outside the context of any currently open tabs (so that closing tabs won't screw up the code, etc)?</p>
<p><a href="http://mxr.mozilla.org/mozilla/source/browser/components/microsummaries/src/nsMicrosummaryService.js#2090" rel="nofollow noreferrer">This</a> is an example of why I'm looking for a solution other than the iframe hack, if I have to write <em>all</em> that code to have a robust solution, then I'd rather keep looking for something else.</p>
| [
{
"answer_id": 3871,
"author": "Steve Willard",
"author_id": 402,
"author_profile": "https://Stackoverflow.com/users/402",
"pm_score": 3,
"selected": false,
"text": "var request = new XMLHttpRequest();\n\nrequest.overrideMimeType( 'text/xml' );\nrequest.onreadystatechange = process;\nrequest.open ( 'GET', url );\nrequest.send( null );\n\nfunction process() { \n if ( request.readyState == 4 && request.status == 200 ) {\n var xml = request.responseXML;\n }\n}\n readyState == 4"
},
{
"answer_id": 3917,
"author": "Steve Willard",
"author_id": 402,
"author_profile": "https://Stackoverflow.com/users/402",
"pm_score": 2,
"selected": false,
"text": "document.createElement( 'div' );\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] |
3,881 | <p>I have a simple setter method for a property and <code>null</code> is not appropriate for this particular property. I have always been torn in this situation: should I throw an <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html" rel="noreferrer"><code>IllegalArgumentException</code></a>, or a <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html" rel="noreferrer"><code>NullPointerException</code></a>? From the javadocs, both seem appropriate. Is there some kind of an understood standard? Or is this just one of those things that you should do whatever you prefer and both are really correct?</p>
| [
{
"answer_id": 3886,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 9,
"selected": true,
"text": "IllegalArgumentException null NullPointerException null"
},
{
"answer_id": 3890,
"author": "Jeremy Privett",
"author_id": 560,
"author_profile": "https://Stackoverflow.com/users/560",
"pm_score": 4,
"selected": false,
"text": "setter null IllegalArgumentException NullPointerException null null NullPointer null IllegalArgument"
},
{
"answer_id": 6358,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 6,
"selected": false,
"text": "NullPointerException Map.containsKey public void someMethod(Object mustNotBeNull) { \n if (mustNotBeNull == null) { \n throw new NullPointerException(\"mustNotBeNull must not be null\"); \n } \n}\n"
},
{
"answer_id": 8132,
"author": "Claude Houle",
"author_id": 244,
"author_profile": "https://Stackoverflow.com/users/244",
"pm_score": 3,
"selected": false,
"text": "if( variable == null )\n throw new IllegalArgumentException(\"The object 'variable' cannot be null\");\n"
},
{
"answer_id": 8160,
"author": "GaryF",
"author_id": 1035,
"author_profile": "https://Stackoverflow.com/users/1035",
"pm_score": 7,
"selected": false,
"text": "NullPointerException"
},
{
"answer_id": 47710,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 9,
"selected": false,
"text": "IllegalArgumentException NullPointerException null null null"
},
{
"answer_id": 8196334,
"author": "MB.",
"author_id": 11961,
"author_profile": "https://Stackoverflow.com/users/11961",
"pm_score": 7,
"selected": false,
"text": "IllegalArgumentException java.util.Objects.requireNonNull if (param == null) {\n throw new IllegalArgumentException(\"param cannot be null.\");\n}\n Objects.requireNonNull(param);\n NullPointerException null java.util NullPointerException NullPointerException IllegalArgumentException NullPointerException NullPointerException NullPointerException"
},
{
"answer_id": 10195862,
"author": "Luis Daniel Mesa Velasquez",
"author_id": 1339367,
"author_profile": "https://Stackoverflow.com/users/1339367",
"pm_score": 2,
"selected": false,
"text": "throw new IllegalArgumentException(new NullPointerException(NULL_ARGUMENT_IN_METHOD_BAD_BOY_BAD));\n"
},
{
"answer_id": 13311822,
"author": "Chris Povirk",
"author_id": 28465,
"author_profile": "https://Stackoverflow.com/users/28465",
"pm_score": 3,
"selected": false,
"text": "null NullPointerException IllegalArgumentException null null containsAll NullPointerException IllegalArgumentException AbstractSet.equals null null null equals NullPointerException NullPointerException NullPointerException"
},
{
"answer_id": 13312050,
"author": "Chris Povirk",
"author_id": 28465,
"author_profile": "https://Stackoverflow.com/users/28465",
"pm_score": 3,
"selected": false,
"text": "null NullPointerException null NullPointerTester NullPointerTester Foo(String string, List<?> list) {\n checkArgument(string.length() > 0);\n // missing null check for list!\n this.string = string;\n this.list = list;\n}\n \"\", null null, ImmutableList.of() NullPointerException null NullPointerException IllegalArgumentException NullPointerTester \"\" NullPointerTester NullPointerException null IllegalArgumentException"
},
{
"answer_id": 30663317,
"author": "leo",
"author_id": 4586938,
"author_profile": "https://Stackoverflow.com/users/4586938",
"pm_score": 2,
"selected": false,
"text": "IllegalArgumentException null"
},
{
"answer_id": 31004679,
"author": "Nitesh Soomani",
"author_id": 5039151,
"author_profile": "https://Stackoverflow.com/users/5039151",
"pm_score": 2,
"selected": false,
"text": "NullPointerException null IllegalArgumentException"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] |
3,894 | <p>Given the constraint of only using T-Sql in Sql Server 2005, is there a better way to remove the decimal point from a money datatype than a conversion to a varchar (here implicitly) and then a replace of the decimal point?</p>
<p>Here is what I have currently.</p>
<pre><code>SELECT REPLACE(1.23, '.', ''), REPLACE(19.99, '.', '')
</code></pre>
<p>Which returns the desired 123 and 1999, but I was wondering if there was a better way. Any thoughts?</p>
| [
{
"answer_id": 5944,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "DECLARE\n@mon1 MONEY,\n@mon2 MONEY,\n@mon3 MONEY,\n@mon4 MONEY,\n@num1 DECIMAL(19,4),\n@num2 DECIMAL(19,4),\n@num3 DECIMAL(19,4),\n@num4 DECIMAL(19,4)\n\nSELECT\n@mon1 = 100, @mon2 = 339, @mon3 = 10000,\n@num1 = 100, @num2 = 339, @num3 = 10000\n\nSET @mon4 = @mon1/@mon2*@mon3\nSET @num4 = @num1/@num2*@num3\n\nSELECT @mon4 AS moneyresult,\n@num4 AS numericresult\n"
},
{
"answer_id": 886375,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "DataFormatString=\"{0:c0}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76/"
] |
3,927 | <p>What profilers have you used when working with .net programs, and which would you particularly recommend?</p>
| [
{
"answer_id": 100490,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 9,
"selected": true,
"text": "windbg.exe"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121/"
] |
3,976 | <p>I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /dev/tty.usbserial . </p>
<p>When i do this everything seems to be hunky-dory:</p>
<pre><code>stty -f /dev/cu.usbserial
speed 9600 baud;
lflags: -icanon -isig -iexten -echo
iflags: -icrnl -ixon -ixany -imaxbel -brkint
oflags: -opost -onlcr -oxtabs
cflags: cs8 -parenb
</code></pre>
<p>Everything also works when I use the <a href="http://www.versiontracker.com/dyn/moreinfo/macosx/24024" rel="noreferrer">serial port tool</a> to talk to it.</p>
<p>If I run this piece of code while the above mentioned serial port tool, everthing also works. But as soon as I disconnect the tool the connection gets lost. </p>
<pre><code>#!/usr/bin/python
import serial
ser = serial.Serial('/dev/cu.usbserial', 9600, timeout=10)
ser.write("<ID01><PA> \r\n")
read_chars = ser.read(20)
print read_chars
ser.close()
</code></pre>
<p>So the question is, what magicks do I need to perform to start talking to the serial port without the serial port tool? Is that a permissions problem? Also, what's the difference between /dev/cu.usbserial and /dev/tty.usbserial?</p>
<hr>
<p>Nope, no serial numbers. The thing is, the problem persists even with sudo-running the python script, and the only thing that makes it go through if I open the connection in the gui tool that I mentioned.</p>
| [
{
"answer_id": 4162,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 3,
"selected": false,
"text": "/dev/cu.xxxxx /dev/tty.xxxxx"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/3976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] |
4,004 | <p><strong>Most recent edits in bold</strong>
I am using the .net <code>HttpListener</code> class, but I won't be running this application on IIS and am not using ASP.net. This <a href="http://www.leastprivilege.com/CommentView.aspx?guid=0c34094a-bdd4-4041-be6e-919f10fe1d31" rel="noreferrer">web site</a> describes what code to actually use to implement SSL with asp.net and <a href="http://blogs.msdn.com/adarshk/archive/2004/11/10/255467.aspx" rel="noreferrer">this site</a> describes how to set up the certificates (although I'm not sure if it works only for IIS or not). </p>
<p>The class documentation describes various types of authentication (basic, digest, Windows, etc.) --- none of them refer to SSL. It does say that if <a href="http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx" rel="noreferrer">HTTPS is used, you will need to set a server certificate</a>. Is this going to be a one line property setting and <code>HttpListener</code> figures out the rest? </p>
<p>In short, I need to know how to set up the certificates and how to modify the code to implement SSL.</p>
<p>Although it doesn't occur when I'm trying to access HTTPS, I did notice an error in my System Event log - the source is "Schannel" and the content of the message is:</p>
<blockquote>
<p>A fatal error occurred when attempting
to access the SSL server credential
private key. The error code returned
from the cryptographic module is
0x80090016.</p>
</blockquote>
<p>Edit:<br>
<strong>Steps taken so far</strong></p>
<ul>
<li>Created a working HTTPListener in C# that works for HTTP connections (e.g. "<a href="http://localhost:8089/foldername/" rel="noreferrer">http://localhost:8089/foldername/</a>"</li>
<li>Created a certificate using makecert.exe</li>
<li>Added the certificate to be trusted using certmgr.exe</li>
<li>Used Httpcfg.exe to listen for SSL connections on a test port (e.g. 8090)</li>
<li>Added port 8080 to the HTTPListener via listener.Prefixes.Add(<a href="https://localhost:8090/foldername/" rel="noreferrer">https://localhost:8090/foldername/</a>");</li>
<li>tested an HTTP client connection, e.g. (<a href="http://localhost:8089/foldername/" rel="noreferrer">http://localhost:8089/foldername/</a>") in a browser and receive correct return</li>
<li>tested an HTTPS client connection, e.g. (<a href="http://localhost:8090/foldername/" rel="noreferrer">http://localhost:8090/foldername/</a>") in a browser and receive "Data Transfer Interrupted" (in Firefox)</li>
<li>debugging in visual studio shows that the listener callback that receives the requests never gets hit when the HTTPS connection starts - I don't see any place that I could set a breakpoint to catch anything else earlier.</li>
<li>netstat shows that listening ports are open for both HTTPS and HTTP. the HTTPS port does go to TIME_WAIT after a connection is attempted.</li>
<li><strong><a href="http://www.fiddlertool.com/fiddler/" rel="noreferrer">Fiddler</a> and <a href="http://www.ieinspector.com/httpanalyzer/" rel="noreferrer">HTTPAnalyzer</a> don't catch any of the traffic, I guess it doesn't get far enough in the process to show up in those HTTP analysis tools</strong></li>
</ul>
<p><strong>Questions</strong></p>
<ul>
<li>What could the problem be? </li>
<li>Is there a piece of .Net code I am missing (meaning I have to do more in C# other than simply add a prefix to the listener that points to HTTPS, which is what i have done)</li>
<li>Have a missed a configuration step somewhere? </li>
<li>What else might I do to analyze the problem?</li>
<li>Is the error message in the System Event log a sign of the problem? If so how would it be fixed?</li>
</ul>
| [
{
"answer_id": 727624,
"author": "galets",
"author_id": 14395,
"author_profile": "https://Stackoverflow.com/users/14395",
"pm_score": 3,
"selected": false,
"text": "makecert.exe -r -a sha1 -n CN=localhost -sky exchange -pe -b 01/01/2000 -e 01/01/2050 -ss my -sr localmachine\n HttpCfg.exe set ssl -i 0.0.0.0:801 -h 35c65fd4853f49552471d2226e03dd10b7a11755\n LPCTSTR pszX500 = subject;\nDWORD cbEncoded = 0;\nCertStrToName(X509_ASN_ENCODING, pszX500, CERT_X500_NAME_STR, NULL, pbEncoded, &cbEncoded, NULL);\npbEncoded = (BYTE *)malloc(cbEncoded);\nCertStrToName(X509_ASN_ENCODING, pszX500, CERT_X500_NAME_STR, NULL, pbEncoded, &cbEncoded, NULL);\n\n// Prepare certificate Subject for self-signed certificate\nCERT_NAME_BLOB SubjectIssuerBlob;\nmemset(&SubjectIssuerBlob, 0, sizeof(SubjectIssuerBlob));\nSubjectIssuerBlob.cbData = cbEncoded;\nSubjectIssuerBlob.pbData = pbEncoded;\n\n// Prepare key provider structure for self-signed certificate\nCRYPT_KEY_PROV_INFO KeyProvInfo;\nmemset(&KeyProvInfo, 0, sizeof(KeyProvInfo));\nKeyProvInfo.pwszContainerName = _T(\"my-container\");\nKeyProvInfo.pwszProvName = NULL;\nKeyProvInfo.dwProvType = PROV_RSA_FULL;\nKeyProvInfo.dwFlags = CRYPT_MACHINE_KEYSET;\nKeyProvInfo.cProvParam = 0;\nKeyProvInfo.rgProvParam = NULL;\nKeyProvInfo.dwKeySpec = AT_SIGNATURE;\n\n// Prepare algorithm structure for self-signed certificate\nCRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;\nmemset(&SignatureAlgorithm, 0, sizeof(SignatureAlgorithm));\nSignatureAlgorithm.pszObjId = szOID_RSA_SHA1RSA;\n\n// Prepare Expiration date for self-signed certificate\nSYSTEMTIME EndTime;\nGetSystemTime(&EndTime);\nEndTime.wYear += 5;\n\n// Create self-signed certificate\npCertContext = CertCreateSelfSignCertificate(NULL, &SubjectIssuerBlob, 0, &KeyProvInfo, &SignatureAlgorithm, 0, &EndTime, 0);\nhStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L\"MY\");\nCertAddCertificateContextToStore(hStore, pCertContext, CERT_STORE_ADD_REPLACE_EXISTING, 0);\n CRYPT_KEY_PROV_INFO KeyProvInfo;\nmemset(&KeyProvInfo, 0, sizeof(KeyProvInfo));\nKeyProvInfo.pwszContainerName = _T(\"my-container\");\nKeyProvInfo.pwszProvName = _T(\"Microsoft RSA SChannel Cryptographic Provider\");\nKeyProvInfo.dwProvType = PROV_RSA_SCHANNEL;\nKeyProvInfo.dwFlags = CRYPT_MACHINE_KEYSET;\nKeyProvInfo.cProvParam = 0;\nKeyProvInfo.rgProvParam = NULL;\nKeyProvInfo.dwKeySpec = AT_KEYEXCHANGE;\n"
},
{
"answer_id": 12649776,
"author": "Despertar",
"author_id": 1160036,
"author_profile": "https://Stackoverflow.com/users/1160036",
"pm_score": 3,
"selected": false,
"text": "netsh http add sslcert ipport=0.0.0.0:1234 certhash=613bb67c4acaab06def391680505bae2ced4053b appid={86476d42-f4f3-48f5-9367-ff60f2ed2cdc}\n HttpListener listener = new HttpListener();\n listener.Prefixes.Add(\"https://+:1234/\");\n listener.Start();\n Console.WriteLine(\"Listening...\");\n HttpListenerContext context = listener.GetContext();\n\n using (Stream stream = context.Response.OutputStream)\n using (StreamWriter writer = new StreamWriter(stream))\n writer.Write(\"hello, https world\");\n\n Console.ReadLine();\n https://localhost:1234 ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, errors) => true;\n"
},
{
"answer_id": 28803107,
"author": "Steven de Salas",
"author_id": 448568,
"author_profile": "https://Stackoverflow.com/users/448568",
"pm_score": 2,
"selected": false,
"text": "httpcfg.exe netsh.exe"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525/"
] |
4,034 | <p>What is the best way to support multiple languages for the interface in an ASP.NET MVC application? I've seen people use resource files for other applications. Is this still the best way?</p>
| [
{
"answer_id": 4038,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "Site.resx\nSite.en.resx\nSite.en-US.resx\nSite.fr.resx\netc...\n"
},
{
"answer_id": 68081,
"author": "user10479",
"author_id": 10479,
"author_profile": "https://Stackoverflow.com/users/10479",
"pm_score": 5,
"selected": false,
"text": "// default global resource\nHtml.Resource(\"GlobalResource, ResourceName\")\n\n// global resource with optional arguments for formatting\nHtml.Resource(\"GlobalResource, ResourceName\", \"foo\", \"bar\")\n\n// default local resource\nHtml.Resource(\"ResourceName\")\n\n// local resource with optional arguments for formatting\nHtml.Resource(\"ResourceName\", \"foo\", \"bar\")\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
] |
4,046 | <p>I'm trying to convince my providers to use ANT instead of Rational Application Development so anyone can recompile, recheck, redeploy the solution anyplace, anytime, anyhow. :P</p>
<p>I started a build.xml for a project that generates a JAR file but stopped there and I need real examples to compare notes. My good friends! I don't have anyone close to chat about this! </p>
<p>This is my <a href="http://pastebin.ca/1094382" rel="noreferrer">build.xml</a> so far. </p>
<p><i>(*) I edited my question based in the <a href="https://stackoverflow.com/questions/4046/can-someone-give-me-a-working-example-of-a-buildxml-for-an-ear-that-deploys-in-#4298">suggestion</a> of to use pastebin.ca</i></p>
| [
{
"answer_id": 4902,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 5,
"selected": true,
"text": "<?xml version=\"1.0\"?>\n<project name=\"project\" default=\"wasListApps\" basedir=\".\">\n <description>\n Script for listing installed apps.\n Example run from:\n /opt/IBM/SDP70/runtimes/base_v61/profiles/AppSrv01/bin\n </description>\n\n <property name=\"was_home\"\n value=\"/opt/IBM/SDP70/runtimes/base_v61/\">\n </property>\n <path id=\"was.runtime\">\n <fileset dir=\"${was_home}/lib\">\n <include name=\"**/*.jar\" />\n </fileset>\n <fileset dir=\"${was_home}/plugins\">\n <include name=\"**/*.jar\" />\n </fileset>\n </path>\n <property name=\"was_cp\" value=\"${toString:was.runtime}\"></property>\n <property environment=\"env\"></property>\n\n <target name=\"wasListApps\">\n <taskdef name=\"wsListApp\"\n classname=\"com.ibm.websphere.ant.tasks.ListApplications\"\n classpath=\"${was_cp}\">\n </taskdef>\n <wsListApp wasHome=\"${was_home}\" />\n </target>\n\n</project>\n ./ws_ant.sh -buildfile ~/IBM/rationalsdp7.0/workspace/mywebappDeploy/applist.xml\n <?xml version=\"1.0\"?>\n<project name=\"project\" default=\"default\" basedir=\".\">\n<description>\nBuild/Deploy an EAR to WebSphere Application Server 6.1\n</description>\n\n <property name=\"was_home\" value=\"/opt/IBM/SDP70/runtimes/base_v61/\" />\n <path id=\"was.runtime\">\n <fileset dir=\"${was_home}/lib\">\n <include name=\"**/*.jar\" />\n </fileset>\n <fileset dir=\"${was_home}/plugins\">\n <include name=\"**/*.jar\" />\n </fileset>\n </path>\n <property name=\"was_cp\" value=\"${toString:was.runtime}\" />\n <property environment=\"env\" />\n <property name=\"ear\" value=\"${env.HOME}/IBM/rationalsdp7.0/workspace/mywebappDeploy/mywebappEAR.ear\" />\n\n <target name=\"default\" depends=\"deployEar\">\n </target>\n\n <target name=\"generateWar\" depends=\"compileWarClasses\">\n <jar destfile=\"mywebapp.war\">\n <fileset dir=\"../mywebapp/WebContent\">\n </fileset>\n </jar>\n </target>\n\n <target name=\"compileWarClasses\">\n <echo message=\"was_cp=${was_cp}\" />\n <javac srcdir=\"../mywebapp/src\" destdir=\"../mywebapp/WebContent/WEB-INF/classes\" classpath=\"${was_cp}\">\n </javac>\n </target>\n\n <target name=\"generateEar\" depends=\"generateWar\">\n <mkdir dir=\"./earbin/META-INF\"/>\n <move file=\"mywebapp.war\" todir=\"./earbin\" />\n <copy file=\"../mywebappEAR/META-INF/application.xml\" todir=\"./earbin/META-INF\" />\n <jar destfile=\"${ear}\">\n <fileset dir=\"./earbin\" />\n </jar>\n </target>\n\n <!-- http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.javadoc.doc/public_html/api/com/ibm/websphere/ant/tasks/package-summary.html -->\n <target name=\"deployEar\" depends=\"generateEar\">\n <taskdef name=\"wsInstallApp\" classname=\"com.ibm.websphere.ant.tasks.InstallApplication\" classpath=\"${was_cp}\"/>\n <wsInstallApp ear=\"${ear}\" \n failonerror=\"true\" \n debug=\"true\" \n taskname=\"\"\n washome=\"${was_home}\" />\n </target>\n\n</project>\n"
},
{
"answer_id": 14796,
"author": "accreativos",
"author_id": 1713,
"author_profile": "https://Stackoverflow.com/users/1713",
"pm_score": 3,
"selected": false,
"text": "<path id=\"classpath\">\n <fileset file=\"com.ibm.websphere.v61_6.1.100.ws_runtime.jar\"/>\n</path>\n\n<taskdef name=\"wsStartApp\" classname=\"com.ibm.websphere.ant.tasks.StartApplication\" classpathref=\"classpath\" />\n<taskdef name=\"wsStopApp\" classname=\"com.ibm.websphere.ant.tasks.StopApplication\" classpathref=\"classpath\" />\n<taskdef name=\"wsInstallApp\" classname=\"com.ibm.websphere.ant.tasks.InstallApplication\" classpathref=\"classpath\" />\n<taskdef name=\"wsUninstallApp\" classname=\"com.ibm.websphere.ant.tasks.UninstallApplication\" classpathref=\"classpath\" />\n\n<target name=\"startWebApp1\" depends=\"installEar\">\n <wsStartApp wasHome=\"${wasHome.dir}\" \n application=\"${remoteAppName}\" \n server=\"${clusterServerName}\" \n conntype=\"${remoteProdConnType}\" \n host=\"${remoteProdHostName}\" \n port=\"${remoteProdPort}\" \n user=\"${remoteProdUserId}\" \n password=\"${remoteProdPassword}\" />\n</target>\n\n<target name=\"stopWebApp1\" depends=\"prepare\">\n <wsStopApp wasHome=\"${wasHome.dir}\"\n application=\"${remoteAppName}\"\n server=\"${clusterServerName}\"\n conntype=\"${remoteConnType}\"\n host=\"${remoteHostName}\"\n port=\"${remotePort}\"\n user=\"${remoteUserId}\"\n password=\"${remotePassword}\"/>\n</target>\n\n<target name=\"uninstallEar\" depends=\"stopWebApp1\">\n <wsUninstallApp wasHome=\"${wasHome.dir}\"\n application=\"${remoteAppName}\"\n options=\"-cell uatNetwork -cluster DOL\"\n conntype=\"${remoteConnType}\"\n host=\"${remoteHostName}\"\n port=\"${remoteDmgrPort}\"\n user=\"${remoteUserId}\"\n password=\"${remotePassword}\"/>\n</target>\n\n<target name=\"installEar\" depends=\"prepare\">\n <wsInstallApp ear=\"${existingEar.dir}/${existingEar}\" \n wasHome=\"${wasHome.dir}\" \n options=\"${install_app_options}\"\n conntype=\"${remoteConnType}\" \n host=\"${remoteHostName}\" \n port=\"${remoteDmgrPort}\" \n user=\"${remoteUserId}\" \n password=\"${remotePassword}\" />\n</target>\n"
},
{
"answer_id": 141442,
"author": "fnCzar",
"author_id": 15053,
"author_profile": "https://Stackoverflow.com/users/15053",
"pm_score": 3,
"selected": false,
"text": "<property name=\"websphere.home.dir\" value=\"${env.WS6_HOME}\" />\n<property name=\"was.server.name\" value=\"server1\" />\n<property name=\"wsadmin.base.command\" value=\"wsadmin.bat\" />\n\n<property name=\"ws.list.command\" value=\"$AdminApp list\" />\n<property name=\"ws.install.command\" value=\"$AdminApp install\" />\n<property name=\"ws.uninstall.command\" value=\"$AdminApp uninstall\" />\n<property name=\"ws.save.command\" value=\"$AdminConfig save\" />\n<property name=\"ws.setManager.command\" value=\"set appManager [$AdminControl queryNames cell=${env.COMPUTERNAME}Node01Cell,node=${env.COMPUTERNAME}Node01,type=ApplicationManager,process=${was.server.name},*]\" />\n<property name=\"ws.startapp.command\" value=\"$AdminControl invoke $appManager startApplication\" />\n<property name=\"ws.stopapp.command\" value=\"$AdminControl invoke $appManager stopApplication\" />\n\n<property name=\"ws.conn.type\" value=\"SOAP\" />\n<property name=\"ws.host.name\" value=\"localhost\" />\n<property name=\"ws.port.name\" value=\"8880\" />\n<property name=\"ws.user.name\" value=\"username\" />\n<property name=\"ws.password.name\" value=\"password\" />\n\n<property name=\"app.deployed.name\" value=\"${artifact.filename}\" />\n<property name=\"app.contextroot.name\" value=\"/${artifact.filename}\" />\n\n<target name=\"websphere-list-applications\">\n <exec dir=\"${websphere.home.dir}/bin\" executable=\"${wsadmin.base.command}\" output=\"waslist.txt\" logError=\"true\">\n <arg line=\"-conntype ${ws.conn.type}\" />\n <arg line=\"-host ${ws.host.name}\" />\n <arg line=\"-port ${ws.port.name}\" />\n <arg line=\"-username ${ws.user.name}\" />\n <arg line=\"-password ${ws.password.name}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.list.command}\" />\n </exec>\n</target>\n\n<target name=\"websphere-install-application\" depends=\"websphere-uninstall-application\">\n <exec executable=\"${websphere.home.dir}/bin/${wsadmin.base.command}\" logError=\"true\" outputproperty=\"websphere.install.output\" failonerror=\"true\">\n <arg line=\"-conntype ${ws.conn.type}\" />\n <arg line=\"-host ${ws.host.name}\" />\n <arg line=\"-port ${ws.port.name}\" />\n <arg line=\"-username ${ws.user.name}\" />\n <arg line=\"-password ${ws.password.name}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.install.command} ${dist.dir}/${artifact.filename}.war {-appname ${app.deployed.name} -server ${was.server.name} -contextroot ${app.contextroot.name}}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.save.command}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.setManager.command}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.startapp.command} ${app.deployed.name}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.save.command}\" />\n </exec>\n <echo message=\"${websphere.install.output}\" />\n</target>\n\n<target name=\"websphere-uninstall-application\">\n <exec executable=\"${websphere.home.dir}/bin/${wsadmin.base.command}\" logError=\"true\" outputproperty=\"websphere.uninstall.output\" failonerror=\"false\">\n <arg line=\"-conntype ${ws.conn.type}\" />\n <arg line=\"-host ${ws.host.name}\" />\n <arg line=\"-port ${ws.port.name}\" />\n <arg line=\"-username ${ws.user.name}\" />\n <arg line=\"-password ${ws.password.name}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.setManager.command}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.stopapp.command} ${app.deployed.name}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.save.command}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.uninstall.command} ${app.deployed.name}\" />\n <arg line=\"-c\" />\n <arg value=\"${ws.save.command}\" />\n </exec>\n <echo message=\"${websphere.uninstall.output}\" />\n</target>\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527/"
] |
4,051 | <p>In <code>C</code> can I <strong>pass a multidimensional array</strong> to a function <strong>as a single argument</strong> when I don't know what the dimensions of the array are going to be?</p>
<p>Besides, my multidimensional array may contain types other than strings.</p>
| [
{
"answer_id": 4192,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 6,
"selected": true,
"text": "typedef struct {\n int myint;\n char* mystring;\n} data;\n\ndata** array;\n //initialize\nint x,y,w,h;\nw = 10; //width of array\nh = 20; //height of array\n\n//malloc the 'y' dimension\narray = malloc(sizeof(data*) * h);\n\n//iterate over 'y' dimension\nfor(y=0;y<h;y++){\n //malloc the 'x' dimension\n array[y] = malloc(sizeof(data) * w);\n\n //iterate over the 'x' dimension\n for(x=0;x<w;x++){\n //malloc the string in the data structure\n array[y][x].mystring = malloc(50); //50 chars\n\n //initialize\n array[y][x].myint = 6;\n strcpy(array[y][x].mystring, \"w00t\");\n }\n}\n int whatsMyInt(data** arrayPtr, int x, int y){\n return arrayPtr[y][x].myint;\n}\n printf(\"My int is %d.\\n\", whatsMyInt(array, 2, 4));\n My int is 6.\n"
},
{
"answer_id": 1916200,
"author": "John Bode",
"author_id": 134554,
"author_profile": "https://Stackoverflow.com/users/134554",
"pm_score": 5,
"selected": false,
"text": "void func_2d(int *p, size_t M, size_t N)\n{\n size_t i, j;\n ...\n p[i*N+j] = ...;\n}\n ...\nint arr1[10][20];\nint arr2[5][80];\n...\nfunc_2d(&arr1[0][0], 10, 20);\nfunc_2d(&arr2[0][0], 5, 80);\n func_3d(int *p, size_t X, size_t Y, size_t Z)\n{\n size_t i, j, k;\n ...\n p[i*Y*Z+j*Z+k] = ...;\n ...\n}\n...\narr2[10][20][30];\n...\nfunc_3d(&arr[0][0][0], 10, 20, 30);\n"
},
{
"answer_id": 8712577,
"author": "Pedro",
"author_id": 1127866,
"author_profile": "https://Stackoverflow.com/users/1127866",
"pm_score": -1,
"selected": false,
"text": "int matmax(int **p, int dim) // p- matrix , dim- dimension of the matrix \n{\n return p[0][0]; \n}\n\nint main()\n{\n int *u[5]; // will be a 5x5 matrix\n\n for(int i = 0; i < 5; i++)\n u[i] = new int[5];\n\n u[0][0] = 1; // initialize u[0][0] - not mandatory\n\n // put data in u[][]\n\n printf(\"%d\", matmax(u, 0)); //call to function\n getche(); // just to see the result\n}\n"
},
{
"answer_id": 24623778,
"author": "rslemos",
"author_id": 1535706,
"author_profile": "https://Stackoverflow.com/users/1535706",
"pm_score": 5,
"selected": false,
"text": "f(int size, int data[][size]) {...}\n f(int size; int data[][size], int size) {...}\n"
},
{
"answer_id": 59321586,
"author": "Andrew Henle",
"author_id": 4756299,
"author_profile": "https://Stackoverflow.com/users/4756299",
"pm_score": 1,
"selected": false,
"text": "void print2dIntArray( size_t x, size_t y, int array[ x ][ y ] )\n{\n for ( size_t ii = 0, ii < x; ii++ )\n {\n char *sep = \"\";\n for ( size_t jj = 0; jj < y; jj++ )\n {\n printf( \"%s%d\", sep, array[ ii ][ jj ] );\n sep = \", \";\n }\n printf( \"\\n\" );\n }\n}\n int a[ 4 ][ 5 ];\nint b[ 255 ][ 16 ];\n\n...\n\nprint2dIntArray( 4, 5, a );\n\n....\n\nprintt2dIntArray( 255, 16, b );\n struct pixel void print3dPixelArray( size_t x, size_t y, size_t z, struct pixel pixelArray[ x ][ y ][ z ] )\n{\n ...\n}\n double void print1dDoubleArray( size_t x, double doubleArray[ x ] )\n{\n ...\n}\n X X X char **argv main() char char * NULL char char * NUL '\\0' NAN NAN double ** void printDoubles( double **notAnArray )\n{\n while ( *notAnArray )\n {\n char *sep = \"\";\n for ( size_t ii = 0; ( *notAnArray )[ ii ] != NAN; ii++ )\n {\n printf( \"%s%f\", sep, ( *notAnArray )[ ii ] );\n sep = \", \";\n }\n\n notAnArray++;\n }\n}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] |
4,052 | <p>I am trying to enable Full-text indexing in SQL Server 2005 Express. I am running this on my laptop with Vista Ultimate.</p>
<p>I understand that the standard version of SQL Server Express does not have full-text indexing. I have already downloaded and installed "Microsoft SQL Server 2005 Express Edition with Advanced Services Service Pack 2" (<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=5B5528B9-13E1-4DB9-A3FC-82116D598C3D&displaylang=en" rel="noreferrer">download</a>).</p>
<p>I have also ensured that both the "SQL Server (instance)" and "SQL Server FullText Search (instance)" services are running on the same account which is "Network Service".</p>
<p>I have also selected the option to "Use full-text indexing" in the Database Properties > Files area.</p>
<p>I can run the sql query "SELECT fulltextserviceproperty('IsFulltextInstalled');" and return 1.</p>
<p>The problem I am having is that when I have my table open in design view and select "Manage FullText Index"; the full-text index window displays the message... </p>
<blockquote>
<p>"Creation of the full-text index is not available. Check that you have the correct permissions or that full-text catalogs are defined."</p>
</blockquote>
<p>Any ideas on what to check or where to go next?</p>
| [
{
"answer_id": 4139,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 5,
"selected": true,
"text": "sp_fulltext_database 'enable'\n\nCREATE FULLTEXT CATALOG [myFullText]\nWITH ACCENT_SENSITIVITY = ON\n\nCREATE FULLTEXT INDEX ON [dbo].[tblName] KEY INDEX [PK_something] ON [myFullText] WITH CHANGE_TRACKING AUTO\nALTER FULLTEXT INDEX ON [dbo].[otherTable] ADD ([Text])\nALTER FULLTEXT INDEX ON [dbo].[teyOtherTable] ENABLE\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576/"
] |
4,062 | <p>Currently I know of only two ways to cache data (I use PHP but I assume that the same will apply to most languages).</p>
<ol>
<li>Save the cache to a file</li>
<li>Save the cache to a large DB field</li>
</ol>
<p>Are there any other (perhaps better) ways of caching or is it really just this simple?</p>
| [
{
"answer_id": 67170,
"author": "Erlend Halvorsen",
"author_id": 1920,
"author_profile": "https://Stackoverflow.com/users/1920",
"pm_score": 0,
"selected": false,
"text": "RewriteEngine on\nRewriteCond %{QUERY_STRING} ^$ # let's not cache urls with queries\nRewriteCond %{REQUEST_METHOD} ^GET$ # or POST/PUT/DELETE requests\nRewriteCond static_cache/%{REQUEST_URI} -s # Check that this file exists and is > 0 bytes\nRewriteRule (^.*$) static_cache$1 [L] # If all the conditions are met, we rewrite this request to hit the static cache instead\n php_value auto_prepend_file \"pre_cache.php\"\nphp_value auto_append_file \"post_cache.php\"\n ob_start();\n $result = ob_get_flush();\nif(!$_SERVER['QUERY_STRING']) { # Again, we're not caching query string requests\n file_put_contents(\"static_cache/\" + __FILE__, $result);\n}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
4,072 | <p>I just did a merge using something like:</p>
<pre><code>svn merge -r 67212:67213 https://my.svn.repository/trunk .
</code></pre>
<p>I only had 2 files, one of which is a simple <code>ChangeLog</code>. Rather than just merging my <code>ChangeLog</code> changes, it actually pulled mine plus some previous ones that were not in the destination <code>ChangeLog</code>. I noticed there was a conflict when I executed --dry-run, so I updated <code>ChangeLog</code>, and there was still a conflict (and I saw the conflict when I did the actual merge).</p>
<p>I then later diffed on the file I was merging from:</p>
<pre><code>svn diff -r 67212:67213 ChangeLog
</code></pre>
<p>And I see just the changes I had made, so I know that extra changes didn't get in there somehow. </p>
<p>This makes me worried that merge is not actually just taking what I changed, which is what I would have expected. Can anybody explain what happened?</p>
<p>UPDATE: In response to NilObject:</p>
<p>So, I have 2 files changed, only ChangeLog is relevant, the other merged fine. When I go to my regular trunk checkout, I do the diff command above and see:</p>
<pre><code>Index: ChangeLog
===================================================================
--- ChangeLog (revision 67212)
+++ ChangeLog (revision 67213)
@@ -1,3 +1,7 @@
+2008-08-06 Mike Stone <myemail>
+
+ * changed_file: Details.
+
2008-08-06 Someone Else <their_email>
* theirChanges: Details.
</code></pre>
<p>After my merge of the previous changes, the diff of ChangeLog looks like this:</p>
<pre><code>Index: ChangeLog
===================================================================
--- ChangeLog (revision 67215)
+++ ChangeLog (working copy)
@@ -1,3 +1,14 @@
+<<<<<<< .working
+=======
+2008-08-06 Mike Stone <myemail>
+
+ * changed_file: Details.
+
+2008-08-06 Someone Else <their_email>
+
+ * theirChanges: Details.
+
+>>>>>>> .merge-right.r67213
2008-08-05 Someone Else2 <their2_email>
* olderChange: Details.
</code></pre>
<p>Note that the entry that was incorrectly pulled in was not in the file I am merging it to, but yet it was not one of my changes and shouldn't have been merged anyways. It was easy to fix (remove the extra lines that weren't part of my changes), but it still makes me worry about merging automatically in <code>SVN</code>.</p>
| [
{
"answer_id": 4104,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 0,
"selected": false,
"text": "svn merge -r 67212:67213 https://my.svn.repository/trunk .\n svn log -r 67212\n"
},
{
"answer_id": 13738,
"author": "Cebjyre",
"author_id": 1612,
"author_profile": "https://Stackoverflow.com/users/1612",
"pm_score": 3,
"selected": true,
"text": "2008-08-06 Mike Stone <myemail>\n\n* changed_file: Details.\n 2008-08-06 Someone Else <their_email>\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] |
4,080 | <p>What code analysis tools do you use on your Java projects?</p>
<p>I am interested in all kinds</p>
<ul>
<li>static code analysis tools (FindBugs, PMD, and any others)</li>
<li>code coverage tools (Cobertura, Emma, and any others)</li>
<li>any other instrumentation-based tools </li>
<li>anything else, if I'm missing something</li>
</ul>
<p>If applicable, also state what build tools you use and how well these tools integrate with both your IDEs and build tools. </p>
<p>If a tool is only available a specific way (as an IDE plugin, or, say, a build tool plugin) that information is also worth noting.</p>
| [
{
"answer_id": 79845,
"author": "Greg Mattes",
"author_id": 13940,
"author_profile": "https://Stackoverflow.com/users/13940",
"pm_score": 7,
"selected": true,
"text": "/absolute-path/filename:line-number:column-number: warning(tool-name): message /project/src/com/example/Foo.java:425:9: warning(Checkstyle):Missing a Javadoc comment. SuppressWarning NOPMD @SuppressWarnings SuppressWarning(PMD. NOPMD // SuppressWarnings(PMD.PreserveStackTrace) justification: (false positive) exceptions are chained SuppressWarnings(PMD. @SuppressWarning @SuppressWarnings(\"PMD.CompareObjectsWithEquals\") // justification: identity comparision intended CHECKSTYLE:OFF CHECKSTYLE:ON BEGIN SuppressWarnings(CheckStyle. END SuppressWarnings(CheckStyle. // BEGIN SuppressWarnings(Checkstyle.HiddenField) justification: \"Effective Java,\" 2nd ed., Bloch, Item 2 // END SuppressWarnings(Checkstyle.HiddenField) HiddenField BEGIN/END @SuppressWarnings @SuppressWarnings @SuppressWarnings SOURCE @SuppressWarnings @edu.umd.cs.findbugs.annotations.SuppressWarnings(\"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR\") SuppressWarnings"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235/"
] |
4,138 | <p>What is the best SVN Ignore Pattern should TortoiseSVN have for a VB.NET solution?</p>
| [
{
"answer_id": 4140,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 5,
"selected": true,
"text": "build deploy */bin */bin/* obj *.dll *.pdb *.user *.suo _ReSharper* *.resharper* bin\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
4,149 | <p>I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time.</p>
<p>I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then? </p>
<p>My intuition is currently pushing me towards BufferedStreams. Is this the way to go?</p>
| [
{
"answer_id": 4498,
"author": "Anthony Cramp",
"author_id": 488,
"author_profile": "https://Stackoverflow.com/users/488",
"pm_score": 2,
"selected": false,
"text": "public class Writer extends Object\n{\n Writer () {\n\n }\n\n public static String[] strings = \n {\n \"Hello World\", \n \"Goodbye World\"\n };\n\n public static void main(String[] args) \n throws java.io.IOException {\n\n java.io.PrintWriter pw =\n new java.io.PrintWriter(new java.io.FileOutputStream(\"out.txt\"), true);\n\n for(String s : strings) {\n pw.println(s);\n System.in.read();\n }\n\n pw.close();\n }\n}\n public class Reader extends Object\n{\n Reader () {\n\n }\n\n public static void main(String[] args) \n throws Exception {\n\n java.io.FileInputStream in = new java.io.FileInputStream(\"out.txt\");\n\n java.nio.channels.FileChannel fc = in.getChannel();\n java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10);\n\n while(fc.read(bb) >= 0) {\n bb.flip();\n while(bb.hasRemaining()) {\n System.out.println((char)bb.get());\n }\n bb.clear();\n }\n\n System.exit(0);\n }\n}\n"
},
{
"answer_id": 38133,
"author": "Frederic Morin",
"author_id": 4064,
"author_profile": "https://Stackoverflow.com/users/4064",
"pm_score": 3,
"selected": false,
"text": "FileChannel lock(long position, long size, boolean shared) \n"
},
{
"answer_id": 154588,
"author": "Joseph Gordon",
"author_id": 1741,
"author_profile": "https://Stackoverflow.com/users/1741",
"pm_score": 7,
"selected": true,
"text": "FileChannel.read(ByteBuffer) boolean running = true;\nBufferedInputStream reader = new BufferedInputStream(new FileInputStream( \"out.txt\" ) );\n\npublic void run() {\n while( running ) {\n if( reader.available() > 0 ) {\n System.out.print( (char)reader.read() );\n }\n else {\n try {\n sleep( 500 );\n }\n catch( InterruptedException ex ) {\n running = false;\n }\n }\n }\n}\n"
},
{
"answer_id": 28818516,
"author": "Rodrigo Menezes",
"author_id": 1255493,
"author_profile": "https://Stackoverflow.com/users/1255493",
"pm_score": 2,
"selected": false,
"text": "public void run() {\n try {\n while (_running) {\n Thread.sleep(_updateInterval);\n long len = _file.length();\n if (len < _filePointer) {\n // Log must have been jibbled or deleted.\n this.appendMessage(\"Log file was reset. Restarting logging from start of file.\");\n _filePointer = len;\n }\n else if (len > _filePointer) {\n // File must have had something added to it!\n RandomAccessFile raf = new RandomAccessFile(_file, \"r\");\n raf.seek(_filePointer);\n String line = null;\n while ((line = raf.readLine()) != null) {\n this.appendLine(line);\n }\n _filePointer = raf.getFilePointer();\n raf.close();\n }\n }\n }\n catch (Exception e) {\n this.appendMessage(\"Fatal error reading log file, log tailing has stopped.\");\n }\n // dispose();\n}\n"
},
{
"answer_id": 32783641,
"author": "ToYonos",
"author_id": 2003986,
"author_profile": "https://Stackoverflow.com/users/2003986",
"pm_score": 3,
"selected": false,
"text": "public class TailerTest\n{\n public static void main(String[] args)\n {\n File f = new File(\"/tmp/test.txt\");\n MyListener listener = new MyListener();\n Tailer.create(f, listener, 2500);\n\n try\n {\n FileOutputStream fos = new FileOutputStream(f);\n int i = 0;\n while (i < 200)\n {\n fos.write((\"test\" + ++i + \"\\n\").getBytes());\n Thread.sleep(150);\n }\n fos.close();\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }\n\n private static class MyListener extends TailerListenerAdapter\n {\n @Override\n public void handle(String line)\n {\n System.out.println(line);\n }\n }\n}\n"
},
{
"answer_id": 32851944,
"author": "tiger.spring",
"author_id": 4042626,
"author_profile": "https://Stackoverflow.com/users/4042626",
"pm_score": 4,
"selected": false,
"text": "public class FileReader {\n\n public static void main(String args[]) throws Exception {\n if(args.length>0){\n File file = new File(args[0]);\n System.out.println(file.getAbsolutePath());\n if(file.exists() && file.canRead()){\n long fileLength = file.length();\n readFile(file,0L);\n while(true){\n\n if(fileLength<file.length()){\n readFile(file,fileLength);\n fileLength=file.length();\n }\n }\n }\n }else{\n System.out.println(\"no file to read\");\n }\n }\n\n public static void readFile(File file,Long fileLength) throws IOException {\n String line = null;\n\n BufferedReader in = new BufferedReader(new java.io.FileReader(file));\n in.skip(fileLength);\n while((line = in.readLine()) != null)\n {\n System.out.println(line);\n }\n in.close();\n }\n}\n"
},
{
"answer_id": 34576387,
"author": "bebbo",
"author_id": 1412279,
"author_profile": "https://Stackoverflow.com/users/1412279",
"pm_score": 2,
"selected": false,
"text": "private static byte[] readSharedFile(File file) throws IOException {\n byte buffer[] = new byte[(int) file.length()];\n final FileChannel fc = FileChannel.open(file.toPath(), EnumSet.of(StandardOpenOption.READ));\n final ByteBuffer dst = ByteBuffer.wrap(buffer);\n fc.read(dst);\n fc.close();\n return buffer;\n}\n"
}
] | 2008/08/06 | [
"https://Stackoverflow.com/questions/4149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/488/"
] |
4,168 | <p>I'm looking for a simple algorithm to 'serialize' a directed graph. In particular I've got a set of files with interdependencies on their execution order, and I want to find the correct order at compile time. I know it must be a fairly common thing to do - compilers do it all the time - but my google-fu has been weak today. What's the 'go-to' algorithm for this?</p>
| [
{
"answer_id": 4185,
"author": "Kieron",
"author_id": 588,
"author_profile": "https://Stackoverflow.com/users/588",
"pm_score": 1,
"selected": false,
"text": "Map<Object, List<Object>> source; // map of each object to its dependency list\nList<Object> dest; // destination list\n\nfunction resolve(a):\n if (dest.contains(a)) return;\n foreach (b in source[a]):\n resolve(b);\n dest.add(a);\n\nforeach (a in source):\n resolve(a);\n"
},
{
"answer_id": 4577,
"author": "Andrew Peters",
"author_id": 608,
"author_profile": "https://Stackoverflow.com/users/608",
"pm_score": 7,
"selected": true,
"text": "L ← Empty list where we put the sorted elements\nQ ← Set of all nodes with no incoming edges\nwhile Q is non-empty do\n remove a node n from Q\n insert n into L\n for each node m with an edge e from n to m do\n remove edge e from the graph\n if m has no other incoming edges then\n insert m into Q\nif graph has edges then\n output error message (graph has a cycle)\nelse \n output message (proposed topologically sorted order: L)\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/588/"
] |
4,170 | <p>I need to learn ADO.NET to build applications based on MS Office. I have read a good deal about ADO.NET in the MSDN Library, but everything seems rather messy to me.</p>
<p>What are the basics one must figure out when using ADO.NET? I think a few key words will suffice to let me organize my learning.</p>
| [
{
"answer_id": 4204,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 4,
"selected": true,
"text": "SQLConnection SqlCommand SqlDataReader Sql MySqlConnection OracleCommand using (SqlConnection connection = new SqlConnection(\"CONNECTION STRING\"))\nusing (SqlCommand command = new SqlCommand())\n{\n command.commandText = \"SELECT Name FROM Users WHERE Status = @OnlineStatus\";\n command.Connection = connection;\n command.Parameters.Add(\"@OnlineStatus\", SqlDbType.Int).Value = 1; //replace with enum\n connection.Open();\n\n using (SqlDataReader dr = command.ExecuteReader))\n {\n List<string> onlineUsers = new List<string>();\n\n while (dr.Read())\n {\n onlineUsers.Add(dr.GetString(0));\n }\n }\n}\n using (SqlConnection connection = new SqlConnection(\"CONNECTION STRING\"))\nusing (SqlCommand command = new SqlCommand())\n{\n command.commandText = \"DELETE FROM Users where Email = @Email\";\n command.Connection = connection;\n command.Parameters.Add(\"@Email\", SqlDbType.VarChar, 100).Value = \"[email protected]\";\n connection.Open();\n command.ExecuteNonQuery();\n}\n"
},
{
"answer_id": 14218,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "connection.CreateCommand() Connection"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
4,208 | <p>Is there a Windows equivalent of the Unix command, <em>nice</em>?</p>
<p>I'm specifically looking for something I can use at the command line, and <strong>not</strong> the "Set Priority" menu from the task manager.</p>
<p>My attempts at finding this on Google have been thwarted by those who can't come up with better adjectives.</p>
| [
{
"answer_id": 4302,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 3,
"selected": false,
"text": "function set-ProcessPriority { \n param($processName = $(throw \"Enter process name\"), $priority = \"Normal\")\n\n get-process -processname $processname | foreach { $_.PriorityClass = $priority }\n write-host \"`\"$($processName)`\"'s priority is set to `\"$($priority)`\"\"\n}\n set-ProcessPriority SomeProcessName \"High\"\n"
},
{
"answer_id": 4332,
"author": "Stephen Pellicer",
"author_id": 360,
"author_profile": "https://Stackoverflow.com/users/360",
"pm_score": 7,
"selected": true,
"text": "START [\"title\"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]\n [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]\n [/WAIT] [/B] [command/program] [parameters]\n"
},
{
"answer_id": 675056,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "# This code sets the priority of a process\n\n# ---------------------------------------------------------------\n# Adapted from VBScript code contained in the book:\n# \"Windows Server Cookbook\" by Robbie Allen\n# ISBN: 0-596-00633-0\n# ---------------------------------------------------------------\n\nuse Win32::OLE;\n$Win32::OLE::Warn = 3;\n\nuse constant NORMAL => 32;\nuse constant IDLE => 64;\nuse constant HIGH_PRIORITY => 128;\nuse constant REALTIME => 256;\nuse constant BELOW_NORMAL => 16384;\nuse constant ABOVE_NORMAL => 32768;\n\n# ------ SCRIPT CONFIGURATION ------\n$strComputer = '.';\n$intPID = 2880; # set this to the PID of the target process\n$intPriority = ABOVE_NORMAL; # Set this to one of the constants above\n# ------ END CONFIGURATION ---------\n\nprint \"Process PID: $intPID\\n\";\n\n$objWMIProcess = Win32::OLE->GetObject('winmgmts:\\\\\\\\' . $strComputer . '\\\\root\\\\cimv2:Win32_Process.Handle=\\'' . $intPID . '\\'');\n\nprint 'Process name: ' . $objWMIProcess->Name, \"\\n\";\n\n$intRC = $objWMIProcess->SetPriority($intPriority);\n\nif ($intRC == 0) {\n print \"Successfully set priority.\\n\";\n}\nelse {\n print 'Could not set priority. Error code: ' . $intRC, \"\\n\";\n}\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55/"
] |
4,221 | <p>I'd like to use a <code>LinqDataSource</code> control on a page and limit the amount of records returned. I know if I use code behind I could do something like this:</p>
<pre><code>IEnumerable<int> values = Enumerable.Range(0, 10);
IEnumerable<int> take3 = values.Take(3);
</code></pre>
<p>Does anyone know if something like this is possible with a <code>LinqDataSource</code> control?</p>
<p><strong>[Update]</strong></p>
<p>I'm going to use the <code>LinqDataSource</code> with the <code>ListView</code> control, <em>not</em> a GridView or Repeater. The <code>LinqDataSource</code> wizard does not provide the ability to limit the number of records return. The Advanced options only allow you to enabled deletes, inserts, and updates.</p>
| [
{
"answer_id": 4231,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 2,
"selected": false,
"text": "SELECT TOP 3 FROM \n"
},
{
"answer_id": 27327,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 4,
"selected": false,
"text": "<LayoutTemplate>\n <div id=\"itemPlaceholder\" runat=\"server\" />\n <asp:DataPager ID=\"DataPager1\" runat=\"server\" PageSize=\"3\">\n </asp:DataPager> \n</LayoutTemplate>\n"
},
{
"answer_id": 62158,
"author": "Ollie",
"author_id": 4453,
"author_profile": "https://Stackoverflow.com/users/4453",
"pm_score": 5,
"selected": false,
"text": "protected void lnqRecentOrder_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n DataClassesDataContext dx = new DataClassesDataContext();\n e.Result = (from o in dx.Orders\n where o.CustomerID == Int32.Parse(Request.QueryString[\"CustomerID\"])\n select o).Take(5);\n}\n"
},
{
"answer_id": 5330890,
"author": "10gler",
"author_id": 663178,
"author_profile": "https://Stackoverflow.com/users/663178",
"pm_score": 2,
"selected": false,
"text": "protected void ldsLastEntries_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n e.Arguments.MaximumRows = 10;\n}\n"
},
{
"answer_id": 13048430,
"author": "Abd-elhameed Quraim",
"author_id": 1771068,
"author_profile": "https://Stackoverflow.com/users/1771068",
"pm_score": 3,
"selected": false,
"text": "protected void DocsData_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n e.Arguments.MaximumRows = 5;\n}\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/519/"
] |
4,227 | <p>I'm using a <code>Dictionary<string, int></code> where the <code>int</code> is a count of the key.</p>
<p>Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:</p>
<pre><code>int LastCount = mydict[mydict.keys[mydict.keys.Count]];
</code></pre>
<p>does not work, because <code>Dictionary.Keys</code> does not implement a []-indexer.</p>
<p>I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a <code>Stack<MyStruct></code>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?</p>
| [
{
"answer_id": 4252,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 3,
"selected": false,
"text": "string[] temp = new string[mydict.count];\nmydict.Keys.CopyTo(temp, 0)\nint LastCount = mydict[temp[mydict.count - 1]]\n"
},
{
"answer_id": 4258,
"author": "Juan",
"author_id": 550,
"author_profile": "https://Stackoverflow.com/users/550",
"pm_score": 3,
"selected": false,
"text": "Dictionary<string, int>.KeyCollection keys = mydict.keys;\nstring lastKey = keys.Last();\n"
},
{
"answer_id": 4589,
"author": "Calanus",
"author_id": 445,
"author_profile": "https://Stackoverflow.com/users/445",
"pm_score": 3,
"selected": false,
"text": "public class ExtendedDictionary : Dictionary<string, int>\n{\n private int lastKeyInserted = -1;\n\n public int LastKeyInserted\n {\n get { return lastKeyInserted; }\n set { lastKeyInserted = value; }\n }\n\n public void AddNew(string s, int i)\n {\n lastKeyInserted = i;\n\n base.Add(s, i);\n }\n}\n"
},
{
"answer_id": 756286,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "public MyDictionary<K, T> : IDictionary<K, T>\n{\n private IDictionary<K, T> _InnerDictionary;\n\n public K LastInsertedKey { get; set; }\n\n public MyDictionary()\n {\n _InnerDictionary = new Dictionary<K, T>();\n }\n\n #region Implementation of IDictionary\n\n public void Add(KeyValuePair<K, T> item)\n {\n _InnerDictionary.Add(item);\n LastInsertedKey = item.Key;\n\n }\n\n public void Add(K key, T value)\n {\n _InnerDictionary.Add(key, value);\n LastInsertedKey = key;\n }\n\n .... rest of IDictionary methods\n\n #endregion\n\n}\n .Remove()"
},
{
"answer_id": 2619931,
"author": "Glenn Slayden",
"author_id": 147511,
"author_profile": "https://Stackoverflow.com/users/147511",
"pm_score": 2,
"selected": false,
"text": "Dictionary<K,V> Keys dict.Keys.ElementAt(i) using System;\nusing System.Collections.Generic;\nusing System.Reflection;\n\npublic static class Extensions\n{\n public static TKey KeyByIndex<TKey,TValue>(this Dictionary<TKey, TValue> dict, int idx)\n {\n Type type = typeof(Dictionary<TKey, TValue>);\n FieldInfo info = type.GetField(\"entries\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (info != null)\n {\n // .NET\n Object element = ((Array)info.GetValue(dict)).GetValue(idx);\n return (TKey)element.GetType().GetField(\"key\", BindingFlags.Public | BindingFlags.Instance).GetValue(element);\n }\n // Mono:\n info = type.GetField(\"keySlots\", BindingFlags.NonPublic | BindingFlags.Instance);\n return (TKey)((Array)info.GetValue(dict)).GetValue(idx);\n }\n};\n"
},
{
"answer_id": 4735712,
"author": "Vitor Hugo",
"author_id": 581486,
"author_profile": "https://Stackoverflow.com/users/581486",
"pm_score": 9,
"selected": true,
"text": "int LastCount = mydict.Keys.ElementAt(mydict.Count -1);\n"
},
{
"answer_id": 6755798,
"author": "Daniel Ballinger",
"author_id": 54026,
"author_profile": "https://Stackoverflow.com/users/54026",
"pm_score": 2,
"selected": false,
"text": "Dictionary<string, int> private sealed class IntDictionary : KeyedCollection<string, int>\n{\n protected override string GetKeyForItem(int item)\n {\n // The example works better when the value contains the key. It falls down a bit for a dictionary of ints.\n return item.ToString();\n }\n}\n\nKeyedCollection<string, int> intCollection = new ClassThatContainsSealedImplementation.IntDictionary();\n\nintCollection.Add(7);\n\nint valueByIndex = intCollection[0];\n"
},
{
"answer_id": 6759645,
"author": "takrl",
"author_id": 520044,
"author_profile": "https://Stackoverflow.com/users/520044",
"pm_score": 2,
"selected": false,
"text": "KeyValuePair<TKey, TValue> public sealed class CustomDictionary<TKey, TValue>\n : KeyedCollection<TKey, KeyValuePair<TKey, TValue>>\n{\n protected override TKey GetKeyForItem(KeyValuePair<TKey, TValue> item)\n {\n return item.Key;\n }\n}\n CustomDictionary<string, int> custDict = new CustomDictionary<string, int>();\n\ncustDict.Add(new KeyValuePair<string, int>(\"key\", 7));\n\nint valueByIndex = custDict[0].Value;\nint valueByKey = custDict[\"key\"].Value;\nstring keyByIndex = custDict[0].Key;\n"
},
{
"answer_id": 36462499,
"author": "espaciomore",
"author_id": 2743497,
"author_profile": "https://Stackoverflow.com/users/2743497",
"pm_score": 2,
"selected": false,
"text": "KeyValuePair<string, string>[] filters;"
},
{
"answer_id": 40397023,
"author": "quicktrick",
"author_id": 6123485,
"author_profile": "https://Stackoverflow.com/users/6123485",
"pm_score": 1,
"selected": false,
"text": "class ListArray<T> : List<T[]> { }\n class ListArray<T> : List<T[]>\n{\n public ListArray() : base() { }\n public ListArray(int capacity) : base(capacity) { }\n}\n ListArray<string> settingsRead = new ListArray<string>();\nusing (var sr = new StreamReader(myFile))\n{\n string line;\n while ((line = sr.ReadLine()) != null)\n {\n string[] keyValueStrings = line.Split(separator);\n for (int i = 0; i < keyValueStrings.Length; i++)\n keyValueStrings[i] = keyValueStrings[i].Trim();\n settingsRead.Add(keyValueStrings);\n }\n}\n// Later you get your key/value strings simply by index\nstring[] myKeyValueStrings = settingsRead[index];\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
4,230 | <p>I've been doing ASP.NET development for a little while now, and I've used both the GridView and the DataGrid controls before for various things, but I never could find a really good reason to use one or the other. I'd like to know:</p>
<p>What is the difference between these 2 ASP.NET controls? What are the advantages or disadvantages of both? Is one any faster? Newer? Easier to maintain?</p>
<p>The intellisense summary for the controls doesn't seem to describe any difference between the two. They both can view, edit, and sort data and automatically generate columns at runtime.</p>
<p><strong>Edit:</strong> Visual Studio 2008 no longer lists DataGrid as an available control in the toolbox. It is still available (for legacy support I assume) if you type it in by hand though.</p>
| [
{
"answer_id": 21901381,
"author": "Suhaib Janjua",
"author_id": 3240038,
"author_profile": "https://Stackoverflow.com/users/3240038",
"pm_score": 4,
"selected": false,
"text": "GridView DataGrid DataGrid GridView DataGrid GridView DataSource DataGrid GridView WebControl DataGrid DataGrid GridView DataGrid DataGrid GridView"
},
{
"answer_id": 55546706,
"author": "Litisqe Kumar",
"author_id": 5047627,
"author_profile": "https://Stackoverflow.com/users/5047627",
"pm_score": 1,
"selected": false,
"text": "DataGrid Asp.Net 1.0 SortCommand event PageIndexChanged event GridView Asp.Net 2.0 Paging and Sorting Update and Delete operations DataGrid events properties Item Row ItemCommand - RowCommand ItemDataBound - RowDataBound e.Item.ItemType - e.Row.RowType"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
4,242 | <p>I want to convert a primitive to a string, and I tried:</p>
<pre><code>myInt.toString();
</code></pre>
<p>This fails with the error:</p>
<pre><code>int cannot be dereferenced
</code></pre>
<p>Now, I get that primitives are not reference types (ie, not an Object) and so cannot have methods. However, Java 5 introduced autoboxing and unboxing (a la C#... which I never liked in C#, but that's beside the point). So with autoboxing, I would expect the above to convert myInt to an Integer and then call toString() on that.</p>
<p>Furthermore, I believe C# allows such a call, unless I remember incorrectly. Is this just an unfortunate shortcoming of Java's autoboxing/unboxing specification, or is there a good reason for this?</p>
| [
{
"answer_id": 4247,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 7,
"selected": true,
"text": "myInt Integer.toString(myInt);\n"
},
{
"answer_id": 4256,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 5,
"selected": false,
"text": "Integer.toString(myInt);\n"
},
{
"answer_id": 4384,
"author": "dlinsin",
"author_id": 198,
"author_profile": "https://Stackoverflow.com/users/198",
"pm_score": 3,
"selected": false,
"text": "public class methodOverloading{\n public static void hello(Integer x){\n System.out.println(\"Integer\");\n }\n\n public static void hello(long x){\n System.out.println(\"long\");\n }\n\n public static void main(String[] args){\n int i = 5;\n hello(i);\n }\n}\n"
},
{
"answer_id": 7083,
"author": "SaM",
"author_id": 883,
"author_profile": "https://Stackoverflow.com/users/883",
"pm_score": 4,
"selected": false,
"text": "String.valueOf(myInt);\n Object Integer.toString(myInt)"
},
{
"answer_id": 128153,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "((Integer) myInt).toString();\n Integer.valueOf(myInt).toString();\n String.valueOf(myInt)"
},
{
"answer_id": 21469629,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "5.asInteger\n some.magic.stuff.Integer.asInteger(5);\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] |
4,269 | <p>What is the best way to programmatically send an SMS text message?</p>
<p>Are there any free Web Service based SMS gateways?</p>
<p>I know that if I happen to know the user's carrier (Sprint, AT&T, etc), I can send an <a href="http://en.wikipedia.org/wiki/SMS_gateways" rel="noreferrer">SMS by emailing an address</a> based on phone number + carrier. I would like a good solution that does not require me to know the carrier. Barring that, is there an easy way to lookup carrier given a cell phone number?</p>
<p>I understand that there are some services independent of the major mobile carriers that offer a per-message fee-based service, with API. What I would like to know is how such organizations tap into the SMS networks. Do they have contracts with mobile carriers to resell their services?</p>
| [
{
"answer_id": 429566,
"author": "masfenix",
"author_id": 50312,
"author_profile": "https://Stackoverflow.com/users/50312",
"pm_score": -1,
"selected": false,
"text": "[email protected]"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] |
4,287 | <p>I have a process in erlang that is supposed to do something immediately after spawn, then send the result back to the parent when it is finished. How do I figure out the PID of the process that spawned it?</p>
| [
{
"answer_id": 4304,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 5,
"selected": true,
"text": "spawn_link(?MODULE, child, [self()]).\n"
},
{
"answer_id": 1261457,
"author": "rvirding",
"author_id": 77617,
"author_profile": "https://Stackoverflow.com/users/77617",
"pm_score": 2,
"selected": false,
"text": "spawn_link(fun () -> child(self()) end)\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121/"
] |
4,306 | <p>I am working on a project that requires the manipulation of enormous matrices, specifically pyramidal summation for a copula calculation. </p>
<p>In short, I need to keep track of a relatively small number of values (usually a value of 1, and in rare cases more than 1) in a sea of zeros in the matrix (multidimensional array). </p>
<p>A sparse array allows the user to store a small number of values, and assume all undefined records to be a preset value. Since it is not physically possibly to store all values in memory, I need to store only the few non-zero elements. This could be several million entries.</p>
<p>Speed is a huge priority, and I would also like to dynamically choose the number of variables in the class at runtime.</p>
<p>I currently work on a system that uses a binary search tree (b-tree) to store entries. Does anyone know of a better system?</p>
| [
{
"answer_id": 4311,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 6,
"selected": true,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <map>\n\nclass triple {\npublic:\n int x;\n int y;\n int z;\n bool operator<(const triple &other) const {\n if (x < other.x) return true;\n if (other.x < x) return false;\n if (y < other.y) return true;\n if (other.y < y) return false;\n return z < other.z;\n }\n};\n\nint main(int, char**)\n{\n std::map<triple,int> data;\n triple point;\n int i;\n\n for (i = 0; i < 10000000; ++i) {\n point.x = rand();\n point.y = rand();\n point.z = rand();\n //printf(\"%d %d %d %d\\n\", i, point.x, point.y, point.z);\n data[point] = i;\n }\n return 0;\n}\n std::map data<string,int> data;\nchar ix[100];\n\nsprintf(ix, \"%d,%d\", x, y); // 2 vars\ndata[ix] = i;\n\nsprintf(ix, \"%d,%d,%d\", x, y, z); // 3 vars\ndata[ix] = i;\n"
},
{
"answer_id": 17051,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 2,
"selected": false,
"text": "a= (1, 2, 1); b= (2, 1, 2);\n(a<b) == (b<a) is true, but b!=a\n return lhs.x<rhs.x\n ? true \n : lhs.x==rhs.x \n ? lhs.y<rhs.y \n ? true \n : lhs.y==rhs.y\n ? lhs.z<rhs.z\n : false\n : false\n"
},
{
"answer_id": 39052,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "std::tuple std::vector std::map #include <vector>\n#include <map>\n\nusing index_type = std::vector<int>;\n\ntemplate <typename T>\nusing sparse_array = std::map<index_type, T>;\n std::unordered_map std::vector std::hash #include <vector>\n#include <unordered_map>\n#include <numeric>\n\nusing index_type = std::vector<int>;\n\nstruct index_hash {\n std::size_t operator()(index_type const& i) const noexcept {\n // Like boost::hash_combine; there might be some caveats, see\n // <https://stackoverflow.com/a/50978188/1968>\n auto const hash_combine = [](auto seed, auto x) {\n return std::hash<int>()(x) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n };\n return std::accumulate(i.begin() + 1, i.end(), i[0], hash_combine);\n }\n};\n\ntemplate <typename T>\nusing sparse_array = std::unordered_map<index_type, T, index_hash>;\n int main() {\n using i = index_type;\n\n auto x = sparse_array<int>();\n x[i{1, 2, 3}] = 42;\n x[i{4, 3, 2}] = 23;\n\n std::cout << x[i{1, 2, 3}] + x[i{4, 3, 2}] << '\\n'; // 65\n}\n"
},
{
"answer_id": 24370334,
"author": "eold",
"author_id": 395744,
"author_profile": "https://Stackoverflow.com/users/395744",
"pm_score": 0,
"selected": false,
"text": "// Copyright 2014 Leo Osvald\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef UTIL_IMMUTABLE_SPARSE_MATRIX_HPP_\n#define UTIL_IMMUTABLE_SPARSE_MATRIX_HPP_\n\n#include <algorithm>\n#include <limits>\n#include <map>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n// A simple time-efficient implementation of an immutable sparse matrix\n// Provides efficient iteration of non-zero elements by rows/cols,\n// e.g. to iterate over a range [row_from, row_to) x [col_from, col_to):\n// for (int row = row_from; row < row_to; ++row) {\n// for (auto col_range = sm.nonzero_col_range(row, col_from, col_to);\n// col_range.first != col_range.second; ++col_range.first) {\n// int col = *col_range.first;\n// // use sm(row, col)\n// ...\n// }\ntemplate<typename T = double, class Coord = int>\nclass SparseMatrix {\n struct PointHasher;\n typedef std::map< Coord, std::vector<Coord> > NonZeroList;\n typedef std::pair<Coord, Coord> Point;\n\n public:\n typedef T ValueType;\n typedef Coord CoordType;\n typedef typename NonZeroList::mapped_type::const_iterator CoordIter;\n typedef std::pair<CoordIter, CoordIter> CoordIterRange;\n\n SparseMatrix() = default;\n\n // Reads a matrix stored in MatrixMarket-like format, i.e.:\n // <num_rows> <num_cols> <num_entries>\n // <row_1> <col_1> <val_1>\n // ...\n // Note: the header (lines starting with '%' are ignored).\n template<class InputStream, size_t max_line_length = 1024>\n void Init(InputStream& is) {\n rows_.clear(), cols_.clear();\n values_.clear();\n\n // skip the header (lines beginning with '%', if any)\n decltype(is.tellg()) offset = 0;\n for (char buf[max_line_length + 1];\n is.getline(buf, sizeof(buf)) && buf[0] == '%'; )\n offset = is.tellg();\n is.seekg(offset);\n\n size_t n;\n is >> row_count_ >> col_count_ >> n;\n values_.reserve(n);\n while (n--) {\n Coord row, col;\n typename std::remove_cv<T>::type val;\n is >> row >> col >> val;\n values_[Point(--row, --col)] = val;\n rows_[col].push_back(row);\n cols_[row].push_back(col);\n }\n SortAndShrink(rows_);\n SortAndShrink(cols_);\n }\n\n const T& operator()(const Coord& row, const Coord& col) const {\n static const T kZero = T();\n auto it = values_.find(Point(row, col));\n if (it != values_.end())\n return it->second;\n return kZero;\n }\n\n CoordIterRange\n nonzero_col_range(Coord row, Coord col_from, Coord col_to) const {\n CoordIterRange r;\n GetRange(cols_, row, col_from, col_to, &r);\n return r;\n }\n\n CoordIterRange\n nonzero_row_range(Coord col, Coord row_from, Coord row_to) const {\n CoordIterRange r;\n GetRange(rows_, col, row_from, row_to, &r);\n return r;\n }\n\n Coord row_count() const { return row_count_; }\n Coord col_count() const { return col_count_; }\n size_t nonzero_count() const { return values_.size(); }\n size_t element_count() const { return size_t(row_count_) * col_count_; }\n\n private:\n typedef std::unordered_map<Point,\n typename std::remove_cv<T>::type,\n PointHasher> ValueMap;\n\n struct PointHasher {\n size_t operator()(const Point& p) const {\n return p.first << (std::numeric_limits<Coord>::digits >> 1) ^ p.second;\n }\n };\n\n static void SortAndShrink(NonZeroList& list) {\n for (auto& it : list) {\n auto& indices = it.second;\n indices.shrink_to_fit();\n std::sort(indices.begin(), indices.end());\n }\n\n // insert a sentinel vector to handle the case of all zeroes\n if (list.empty())\n list.emplace(Coord(), std::vector<Coord>(Coord()));\n }\n\n static void GetRange(const NonZeroList& list, Coord i, Coord from, Coord to,\n CoordIterRange* r) {\n auto lr = list.equal_range(i);\n if (lr.first == lr.second) {\n r->first = r->second = list.begin()->second.end();\n return;\n }\n\n auto begin = lr.first->second.begin(), end = lr.first->second.end();\n r->first = lower_bound(begin, end, from);\n r->second = lower_bound(r->first, end, to);\n }\n\n ValueMap values_;\n NonZeroList rows_, cols_;\n Coord row_count_, col_count_;\n};\n\n#endif /* UTIL_IMMUTABLE_SPARSE_MATRIX_HPP_ */\n immutable std::vector std::set"
},
{
"answer_id": 39989181,
"author": "BenGoldberg",
"author_id": 3093194,
"author_profile": "https://Stackoverflow.com/users/3093194",
"pm_score": 0,
"selected": false,
"text": "typedef std::tuple<int, int, int> coord_t;\ntypedef boost::hash<coord_t> coord_hash_t;\ntypedef std::unordered_map<coord_hash_t, int, c_hash_t> sparse_array_t;\n\nsparse_array_t the_data;\nthe_data[ { x, y, z } ] = 1; /* list-initialization is cool */\n\nfor( const auto& element : the_data ) {\n int xx, yy, zz, val;\n std::tie( std::tie( xx, yy, zz ), val ) = element;\n /* ... */\n}\n unorderd_map"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522/"
] |
4,369 | <p>I have a directory structure like the following;</p>
<blockquote>
<p>script.php</p>
<p>inc/include1.php<br/>
inc/include2.php</p>
<p>objects/object1.php<br/>
objects/object2.php</p>
<p>soap/soap.php</p>
</blockquote>
<p>Now, I use those objects in both <code>script.php</code> and <code>/soap/soap.php</code>, I could move them, but I want the directory structure like that for a specific reason. When executing <code>script.php</code> the include path is <code>inc/include.php</code> and when executing <code>/soap/soap.php</code> it's <code>../inc</code>, absolute paths work, <code>/mnt/webdev/[project name]/inc/include1.php...</code> But it's an ugly solution if I ever want to move the directory to a different location.</p>
<p>So is there a way to use relative paths, or a way to programmatically generate the <code>"/mnt/webdev/[project name]/"</code>?</p>
| [
{
"answer_id": 4385,
"author": "Peter Coulton",
"author_id": 117,
"author_profile": "https://Stackoverflow.com/users/117",
"pm_score": 8,
"selected": true,
"text": "$root = realpath($_SERVER[\"DOCUMENT_ROOT\"]);\n\ninclude \"$root/inc/include1.php\";\n"
},
{
"answer_id": 4388,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 3,
"selected": false,
"text": "$_SERVER[\"DOCUMENT_ROOT\"]"
},
{
"answer_id": 4408,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 6,
"selected": false,
"text": "__FILE__ soap.php include dirname(__FILE__).'/../inc/include.php';\n __FILE__"
},
{
"answer_id": 5187,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 1,
"selected": false,
"text": "require_once 'inc1.php';\n site directory\n html (web root)\n your web-accessible files\n includes\n your include files\n"
},
{
"answer_id": 6463,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 0,
"selected": false,
"text": "require_once('library/string.class.php')\n 'model/user.class'\n'controllers/front.php'\n"
},
{
"answer_id": 53079,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 2,
"selected": false,
"text": "__FILE__ <?php\n\n$docRoot = str_replace($_SERVER['SCRIPT_NAME'], '', __FILE__);\nrequire_once($docRoot . '/lib/include.php');\n\n?>\n $_SERVER['SCRIPT_NAME']"
},
{
"answer_id": 93036,
"author": "Sam McAfee",
"author_id": 577,
"author_profile": "https://Stackoverflow.com/users/577",
"pm_score": 3,
"selected": false,
"text": "__autoload() function __autoload($class_name) {\n require_once $class_name . '.php';\n}\n\n$obj = new MyClass1();\n$obj2 = new MyClass2(); \n"
},
{
"answer_id": 9233260,
"author": "Thane Gill",
"author_id": 1202754,
"author_profile": "https://Stackoverflow.com/users/1202754",
"pm_score": 2,
"selected": false,
"text": "function findRoot() { \n return(substr($_SERVER[\"SCRIPT_FILENAME\"], 0, (stripos($_SERVER[\"SCRIPT_FILENAME\"], $_SERVER[\"SCRIPT_NAME\"])+1)));\n}\n <?php\n\nfunction findRoot() {\n return(substr($_SERVER[\"SCRIPT_FILENAME\"], 0, (stripos($_SERVER[\"SCRIPT_FILENAME\"], $_SERVER[\"SCRIPT_NAME\"])+1)));\n}\n\ninclude(findRoot() . 'Post.php');\n$posts = getPosts(findRoot() . 'posts_content');\n\ninclude(findRoot() . 'includes/head.php');\n\nfor ($i=(sizeof($posts)-1); 0 <= $i; $i--) {\n $posts[$i]->displayArticle();\n}\n\ninclude(findRoot() . 'includes/footer.php');\n\n?>\n"
},
{
"answer_id": 29608002,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1)).\"/path/to/file.php\");\n require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1)).\"/_resources/functions.php\");\n str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1)) path_back require(path_back().\"/_resources/another_php_file.php\");\n"
},
{
"answer_id": 50250763,
"author": "yuvraj",
"author_id": 9670536,
"author_profile": "https://Stackoverflow.com/users/9670536",
"pm_score": 0,
"selected": false,
"text": "define(\"APPLICATION_PATH\", realpath(dirname(__FILE__) . '/../app'));\nor \ndefine(\"APPLICATION_PATH\", realpath(DIR(__FILE__) . '/../app'));\n include(APPLICATION_PATH .\"/config/config.ini\";\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264/"
] |
4,371 | <p>I lost my MySQL username and password. How do I retrieve it?</p>
| [
{
"answer_id": 4376,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 9,
"selected": true,
"text": "SELECT * FROM mysql.user;\n UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';\n"
},
{
"answer_id": 4403,
"author": "jake",
"author_id": 389,
"author_profile": "https://Stackoverflow.com/users/389",
"pm_score": 6,
"selected": false,
"text": "UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';\nFLUSH PRIVILEGES;\n C:\\> C:\\mysql\\bin\\mysqld-nt --init-file = C:\\mysql-init.txt\n C:\\> \"C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqld-nt.exe\" --defaults-file=\"C:\\Program Files\\MySQL\\MySQL Server 5.0\\my.ini\" --init-file=C:\\mysql-init.txt\n"
},
{
"answer_id": 8078308,
"author": "ThinkingMonkey",
"author_id": 858515,
"author_profile": "https://Stackoverflow.com/users/858515",
"pm_score": 5,
"selected": false,
"text": "FLUSH PRIVILEGES; --skip-grant-options"
},
{
"answer_id": 27244876,
"author": "Syeful Islam",
"author_id": 1468773,
"author_profile": "https://Stackoverflow.com/users/1468773",
"pm_score": 2,
"selected": false,
"text": "mysql> SELECT * FROM mysql.user;\n mysql> UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';\n"
},
{
"answer_id": 33506775,
"author": "snemarch",
"author_id": 430360,
"author_profile": "https://Stackoverflow.com/users/430360",
"pm_score": 3,
"selected": false,
"text": "std::vector<unsigned char> decrypt(BYTE *input, size_t length) {\n DATA_BLOB inblob { length, input };\n DATA_BLOB outblob;\n\n if (!CryptUnprotectData(&inblob, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &outblob)) {\n throw std::runtime_error(\"Couldn't decrypt\");\n }\n\n std::vector<unsigned char> output(length);\n memcpy(&output[0], outblob.pbData, outblob.cbData);\n\n return output;\n}\n"
},
{
"answer_id": 34945832,
"author": "Sajjad Ashraf",
"author_id": 1131673,
"author_profile": "https://Stackoverflow.com/users/1131673",
"pm_score": 3,
"selected": false,
"text": "sudo service mysql stop\n sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &\n sudo mysql\nFLUSH PRIVILEGES;\nSET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');\n"
},
{
"answer_id": 49207760,
"author": "S.M.Mousavi",
"author_id": 1074799,
"author_profile": "https://Stackoverflow.com/users/1074799",
"pm_score": 3,
"selected": false,
"text": "sudo mysql -u root -p;\n mousavi 123456 UPDATE mysql.user SET authentication_string=PASSWORD('123456') WHERE user='mousavi'; \n FLUSH PRIVILEGES;\n"
},
{
"answer_id": 72846018,
"author": "Raikish",
"author_id": 8018902,
"author_profile": "https://Stackoverflow.com/users/8018902",
"pm_score": 0,
"selected": false,
"text": "ALTER USER 'some_user_name'@'localhost' IDENTIFIED BY 'a_super_secure_password';\n ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'mynewpassword';\n select user from mysql.user;\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131/"
] |
4,393 | <p>How can I drop all tables whose names begin with a given string? </p>
<p>I think this can be done with some dynamic SQL and the <code>INFORMATION_SCHEMA</code> tables.</p>
| [
{
"answer_id": 4394,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 7,
"selected": false,
"text": "SELECT 'DROP TABLE \"' + TABLE_NAME + '\"' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n"
},
{
"answer_id": 4400,
"author": "FryHard",
"author_id": 231,
"author_profile": "https://Stackoverflow.com/users/231",
"pm_score": 2,
"selected": false,
"text": "DECLARE @startStr AS Varchar (20)\nSET @startStr = 'tableName'\n\nDECLARE @startStrLen AS int\nSELECT @startStrLen = LEN(@startStr)\n\nSELECT 'DROP TABLE ' + name FROM sysobjects\nWHERE type = 'U' AND LEFT(name, @startStrLen) = @startStr\n tableName"
},
{
"answer_id": 4401,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 8,
"selected": true,
"text": "DECLARE @cmd varchar(4000)\nDECLARE cmds CURSOR FOR\nSELECT 'drop table [' + Table_Name + ']'\nFROM INFORMATION_SCHEMA.TABLES\nWHERE Table_Name LIKE 'prefix%'\n\nOPEN cmds\nWHILE 1 = 1\nBEGIN\n FETCH cmds INTO @cmd\n IF @@fetch_status != 0 BREAK\n EXEC(@cmd)\nEND\nCLOSE cmds;\nDEALLOCATE cmds\n"
},
{
"answer_id": 189920,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": false,
"text": "CREATE PROCEDURE usp_GenerateDROP\n @Pattern AS varchar(255)\n ,@PrintQuery AS bit\n ,@ExecQuery AS bit\nAS\nBEGIN\n DECLARE @sql AS varchar(max)\n\n SELECT @sql = COALESCE(@sql, '') + 'DROP TABLE [' + TABLE_NAME + ']' + CHAR(13) + CHAR(10)\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_NAME LIKE @Pattern\n\n IF @PrintQuery = 1 PRINT @sql\n IF @ExecQuery = 1 EXEC (@sql)\nEND\n"
},
{
"answer_id": 17281642,
"author": "Shashank",
"author_id": 2517289,
"author_profile": "https://Stackoverflow.com/users/2517289",
"pm_score": 1,
"selected": false,
"text": "select 'DROP TABLE ' + name from sysobjects\nwhere type = 'U' and sysobjects.name like '%test%'\n"
},
{
"answer_id": 21671836,
"author": "Tony O'Hagan",
"author_id": 365261,
"author_profile": "https://Stackoverflow.com/users/365261",
"pm_score": 4,
"selected": false,
"text": "t.Ordinal WITH TablesCTE(SchemaName, TableName, TableID, Ordinal) AS\n(\n SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n 0 AS Ordinal\n FROM sys.objects AS so\n WHERE so.type = 'U'\n AND so.is_ms_Shipped = 0\n AND OBJECT_NAME(so.object_id)\n LIKE 'MyPrefix%'\n\n UNION ALL\n SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n tt.Ordinal + 1 AS Ordinal\n FROM sys.objects AS so\n INNER JOIN sys.foreign_keys AS f\n ON f.parent_object_id = so.object_id\n AND f.parent_object_id != f.referenced_object_id\n INNER JOIN TablesCTE AS tt\n ON f.referenced_object_id = tt.TableID\n WHERE so.type = 'U'\n AND so.is_ms_Shipped = 0\n AND OBJECT_NAME(so.object_id)\n LIKE 'MyPrefix%'\n)\nSELECT DISTINCT t.Ordinal, t.SchemaName, t.TableName, t.TableID\nFROM TablesCTE AS t\n INNER JOIN\n (\n SELECT\n itt.SchemaName AS SchemaName,\n itt.TableName AS TableName,\n itt.TableID AS TableID,\n Max(itt.Ordinal) AS Ordinal\n FROM TablesCTE AS itt\n GROUP BY itt.SchemaName, itt.TableName, itt.TableID\n ) AS tt\n ON t.TableID = tt.TableID\n AND t.Ordinal = tt.Ordinal\nORDER BY t.Ordinal DESC, t.TableName ASC\n"
},
{
"answer_id": 25082268,
"author": "RGH",
"author_id": 1908292,
"author_profile": "https://Stackoverflow.com/users/1908292",
"pm_score": 1,
"selected": false,
"text": "SELECT 'if object_id(''' + TABLE_NAME + ''') is not null begin drop table \"' + TABLE_NAME + '\" end;' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n"
},
{
"answer_id": 28533145,
"author": "Xaxum",
"author_id": 873487,
"author_profile": "https://Stackoverflow.com/users/873487",
"pm_score": 1,
"selected": false,
"text": "SELECT 'DROP TABLE Databasename.schema.' + TABLE_NAME \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE 'strmatch%'\n"
},
{
"answer_id": 30372503,
"author": "Rosdi Kasim",
"author_id": 193634,
"author_profile": "https://Stackoverflow.com/users/193634",
"pm_score": 3,
"selected": false,
"text": "SELECT 'DROP TABLE \"' || TABLE_NAME || '\";'\nFROM USER_TABLES\nWHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'\n SELECT 'DROP TABLE \"' || TABLE_NAME || '\" cascade constraints PURGE;'\nFROM USER_TABLES\nWHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'\n DROP TABLE cascade constraints PURGE VIEWS SELECT 'DROP VIEW \"' || VIEW_NAME || '\";'\nFROM USER_VIEWS\nWHERE VIEW_NAME LIKE 'YOURVIEWPREFIX%'\n"
},
{
"answer_id": 31668613,
"author": "talsibony",
"author_id": 1220652,
"author_profile": "https://Stackoverflow.com/users/1220652",
"pm_score": 3,
"selected": false,
"text": "SELECT CONCAT( 'DROP TABLE `', TABLE_NAME, '`;' ) AS query\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_NAME LIKE 'wp_%'\n"
},
{
"answer_id": 36200064,
"author": "vencedor",
"author_id": 2653457,
"author_profile": "https://Stackoverflow.com/users/2653457",
"pm_score": 3,
"selected": false,
"text": "SELECT CONCAT('DROP TABLE `', TABLE_NAME,'`;') \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE 'TABLE_PREFIX_GOES_HERE%';\n TABLE_PREFIX_GOES_HERE"
},
{
"answer_id": 37708151,
"author": "mrosiak",
"author_id": 3242203,
"author_profile": "https://Stackoverflow.com/users/3242203",
"pm_score": 3,
"selected": false,
"text": "EXEC sp_MSforeachtable 'if PARSENAME(\"?\",1) like ''%CertainString%'' DROP TABLE ?'\n"
},
{
"answer_id": 39347828,
"author": "João Mergulhão",
"author_id": 6795613,
"author_profile": "https://Stackoverflow.com/users/6795613",
"pm_score": 1,
"selected": false,
"text": "SELECT 'DROP TABLE \"' + t.name + '\"' \nFROM tempdb.sys.tables t\nWHERE t.name LIKE '[prefix]%'\n"
},
{
"answer_id": 57511478,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 2,
"selected": false,
"text": "DECLARE @sql NVARCHAR(MAX) = N'';\n\nSELECT @sql += '\nDROP TABLE ' \n + QUOTENAME(s.name)\n + '.' + QUOTENAME(t.name) + ';'\n FROM sys.tables AS t\n INNER JOIN sys.schemas AS s\n ON t.[schema_id] = s.[schema_id] \n WHERE t.name LIKE 'something%';\n\nPRINT @sql;\n-- EXEC sp_executesql @sql;\n"
},
{
"answer_id": 65718571,
"author": "Tomasz Wieczorkowski",
"author_id": 2355469,
"author_profile": "https://Stackoverflow.com/users/2355469",
"pm_score": 1,
"selected": false,
"text": "DECLARE \n @drop_command NVARCHAR(MAX) = '',\n @system_time date,\n @table_date nvarchar(8),\n @older_than int = 7\n \nSet @system_time = (select getdate() - @older_than)\nSet @table_date = (SELECT CONVERT(char(8), @system_time, 112))\n\nSELECT @drop_command += N'DROP TABLE ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME([Name]) + ';'\nFROM <your_database_name>.sys.tables\nWHERE [Name] LIKE 'table_%' AND RIGHT([Name],8) < @table_date\n\nSELECT @drop_command\n \nEXEC sp_executesql @drop_command\n"
},
{
"answer_id": 71514887,
"author": "Arthur Cam",
"author_id": 10475213,
"author_profile": "https://Stackoverflow.com/users/10475213",
"pm_score": 1,
"selected": false,
"text": "declare @Tables as nvarchar(max) = '[schemaName].['\nselect @Tables =@Tables + TABLE_NAME +'],[schemaName].['\nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_TYPE='BASE TABLE'\nAND TABLE_SCHEMA = 'schemaName'\nAND TABLE_NAME like '%whateverYourQueryIs%'\n\nselect @Tables = Left(@Tables,LEN(@Tables)-13) --trying to remove last \",[schemaName].[\" part, so you need to change this 13 with actual lenght \n\n--print @Tables\n\ndeclare @Query as nvarchar(max) = 'Drop table ' +@Tables \n\n--print @Query\n\n\nexec sp_executeSQL @Query\n"
},
{
"answer_id": 73278269,
"author": "AliNajafZadeh",
"author_id": 16746668,
"author_profile": "https://Stackoverflow.com/users/16746668",
"pm_score": 0,
"selected": false,
"text": "declare @TableLst table(TblNames nvarchar(500))\ninsert into @TableLst (TblNames)\nSELECT 'DROP TABLE [' + Table_Name + ']'\nFROM INFORMATION_SCHEMA.TABLES\nWHERE Table_Name LIKE 'yourFilter%'\nWHILE ((select COUNT(*) as CntTables from @TableLst) > 0)\nBEGIN\n declare @ForExecCms nvarchar(500) = (select top(1) TblNames from @TableLst)\n EXEC(@ForExecCms)\n delete from @TableLst where TblNames = @ForExecCms\nEND\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] |
4,416 | <p>I am walking through the MS Press Windows Workflow Step-by-Step book and in chapter 8 it mentions a tool with the filename "wca.exe". This is supposed to be able to generate workflow communication helper classes based on an interface you provide it. I can't find that file. I thought it would be in the latest .NET 3.5 SDK, but I just downloaded and fully installed, and it's not there. Also, some MSDN forum posts had links posted that just go to 404s. So, where can I find wca.exe?</p>
| [
{
"answer_id": 4394,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 7,
"selected": false,
"text": "SELECT 'DROP TABLE \"' + TABLE_NAME + '\"' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n"
},
{
"answer_id": 4400,
"author": "FryHard",
"author_id": 231,
"author_profile": "https://Stackoverflow.com/users/231",
"pm_score": 2,
"selected": false,
"text": "DECLARE @startStr AS Varchar (20)\nSET @startStr = 'tableName'\n\nDECLARE @startStrLen AS int\nSELECT @startStrLen = LEN(@startStr)\n\nSELECT 'DROP TABLE ' + name FROM sysobjects\nWHERE type = 'U' AND LEFT(name, @startStrLen) = @startStr\n tableName"
},
{
"answer_id": 4401,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 8,
"selected": true,
"text": "DECLARE @cmd varchar(4000)\nDECLARE cmds CURSOR FOR\nSELECT 'drop table [' + Table_Name + ']'\nFROM INFORMATION_SCHEMA.TABLES\nWHERE Table_Name LIKE 'prefix%'\n\nOPEN cmds\nWHILE 1 = 1\nBEGIN\n FETCH cmds INTO @cmd\n IF @@fetch_status != 0 BREAK\n EXEC(@cmd)\nEND\nCLOSE cmds;\nDEALLOCATE cmds\n"
},
{
"answer_id": 189920,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": false,
"text": "CREATE PROCEDURE usp_GenerateDROP\n @Pattern AS varchar(255)\n ,@PrintQuery AS bit\n ,@ExecQuery AS bit\nAS\nBEGIN\n DECLARE @sql AS varchar(max)\n\n SELECT @sql = COALESCE(@sql, '') + 'DROP TABLE [' + TABLE_NAME + ']' + CHAR(13) + CHAR(10)\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_NAME LIKE @Pattern\n\n IF @PrintQuery = 1 PRINT @sql\n IF @ExecQuery = 1 EXEC (@sql)\nEND\n"
},
{
"answer_id": 17281642,
"author": "Shashank",
"author_id": 2517289,
"author_profile": "https://Stackoverflow.com/users/2517289",
"pm_score": 1,
"selected": false,
"text": "select 'DROP TABLE ' + name from sysobjects\nwhere type = 'U' and sysobjects.name like '%test%'\n"
},
{
"answer_id": 21671836,
"author": "Tony O'Hagan",
"author_id": 365261,
"author_profile": "https://Stackoverflow.com/users/365261",
"pm_score": 4,
"selected": false,
"text": "t.Ordinal WITH TablesCTE(SchemaName, TableName, TableID, Ordinal) AS\n(\n SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n 0 AS Ordinal\n FROM sys.objects AS so\n WHERE so.type = 'U'\n AND so.is_ms_Shipped = 0\n AND OBJECT_NAME(so.object_id)\n LIKE 'MyPrefix%'\n\n UNION ALL\n SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n tt.Ordinal + 1 AS Ordinal\n FROM sys.objects AS so\n INNER JOIN sys.foreign_keys AS f\n ON f.parent_object_id = so.object_id\n AND f.parent_object_id != f.referenced_object_id\n INNER JOIN TablesCTE AS tt\n ON f.referenced_object_id = tt.TableID\n WHERE so.type = 'U'\n AND so.is_ms_Shipped = 0\n AND OBJECT_NAME(so.object_id)\n LIKE 'MyPrefix%'\n)\nSELECT DISTINCT t.Ordinal, t.SchemaName, t.TableName, t.TableID\nFROM TablesCTE AS t\n INNER JOIN\n (\n SELECT\n itt.SchemaName AS SchemaName,\n itt.TableName AS TableName,\n itt.TableID AS TableID,\n Max(itt.Ordinal) AS Ordinal\n FROM TablesCTE AS itt\n GROUP BY itt.SchemaName, itt.TableName, itt.TableID\n ) AS tt\n ON t.TableID = tt.TableID\n AND t.Ordinal = tt.Ordinal\nORDER BY t.Ordinal DESC, t.TableName ASC\n"
},
{
"answer_id": 25082268,
"author": "RGH",
"author_id": 1908292,
"author_profile": "https://Stackoverflow.com/users/1908292",
"pm_score": 1,
"selected": false,
"text": "SELECT 'if object_id(''' + TABLE_NAME + ''') is not null begin drop table \"' + TABLE_NAME + '\" end;' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n"
},
{
"answer_id": 28533145,
"author": "Xaxum",
"author_id": 873487,
"author_profile": "https://Stackoverflow.com/users/873487",
"pm_score": 1,
"selected": false,
"text": "SELECT 'DROP TABLE Databasename.schema.' + TABLE_NAME \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE 'strmatch%'\n"
},
{
"answer_id": 30372503,
"author": "Rosdi Kasim",
"author_id": 193634,
"author_profile": "https://Stackoverflow.com/users/193634",
"pm_score": 3,
"selected": false,
"text": "SELECT 'DROP TABLE \"' || TABLE_NAME || '\";'\nFROM USER_TABLES\nWHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'\n SELECT 'DROP TABLE \"' || TABLE_NAME || '\" cascade constraints PURGE;'\nFROM USER_TABLES\nWHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'\n DROP TABLE cascade constraints PURGE VIEWS SELECT 'DROP VIEW \"' || VIEW_NAME || '\";'\nFROM USER_VIEWS\nWHERE VIEW_NAME LIKE 'YOURVIEWPREFIX%'\n"
},
{
"answer_id": 31668613,
"author": "talsibony",
"author_id": 1220652,
"author_profile": "https://Stackoverflow.com/users/1220652",
"pm_score": 3,
"selected": false,
"text": "SELECT CONCAT( 'DROP TABLE `', TABLE_NAME, '`;' ) AS query\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_NAME LIKE 'wp_%'\n"
},
{
"answer_id": 36200064,
"author": "vencedor",
"author_id": 2653457,
"author_profile": "https://Stackoverflow.com/users/2653457",
"pm_score": 3,
"selected": false,
"text": "SELECT CONCAT('DROP TABLE `', TABLE_NAME,'`;') \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE 'TABLE_PREFIX_GOES_HERE%';\n TABLE_PREFIX_GOES_HERE"
},
{
"answer_id": 37708151,
"author": "mrosiak",
"author_id": 3242203,
"author_profile": "https://Stackoverflow.com/users/3242203",
"pm_score": 3,
"selected": false,
"text": "EXEC sp_MSforeachtable 'if PARSENAME(\"?\",1) like ''%CertainString%'' DROP TABLE ?'\n"
},
{
"answer_id": 39347828,
"author": "João Mergulhão",
"author_id": 6795613,
"author_profile": "https://Stackoverflow.com/users/6795613",
"pm_score": 1,
"selected": false,
"text": "SELECT 'DROP TABLE \"' + t.name + '\"' \nFROM tempdb.sys.tables t\nWHERE t.name LIKE '[prefix]%'\n"
},
{
"answer_id": 57511478,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 2,
"selected": false,
"text": "DECLARE @sql NVARCHAR(MAX) = N'';\n\nSELECT @sql += '\nDROP TABLE ' \n + QUOTENAME(s.name)\n + '.' + QUOTENAME(t.name) + ';'\n FROM sys.tables AS t\n INNER JOIN sys.schemas AS s\n ON t.[schema_id] = s.[schema_id] \n WHERE t.name LIKE 'something%';\n\nPRINT @sql;\n-- EXEC sp_executesql @sql;\n"
},
{
"answer_id": 65718571,
"author": "Tomasz Wieczorkowski",
"author_id": 2355469,
"author_profile": "https://Stackoverflow.com/users/2355469",
"pm_score": 1,
"selected": false,
"text": "DECLARE \n @drop_command NVARCHAR(MAX) = '',\n @system_time date,\n @table_date nvarchar(8),\n @older_than int = 7\n \nSet @system_time = (select getdate() - @older_than)\nSet @table_date = (SELECT CONVERT(char(8), @system_time, 112))\n\nSELECT @drop_command += N'DROP TABLE ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME([Name]) + ';'\nFROM <your_database_name>.sys.tables\nWHERE [Name] LIKE 'table_%' AND RIGHT([Name],8) < @table_date\n\nSELECT @drop_command\n \nEXEC sp_executesql @drop_command\n"
},
{
"answer_id": 71514887,
"author": "Arthur Cam",
"author_id": 10475213,
"author_profile": "https://Stackoverflow.com/users/10475213",
"pm_score": 1,
"selected": false,
"text": "declare @Tables as nvarchar(max) = '[schemaName].['\nselect @Tables =@Tables + TABLE_NAME +'],[schemaName].['\nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_TYPE='BASE TABLE'\nAND TABLE_SCHEMA = 'schemaName'\nAND TABLE_NAME like '%whateverYourQueryIs%'\n\nselect @Tables = Left(@Tables,LEN(@Tables)-13) --trying to remove last \",[schemaName].[\" part, so you need to change this 13 with actual lenght \n\n--print @Tables\n\ndeclare @Query as nvarchar(max) = 'Drop table ' +@Tables \n\n--print @Query\n\n\nexec sp_executeSQL @Query\n"
},
{
"answer_id": 73278269,
"author": "AliNajafZadeh",
"author_id": 16746668,
"author_profile": "https://Stackoverflow.com/users/16746668",
"pm_score": 0,
"selected": false,
"text": "declare @TableLst table(TblNames nvarchar(500))\ninsert into @TableLst (TblNames)\nSELECT 'DROP TABLE [' + Table_Name + ']'\nFROM INFORMATION_SCHEMA.TABLES\nWHERE Table_Name LIKE 'yourFilter%'\nWHILE ((select COUNT(*) as CntTables from @TableLst) > 0)\nBEGIN\n declare @ForExecCms nvarchar(500) = (select top(1) TblNames from @TableLst)\n EXEC(@ForExecCms)\n delete from @TableLst where TblNames = @ForExecCms\nEND\n"
}
] | 2008/08/07 | [
"https://Stackoverflow.com/questions/4416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] |