qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
254,080
|
<p>I am using the SoundEngine sample code from Apple in the CrashLanding sample to play back multiple audio files. Using the sample caf files included with CrashLanding everything works fine but when I try and use my own samplesconverted to CAF using afconvert all I get is a stony silence ;)</p>
<p>Does anyone have settings for afconvert that will produce a CAF file capable of being played back through OpenAL?</p>
|
[
{
"answer_id": 255151,
"author": "Dave Verwer",
"author_id": 4496,
"author_profile": "https://Stackoverflow.com/users/4496",
"pm_score": 9,
"selected": true,
"text": "afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf\n afconvert -h"
},
{
"answer_id": 2413799,
"author": "tomwilson",
"author_id": 290115,
"author_profile": "https://Stackoverflow.com/users/290115",
"pm_score": 6,
"selected": false,
"text": "#!/bin/bash\nfor f in *.mp3; do\n echo \"Processing $f file...\"\n afconvert -f caff -d LEI16@44100 -c 1 \"$f\" \"${f/mp3/caf}\"\ndone\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496/"
] |
254,096
|
<p>In .Net (VB more specifically, but that doesn't really matter), is there a way to change the format of a number from one culture to another strictly through the that number's type? </p>
<p>The issue is this: In English, the number is say, 123.45. Whereas in Sweden, the number would be 123,45</p>
<p>Is there a way to convert 123,45 to 123.45 without having to convert it to a string (and then use the formatting methods) then convert it back to the correct type (single, double, etc)?</p>
|
[
{
"answer_id": 254108,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 2,
"selected": false,
"text": "Thread.CurrentThread.CurrentCulture = New CultureInfo(\"se-SE\")\nThread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30816/"
] |
254,099
|
<p>I'm trying to write some LINQ To SQL code that would generate SQL like</p>
<pre><code>SELECT t.Name, g.Name
FROM Theme t
INNER JOIN (
SELECT TOP 5 * FROM [Group] ORDER BY TotalMembers
) as g ON t.K = g.ThemeK
</code></pre>
<p>So far I have</p>
<pre><code>var q = from t in dc.Themes
join g in dc.Groups on t.K equals g.ThemeK into groups
select new {
t.Name, Groups = (from z in groups orderby z.TotalMembers select z.Name )
};
</code></pre>
<p>but I need to do a top/take on the ordered groups subquery. According to <a href="http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx</a> in VB I could just add TAKE 5 on the end, but I can't get this syntax to work in c#. How do you use the take syntax in c#?</p>
<p>edit: PS adding .Take(5) at the end causes it to run loads of individual queries</p>
<p>edit 2: I made a slight mistake with the intent of the SQL above, but the question still stands. <b>The problem is that if you use extension methods in the query like .Take(5), LinqToSql runs lots of SQL queries instead of a single query.</b></p>
|
[
{
"answer_id": 254105,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "var q = from t in dc.Themes \njoin g in dc.Groups on t.K equals g.ThemeK into groups \nselect new { t.Name, Groups = \n (from z in groups orderby z.TotalMembers select z.Name).Take(5) };\n var q = from t in dc.Themes \njoin g in dc.Groups on t.K equals g.ThemeK into groups \nselect new { t.Name, Groups = groups.OrderBy(z => z.TotalMembers).Take(5) };\n"
},
{
"answer_id": 254128,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "var q = from t in dc.Themes \njoin g in dc.Groups.OrderBy(z => z.TotalMembers).Take(5)\n on t.K equals g.ThemeK into groups \nselect new { t.Name, Groups = groups };\n"
},
{
"answer_id": 254455,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": true,
"text": "var subquery =\n dc.Groups\n .OrderBy(g => g.TotalMembers)\n .Take(5);\n\nvar query =\n dc.Themes\n .Join(subquery, t => t.K, g => g.ThemeK, (t, g) => new\n {\n ThemeName = t.Name, GroupName = g.Name\n }\n );\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2086/"
] |
254,111
|
<p>I have a flash app in my page, and when a user interacts with the flash app, the browser/html/javascript stops receiving keyboard input. </p>
<p>For example, in Firefox control-t no longer opens a new tab.</p>
<p>However, if I click on part of the page that isn't flash, the browser starts receiving these events again.</p>
<p>Is there anyway to programatically (either through flash or javascript) to return focus to the browser?</p>
<p>After the user clicks a button in flash, I have the flash executing a javascript callback, so I've tried giving focus to a form field (and to the body) through javascript, but that approach doesn't seem to be working.</p>
<p>A perhaps more concrete example is Youtube. They also have this problem. When I click the play/pause button, or adjust the volume, I would expect my browser keyboard controls to still work, but they don't, I have to click somewhere on the page outside the movie area. This is the exact problem I'm trying to solve.</p>
|
[
{
"answer_id": 254180,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "document.body.focus()\n"
},
{
"answer_id": 254440,
"author": "discorax",
"author_id": 30408,
"author_profile": "https://Stackoverflow.com/users/30408",
"pm_score": 3,
"selected": false,
"text": "document.body.focus();\n package {\n import flash.display.*;\n import flash.events.*;\n import flash.external.ExternalInterface;\n\n public class TestMouseLeave extends Sprite\n {\n public function TestMouseLeave()\n {\n // Add event listener for when the mouse LEAVES FLASH\n addEventListener(MouseEvent.MOUSE_OUT, onMouseLeave);\n }\n\n private function onMouseLeave(ev:Event):void\n {\n var jslink = new ExternalInterface();\n jslink.call(\"changeFocus\");\n }\n }\n\n}\n <script type=\"text/javascript\" language=\"javascript\">\n function changeFocus(){\n document.body.focus();\n }\n</script>\n"
},
{
"answer_id": 657143,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\" creationComplete=\"init();\">\n <mx:Script>\n <![CDATA[\n private function init():void {\n i.setFocus();\n this.addEventListener(KeyboardEvent.KEY_UP,keyPressed);\n }\n\n private function keyPressed(event:KeyboardEvent):void {\n if(event.keyCode.toString()==\"84\" && event.ctrlKey==true)\n ExternalInterface.call('newtab');\n }\n\n ]]>\n </mx:Script>\n <mx:TextInput x=\"23\" y=\"268\" width=\"256\" id=\"i\" text=\"Text Box\"/>\n</mx:Application>\n\n<script type=\"text/javascript\">\nfunction newtab(e){\n document.body.focus();\n window.open('about:blank');\n}\n</script> \n"
},
{
"answer_id": 4565102,
"author": "Chris Anthony",
"author_id": 552555,
"author_profile": "https://Stackoverflow.com/users/552555",
"pm_score": 2,
"selected": false,
"text": "document.body.focus(); document.body.tabIndex = 0;\ndocument.body.focus();\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32951/"
] |
254,121
|
<p>I have an application in which most requests are submitted via AJAX, though some are submitted via "regular" HTTP requests. If a request is submitted and the user's session has timed out, the following JSON is returned:</p>
<pre><code>{"authentication":"required"}
</code></pre>
<p>The JavaScript function which submits all AJAX requests handles this response by showing a popup message and redirecting the user back to the login page.</p>
<p>However, when a non-AJAX request receives this response the JSON is simply shown in the browser because the response is processed directly by the browser (i.e. the aforementioned JavaScript function is bypassed). Obviously this is not ideal and I would like the non-AJAX requests that receive this response to behave the same as the AJAX requests. In order to achieve this, I can think of 2 options:</p>
<ol>
<li><p>Go through the application and convert all the requests to AJAX requests. This would work, but could also take a long time!</p></li>
<li><p>The JSON shown above is generated by a very simple JSP. I'm wondering if it might be possible to add a JavaScript event handler to this JSP which is run just before the content is displayed in the browser - I'm assuming this would never be called for AJAX requests? This handler could call the other JavaScript code that displays the popup and performs the redirection.</p></li>
</ol>
<p>If anyone knows how exactly I can implement the handler I've outlined in (2), or has any other potential solutions, I'd be very grateful if they'd pass them on.</p>
<p>Cheers,
Don</p>
|
[
{
"answer_id": 254142,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "outputJson=1"
},
{
"answer_id": 254157,
"author": "AlexJReid",
"author_id": 32320,
"author_profile": "https://Stackoverflow.com/users/32320",
"pm_score": 0,
"selected": false,
"text": "if(Accept contains application/json...) { // client asking for json, likely to be XHR\n return {\"foo\":\"bar\"}\n} else { // other\n return \"Location: /login-please\";\n}\n"
},
{
"answer_id": 306411,
"author": "Kent Brewster",
"author_id": 1151280,
"author_profile": "https://Stackoverflow.com/users/1151280",
"pm_score": 0,
"selected": false,
"text": "{\"error\":\"authentication required\"}\n errorHandler({\"error\":\"authentication required\"});\n function errorHandler(r) {\n alert(r.error);\n}\n text/javascript application/x-json"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
254,125
|
<p>I'm writing a mapping app that uses a Canvas for positioning elements. For each element I have to programatically convert element's Lat/Long to the canvas' coordinate, then set the Canvas.Top and Canvas.Left properties.</p>
<p>If I had a 360x180 Canvas, can I convert the coordinates on the canvas to go from -180 to 180 rather than 0 to 360 on the X axis and 90 to -90 rather than 0 to 180 on the Y axis?</p>
<p>Scaling requirements:</p>
<ul>
<li>The canvas can be any size, so should still work if it's 360x180 or 5000x100.</li>
<li>The Lat/Long area may not always be (-90,-180)x(90,180), it could be anything (ie (5,-175)x(89,-174)).</li>
<li>Elements such as PathGeometry which are point base, rather than Canvas.Top/Left based need to work.</li>
</ul>
|
[
{
"answer_id": 254155,
"author": "MojoFilter",
"author_id": 93,
"author_profile": "https://Stackoverflow.com/users/93",
"pm_score": 0,
"selected": false,
"text": "Point ToCanvas(double lat, double lon) {\n double x = ((lon * myCanvas.ActualWidth) / 360.0) - 180.0;\n double y = ((lat * myCanvas.ActualHeight) / 180.0) - 90.0;\n return new Point(x,y);\n}\n"
},
{
"answer_id": 254729,
"author": "Dylan",
"author_id": 4580,
"author_profile": "https://Stackoverflow.com/users/4580",
"pm_score": 1,
"selected": false,
"text": " public class CustomCanvas : Canvas\n {\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n foreach (UIElement child in InternalChildren)\n {\n double left = Canvas.GetLeft(child);\n double top = Canvas.GetTop(child);\n Point canvasPoint = ToCanvas(top, left);\n child.Arrange(new Rect(canvasPoint, child.DesiredSize));\n }\n return arrangeSize;\n }\n Point ToCanvas(double lat, double lon)\n {\n double x = this.Width / 360;\n x *= (lon - -180);\n double y = this.Height / 180;\n y *= -(lat + -90);\n return new Point(x, y);\n }\n }\n"
},
{
"answer_id": 254757,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 3,
"selected": false,
"text": "namespace YourProject\n{\n public class MultiplyConverter : System.Windows.Data.IValueConverter\n {\n public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n return AsDouble(value)* AsDouble(parameter);\n }\n double AsDouble(object value)\n {\n var valueText = value as string;\n if (valueText != null)\n return double.Parse(valueText);\n else\n return (double)value;\n }\n\n public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new System.NotSupportedException();\n }\n }\n}\n <Canvas Name=\"canvas\" Background=\"Moccasin\">\n <Canvas Name=\"innerCanvas\">\n <Canvas.RenderTransform>\n <TransformGroup>\n <TranslateTransform x:Name=\"translate\">\n <TranslateTransform.X>\n <Binding ElementName=\"canvas\" Path=\"ActualWidth\"\n Converter=\"{StaticResource multiplyConverter}\" ConverterParameter=\"0.5\" />\n </TranslateTransform.X>\n <TranslateTransform.Y>\n <Binding ElementName=\"canvas\" Path=\"ActualHeight\"\n Converter=\"{StaticResource multiplyConverter}\" ConverterParameter=\"0.5\" />\n </TranslateTransform.Y>\n </TranslateTransform>\n <ScaleTransform ScaleX=\"1\" ScaleY=\"-1\" CenterX=\"{Binding ElementName=translate,Path=X}\"\n CenterY=\"{Binding ElementName=translate,Path=Y}\" />\n </TransformGroup>\n </Canvas.RenderTransform>\n <Rectangle Canvas.Top=\"-50\" Canvas.Left=\"-50\" Height=\"100\" Width=\"200\" Fill=\"Blue\" />\n <Rectangle Canvas.Top=\"0\" Canvas.Left=\"0\" Height=\"200\" Width=\"100\" Fill=\"Green\" />\n <Rectangle Canvas.Top=\"-25\" Canvas.Left=\"-25\" Height=\"50\" Width=\"50\" Fill=\"HotPink\" />\n </Canvas>\n</Canvas>\n"
},
{
"answer_id": 13547289,
"author": "dharmatech",
"author_id": 268581,
"author_profile": "https://Stackoverflow.com/users/268581",
"pm_score": 0,
"selected": false,
"text": "Canvas canvas.SetCoordinateSystem(-10, 10, -10, 10)\n canvas x y"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4580/"
] |
254,129
|
<p>How can I display a sort arrow in the header of the sorted column in a list view which follows the native look of the operating system?</p>
|
[
{
"answer_id": 254139,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 7,
"selected": true,
"text": "[EditorBrowsable(EditorBrowsableState.Never)]\npublic static class ListViewExtensions\n{\n [StructLayout(LayoutKind.Sequential)]\n public struct HDITEM\n {\n public Mask mask;\n public int cxy;\n [MarshalAs(UnmanagedType.LPTStr)] public string pszText;\n public IntPtr hbm;\n public int cchTextMax;\n public Format fmt;\n public IntPtr lParam;\n // _WIN32_IE >= 0x0300 \n public int iImage;\n public int iOrder;\n // _WIN32_IE >= 0x0500\n public uint type;\n public IntPtr pvFilter;\n // _WIN32_WINNT >= 0x0600\n public uint state;\n\n [Flags]\n public enum Mask\n {\n Format = 0x4, // HDI_FORMAT\n };\n\n [Flags]\n public enum Format\n {\n SortDown = 0x200, // HDF_SORTDOWN\n SortUp = 0x400, // HDF_SORTUP\n };\n };\n\n public const int LVM_FIRST = 0x1000;\n public const int LVM_GETHEADER = LVM_FIRST + 31;\n\n public const int HDM_FIRST = 0x1200;\n public const int HDM_GETITEM = HDM_FIRST + 11;\n public const int HDM_SETITEM = HDM_FIRST + 12;\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, ref HDITEM lParam);\n\n public static void SetSortIcon(this ListView listViewControl, int columnIndex, SortOrder order)\n {\n IntPtr columnHeader = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);\n for (int columnNumber = 0; columnNumber <= listViewControl.Columns.Count - 1; columnNumber++)\n {\n var columnPtr = new IntPtr(columnNumber);\n var item = new HDITEM\n {\n mask = HDITEM.Mask.Format\n };\n\n if (SendMessage(columnHeader, HDM_GETITEM, columnPtr, ref item) == IntPtr.Zero)\n {\n throw new Win32Exception();\n }\n\n if (order != SortOrder.None && columnNumber == columnIndex)\n {\n switch (order)\n {\n case SortOrder.Ascending:\n item.fmt &= ~HDITEM.Format.SortDown;\n item.fmt |= HDITEM.Format.SortUp;\n break;\n case SortOrder.Descending:\n item.fmt &= ~HDITEM.Format.SortUp;\n item.fmt |= HDITEM.Format.SortDown;\n break;\n }\n }\n else\n {\n item.fmt &= ~HDITEM.Format.SortDown & ~HDITEM.Format.SortUp;\n }\n\n if (SendMessage(columnHeader, HDM_SETITEM, columnPtr, ref item) == IntPtr.Zero)\n {\n throw new Win32Exception();\n }\n }\n }\n}\n myListView.SetSortIcon(0, SortOrder.Ascending);\n fmt HDF_SORTDOWN HDF_SORTUP"
},
{
"answer_id": 26974367,
"author": "Jesse",
"author_id": 2969067,
"author_profile": "https://Stackoverflow.com/users/2969067",
"pm_score": 3,
"selected": false,
"text": "Public Module ListViewExtensions\n Public Enum SortOrder\n None\n Ascending\n Descending\n End Enum\n\n <StructLayout(LayoutKind.Sequential)>\n Public Structure HDITEM\n Public theMask As Mask\n Public cxy As Integer\n <MarshalAs(UnmanagedType.LPTStr)>\n Public pszText As String\n Public hbm As IntPtr\n Public cchTextMax As Integer\n Public fmt As Format\n Public lParam As IntPtr\n ' _WIN32_IE >= 0x0300 \n Public iImage As Integer\n Public iOrder As Integer\n ' _WIN32_IE >= 0x0500\n Public type As UInteger\n Public pvFilter As IntPtr\n ' _WIN32_WINNT >= 0x0600\n Public state As UInteger\n\n <Flags()>\n Public Enum Mask\n Format = &H4 ' HDI_FORMAT\n End Enum\n\n\n <Flags()>\n Public Enum Format\n SortDown = &H200 ' HDF_SORTDOWN\n SortUp = &H400 ' HDF_SORTUP\n End Enum\n End Structure\n\n Public Const LVM_FIRST As Integer = &H1000\n Public Const LVM_GETHEADER As Integer = LVM_FIRST + 31\n\n Public Const HDM_FIRST As Integer = &H1200\n Public Const HDM_GETITEM As Integer = HDM_FIRST + 11\n Public Const HDM_SETITEM As Integer = HDM_FIRST + 12\n\n <DllImport(\"user32.dll\", CharSet:=CharSet.Auto, SetLastError:=True)>\n Public Function SendMessage(hWnd As IntPtr, msg As UInt32, wParam As IntPtr, lParam As IntPtr) As IntPtr\n End Function\n\n <DllImport(\"user32.dll\", CharSet:=CharSet.Auto, SetLastError:=True)>\n Public Function SendMessage(hWnd As IntPtr, msg As UInt32, wParam As IntPtr, ByRef lParam As HDITEM) As IntPtr\n End Function\n\n <Extension()>\n Public Sub SetSortIcon(listViewControl As ListView, columnIndex As Integer, order As SortOrder)\n Dim columnHeader As IntPtr = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero)\n For columnNumber As Integer = 0 To listViewControl.Columns.Count - 1\n\n Dim columnPtr As New IntPtr(columnNumber)\n Dim item As New HDITEM\n\n item.theMask = HDITEM.Mask.Format\n\n If SendMessage(columnHeader, HDM_GETITEM, columnPtr, item) = IntPtr.Zero Then Throw New Win32Exception\n\n If order <> SortOrder.None AndAlso columnNumber = columnIndex Then\n Select Case order\n Case SortOrder.Ascending\n item.fmt = item.fmt And Not HDITEM.Format.SortDown\n item.fmt = item.fmt Or HDITEM.Format.SortUp\n Case SortOrder.Descending\n item.fmt = item.fmt And Not HDITEM.Format.SortUp\n item.fmt = item.fmt Or HDITEM.Format.SortDown\n End Select\n Else\n item.fmt = item.fmt And Not HDITEM.Format.SortDown And Not HDITEM.Format.SortUp\n End If\n\n If SendMessage(columnHeader, HDM_SETITEM, columnPtr, item) = IntPtr.Zero Then Throw New Win32Exception\n Next\n End Sub\nEnd Module\n"
},
{
"answer_id": 45310194,
"author": "Mordachai",
"author_id": 112755,
"author_profile": "https://Stackoverflow.com/users/112755",
"pm_score": 2,
"selected": false,
"text": "// possible sorting header icons / indicators\nenum class ListViewSortArrow { None, Ascending, Descending };\n\nBOOL LVHeader_SetSortArrow(HWND hHeader, int nColumn, ListViewSortArrow sortArrow)\n{\n ASSERT(hHeader);\n\n HDITEM hdrItem = { 0 };\n hdrItem.mask = HDI_FORMAT;\n if (Header_GetItem(hHeader, nColumn, &hdrItem))\n {\n switch (sortArrow)\n {\n default:\n ASSERT(false);\n case ListViewSortArrow::None:\n hdrItem.fmt = hdrItem.fmt & ~(HDF_SORTDOWN | HDF_SORTUP);\n break;\n case ListViewSortArrow::Ascending:\n hdrItem.fmt = (hdrItem.fmt & ~HDF_SORTDOWN) | HDF_SORTUP;\n break;\n case ListViewSortArrow::Descending:\n hdrItem.fmt = (hdrItem.fmt & ~HDF_SORTUP) | HDF_SORTDOWN;\n break;\n }\n\n return Header_SetItem(hHeader, nColumn, &hdrItem);\n }\n\n return FALSE;\n}\n\nBOOL ListView_SetSortArrow(HWND hListView, int nColumn, ListViewSortArrow sortArrow)\n{\n ASSERT(hListView);\n\n if (HWND hHeader = ListView_GetHeader(hListView))\n return LVHeader_SetSortArrow(hHeader, nColumn, sortArrow);\n\n return FALSE;\n}\n"
},
{
"answer_id": 55549628,
"author": "symbiont",
"author_id": 2411916,
"author_profile": "https://Stackoverflow.com/users/2411916",
"pm_score": 2,
"selected": false,
"text": "private void SetSortArrow(ColumnHeader head, SortOrder order)\n{\n const string ascArrow = \" ▲\";\n const string descArrow = \" ▼\";\n\n // remove arrow\n if(head.Text.EndsWith(ascArrow) || head.Text.EndsWith(descArrow))\n head.Text = head.Text.Substring(0, head.Text.Length-2);\n\n // add arrow\n switch (order)\n {\n case SortOrder.Ascending: head.Text += ascArrow; break;\n case SortOrder.Descending: head.Text += descArrow; break;\n }\n}\n\nSetSortArrow(listView1.Columns[0], SortOrder.None); // remove arrow from first column if present\nSetSortArrow(listView1.Columns[1], SortOrder.Ascending); // set second column arrow to ascending\nSetSortArrow(listView1.Columns[1], SortOrder.Descending); // set second column arrow to descending\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26210/"
] |
254,132
|
<p>I am wondering what are the possible value for *_la_LDFLAGS in Makefile.am ? </p>
<p>If I ask this question, it is because I would like the following :</p>
<pre><code>Actual shared library : libA.so (or with the version number I don't care)
Symbolic links : libA-X.Y.Z.so, libA-X.so, libA.so
soname : libA-X.so
</code></pre>
<p>However here is what I get by using the <em>-release</em> flag :</p>
<pre><code>Actual shared library : libA-X.Y.Z.so
Symbolic links : libA.so
soname : libA-X.Y.Z.so !!! this is not what I want
</code></pre>
<p>I also tried with no flags at all and got </p>
<pre><code>Actual shared library : libA-0.0.0.so !!! 0.0.0 and not the real version
Symbolic links : libA.so, libA-0.so
soname : libA-0.so !!! 0.0.0 and not the real version
</code></pre>
<p>How should I do ? which flag should I use ? </p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 255663,
"author": "adl",
"author_id": 27835,
"author_profile": "https://Stackoverflow.com/users/27835",
"pm_score": 3,
"selected": true,
"text": "-version-info -release"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20986/"
] |
254,152
|
<p>I'm curious to know how NULLs are stored into a database ?</p>
<p>It surely depends on the database server but I would like to have an general idea about it.</p>
<hr>
<p>First try:</p>
<p>Suppose that the server put a undefined value (could be anything) into the field for a NULL value.</p>
<p>Could you be very lucky and retrieve the NULL value with</p>
<pre><code>...WHERE field = 'the undefined value (remember, could be anything...)'
</code></pre>
<hr>
<p>Second try:</p>
<p>Does the server have a flag or any meta-data somewhere to indicate this field is NULL ?</p>
<p>Then the server must read this meta data to verify the field.</p>
<p>If the meta-data indicates a NULL value and if the query doesn't have "field IS NULL",
then the record is ignored.</p>
<hr>
<p>It seems too easy...</p>
|
[
{
"answer_id": 266692,
"author": "Bjarke Ebert",
"author_id": 31890,
"author_profile": "https://Stackoverflow.com/users/31890",
"pm_score": 1,
"selected": false,
"text": "| DBServer | SpecialValue |\n+--------------+--------------+\n| 'Oracle' | 'Glyph' |\n| 'SQL Server' | 'Redmond' |\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14673/"
] |
254,168
|
<p>I have two tables:</p>
<p>Table 1:
ID, PersonCode, Name, </p>
<p>Table 2:
ID, Table1ID, Location, ServiceDate</p>
<p>I've got a query joining table 1 to table 2 on table1.ID = table2.Table1ID where PersonCode = 'XYZ'</p>
<p>What I want to do is return Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate, I don't want all rows, In table 2 I'm only interested in the row with the most recent ServiceDate for each location. How would I go about doing this?</p>
|
[
{
"answer_id": 254185,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "select Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate\nfrom Table1\njoin Table2 on table1.ID = table2.Table1ID \nwhere table1.PersonCode = 'XYZ'\nand table2.ServiceDate = (select max(t2.ServiceDate)\n from table2 t2\n where t2.table1ID = table2.table1ID\n and t2.location = table2.location\n );\n"
},
{
"answer_id": 254187,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 3,
"selected": true,
"text": "SELECT\n Table1.PersonCode, Table1.Name, Table2.Location, MAX(Table2.ServiceDate)\nFROM\n Table1 \n INNER JOIN Table2 on Table1.ID = Table2.Table1ID \nWHERE\n TABLE1.PersonCode = 'XYZ'\nGROUP BY\n Table1.PersonCode,Table1.Name, Table2.Location\n"
},
{
"answer_id": 254226,
"author": "Julius A",
"author_id": 13370,
"author_profile": "https://Stackoverflow.com/users/13370",
"pm_score": 0,
"selected": false,
"text": "INNER JOIN SELECT TOP 1\n Table1.PersonCode, Table1.Name, Table2.Location, Table2.ServiceDate\nFROM\n Table1 \n INNER JOIN Table2 on Table1.ID = Table2.Table1ID \nWHERE\n TABLE1.PersonCode = 'XYZ'\nORDER BY Table2.ServiceDate DESC\nGROUP BY\n Table1.PersonCode,Table1.Name, Table2.Location\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
254,172
|
<p>I'm experiencing a strange issue where my Visual Studio 2005 C++ program crashes the first time it runs after a new build. I'm having a difficult time debugging this intermittent issue and I suspect it's somehow related to a file somewhere on my hard drive that is being changed. If I can find the file(s), that might provide some more insight into this issue. Are there any good tools for observing which files are being created/deleted/modified when a specific program is run?</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 254268,
"author": "Joshua Swink",
"author_id": 14732,
"author_profile": "https://Stackoverflow.com/users/14732",
"pm_score": 0,
"selected": false,
"text": "touch ~/test-marker\n# run your program\nfind <directory> -newer ~/test-marker\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191808/"
] |
254,178
|
<p>Currently I'm using</p>
<pre><code>var x = dict.ContainsKey(key) ? dict[key] : defaultValue
</code></pre>
<p>I'd like some way to have dictionary[key] return null for nonexistant keys, so I could write something like</p>
<pre><code>var x = dict[key] ?? defaultValue;
</code></pre>
<p>this also winds up being part of linq queries etc. so I'd prefer one-line solutions. </p>
|
[
{
"answer_id": 254188,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 3,
"selected": false,
"text": "public abstract class MyHelper {\n public static V GetValueOrDefault<K,V>( Dictionary<K,V> dic, K key ) {\n V ret;\n bool found = dic.TryGetValue( key, out ret );\n if ( found ) { return ret; }\n return default(V);\n }\n}\n\nvar x = MyHelper.GetValueOrDefault( dic, key );\n"
},
{
"answer_id": 254221,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 5,
"selected": true,
"text": "public static class MyHelper\n{\n public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dic, \n K key, \n V defaultVal = default(V))\n {\n V ret;\n bool found = dic.TryGetValue(key, out ret);\n if (found) { return ret; }\n return defaultVal;\n }\n void Example()\n {\n var dict = new Dictionary<int, string>();\n dict.GetValueOrDefault(42, \"default\");\n }\n}\n"
},
{
"answer_id": 10746505,
"author": "Matt Connolly",
"author_id": 365932,
"author_profile": "https://Stackoverflow.com/users/365932",
"pm_score": 0,
"selected": false,
"text": "TryGetValue(key, out value) When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.\n"
},
{
"answer_id": 12632553,
"author": "Mike Chamberlain",
"author_id": 289319,
"author_profile": "https://Stackoverflow.com/users/289319",
"pm_score": 3,
"selected": false,
"text": "public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dic, TK key,\n TV defaultVal=default(TV))\n{\n TV val;\n return dic.TryGetValue(key, out val) \n ? val \n : defaultVal;\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4435/"
] |
254,184
|
<p>I have a simple HTML upload form, and I want to specify a default extension ("*.drp" for example). I've read that the way to do this is through the ACCEPT attribute of the input tag, but I don't know how exactly.</p>
<pre><code><form enctype="multipart/form-data" action="uploader.php" method="POST">
Upload DRP File:
<input name="Upload Saved Replay" type="file" accept="*.drp"/><br />
<input type="submit" value="Upload File" />
</form>
</code></pre>
<p><strong>Edit</strong>
I know validation is possible using javascript, but I would like the user to only see ".drp" files in his popup dialog. Also, I don't care much about server-side validation in this application.</p>
|
[
{
"answer_id": 254205,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 1,
"selected": false,
"text": "<form name=\"someform\"enctype=\"multipart/form-data\" action=\"uploader.php\" method=\"POST\">\n<input type=file name=\"file1\" />\n<input type=button onclick=\"val()\" value=\"xxxx\" />\n</form>\n<script>\nfunction val() {\n alert(document.someform.file1.value)\n}\n</script>\n"
},
{
"answer_id": 6788623,
"author": "Nazri",
"author_id": 857723,
"author_profile": "https://Stackoverflow.com/users/857723",
"pm_score": 5,
"selected": false,
"text": "<input name=\"fileToUpload\" type=\"file\" onchange=\"check_file()\" >\n function check_file(){\n str=document.getElementById('fileToUpload').value.toUpperCase();\n suffix=\".JPG\";\n suffix2=\".JPEG\";\n if(str.indexOf(suffix, str.length - suffix.length) == -1||\n str.indexOf(suffix2, str.length - suffix2.length) == -1){\n alert('File type not allowed,\\nAllowed file: *.jpg,*.jpeg');\n document.getElementById('fileToUpload').value='';\n }\n }\n"
},
{
"answer_id": 16858214,
"author": "Alistair R",
"author_id": 376164,
"author_profile": "https://Stackoverflow.com/users/376164",
"pm_score": -1,
"selected": false,
"text": "function checkFile(i){\n i = i.substr(i.length - 4, i.length).toLowerCase();\n i = i.replace('.','');\n switch(i){\n case 'jpg':\n case 'jpeg':\n case 'png':\n case 'gif':\n // do OK stuff\n break;\n default:\n // do error stuff\n break;\n }\n}\n"
},
{
"answer_id": 17042197,
"author": "ParaMeterz",
"author_id": 1192220,
"author_profile": "https://Stackoverflow.com/users/1192220",
"pm_score": 5,
"selected": false,
"text": "<input name=\"Upload Saved Replay\" type=\"file\" accept=\".drp\" />\n<br/>"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
254,197
|
<p>What I am looking for is the equivalent of <code>System.Windows.SystemParameters.WorkArea</code> for the monitor that the window is currently on.</p>
<p><strong>Clarification:</strong> The window in question is <code>WPF</code>, not <code>WinForm</code>.</p>
|
[
{
"answer_id": 254241,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 8,
"selected": true,
"text": "Screen.FromControl Screen.FromPoint Screen.FromRectangle class MyForm : Form\n{\n public Rectangle GetScreen()\n {\n return Screen.FromControl(this).Bounds;\n }\n}\n static class ExtensionsForWPF\n{\n public static System.Windows.Forms.Screen GetScreen(this Window window)\n {\n return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle);\n }\n}\n"
},
{
"answer_id": 254258,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 4,
"selected": false,
"text": "Screen.FromControl(this).Bounds\n"
},
{
"answer_id": 744306,
"author": "Pyttroll",
"author_id": 88118,
"author_profile": "https://Stackoverflow.com/users/88118",
"pm_score": 6,
"selected": false,
"text": "System.Windows.SystemParameters.WorkArea System.Windows.SystemParameters.PrimaryScreenWidth System.Windows.SystemParameters.PrimaryScreenHeight"
},
{
"answer_id": 12265169,
"author": "Andre",
"author_id": 1603918,
"author_profile": "https://Stackoverflow.com/users/1603918",
"pm_score": 3,
"selected": false,
"text": "WindowStartupLocation Window w = new Window();\nw.ResizeMode = ResizeMode.NoResize;\nw.WindowState = WindowState.Normal;\nw.WindowStyle = WindowStyle.None;\nw.Background = Brushes.Transparent;\nw.Width = 0;\nw.Height = 0;\nw.AllowsTransparency = true;\nw.IsHitTestVisible = false;\nw.WindowStartupLocation = WindowStartupLocation.Manual;\nw.Show();\nScreen scr = Screen.FromHandle(new WindowInteropHelper(w).Handle);\nw.Close();\n"
},
{
"answer_id": 17574075,
"author": "Ricardo Magalhães",
"author_id": 1735425,
"author_profile": "https://Stackoverflow.com/users/1735425",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Set the max size of the application window taking into account the current monitor\n/// </summary>\npublic static void SetMaxSizeWindow(ioConnect _receiver)\n{\n Point absoluteScreenPos = _receiver.PointToScreen(Mouse.GetPosition(_receiver));\n\n if (System.Windows.SystemParameters.VirtualScreenLeft == System.Windows.SystemParameters.WorkArea.Left)\n {\n //Primary Monitor is on the Left\n if (absoluteScreenPos.X <= System.Windows.SystemParameters.PrimaryScreenWidth)\n {\n //Primary monitor\n _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;\n _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;\n }\n else\n {\n //Secondary monitor\n _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;\n _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;\n }\n }\n\n if (System.Windows.SystemParameters.VirtualScreenLeft < 0)\n {\n //Primary Monitor is on the Right\n if (absoluteScreenPos.X > 0)\n {\n //Primary monitor\n _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;\n _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;\n }\n else\n {\n //Secondary monitor\n _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;\n _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;\n }\n }\n}\n"
},
{
"answer_id": 19295701,
"author": "Nasenbaer",
"author_id": 375368,
"author_profile": "https://Stackoverflow.com/users/375368",
"pm_score": 2,
"selected": false,
"text": "Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded\n Dim BarWidth As Double = SystemParameters.VirtualScreenWidth - SystemParameters.WorkArea.Width\n Dim BarHeight As Double = SystemParameters.VirtualScreenHeight - SystemParameters.WorkArea.Height\n Me.Left = (SystemParameters.VirtualScreenWidth - Me.ActualWidth - BarWidth) / 2\n Me.Top = (SystemParameters.VirtualScreenHeight - Me.ActualHeight - BarHeight) / 2 \nEnd Sub\n"
},
{
"answer_id": 19973955,
"author": "aDoubleSo",
"author_id": 2294365,
"author_profile": "https://Stackoverflow.com/users/2294365",
"pm_score": 4,
"selected": false,
"text": "SystemParameters.FullPrimaryScreenHeight\nSystemParameters.FullPrimaryScreenWidth\n"
},
{
"answer_id": 36920187,
"author": "R.Rusev",
"author_id": 5788595,
"author_profile": "https://Stackoverflow.com/users/5788595",
"pm_score": 4,
"selected": false,
"text": "public static class NativeMethods\n{\n public const Int32 MONITOR_DEFAULTTOPRIMERTY = 0x00000001;\n public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;\n\n\n [DllImport( \"user32.dll\" )]\n public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );\n\n\n [DllImport( \"user32.dll\" )]\n public static extern Boolean GetMonitorInfo( IntPtr hMonitor, NativeMonitorInfo lpmi );\n\n\n [Serializable, StructLayout( LayoutKind.Sequential )]\n public struct NativeRectangle\n {\n public Int32 Left;\n public Int32 Top;\n public Int32 Right;\n public Int32 Bottom;\n\n\n public NativeRectangle( Int32 left, Int32 top, Int32 right, Int32 bottom )\n {\n this.Left = left;\n this.Top = top;\n this.Right = right;\n this.Bottom = bottom;\n }\n }\n\n\n [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )]\n public sealed class NativeMonitorInfo\n {\n public Int32 Size = Marshal.SizeOf( typeof( NativeMonitorInfo ) );\n public NativeRectangle Monitor;\n public NativeRectangle Work;\n public Int32 Flags;\n }\n}\n var hwnd = new WindowInteropHelper( this ).EnsureHandle();\n var monitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );\n\n if ( monitor != IntPtr.Zero )\n {\n var monitorInfo = new NativeMonitorInfo();\n NativeMethods.GetMonitorInfo( monitor, monitorInfo );\n\n var left = monitorInfo.Monitor.Left;\n var top = monitorInfo.Monitor.Top;\n var width = ( monitorInfo.Monitor.Right - monitorInfo.Monitor.Left );\n var height = ( monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top );\n }\n"
},
{
"answer_id": 44985172,
"author": "Oleg Bash",
"author_id": 8274657,
"author_profile": "https://Stackoverflow.com/users/8274657",
"pm_score": 1,
"selected": false,
"text": "private Point get_start_point()\n {\n return\n new Point(Screen.GetBounds(parent_class_with_form.ActiveForm).X,\n Screen.GetBounds(parent_class_with_form.ActiveForm).Y\n );\n }\n"
},
{
"answer_id": 60250152,
"author": "user3424480",
"author_id": 3424480,
"author_profile": "https://Stackoverflow.com/users/3424480",
"pm_score": 2,
"selected": false,
"text": "Rectangle activeScreenDimensions = Screen.FromControl(this).Bounds;\nthis.Size = new Size(activeScreenDimensions.Width + activeScreenDimensions.X, activeScreenDimensions.Height + activeScreenDimensions.Y);\n"
},
{
"answer_id": 63028215,
"author": "Daniel Santos",
"author_id": 5001161,
"author_profile": "https://Stackoverflow.com/users/5001161",
"pm_score": 0,
"selected": false,
"text": " {\n List<Screen> arrAvailableDisplays = new List<Screen>();\n List<string> arrDisplayNames = new List<string>();\n\n foreach (Screen Display in Screen.AllScreens)\n {\n arrAvailableDisplays.Add(Display);\n arrDisplayNames.Add(Display.DeviceName);\n }\n\n Screen scrCurrentDisplayInfo = Screen.FromControl(this);\n string strDeviceName = Screen.FromControl(this).DeviceName;\n int idxDevice = arrDisplayNames.IndexOf(strDeviceName);\n\n MessageBox.Show(this, \"Number of Displays Found: \" + arrAvailableDisplays.Count.ToString() + Constants.vbCrLf + \"ID: \" + idxDevice.ToString() + Constants.vbCrLf + \"Device Name: \" + scrCurrentDisplayInfo.DeviceName.ToString + Constants.vbCrLf + \"Primary: \" + scrCurrentDisplayInfo.Primary.ToString + Constants.vbCrLf + \"Bounds: \" + scrCurrentDisplayInfo.Bounds.ToString + Constants.vbCrLf + \"Working Area: \" + scrCurrentDisplayInfo.WorkingArea.ToString + Constants.vbCrLf + \"Bits per Pixel: \" + scrCurrentDisplayInfo.BitsPerPixel.ToString + Constants.vbCrLf + \"Width: \" + scrCurrentDisplayInfo.Bounds.Width.ToString + Constants.vbCrLf + \"Height: \" + scrCurrentDisplayInfo.Bounds.Height.ToString + Constants.vbCrLf + \"Work Area Width: \" + scrCurrentDisplayInfo.WorkingArea.Width.ToString + Constants.vbCrLf + \"Work Area Height: \" + scrCurrentDisplayInfo.WorkingArea.Height.ToString, \"Current Info for Display '\" + scrCurrentDisplayInfo.DeviceName.ToString + \"' - ID: \" + idxDevice.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);\n}\n Dim arrAvailableDisplays As New List(Of Screen)()\n Dim arrDisplayNames As New List(Of String)()\n\n For Each Display As Screen In Screen.AllScreens\n arrAvailableDisplays.Add(Display)\n arrDisplayNames.Add(Display.DeviceName)\n Next\n\n Dim scrCurrentDisplayInfo As Screen = Screen.FromControl(Me)\n Dim strDeviceName As String = Screen.FromControl(Me).DeviceName\n Dim idxDevice As Integer = arrDisplayNames.IndexOf(strDeviceName)\n\n MessageBox.Show(Me,\n \"Number of Displays Found: \" + arrAvailableDisplays.Count.ToString & vbCrLf &\n \"ID: \" & idxDevice.ToString + vbCrLf &\n \"Device Name: \" & scrCurrentDisplayInfo.DeviceName.ToString + vbCrLf &\n \"Primary: \" & scrCurrentDisplayInfo.Primary.ToString + vbCrLf &\n \"Bounds: \" & scrCurrentDisplayInfo.Bounds.ToString + vbCrLf &\n \"Working Area: \" & scrCurrentDisplayInfo.WorkingArea.ToString + vbCrLf &\n \"Bits per Pixel: \" & scrCurrentDisplayInfo.BitsPerPixel.ToString + vbCrLf &\n \"Width: \" & scrCurrentDisplayInfo.Bounds.Width.ToString + vbCrLf &\n \"Height: \" & scrCurrentDisplayInfo.Bounds.Height.ToString + vbCrLf &\n \"Work Area Width: \" & scrCurrentDisplayInfo.WorkingArea.Width.ToString + vbCrLf &\n \"Work Area Height: \" & scrCurrentDisplayInfo.WorkingArea.Height.ToString,\n \"Current Info for Display '\" & scrCurrentDisplayInfo.DeviceName.ToString & \"' - ID: \" & idxDevice.ToString, MessageBoxButtons.OK, MessageBoxIcon.Information)\n"
},
{
"answer_id": 71232027,
"author": "HemmaRoyD",
"author_id": 12781899,
"author_profile": "https://Stackoverflow.com/users/12781899",
"pm_score": 0,
"selected": false,
"text": "int formWidth = form.Width;\nint formHeight = form.Height;\nint formTop = form.Top;\nint formLeft = form.Left;\n\nScreen screen = Screen.PrimaryScreen;\nRectangle rect = screen.Bounds;\nint screenWidth = rect.Width;\nint screenHeight = rect.Height;\nint screenTop = rect.Top;\nint screenLeft = rect.Left;\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28736/"
] |
254,200
|
<p>Unsure if I've phrased this correctly, but in the callback how do I reference the controls property of the base class?</p>
<p>This has been bugging me for some time and I usually work around it, but I'd be grateful if anybody can enlighten me on how I should do this properly.</p>
<pre><code>var base = function() {
var controls = {};
return {
init: function(c) {
this.controls = c
},
foo: function(args) {
this.init(args.controls);
$(this.controls.DropDown).change(function() {
$(this.controls.PlaceHolder).toggle();
});
}
}
};
</code></pre>
<p>Much Obliged,</p>
<p>Paul</p>
|
[
{
"answer_id": 254233,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 1,
"selected": false,
"text": "var base = function() {\nvar controls = {};\n\nreturn {\n init: function(c) {\n this.controls = c\n },\n foo: function(args) {\n this.init(args.controls);\n $(this.controls.DropDown).change(function(controls) {\n return function(){\n $(controls.PlaceHolder).toggle();\n }\n }(this.controls));\n }\n}\n"
},
{
"answer_id": 254237,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 3,
"selected": true,
"text": "var base = function() {\n var controls = {};\n\n return {\n init: function(c) {\n this.controls = c\n },\n foo: function(args) {\n var self = this;\n\n this.init(args.controls);\n $(this.controls.DropDown).change(function() {\n $(self.controls.PlaceHolder).toggle();\n });\n }\n }\n};\n"
},
{
"answer_id": 254589,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 2,
"selected": false,
"text": "bind var base = function() {\n var controls = {};\n\n return {\n init: function(c) {\n this.controls = c\n },\n foo: function(args) {\n this.init(args.controls);\n $(this.controls.DropDown).bind('change', {controls: this.controls}, function(event) {\n $(event.data.controls.PlaceHolder).toggle();\n });\n }\n }\n};\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9948/"
] |
254,212
|
<p>We're seeing <code>JTable</code> selection get cleared when we do a <code>fireTableDataChanged()</code> or <code>fireTableRowsUpdated()</code> from the <code>TableModel</code>.</p>
<p>Is this expected, or are we doing something wrong? I didn't see any property on the <code>JTable</code> (or other related classes) about clearing/preserving selection on model updates.</p>
<p>If this is default behavior, is there a good way to prevent this? Maybe some way to "lock" the selection before the update and unlock after?</p>
<p>The developer has been experimenting with saving the selection before the update and re-applying it. It's a little slow.</p>
<p>This is Java 1.4.2 on Windows XP, if that matters. We're limited to that version based on some vendor code we use.</p>
|
[
{
"answer_id": 256846,
"author": "Rastislav Komara",
"author_id": 22068,
"author_profile": "https://Stackoverflow.com/users/22068",
"pm_score": 1,
"selected": false,
"text": "fireTableDataChanged() fireTableRowsUpdated()"
},
{
"answer_id": 9786644,
"author": "Peter Berg",
"author_id": 908886,
"author_profile": "https://Stackoverflow.com/users/908886",
"pm_score": 2,
"selected": false,
"text": "@Override\npublic void fireTableDataChanged() {\n fireTableChanged(new TableModelEvent(this, //tableModel\n 0, //firstRow\n getRowCount() - 1, //lastRow \n TableModelEvent.ALL_COLUMNS, //column \n TableModelEvent.UPDATE)); //changeType\n}\n"
},
{
"answer_id": 18143231,
"author": "Ram Dutt Shukla",
"author_id": 591061,
"author_profile": "https://Stackoverflow.com/users/591061",
"pm_score": -1,
"selected": false,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\nimport javax.swing.event.*;\nimport javax.swing.plaf.basic.*;\n\npublic class FixedTable extends JTable {\n\n private boolean isControlDownInDrag;\n\n public FixedTable(TableModel model) {\n super(model);\n setUI(new FixedTableUI());\n }\n\n private class FixedTableUI extends BasicTableUI {\n private MouseInputHandler handler = new MouseInputHandler() {\n public void mouseDragged(MouseEvent e) {\n if (e.isControlDown()) {\n isControlDownInDrag = true;\n }\n super.mouseDragged(e);\n }\n\n public void mousePressed(MouseEvent e) {\n isControlDownInDrag = false;\n super.mousePressed(e);\n }\n\n public void mouseReleased(MouseEvent e) {\n isControlDownInDrag = false;\n super.mouseReleased(e);\n }\n };\n\n protected MouseInputListener createMouseInputListener() {\n return handler;\n }\n }\n\n public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {\n if (isControlDownInDrag) {\n ListSelectionModel rsm = getSelectionModel();\n ListSelectionModel csm = getColumnModel().getSelectionModel();\n\n int anchorRow = rsm.getAnchorSelectionIndex();\n int anchorCol = csm.getAnchorSelectionIndex();\n\n boolean anchorSelected = isCellSelected(anchorRow, anchorCol);\n\n if (anchorSelected) {\n rsm.addSelectionInterval(anchorRow, rowIndex);\n csm.addSelectionInterval(anchorCol, columnIndex);\n } else {\n rsm.removeSelectionInterval(anchorRow, rowIndex);\n csm.removeSelectionInterval(anchorCol, columnIndex);\n }\n\n if (getAutoscrolls()) {\n Rectangle cellRect = getCellRect(rowIndex, columnIndex, false);\n if (cellRect != null) {\n scrollRectToVisible(cellRect);\n }\n }\n } else {\n super.changeSelection(rowIndex, columnIndex, toggle, extend);\n }\n }\n}\n"
},
{
"answer_id": 32202230,
"author": "Exceptyon",
"author_id": 2135168,
"author_profile": "https://Stackoverflow.com/users/2135168",
"pm_score": 1,
"selected": false,
"text": "// preserve selection calling fireTableDataChanged()\nfinal int[] sel = table.getSelectedRows();\n\nfireTableDataChanged();\n\nfor (int i=0; i<sel.length; i++)\n table.getSelectionModel().addSelectionInterval(sel[i], sel[i]);\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20734/"
] |
254,213
|
<p>I need to handle resultsets returning stored procedures/functions for three databases (Oracle, sybase, MS-Server). The procedures/functions are generally the same but the call is a little different in Oracle.</p>
<pre><code>statement.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
...
statement.execute();
ResultSet rs = (ResultSet)statement.getObject(1);
</code></pre>
<p>JDBC doesn't provide a generic way to handle this, so I'll need to distinguish the different types of DBs in my code. I'm given the connection but don't know the best way to determine if the DB is oracle. I can use the driver name but would rather find a cleaner way.</p>
|
[
{
"answer_id": 9064789,
"author": "Rinat Tainov",
"author_id": 479625,
"author_profile": "https://Stackoverflow.com/users/479625",
"pm_score": 2,
"selected": false,
"text": "databaseName = new PlatformUtils().determineDatabaseType(dataSource)\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
254,214
|
<p>Is there any good software that will allow me to search through my SVN respository for code snippets? I found 'FishEye' but the cost is 1,200 and well outside my budget.</p>
|
[
{
"answer_id": 254801,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 2,
"selected": false,
"text": "svn log filetosearch |\n grep '^r' |\n cut -f1 -d' ' |\n xargs -i bash -c \"echo '{}'; svn cat filetosearch -'{}'\" \n"
},
{
"answer_id": 3064429,
"author": "phil_w",
"author_id": 369665,
"author_profile": "https://Stackoverflow.com/users/369665",
"pm_score": 6,
"selected": false,
"text": "svn list -R file:///subversion/repository | grep filename\n svn list -R file:///subversion/repository | findstr filename\n egrep -r _code_ .\n"
},
{
"answer_id": 3064621,
"author": "Vi.",
"author_id": 266720,
"author_profile": "https://Stackoverflow.com/users/266720",
"pm_score": 3,
"selected": false,
"text": "git-svn git log -S'my line of code' gitk"
},
{
"answer_id": 19297190,
"author": "Contango",
"author_id": 107409,
"author_profile": "https://Stackoverflow.com/users/107409",
"pm_score": 3,
"selected": false,
"text": "svn list -R svn://svn > filelist.txt\n"
},
{
"answer_id": 20397195,
"author": "bahrep",
"author_id": 761095,
"author_profile": "https://Stackoverflow.com/users/761095",
"pm_score": 4,
"selected": false,
"text": "--search svn log svn:author svn:date svn:log If the --search option is used, log messages are displayed only if the\n provided search pattern matches any of the author, date, log message\n text (unless --quiet is used), or, if the --verbose option is also\n provided, a changed path.\n The search pattern may include \"glob syntax\" wildcards:\n ? matches any single character\n * matches a sequence of arbitrary characters\n [abc] matches any of the characters listed inside the brackets\n If multiple --search options are provided, a log message is shown if\n it matches any of the provided search patterns. If the --search-and\n option is used, that option's argument is combined with the pattern\n from the previous --search or --search-and option, and a log message\n is shown only if it matches the combined search pattern.\n If --limit is used in combination with --search, --limit restricts the\n number of log messages searched, rather than restricting the output\n to a particular number of matching log messages.\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33149/"
] |
254,216
|
<p>My table structure looks like this:</p>
<pre><code> tbl.users tbl.issues
+--------+-----------+ +---------+------------+-----------+
| userid | real_name | | issueid | assignedid | creatorid |
+--------+-----------+ +---------+------------+-----------+
| 1 | test_1 | | 1 | 1 | 1 |
| 2 | test_2 | | 2 | 1 | 2 |
+--------+-----------+ +---------+------------+-----------+
</code></pre>
<p>Basically I want to write a query that will end in a results table looking like this:</p>
<pre><code> (results table)
+---------+------------+---------------+-----------+--------------+
| issueid | assignedid | assigned_name | creatorid | creator_name |
+---------+------------+---------------+-----------+--------------+
| 1 | 1 | test_1 | 1 | test_1 |
| 2 | 1 | test_1 | 2 | test_2 |
+---------+------------+---------------+-----------+--------------+
</code></pre>
<p>My SQL looks like this at the moment:</p>
<pre><code>SELECT
`issues`.`issueid`,
`issues`.`creatorid`,
`issues`.`assignedid`,
`users`.`real_name`
FROM `issues`
JOIN `users`
ON ( `users`.`userid` = `issues`.`creatorid` )
OR (`users`.`userid` = `issues`.`assignedid`)
ORDER BY `issueid` ASC
LIMIT 0 , 30
</code></pre>
<p>This returns something like this:</p>
<pre><code> (results table)
+---------+------------+-----------+-----------+
| issueid | assignedid | creatorid | real_name |
+---------+------------+-----------+-----------+
| 1 | 1 | 1 | test_1 |
| 2 | 1 | 2 | test_1 |
| 2 | 1 | 2 | test_2 |
+---------+------------+-----------+-----------+
</code></pre>
<p>Can anyone help me get to the desired results table?</p>
|
[
{
"answer_id": 254232,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT (i.issueid, i.creatorid, i.assignedid, u.real_name)\nFROM issues i, users u\nWHERE u.userid = i.creatorid OR u.userid = assignedid\nORDER BY i.issueid ASC\nLIMIT 0 , 30\n"
},
{
"answer_id": 254234,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 4,
"selected": true,
"text": "SELECT \n IssueID, \n AssignedID, \n CreatorID, \n AssignedUser.real_name AS AssignedName, \n CreatorUser.real_name AS CreatorName\nFROM Issues\n LEFT JOIN Users AS AssignedUser\n ON Issues.AssignedID = AssignedUser.UserID\n LEFT JOIN Users AS CreatorUser\n ON Issues.CreatorID = CreatorUser.UserID\nORDER BY `issueid` ASC\nLIMIT 0, 30\n"
},
{
"answer_id": 254235,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 1,
"selected": false,
"text": "SELECT \n`issues`.`issueid`,\n`issues`.`creatorid`,\n`creator`.`real_name`,\n`issues`.`assignedid`,\n`assigned`.`real_name`\nFROM `issues` i\nINNER JOIN `users` creator ON ( `creator`.`userid` = `issues`.`creatorid` )\nINNER JOIN `users` assigned ON (`assigned`.`userid` = `issues`.`assignedid`)\nORDER BY `issueid` ASC\nLIMIT 0 , 30\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] |
254,229
|
<p>I have a project that I thought was going to be relatively easy, but is turning out to be more of a pain that I had hoped. First, most of the code I'm interacting with is legacy code that I don't have control over, so I can't do big paradigm changes.</p>
<p>Here's a simplified explanation of what I need to do: Say I have a large number of simple programs that read from stdin and write to stdout. (These I can't touch). Basically, input to stdin is a command like "Set temperature to 100" or something like that. And the output is an event "Temperature has been set to 100" or "Temperature has fallen below setpoint".</p>
<p>What I'd like to do is write an application that can start a bunch of these simple programs, watch for events and then send commands to them as necessary. My initial plan was to something like popen, but I need a bidrectional popen to get both read and write pipes. I hacked something together that I call popen2 where I pass it the command to run and two FILE* that get filled with the read and write stream. Then all I need to do is write a simple loop that reads from each of the stdouts from each of the processes, does the logic that it needs and then writes commands back to the proper process.</p>
<p>Here's some pseudocode</p>
<pre><code>FILE *p1read, *p1write;
FILE *p2read, *p2write;
FILE *p3read, *p3write;
//start each command, attach to stdin and stdout
popen2("process1",&p1read,&p1write);
popen2("process2",&p2read,&p2write);
popen2("process3",&p3read,&p3write);
while (1)
{
//read status from each process
char status1[1024];
char status2[1024];
char status3[1024];
fread(status1,1024,p1read);
fread(status2,1024,p2read);
fread(status3,1024,p3read);
char command1[1024];
char command2[1024];
char command3[1024];
//do some logic here
//write command back to each process
fwrite(command1,p1write);
fwrite(command2,p2write);
fwrite(command3,p3write);
}
</code></pre>
<p>The real program is more complicated where it peeks in the stream to see if anything is waiting, if not, it will skip that process, likewise if it doesn't need to send a command to a certain process it doesn't. But this code gives the basic idea.</p>
<p>Now this works great on my UNIX box and even pretty good on a Windows XP box with cygwin. However, now I need to get it to work on Win32 natively. </p>
<p>The hard part is that my popen2 uses fork() and execl() to start the process and assign the streams to stdin and stdout of the child processes. Is there a clean way I can do this in windows? Basically, I'd like to create a popen2 that works in windows the same way as my unix version. This way the only windows specific code would be in that function and I could get away with everything else working the same way.</p>
<p>Any Ideas?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 254283,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "fork exec"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33152/"
] |
254,238
|
<p>I have a table with columns</p>
<blockquote>
<p>Index, Date</p>
</blockquote>
<p>where an Index may have multiple Dates, and my goal is the following: select a list that looks like</p>
<blockquote>
<p>Index, MinDate, MaxDate</p>
</blockquote>
<p>where each Index is listed only once, and MinDate (MaxDate) represents the earliest (latest) date present <em>in the entire table for that index</em>. That's easy enough, but then let's constrain this list to appear only for Indexes that are present in a given range of dates. </p>
<p>So far, I have the following:</p>
<pre><code>SELECT
Index,
MIN([Date]),
MAX([Date])
FROM myTable
WHERE
Index IN
(SELECT Index From myTable WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000')
GROUP BY Index
ORDER BY Index ASC
</code></pre>
<p>This is excruciatingly slow. Any way to speed this up? [I am running SQL Server 2000.]</p>
<p>Thanks!</p>
<p>Edited: For clarity.</p>
|
[
{
"answer_id": 254249,
"author": "John",
"author_id": 33149,
"author_profile": "https://Stackoverflow.com/users/33149",
"pm_score": -1,
"selected": false,
"text": "SELECT\n [INDEX],\n MIN ( [Date] ),\n MAX ( [Date] )\nFROM\n myTable\nWHERE \n [Date] Between '1/1/2000' And '12/31/2000'\nGROUP BY\n [Index]\nORDER BY\n [INDEX] ASC\n"
},
{
"answer_id": 254285,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 2,
"selected": false,
"text": "SELECT Index,\n (SELECT MIN([Date] FROM myTable WHERE Index = m.Index),\n (SELECT MAX([Date] FROM myTable WHERE Index = m.Index)\nFrom myTable m \nWHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000'\n"
},
{
"answer_id": 254290,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 3,
"selected": true,
"text": "SELECT \n myTable.Index,\n MIN(myTable.[Date]),\n MAX(myTable.[Date])\nFROM myTable\n Inner Join (\n SELECT Index \n From myTable \n WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000') As AliasName\n On myTable.Index = AliasName.Index\nGROUP BY myTable.Index\nORDER BY myTable.Index ASC\n Select [Index],\n Min([Date]),\n Max([Date])\nFrom myTable\nGroup By [Index]\nHaving Sum(Case When [Date] Between '1/1/2000' And '12/31/2000' Then 1 Else 0 End) > 0\n"
},
{
"answer_id": 254316,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 1,
"selected": false,
"text": "**Index, Min(Date), Max(Date)** SELECT \n Index, \n Min(Date) as MinDate, \n Max(Date) as MaxDate\n INTO \n MySummaryTable\n FROM \n MyOriginalTable\n GROUP BY\n Index\n SELECT \n summary.Index,\n summary.MinDate,\n summary.MaxDate\nFROM\n MyOriginalTable mot\n INNER JOIN MySummaryTable summary\n ON mot.Index = summary.Index --THIS IS WHERE YOUR CLUSTERED INDEX WILL PAY OFF\nWHERE\n mot.Date BETWEEN '2000-01-01' AND '2000-12-31' --THIS IS WHERE A SECOND NC INDEX WILL PAY OFF\n"
},
{
"answer_id": 254339,
"author": "Ryan",
"author_id": 29762,
"author_profile": "https://Stackoverflow.com/users/29762",
"pm_score": 0,
"selected": false,
"text": "DECLARE @MaxDate datetime, @MinDate datetime\nSELECT\n @MinDate = MIN([Date]),\n @MaxDate = MAX([Date])\nFROM myTable\n--\nSELECT\n [Index],\n @MinDate,\n @MaxDate\nFROM myTable\nWHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000'\n SELECT\n [Index],\n MIN([Date]) AS IndexMinDate,\n MAX([Date]) AS IndexMaxDate,\n @MinDate AS TableMinDate,\n @MaxDate AS TableMaxDate\nFROM myTable\nWHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000'\nGROUP BY [Index]\nORDER BY [Index] ASC\n"
},
{
"answer_id": 254416,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "SELECT\n t1.Index,\n MIN(t1.[Date]),\n MAX(t1.[Date])\nFROM\n myTable t1\nWHERE\n EXISTS (SELECT * FROM myTable t2 WHERE t2.Index = t1.Index AND t2.[Date] >= '1/1/2000' AND t2.[Date] < '1/1/2001')\n GROUP BY\n t1.Index\n"
},
{
"answer_id": 254582,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "SELECT\n Index,\n MIN([Date]),\n MAX([Date])\nFROM myTable\nWHERE\n Index IN\n (SELECT Index From myTable WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000')\nGROUP BY Index\nORDER BY Index ASC\nOPTION (MERGE JOIN)\n SELECT\n Index,\n MIN([Date]),\n MAX([Date])\nFROM myTable\nGROUP BY Index\nHAVING MIN([Date]) < '2001-01-01' AND MAX([Date]) >= '2000-01-01')\nORDER BY Index ASC\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
] |
254,244
|
<p>I am wrestling with a php 5.2.6 problem. An api we use returns dates in this format DDMMYYYYHHMM. Exactly that format, fixed length, no delimiters. However, in my experimentation, this format seems to break strptime, which returns a false (fail) when I feed it a date in this format. It can reproduced, at least on my system, with this example:</p>
<pre><code>$format = "%d%m%Y%H%M"; echo print_r(strptime(strftime($format,1225405967),$format),true);
</code></pre>
<p>If I add any character between the date and the time, it works, even a space. So, this DOES work:</p>
<pre><code>$format = "%d%m%Y %H%M"; echo print_r(strptime(strftime($format,1225405967),$format),true);
</code></pre>
<p>Am I missing something obvious?</p>
<p>edit: further to this and owing to the results indicated by the comments, this seems to be platform specific. I can reproduce it on the Macs running OSX Leopard in the office but the Linux boxes parse it fine. I assume it is a bug or idiosyncrasy of the strptime in the underlying C library in the *nix of OSX.</p>
|
[
{
"answer_id": 256018,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 1,
"selected": false,
"text": "setlocale()"
},
{
"answer_id": 256053,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "5.2.6\nFatal error: Call to undefined function strptime() in F:\\htdocs\\strptime.php on line 5\n"
},
{
"answer_id": 256131,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "Now: 1225573977\nFormatted (12): 011120082112\nEnd: 0xBFFFF553 (Buffer: 0xBFFFF547)\nThen: year = 2008, month = 11, day = 1, hour = 21, minute = 12\nReformatted (12): 011120082112\n #include <time.h>\n#include <stdio.h>\n\nint main(void)\n{\n time_t now = time(0);\n struct tm *tm = gmtime(&now);\n char format[] = \"%d%m%Y%H%M\";\n char buffer1[64];\n char buffer2[64];\n size_t f_len = strftime(buffer1, sizeof(buffer1), format, tm);\n struct tm then;\n char *end = strptime(buffer1, format, &then);\n size_t p_len = strftime(buffer2, sizeof(buffer2), format, &then);\n\n printf(\"Now: %ld\\n\", (long)now);\n printf(\"Formatted (%lu): %s\\n\", (unsigned long)f_len, buffer1);\n printf(\"End: 0x%08lX (Buffer: 0x%08lX)\\n\", (unsigned long)end, (unsigned long)buffer1);\n printf(\"Then: year = %d, month = %d, day = %d, hour = %d, minute = %d\\n\",\n then.tm_year + 1900, then.tm_mon + 1, then.tm_mday, then.tm_hour, then.tm_min);\n printf(\"Reformatted (%lu): %s\\n\", (unsigned long)p_len, buffer2);\n\n return(0);\n}\n <inttypes.h> gmtime() localtime()"
},
{
"answer_id": 7093601,
"author": "German",
"author_id": 292609,
"author_profile": "https://Stackoverflow.com/users/292609",
"pm_score": 0,
"selected": false,
"text": " $p = strptime(\"09.02.2002\", \"%d.%m.%Y\");\n var_dump($p);\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33150/"
] |
254,251
|
<p>I need an easy way to allow users to upload multiple files at once (ie I need to allow a user to upload a folder). I do not wish to put the burden of zipping on the user. </p>
<p><em>I would prefer to avoid Flash or variants if possible.</em> I'm looking for a straight javascript / HTML solution if it is possible. Please note, this rules out the answers at: <a href="https://stackoverflow.com/questions/159600/multiple-file-upload">What is the best client side browser library to upload multiple files over http?</a>.</p>
|
[
{
"answer_id": 254261,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "input onchange input input"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13990/"
] |
254,252
|
<p>I have some servers in Europe and some in Asia.<br>
I would like to be able to work out where the current server is by querying ... something. </p>
<p>Is there some global variable I can query or sp_xxx I can execute to find out the locale of the server? </p>
|
[
{
"answer_id": 257376,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 2,
"selected": false,
"text": "sp_helpsort\n"
},
{
"answer_id": 262359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " xp_cmdshell 'domainname'\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7211/"
] |
254,259
|
<p>I use vim (7.1) on OpenVMS V7.3-2.</p>
<p>I connect to VMS trough a telnet session with SmartTerm, a terminal emulator.</p>
<p>It works fine.</p>
<p>But when I start a telnet session from a VMS session (connected via SmartTerm) to another VMS session, some keys doesn't work properly.</p>
<pre><code>|--------------| telnet |-------------| telnet |-----------------|
| Smartterm | ------> | VMS, Vim OK | ------> | VMS, Vim broken |
|--------------| |-------------| |-----------------|
</code></pre>
<p>Insert, Delete, Home, End, PageUp and PageDown are like ~ in normal mode ( upcase to lowercase or vice-versa )</p>
<p>Any idea ?</p>
<p>=============================================</p>
<p>Edit </p>
<p>I just realized that I didn't mention that the second telneted session is on the same VMS box.</p>
<p>I do that because I need to do something with rights from another user.</p>
|
[
{
"answer_id": 257228,
"author": "ngn",
"author_id": 23109,
"author_profile": "https://Stackoverflow.com/users/23109",
"pm_score": 1,
"selected": false,
"text": "t_ :map xxx 0 (press <C-v><Home> in place of xxx)\n:map xxx <C-b> (press <C-v><PgUp> in place of xxx)\n... etc\n :h terminal-options\n"
},
{
"answer_id": 10402314,
"author": "Yauhen Yakimovich",
"author_id": 544463,
"author_profile": "https://Stackoverflow.com/users/544463",
"pm_score": 0,
"selected": false,
"text": "Ctrl+[ Esc :q!\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14673/"
] |
254,260
|
<p>This question is a follow up to:
<a href="https://stackoverflow.com/questions/252267/why-cant-i-call-a-method-outside-of-an-anonymous-class-of-the-same-name">Why can’t I call a method outside of an anonymous class of the same name</a></p>
<p>This previous question answer <b>why</b>, but now I want to know if javac <b>should</b> find run(int bar)? (See previous question to see why run(42) fails)</p>
<p>If it shouldn't, is it due to a spec? Does it produce ambiguous code? My point is, I think this is a bug. While the previous question explained why this code fails to compile, I feel it should compile if javac searched higher in the tree if it fails to find a match at the current level. IE. If this.run() does not match, it should automatically check NotApplicable.this for a run method.</p>
<p>Also note that foo(int bar) is correctly found. If you give any reason why run(int bar) shouldn't be found, it must also explain why foo(int bar) is found.</p>
<pre><code>public class NotApplicable {
public NotApplicable() {
new Runnable() {
public void run() {
// this works just fine, it automatically used NotApplicable.this when it couldn't find this.foo
foo(42);
// this fails to compile, javac find this.run(), and it does not match
run(42);
// to force javac to find run(int bar) you must use the following
//NotApplicable.this.run(42);
}
};
}
private void run(int bar) {
}
public void foo(int bar) {
}
}
</code></pre>
|
[
{
"answer_id": 254328,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 1,
"selected": false,
"text": "NotApplicable.this.run(42);\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21838/"
] |
254,267
|
<p>I'm thinking about how to do this, but I have several different shapes of Data in my Database, Articles, NewsItems, etc. </p>
<p>They All have something in common, they all have IDs (in the DB they're named ArticleID, NewsID etc. )</p>
<p>They all have a <strong>Title</strong></p>
<p>They all have <strong>BodyText</strong>.</p>
<p>They all have a <strong>Status</strong></p>
<p>They all have a <strong>DateAdded</strong></p>
<p>What I'd like to do is standard class inheritance.</p>
<p>I'd like a Master Class (I don't need to write this to the database) called <strong>Content</strong> with fields like:</p>
<ul>
<li>ID</li>
<li>Title</li>
<li>SubTitle</li>
<li>BodyText</li>
<li>Status</li>
<li>AddedDate</li>
</ul>
<p>I'm not sure how I can do this with the ORM. Why I want this is because then I can pass a list of COntent to my UserControl which is responsible for Rendering it. It will only need the information that is common to all objects.</p>
<p>Is this even possible?</p>
|
[
{
"answer_id": 254452,
"author": "Vyrotek",
"author_id": 10941,
"author_profile": "https://Stackoverflow.com/users/10941",
"pm_score": 3,
"selected": true,
"text": "List<IContent> public partial class SomeContent : IContent\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26931/"
] |
254,271
|
<p>The WPF control WindowsFormsHost inherits from IDisposable.</p>
<p>If I have a complex WPF visual tree containing some of the above controls what event or method can I use to call IDispose during shutdown?</p>
|
[
{
"answer_id": 257591,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 3,
"selected": false,
"text": "public partial class Dialog : Window\n{\n public Dialog()\n {\n InitializeComponent();\n }\n\n protected override void OnClosed(EventArgs e)\n {\n if (host != null)\n host.Dispose();\n\n base.OnClosed(e);\n }\n}\n public class CustomWindowsFormsHost : WindowsFormsHost\n{\n protected override void Dispose(bool disposing)\n {\n base.Dispose(disposing);\n }\n}\n"
},
{
"answer_id": 258482,
"author": "morechilli",
"author_id": 5427,
"author_profile": "https://Stackoverflow.com/users/5427",
"pm_score": 3,
"selected": true,
"text": "public partial class MyCustomControl : IDisposable\n {\n\n public MyCustomControl() {\n InitializeComponent();\n\n Loaded += delegate(object sender, RoutedEventArgs e) {\n System.Windows.Window parent_window = Window.GetWindow(this);\n if (parent_window != null) {\n parent_window.Closed += delegate(object sender2, EventArgs e2) {\n Dispose();\n };\n }\n };\n\n ...\n\n }\n\n ...\n }\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5427/"
] |
254,273
|
<p>Why does this lambda expression not compile?</p>
<pre><code>Action a = () => throw new InvalidOperationException();
</code></pre>
<p>Conjecture is fine, but I would really appreciate references to the C# language specification or other documentation.</p>
<p>And yes, I know that the following is valid and will compile:</p>
<pre><code>Action a = () => { throw new InvalidOperationException(); };
</code></pre>
<p>The context where I would use something like this is described on <a href="http://jacobcarpenter.wordpress.com/2008/10/06/c-compiler-eccentricity-of-the-day-throwing-lambda/" rel="noreferrer">this blog post</a>.</p>
|
[
{
"answer_id": 254298,
"author": "Nic Wise",
"author_id": 2947,
"author_profile": "https://Stackoverflow.com/users/2947",
"pm_score": 1,
"selected": false,
"text": "Action a = () => { throw new InvalidOperationException(); };\n Action a = () => throw new InvalidOperationException()\n x => x + 1 // Implicitly typed, expression body\nx => { return x + 1; } // Implicitly typed, statement body\n(int x) => x + 1 // Explicitly typed, expression body\n(int x) => { return x + 1; } // Explicitly typed, statement body\n(x, y) => x * y // Multiple parameters\n() => Console.WriteLine() // No parameters\n"
},
{
"answer_id": 254319,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 4,
"selected": false,
"text": "throw throw expr; delegate () { return XXX; }\n XXX"
},
{
"answer_id": 254322,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "throw void"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26627/"
] |
254,276
|
<p>First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:<br>
a: why it sucks<br>
b: how language x has had that for years<br>
c: how my mind sucks<br>
d: all of the above</p>
<p>The idea would give composition the same ease of code reuse that <code>extends</code> does. </p>
<p>So if you had a class like this:</p>
<pre>
public interface A {
public void methodInA();
}
</pre>
<p>And then you had a class like this:</p>
<pre>
public class B {
private composed A;
public B() {
// construct A within constructor
}
}
</pre>
<p>You would then be able to do this:</p>
<pre>
B myB = new B();
myB.methodInA();
</pre>
<p>Without having to add in the delegation in B's class. But you could also do the same as with inheritance, ie:</p>
<pre>
@Overrides
public void methodInA(){
// B's own delegation method
}
</pre>
<p>Disadvantages include:</p>
<ul>
<li>methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with <code>extends</code></li>
<li>if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?)</li>
<li>if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to</li>
<li>probably 100 other things I've not thought of</li>
</ul>
<p>Like I say, I'm obviously no language theorist, and I haven't spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.</p>
|
[
{
"answer_id": 254352,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": -1,
"selected": false,
"text": "belongsTo has-many"
},
{
"answer_id": 254425,
"author": "Mike Deck",
"author_id": 1247,
"author_profile": "https://Stackoverflow.com/users/1247",
"pm_score": 1,
"selected": true,
"text": "public class Foo {\n\n @Delegate(IBar.class)\n private Bar bar;\n\n // initialize bar via constructor or setter\n}\n public Baz method1(Qux val) {\n return bar.method1(val);\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120/"
] |
254,278
|
<p>I'm trying to define a table to store student grades for a online report card. I can't decide how to do it, though.</p>
<p>The grades are given by subject, in a trimestral period. Every trimester has a average grade, the total missed classes and a "recovering grade" (I don't know the right term in English, but it's an extra test you take to try to raise your grade if you're below the average), I also gotta store the year average and final "recovering grade". Basically, it's like this:</p>
<pre><code> |1st Trimester |2nd Trimester |3rd Trimester
Subj. |Avg. |Mis. |Rec |Avg. |Mis. |Rec |Avg. |Mis. |Rec |Year Avg. |Final Rec.
Math |5.33 |1 |4 |8.0 |0 |7.0 |2 |6.5 |7.0
Sci. |5.33 |1 |4 |8.0 |0 |7.0 |2 |6.5 |7.0
</code></pre>
<p>I could store this information in a single DB row, with each row like this:</p>
<pre><code>1tAverage | 1tMissedClasses | 1tRecoveringGrade | 2tAverage | 2tMissedClasses | 2tRecoveringGrade
</code></pre>
<p>And so on, but I figured this would be a pain to mantain, if the scholl ever decides to grade by bimester or some other period (like it used to be up until 3 years ago).<br />
I could also generalize the table fields, and use a tinyint for flagging for which trimester those grades are, or if they're the year finals.
But this one would ask for a lot of subqueries to write the report card, also a pain to mantain.</p>
<p>Which of the two is better, or is there some other way?
Thanks</p>
|
[
{
"answer_id": 254304,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 0,
"selected": false,
"text": "grades\n------\nstudentID\nperiodNumber\naverageGrade\nmissedClasses\nrecoveringGrade\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9835/"
] |
254,281
|
<p>How do you properly override <code>isEqual:</code> in Objective-C? The "catch" seems to be that if two objects are equal (as determined by the <code>isEqual:</code> method), they must have the same hash value.</p>
<p>The <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW25" rel="noreferrer">Introspection</a> section of the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/" rel="noreferrer">Cocoa Fundamentals Guide</a> does have an example on how to override <code>isEqual:</code>, copied as follows, for a class named <code>MyWidget</code>:</p>
<pre><code>- (BOOL)isEqual:(id)other {
if (other == self)
return YES;
if (!other || ![other isKindOfClass:[self class]])
return NO;
return [self isEqualToWidget:other];
}
- (BOOL)isEqualToWidget:(MyWidget *)aWidget {
if (self == aWidget)
return YES;
if (![(id)[self name] isEqual:[aWidget name]])
return NO;
if (![[self data] isEqualToData:[aWidget data]])
return NO;
return YES;
}
</code></pre>
<p>It checks pointer equality, then class equality, and finally compares the objects using <code>isEqualToWidget:</code>, which only checks the <code>name</code> and <code>data</code> properties. What the example <em>doesn't</em> show is how to override <code>hash</code>.</p>
<p>Let's assume there are other properties that do not affect equality, say <code>age</code>. Shouldn't the <code>hash</code> method be overridden such that only <code>name</code> and <code>data</code> affect the hash? And if so, how would you do that? Just add the hashes of <code>name</code> and <code>data</code>? For example:</p>
<pre><code>- (NSUInteger)hash {
NSUInteger hash = 0;
hash += [[self name] hash];
hash += [[self data] hash];
return hash;
}
</code></pre>
<p>Is that sufficient? Is there a better technique? What if you have primitives, like <code>int</code>? Convert them to <code>NSNumber</code> to get their hash? Or structs like <code>NSRect</code>?</p>
<p>(<strong>Brain fart</strong>: Originally wrote "bitwise OR" them together with <code>|=</code>. Meant add.)</p>
|
[
{
"answer_id": 254315,
"author": "Jens Ayton",
"author_id": 6443,
"author_profile": "https://Stackoverflow.com/users/6443",
"pm_score": 4,
"selected": false,
"text": "-hash -isEqual: [[NSNumber numberWithInt:0] isEqual:[NSNumber numberWithBool:NO]] [[NSNumber numberWithInt:0] hash] != [[NSNumber numberWithBool:NO] hash]"
},
{
"answer_id": 254380,
"author": "tcurdt",
"author_id": 33165,
"author_profile": "https://Stackoverflow.com/users/33165",
"pm_score": 8,
"selected": true,
"text": " NSUInteger prime = 31;\n NSUInteger result = 1;\n result = prime * result + var\n result = prime * result + [var hash];\n result = prime * result + ((var)?1231:1237);\n"
},
{
"answer_id": 4288017,
"author": "LavaSlider",
"author_id": 313757,
"author_profile": "https://Stackoverflow.com/users/313757",
"pm_score": 5,
"selected": false,
"text": "isEqual: hash isEqual: if (![(id)[self name] isEqual:[aWidget name]])\n return NO;\n NSString if (![nil isEqual: nil])\n return NO;\n [nil isEqual: nil]\n isEqual: if ([self name] != [aWidget name] && ![(id)[self name] isEqual:[aWidget name]])\n return NO;\n"
},
{
"answer_id": 4393493,
"author": "Paul Solt",
"author_id": 276626,
"author_profile": "https://Stackoverflow.com/users/276626",
"pm_score": 5,
"selected": false,
"text": "-(NSUInteger)hash {\n NSUInteger result = 1;\n NSUInteger prime = 31;\n NSUInteger yesPrime = 1231;\n NSUInteger noPrime = 1237;\n \n // Add any object that already has a hash function (NSString)\n result = prime * result + [self.myObject hash];\n \n // Add primitive variables (int)\n result = prime * result + self.primitiveVariable; \n\n // Boolean values (BOOL)\n result = prime * result + (self.isSelected ? yesPrime : noPrime);\n \n return result;\n}\n"
},
{
"answer_id": 8902201,
"author": "Jonathan Ellis",
"author_id": 555485,
"author_profile": "https://Stackoverflow.com/users/555485",
"pm_score": 3,
"selected": false,
"text": "- (NSString )description hash - (NSUInteger)hash {\n return [[self description] hash];\n}\n"
},
{
"answer_id": 12557880,
"author": "user4951",
"author_id": 700663,
"author_profile": "https://Stackoverflow.com/users/700663",
"pm_score": 3,
"selected": false,
"text": "isEqual isEqual @interface CLPlacemark (equal)\n- (BOOL)isEqual:(CLPlacemark*)other;\n@end\n\n@implementation CLPlacemark (equal)\n -(NSUInteger) hash\n{\n return self.name.hash;\n}\n\n\n@end\n hash = self.member1.hash ^ self.member2.hash ^ self.member3.hash\n Hash must be O(1), and not O(n)\n"
},
{
"answer_id": 16633700,
"author": "jedwidz",
"author_id": 2396171,
"author_profile": "https://Stackoverflow.com/users/2396171",
"pm_score": 3,
"selected": false,
"text": "- (BOOL)isEqual:(id)object {\n if (self == object)\n return true;\n if ([self class] != [object class])\n return false;\n MyWidget *other = (MyWidget *)object;\n if (_name == nil) {\n if (other->_name != nil)\n return false;\n }\n else if (![_name isEqual:other->_name])\n return false;\n if (_data == nil) {\n if (other->_data != nil)\n return false;\n }\n else if (![_data isEqual:other->_data])\n return false;\n return true;\n}\n\n- (NSUInteger)hash {\n const NSUInteger prime = 31;\n NSUInteger result = 1;\n result = prime * result + [_name hash];\n result = prime * result + [_data hash];\n return result;\n}\n YourWidget serialNo - (BOOL)isEqual:(id)object {\n if (self == object)\n return true;\n if (![super isEqual:object])\n return false;\n if ([self class] != [object class])\n return false;\n YourWidget *other = (YourWidget *)object;\n if (_serialNo == nil) {\n if (other->_serialNo != nil)\n return false;\n }\n else if (![_serialNo isEqual:other->_serialNo])\n return false;\n return true;\n}\n\n- (NSUInteger)hash {\n const NSUInteger prime = 31;\n NSUInteger result = [super hash];\n result = prime * result + [_serialNo hash];\n return result;\n}\n isEqual: other isKindOfClass:[self class] MyWidget other isKindOfClass:[MyWidget class] MyWidget isKindOfClass: isEqual: MyWidget YourWidget YourWidget serialNo [self class] != [object class] isKindOfClass: NSString NSString NSString NSMutableString NSString isEqual: final"
},
{
"answer_id": 19667370,
"author": "johnboiles",
"author_id": 163827,
"author_profile": "https://Stackoverflow.com/users/163827",
"pm_score": 2,
"selected": false,
"text": "NSArray *PropertyNamesFromObject(id object)\n{\n unsigned int propertyCount = 0;\n objc_property_t * properties = class_copyPropertyList([object class], &propertyCount);\n NSMutableArray *propertyNames = [NSMutableArray arrayWithCapacity:propertyCount];\n\n for (unsigned int i = 0; i < propertyCount; ++i) {\n objc_property_t property = properties[i];\n const char * name = property_getName(property);\n NSString *propertyName = [NSString stringWithUTF8String:name];\n [propertyNames addObject:propertyName];\n }\n free(properties);\n return propertyNames;\n}\n\nBOOL IsEqualObjects(id object1, id object2)\n{\n if (object1 == object2)\n return YES;\n if (!object1 || ![object2 isKindOfClass:[object1 class]])\n return NO;\n\n NSArray *propertyNames = PropertyNamesFromObject(object1);\n for (NSString *propertyName in propertyNames) {\n if (([object1 valueForKey:propertyName] != [object2 valueForKey:propertyName])\n && (![[object1 valueForKey:propertyName] isEqual:[object2 valueForKey:propertyName]])) return NO;\n }\n\n return YES;\n}\n\nNSUInteger MagicHash(id object)\n{\n NSUInteger prime = 31;\n NSUInteger result = 1;\n\n NSArray *propertyNames = PropertyNamesFromObject(object);\n\n for (NSString *propertyName in propertyNames) {\n id value = [object valueForKey:propertyName];\n result = prime * result + [value hash];\n }\n\n return result;\n}\n isEqual: hash - (NSUInteger)hash\n{\n return MagicHash(self);\n}\n\n- (BOOL)isEqual:(id)other\n{\n return IsEqualObjects(self, other);\n}\n"
},
{
"answer_id": 20014074,
"author": "Yariv Nissim",
"author_id": 1220642,
"author_profile": "https://Stackoverflow.com/users/1220642",
"pm_score": 5,
"selected": false,
"text": "- (NSUInteger)hash\n{\n return [self.name hash] ^ [self.data hash];\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26825/"
] |
254,291
|
<p>I'm working through <a href="https://rads.stackoverflow.com/amzn/click/com/1590599063" rel="nofollow noreferrer" rel="nofollow noreferrer">Practical Web 2.0 Appications</a> currently and have hit a bit of a roadblock. I'm trying to get PHP, MySQL, Apache, Smarty and the Zend Framework all working correctly so I can begin to build the application. I have gotten the bootstrap file for Zend working, shown here:</p>
<pre><code><?php
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();
// load the application configuration
$config = new Zend_Config_Ini('../settings.ini', 'development');
Zend_Registry::set('config', $config);
// create the application logger
$logger = new Zend_Log(new Zend_Log_Writer_Stream($config->logging->file));
Zend_Registry::set('logger', $logger);
// connect to the database
$params = array('host' => $config->database->hostname,
'username' => $config->database->username,
'password' => $config->database->password,
'dbname' => $config->database->database);
$db = Zend_Db::factory($config->database->type, $params);
Zend_Registry::set('db', $db);
// handle the user request
$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory($config->paths->base .
'/include/Controllers');
// setup the view renderer
$vr = new Zend_Controller_Action_Helper_ViewRenderer();
$vr->setView(new Templater());
$vr->setViewSuffix('tpl');
Zend_Controller_Action_HelperBroker::addHelper($vr);
$controller->dispatch();
?>
</code></pre>
<p>This calls the IndexController. The error comes with the use of this Templater.php to implement Smarty with Zend:</p>
<pre><code><?php
class Templater extends Zend_View_Abstract
{
protected $_path;
protected $_engine;
public function __construct()
{
$config = Zend_Registry::get('config');
require_once('Smarty/Smarty.class.php');
$this->_engine = new Smarty();
$this->_engine->template_dir = $config->paths->templates;
$this->_engine->compile_dir = sprintf('%s/tmp/templates_c',
$config->paths->data);
$this->_engine->plugins_dir = array($config->paths->base .
'/include/Templater/plugins',
'plugins');
}
public function getEngine()
{
return $this->_engine;
}
public function __set($key, $val)
{
$this->_engine->assign($key, $val);
}
public function __get($key)
{
return $this->_engine->get_template_vars($key);
}
public function __isset($key)
{
return $this->_engine->get_template_vars($key) !== null;
}
public function __unset($key)
{
$this->_engine->clear_assign($key);
}
public function assign($spec, $value = null)
{
if (is_array($spec)) {
$this->_engine->assign($spec);
return;
}
$this->_engine->assign($spec, $value);
}
public function clearVars()
{
$this->_engine->clear_all_assign();
}
public function render($name)
{
return $this->_engine->fetch(strtolower($name));
}
public function _run()
{ }
}
?>
</code></pre>
<p>The error I am getting when I load the page is this:</p>
<p><code>Fatal error: Call to a member function fetch() on a non-object in /var/www/phpweb20/include/Templater.php on line 60</code></p>
<p>I understand it doesn't see $name as an object, but I don't know how to go about fixing this. Isn't the controller supposed to refer to the index.tpl? I haven't been able to discover what the $name variable represents and how to fix this to get the foundation working.</p>
<p>Any help you have is much appreciated!</p>
|
[
{
"answer_id": 254358,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 4,
"selected": true,
"text": "$this->_engine = new Smarty();\nprint_r($this->_engine);\n"
},
{
"answer_id": 8919639,
"author": "nufnuf",
"author_id": 1157450,
"author_profile": "https://Stackoverflow.com/users/1157450",
"pm_score": 0,
"selected": false,
"text": "__construct() Tempater()"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27673/"
] |
254,295
|
<p>In a table, I have three columns - id, name, and count. A good number of name columns are identical (due to the lack of a UNIQUE early on) and I want to fix this. However, the id column is used by other (4 or 5, I think - I would have to check the docs) tables to look up the name and just removing them would break things. So is there a good, clean way of saying "find all identical records and merge them together"?</p>
|
[
{
"answer_id": 254353,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 0,
"selected": false,
"text": "update dependent_table set name_id = <id you want to keep> where name_id in (\n select id from names where name = 'foo' and id != <id you want to keep>)\n"
},
{
"answer_id": 254392,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "UPDATE DELETE UPDATE names n1\n JOIN names n2 ON (n1.id < n2.id AND n1.name = n2.name)\n JOIN child_table c ON (n2.id = c.id)\nSET c.name_id = n1.id\nORDER BY n1.id DESC;\n DELETE DELETE FROM n2\n USING names n1 JOIN names n2 ON (n1.id < n2.id AND n1.name = n2.name);\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
254,302
|
<p>I need a way to determine the type of an HTML element in JavaScript. It has the ID, but the element itself could be a <code><div></code>, a <code><form></code> field, a <code><fieldset></code>, etc. How can I achieve this?</p>
|
[
{
"answer_id": 254308,
"author": "Brian Cline",
"author_id": 32536,
"author_profile": "https://Stackoverflow.com/users/32536",
"pm_score": 6,
"selected": false,
"text": "element.tagName tagName"
},
{
"answer_id": 254313,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 10,
"selected": true,
"text": "nodeName var elt = document.getElementById('foo');\nconsole.log(elt.nodeName);\n nodeName <div> elt.nodeName == \"DIV\"\n elt.nodeName == \"<div>\"\n"
},
{
"answer_id": 55273598,
"author": "golopot",
"author_id": 3290397,
"author_profile": "https://Stackoverflow.com/users/3290397",
"pm_score": 4,
"selected": false,
"text": "element.constructor.name document.createElement('div').constructor.name\n// HTMLDivElement\n\ndocument.createElement('a').constructor.name\n// HTMLAnchorElement\n\ndocument.createElement('foo').constructor.name\n// HTMLUnknownElement\n"
},
{
"answer_id": 60020069,
"author": "Code4R7",
"author_id": 7740888,
"author_profile": "https://Stackoverflow.com/users/7740888",
"pm_score": 5,
"selected": false,
"text": "instanceof var e = document.getElementById('#my-element');\nif (e instanceof HTMLInputElement) {} // <input>\nelseif (e instanceof HTMLSelectElement) {} // <select>\nelseif (e instanceof HTMLTextAreaElement) {} // <textarea>\nelseif ( ... ) {} // any interface\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103/"
] |
254,340
|
<p>I've tried variations of this, but had no luck other than the ability to start a cygwin window. (wrapped on <strong>;</strong> for clarity)</p>
<pre><code>Filename: "c:\cygwin\bin\bash.exe";
Parameters: "-c c:/scripts/step1.sh paramX";
Flags: shellexec waituntilterminated;
StatusMsg: "Running the script..."
</code></pre>
<p>(this is for an internal install, thus cywin is installed, and all paths, scripts are known)</p>
|
[
{
"answer_id": 254370,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "cmd.exe shellexec waituntilterminated Filename: \"cmd.exe\"; Parameters: \"/c c:\\cygwin\\bin\\bash -c 'c:/scripts/step1.sh paramx'\"\n"
},
{
"answer_id": 14785573,
"author": "Joshua Clayton",
"author_id": 1419731,
"author_profile": "https://Stackoverflow.com/users/1419731",
"pm_score": 3,
"selected": false,
"text": "-c c:\\cygwin\\bin\\bash.exe -c 'for NUM in 1 2 3 4 5 6 7 8 9 10; do echo $NUM; done'\n c:\\cygwin\\bin\\bash.exe \"/scripts/step1.sh paramX\"\n Filename: \"c:\\cygwin\\bin\\bash.exe\";\n Parameters: \"c:/scripts/step1.sh paramX\";\n Flags: shellexec waituntilterminated;\n StatusMsg: \"Running the script...\"\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6144/"
] |
254,345
|
<p>I previously asked how to do this in Groovy. However, now I'm rewriting my app in Perl because of all the CPAN libraries.</p>
<p>If the page contained these links:</p>
<pre>
<a href="http://www.google.com">Google</a>
<a href="http://www.apple.com">Apple</a>
</pre>
<p>The output would be:</p>
<pre>
Google, http://www.google.com
Apple, http://www.apple.com
</pre>
<p>What is the best way to do this in Perl?</p>
|
[
{
"answer_id": 254506,
"author": "draegtun",
"author_id": 12195,
"author_profile": "https://Stackoverflow.com/users/12195",
"pm_score": 3,
"selected": false,
"text": "use pQuery;\n\npQuery( 'http://www.perlbuzz.com' )->find( 'a' )->each(\n sub {\n say $_->innerHTML . q{, } . $_->getAttribute( 'href' );\n }\n);\n"
},
{
"answer_id": 254687,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 6,
"selected": true,
"text": "my $mech = WWW::Mechanize->new();\n$mech->get( $some_url );\nmy @links = $mech->links();\nfor my $link ( @links ) {\n printf \"%s, %s\\n\", $link->text, $link->url;\n}\n"
},
{
"answer_id": 266022,
"author": "Alexandr Ciornii",
"author_id": 13467,
"author_profile": "https://Stackoverflow.com/users/13467",
"pm_score": 3,
"selected": false,
"text": " my $tree=HTML::TreeBuilder::XPath->new_from_content($c);\n my $nodes=$tree->findnodes(q{//map[@name='map1']/area});\n while (my $node=$nodes->shift) {\n my $t=$node->attr('title');\n }\n"
},
{
"answer_id": 5398997,
"author": "Ashley",
"author_id": 109483,
"author_profile": "https://Stackoverflow.com/users/109483",
"pm_score": 2,
"selected": false,
"text": "recover use XML::LibXML;\n\nmy $doc = XML::LibXML->load_html(IO => \\*DATA);\nfor my $anchor ( $doc->findnodes(\"//a[\\@href]\") )\n{\n printf \"%15s -> %s\\n\",\n $anchor->textContent,\n $anchor->getAttribute(\"href\");\n}\n\n__DATA__\n<html><head><title/></head><body>\n<a href=\"http://www.google.com\">Google</a>\n<a href=\"http://www.apple.com\">Apple</a>\n</body></html>\n Google -> http://www.google.com\n Apple -> http://www.apple.com\n"
},
{
"answer_id": 10888037,
"author": "Aaron Graves",
"author_id": 1435982,
"author_profile": "https://Stackoverflow.com/users/1435982",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/perl\n\nif($#ARGV < 0) {\n print \"$0: Need URL argument.\\n\";\n exit 1;\n}\n\nmy @content = split(/\\n/,`wget -qO- $ARGV[0]`);\nmy @links = grep(/<a.*href=.*>/,@content);\n\nforeach my $c (@links){\n $c =~ /<a.*href=\"([\\s\\S]+?)\".*>/;\n $link = $1;\n $c =~ /<a.*href.*>([\\s\\S]+?)<\\/a>/;\n $title = $1;\n print \"$title, $link\\n\";\n}\n"
},
{
"answer_id": 14579702,
"author": "Deiveegaraja Andaver",
"author_id": 944073,
"author_profile": "https://Stackoverflow.com/users/944073",
"pm_score": -1,
"selected": false,
"text": "local $/ = '';\nmy $a = <DATA>;\n\nwhile( $a =~ m/<a[^>]*?href=\\\"([^>]*?)\\\"[^>]*?>\\s*([\\w\\W]*?)\\s*<\\/a>/igs )\n{ \n print \"Link:$1 \\t Text: $2\\n\";\n}\n\n\n__DATA__\n\n<a href=\"http://www.google.com\">Google</a>\n\n<a href=\"http://www.apple.com\">Apple</a>\n"
},
{
"answer_id": 18786147,
"author": "user13107",
"author_id": 1729501,
"author_profile": "https://Stackoverflow.com/users/1729501",
"pm_score": 2,
"selected": false,
"text": " use HTML::LinkExtractor;\n my $input = q{If <a href=\"http://apple.com/\"> Apple </a>}; #HTML string\n my $LX = new HTML::LinkExtractor(undef,undef,1);\n $LX->parse(\\$input);\n for my $Link( @{ $LX->links } ) {\n if( $$Link{_TEXT}=~ m/Apple/ ) {\n print \"\\n LinkText $$Link{_TEXT} URL $$Link{href}\\n\";\n }\n }\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
254,347
|
<p>We currently have developed an application using WCF. Our clients make connections to different WCF servicehosts located on the server, and the servicehosts return the data from the DB that the clients need. Standard model. However, this current design has all of our WCF data in app.config files both on the client side as well as the servicehost side. We want to make this more dynamic, and have moved all of the data, including the endpoints, the contracts, and the bindings, into the DB.</p>
<p>Now the question is how do we retrieve this data, and access it properly. We've got the design working where we have one defined endpoint in a config file, and using that endpoint, we can make a call to it to get the rest of the endpoint information that we need (i.e. all of the bindings, contracts and different endpoints that it used to have defined in its app.config). This is the case on both the client side as well as the servicehost side.</p>
<p>The issue that I'm now struggling with is how do I code against these dynamic endpoints? When the client makes a call to the servicehost, it not only is making simple calls to the servicehost, but retrieving and passing back objects for the servicehost to process as needed. For example, on form load we may retrieve the object with all of the currently defined settings from the DB, and then the user does whatever on the fornm, and we then pass back the updated object to the servicehost. We can do that now because in Visual Studio 2008 we've added all of the service references, which has auto-generated the methods and objects that can be called and retrieved from the servicehosts. If we go to a dynamic endpoint connection, how do we get this data during the development phase?</p>
<p>I've developed a similar application in the past in .NET 2.0 using .NET remoting, where we were passing the object back and forth, and the client and server both used the same object definition class to know about the object. I'm not sure how we would go about doing this with WCF.</p>
|
[
{
"answer_id": 254506,
"author": "draegtun",
"author_id": 12195,
"author_profile": "https://Stackoverflow.com/users/12195",
"pm_score": 3,
"selected": false,
"text": "use pQuery;\n\npQuery( 'http://www.perlbuzz.com' )->find( 'a' )->each(\n sub {\n say $_->innerHTML . q{, } . $_->getAttribute( 'href' );\n }\n);\n"
},
{
"answer_id": 254687,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 6,
"selected": true,
"text": "my $mech = WWW::Mechanize->new();\n$mech->get( $some_url );\nmy @links = $mech->links();\nfor my $link ( @links ) {\n printf \"%s, %s\\n\", $link->text, $link->url;\n}\n"
},
{
"answer_id": 266022,
"author": "Alexandr Ciornii",
"author_id": 13467,
"author_profile": "https://Stackoverflow.com/users/13467",
"pm_score": 3,
"selected": false,
"text": " my $tree=HTML::TreeBuilder::XPath->new_from_content($c);\n my $nodes=$tree->findnodes(q{//map[@name='map1']/area});\n while (my $node=$nodes->shift) {\n my $t=$node->attr('title');\n }\n"
},
{
"answer_id": 5398997,
"author": "Ashley",
"author_id": 109483,
"author_profile": "https://Stackoverflow.com/users/109483",
"pm_score": 2,
"selected": false,
"text": "recover use XML::LibXML;\n\nmy $doc = XML::LibXML->load_html(IO => \\*DATA);\nfor my $anchor ( $doc->findnodes(\"//a[\\@href]\") )\n{\n printf \"%15s -> %s\\n\",\n $anchor->textContent,\n $anchor->getAttribute(\"href\");\n}\n\n__DATA__\n<html><head><title/></head><body>\n<a href=\"http://www.google.com\">Google</a>\n<a href=\"http://www.apple.com\">Apple</a>\n</body></html>\n Google -> http://www.google.com\n Apple -> http://www.apple.com\n"
},
{
"answer_id": 10888037,
"author": "Aaron Graves",
"author_id": 1435982,
"author_profile": "https://Stackoverflow.com/users/1435982",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/perl\n\nif($#ARGV < 0) {\n print \"$0: Need URL argument.\\n\";\n exit 1;\n}\n\nmy @content = split(/\\n/,`wget -qO- $ARGV[0]`);\nmy @links = grep(/<a.*href=.*>/,@content);\n\nforeach my $c (@links){\n $c =~ /<a.*href=\"([\\s\\S]+?)\".*>/;\n $link = $1;\n $c =~ /<a.*href.*>([\\s\\S]+?)<\\/a>/;\n $title = $1;\n print \"$title, $link\\n\";\n}\n"
},
{
"answer_id": 14579702,
"author": "Deiveegaraja Andaver",
"author_id": 944073,
"author_profile": "https://Stackoverflow.com/users/944073",
"pm_score": -1,
"selected": false,
"text": "local $/ = '';\nmy $a = <DATA>;\n\nwhile( $a =~ m/<a[^>]*?href=\\\"([^>]*?)\\\"[^>]*?>\\s*([\\w\\W]*?)\\s*<\\/a>/igs )\n{ \n print \"Link:$1 \\t Text: $2\\n\";\n}\n\n\n__DATA__\n\n<a href=\"http://www.google.com\">Google</a>\n\n<a href=\"http://www.apple.com\">Apple</a>\n"
},
{
"answer_id": 18786147,
"author": "user13107",
"author_id": 1729501,
"author_profile": "https://Stackoverflow.com/users/1729501",
"pm_score": 2,
"selected": false,
"text": " use HTML::LinkExtractor;\n my $input = q{If <a href=\"http://apple.com/\"> Apple </a>}; #HTML string\n my $LX = new HTML::LinkExtractor(undef,undef,1);\n $LX->parse(\\$input);\n for my $Link( @{ $LX->links } ) {\n if( $$Link{_TEXT}=~ m/Apple/ ) {\n print \"\\n LinkText $$Link{_TEXT} URL $$Link{href}\\n\";\n }\n }\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4539/"
] |
254,349
|
<p>I have a page with some dynamically added buttons. If you click a button before the page has fully loaded, it throws the classic exception:</p>
<blockquote>
<pre><code>Invalid postback or callback argument.
Event validation is enabled using in configuration or in a page. For
</code></pre>
<p>security purposes,
this feature verifies that arguments to postback or callback
events originate from the
server control that originally rendered them. If the data is valid
and expected, use
the ClientScriptManager.RegisterForEventValidation
method in order to register the
postback or callback data for validation.</p>
</blockquote>
<p>I am guessing the Viewstate field hasn't loaded on the form yet, the the other bits are being submitted. What's the best way to prevent this error, while maintaining Event Validation?</p>
|
[
{
"answer_id": 254561,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "ClientScriptManager.RegisterForEventValidation( button.UniqueID )"
},
{
"answer_id": 254677,
"author": "Jeffrey Harrington",
"author_id": 4307,
"author_profile": "https://Stackoverflow.com/users/4307",
"pm_score": 3,
"selected": true,
"text": "<configuration>\n\n <system.web>\n\n <pages renderAllHiddenFieldsAtTopOfForm=\"true\"></pages>\n\n </system.web>\n\n</configuration>\n"
},
{
"answer_id": 260772,
"author": "Andy C.",
"author_id": 28541,
"author_profile": "https://Stackoverflow.com/users/28541",
"pm_score": 2,
"selected": false,
"text": "__EVENTVALIDATION __EVENTVALIDATION"
},
{
"answer_id": 36751816,
"author": "Bolo",
"author_id": 4241466,
"author_profile": "https://Stackoverflow.com/users/4241466",
"pm_score": 0,
"selected": false,
"text": "function CheckForHiddenFields()\n{\n var EventValidation = document.getElementById('__EVENTVALIDATION');\n if (EventValidation && EventValidation.value && EventValidation.value != '')\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n OnClientClick=\"return CheckForHiddenFields();\"\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] |
254,350
|
<p>I don't care what the differences are. I just want to know whether the contents are different.</p>
|
[
{
"answer_id": 254357,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 8,
"selected": true,
"text": "from __future__ import with_statement\nwith open(filename1) as f1:\n with open(filename2) as f2:\n if f1.read() == f2.read():\n ...\n import filecmp\nif filecmp.cmp(filename1, filename2, shallow=False):\n ...\n"
},
{
"answer_id": 254362,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "\nf = open(filename1, \"r\").read()\nf2 = open(filename2,\"r\").read()\nprint f == f2\n\n"
},
{
"answer_id": 254373,
"author": "Rich",
"author_id": 22003,
"author_profile": "https://Stackoverflow.com/users/22003",
"pm_score": 5,
"selected": false,
"text": "if os.path.getsize(filename1) == os.path.getsize(filename2):\n if open('filename1','r').read() == open('filename2','r').read():\n # Files are the same.\n"
},
{
"answer_id": 254518,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 2,
"selected": false,
"text": "import hashlib\n\ndef checksum(f):\n md5 = hashlib.md5()\n md5.update(open(f).read())\n return md5.hexdigest()\n\ndef is_contents_same(f1, f2):\n return checksum(f1) == checksum(f2)\n\nif not is_contents_same('foo.txt', 'bar.txt'):\n print 'The contents are not the same!'\n"
},
{
"answer_id": 254567,
"author": "user32141",
"author_id": 32141,
"author_profile": "https://Stackoverflow.com/users/32141",
"pm_score": 3,
"selected": false,
"text": "def get_file_md5(f, chunk_size=8192):\n h = hashlib.md5()\n while True:\n chunk = f.read(chunk_size)\n if not chunk:\n break\n h.update(chunk)\n return h.hexdigest()\n"
},
{
"answer_id": 255210,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 4,
"selected": false,
"text": "from __future__ import with_statement\nimport os\nimport itertools, functools, operator\ntry:\n izip= itertools.izip # Python 2\nexcept AttributeError:\n izip= zip # Python 3\n\ndef filecmp(filename1, filename2):\n \"Do the two files have exactly the same contents?\"\n with open(filename1, \"rb\") as fp1, open(filename2, \"rb\") as fp2:\n if os.fstat(fp1.fileno()).st_size != os.fstat(fp2.fileno()).st_size:\n return False # different sizes ∴ not equal\n\n # set up one 4k-reader for each file\n fp1_reader= functools.partial(fp1.read, 4096)\n fp2_reader= functools.partial(fp2.read, 4096)\n\n # pair each 4k-chunk from the two readers while they do not return '' (EOF)\n cmp_pairs= izip(iter(fp1_reader, b''), iter(fp2_reader, b''))\n\n # return True for all pairs that are not equal\n inequalities= itertools.starmap(operator.ne, cmp_pairs)\n\n # voilà; any() stops at first True value\n return not any(inequalities)\n\nif __name__ == \"__main__\":\n import sys\n print filecmp(sys.argv[1], sys.argv[2])\n"
},
{
"answer_id": 41169735,
"author": "Prashanth Babu",
"author_id": 7303225,
"author_profile": "https://Stackoverflow.com/users/7303225",
"pm_score": 1,
"selected": false,
"text": "from __future__ import with_statement\n\nfilename1 = \"G:\\\\test1.TXT\"\n\nfilename2 = \"G:\\\\test2.TXT\"\n\n\nwith open(filename1) as f1:\n\n with open(filename2) as f2:\n\n file1list = f1.read().splitlines()\n\n file2list = f2.read().splitlines()\n\n list1length = len(file1list)\n\n list2length = len(file2list)\n\n if list1length == list2length:\n\n for index in range(len(file1list)):\n\n if file1list[index] == file2list[index]:\n\n print file1list[index] + \"==\" + file2list[index]\n\n else: \n\n print file1list[index] + \"!=\" + file2list[index]+\" Not-Equel\"\n\n else:\n\n print \"difference inthe size of the file and number of lines\"\n"
},
{
"answer_id": 68601548,
"author": "Angel",
"author_id": 12234006,
"author_profile": "https://Stackoverflow.com/users/12234006",
"pm_score": 0,
"selected": false,
"text": "import os\n\n\ndef is_file_content_equal(\n file_path_1: str, file_path_2: str, buffer_size: int = 1024 * 8\n) -> bool:\n \"\"\"Checks if two files content is equal\n Arguments:\n file_path_1 (str): Path to the first file\n file_path_2 (str): Path to the second file\n buffer_size (int): Size of the buffer to read the file\n Returns:\n bool that indicates if the file contents are equal\n Example:\n >>> is_file_content_equal(\"filecomp.py\", \"filecomp copy.py\")\n True\n >>> is_file_content_equal(\"filecomp.py\", \"diagram.dio\")\n False\n \"\"\"\n # First check sizes\n s1, s2 = os.path.getsize(file_path_1), os.path.getsize(file_path_2)\n if s1 != s2:\n return False\n # If the sizes are the same check the content\n with open(file_path_1, \"rb\") as fp1, open(file_path_2, \"rb\") as fp2:\n while True:\n b1 = fp1.read(buffer_size)\n b2 = fp2.read(buffer_size)\n if b1 != b2:\n return False\n # if the content is the same and they are both empty bytes\n # the file is the same\n if not b1:\n return True\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
254,351
|
<p>I wanted to make Map of Collections in Java, so I can make something like </p>
<pre><code>public void add(K key, V value) {
if (containsKey(key)) {
get(key).add(value);
} else {
Collection c = new Collection();
c.add(value);
put(key, value);
}
}
</code></pre>
<p>I've tried to make it with something like </p>
<pre><code>public class CollectionMap<K, C extends Collection<V>> extends HashMap<K, C>
</code></pre>
<p>but compiler complains about the <code><V></code> part, and there would still be an issue of making proper new collection. </p>
<p>At the moment, I've made two classes: SetMap that look like this </p>
<pre><code> 1: public class SetMap<K, V> extends HashMap<K, Set<V>> {
2:
3: public void add(K key, V value) {
4: if (containsKey(key)) {
5: get(key).add(value);
6: } else {
7: Set<V> list = new HashSet<V>();
8: list.add(value);
9: put(key, list);
10: }
11: }
12:
13: }
</code></pre>
<p>and ListMap looks pretty much the same except the line 7 where I make new ArrayList. This sort of duplication is small enough to be tolerable, but question remains is this sort of "nested generics" possible in Java? </p>
<p>EDIT:</p>
<p>As <a href="https://stackoverflow.com/questions/254351/map-of-collections#254372">erickson said</a>, solution is in <code><A, B extends Something<A>></code> rather than just <code><B extends Something<A>></code></p>
<p>so code can look something like </p>
<pre><code>public abstract class CollelctionMap<K, V, C extends Collection<V>> extends HashMap<K, C> {
protected abstract C newCollection();
public void add(K key, V value) {
if (containsKey(key)) {
get(key).add(value);
} else {
C c = newCollection();
c.add(value);
put(key, c);
}
}
}
</code></pre>
<p>and ListMap and SetMap only provide proper collection </p>
|
[
{
"answer_id": 254372,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 5,
"selected": true,
"text": "map Map<K, Collection<V>> computeIfAbsent(...).add(...) map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);\n Set map.computeIfAbsent(key, k -> new HashSet<>()).add(value);\n"
},
{
"answer_id": 254396,
"author": "sakana",
"author_id": 28921,
"author_profile": "https://Stackoverflow.com/users/28921",
"pm_score": 2,
"selected": false,
"text": "public class CollectionMap<K, V> extends HashMap<K, Collection<V>> {\n\n\n ...\n ...\n ...\n\n\n public void add(K key, V value) {\n if (containsKey(key)) {\n get(key).add(value);\n } else {\n Collection<V> c = new ArrayList<V>();\n c.add(value);\n super.put(key, c);\n }\n }\n}\n"
},
{
"answer_id": 257013,
"author": "Manoj",
"author_id": 5541,
"author_profile": "https://Stackoverflow.com/users/5541",
"pm_score": 2,
"selected": false,
"text": "abstract class MultiMap<K, V> {\n\n private Map<K, Collection<V>> entries = new LinkedHashMap<K, Collection<V>>();\n\n public void put(K key, V value) {\n Collection<V> values = entries.get(key);\n if (values == null) {\n entries.put(key, values = newValueCollection());\n }\n values.add(value);\n }\n\n // other methods\n // ..\n\n abstract Collection<V> newValueCollection();\n\n\n\n // Helper methods to create different flavors of MultiMaps\n\n public static <K, V> MultiMap<K, V> newArrayListMultiMap() {\n return new MultiMap<K, V>() {\n Collection<V> newValueCollection() {\n return new ArrayList<V>();\n }\n };\n }\n\n public static <K, V> MultiMap<K, V> newHashSetMultiMap() {\n return new MultiMap<K, V>() {\n Collection<V> newValueCollection() {\n return new HashSet<V>();\n }\n };\n }\n\n }\n MultiMap<String, Integer> data = MultiMap.newArrayListMultiMap();\ndata.put(\"first\", 1);\ndata.put(\"first\", 2);\ndata.put(\"first\", 3);\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4433/"
] |
254,354
|
<p><strong>General Description:</strong></p>
<p>To start with what works, I have a <code>UITableView</code> which has been placed onto an Xcode-generated view using Interface Builder. The view's File Owner is set to an Xcode-generated subclass of <code>UIViewController</code>. To this subclass I have added working implementations of <code>numberOfSectionsInTableView: tableView:numberOfRowsInSection:</code> and <code>tableView:cellForRowAtIndexPath:</code> and the Table View's <code>dataSource</code> and <code>delegate</code> are connected to this class via the File Owner in Interface Builder.</p>
<p>The above configuration works with no problems. The issue occurs when I want to move this Table View's <code>dataSource</code> and <code>delegate</code>-implementations out to a separate class, most likely because there are other controls on the View besides the Table View and I'd like to move the Table View-related code out to its own class. To accomplish this, I try the following:</p>
<ul>
<li>Create a new subclass of <code>UITableViewController</code> in Xcode</li></li>
<li>Move the known-good implementations of <code>numberOfSectionsInTableView:</code>, <code>tableView:numberOfRowsInSection:</code> and <code>tableView:cellForRowAtIndexPath:</code> to the new subclass</li>
<li>Drag a <code>UITableViewController</code> to the top level of the <em>existing</em> XIB in InterfaceBuilder, delete the <code>UIView</code>/<code>UITableView</code> that are automatically created for this <code>UITableViewController</code>, then set the <code>UITableViewController</code>'s class to match the new subclass</li>
<li>Remove the previously-working <code>UITableView</code>'s existing <code>dataSource</code> and <code>delegate</code> connections and connect them to the new <code>UITableViewController</code></li>
</ul>
<p>When complete, I do not have a working <code>UITableView</code>. I end up with one of three outcomes which can seemingly happen at random:</p>
<ul>
<li>When the <code>UITableView</code> loads, I get a runtime error indicating I am sending <code>tableView:cellForRowAtIndexPath:</code> to an object which does not recognize it</li>
<li>When the <code>UITableView</code> loads, the project breaks into the debugger without error</li>
<li>There is no error, but the <code>UITableView</code> does not appear</li>
</ul>
<p>With some debugging and having created a basic project just to reproduce this issue, I am usually seeing the 3rd option above (no error but no visible table view). I added some NSLog calls and found that although <code>numberOfSectionsInTableView:</code> and <code>numberOfRowsInSection:</code> are both getting called, <code>cellForRowAtIndexPath:</code> is not. I am convinced I'm missing something really simple and was hoping the answer may be obvious to someone with more experience than I have. If this doesn't turn out to be an easy answer I would be happy to update with some code or a sample project. Thanks for your time!</p>
<p><strong>Complete steps to reproduce:</strong></p>
<ul>
<li>Create a new iPhone OS, View-Based Application in Xcode and call it <code>TableTest</code></li>
<li>Open <code>TableTestViewController.xib</code> in Interface Builder and drag a <code>UITableView</code> onto the provided view surface.</li>
<li>Connect the <code>UITableView</code>'s <code>dataSource</code> and <code>delegate</code>-outlets to File's Owner, which should already represent the <code>TableTestViewController</code>-class. Save your changes</li>
<li>Back in Xcode, add the following code to <code>TableTestViewController.m:</code></li>
</ul>
<hr>
<pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(@"Returning num sections");
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(@"Returning num rows");
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"Trying to return cell");
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.text = @"Hello";
NSLog(@"Returning cell");
return cell;
}
</code></pre>
<ul>
<li><p>Build and Go, and you should see the word <code>Hello</code> appear in the <code>UITableView</code></p></li>
<li><p>Now to attempt to move this <code>UITableView</code>'s logic out to a separate class, first create a new file in Xcode, choosing <code>UITableViewController</code> subclass and calling the class <code>TableTestTableViewController</code></p></li>
<li>Remove the above code snippet from <code>TableTestViewController.m</code> and place it into <code>TableTestTableViewController.m</code>, replacing the default implementation of these three methods with ours.</li>
<li>Back in Interface Builder within the same <code>TableTestViewController.xib</code>-file, drag a <code>UITableViewController</code> into the main IB window and delete the new <code>UITableView</code> object that automatically came with it</li>
<li>Set the class for this new <code>UITableViewController</code> to <code>TableTestTableViewController</code></li>
<li>Remove the <code>dataSource</code> and <code>delegate</code> bindings from the existing, previously-working <code>UITableView</code> and reconnect the same two bindings to the new <code>TableTestTableViewController</code> we created.</li>
<li>Save changes, Build and Go, and if you're getting the results I'm getting, note the <code>UITableView</code> no longer functions properly</li>
</ul>
<p><strong>Solution:</strong>
With some more troubleshooting and some assistance from the <a href="https://devforums.apple.com/message/5453" rel="noreferrer">iPhone Developer Forums</a>, I've documented a solution! The main <code>UIViewController</code> subclass of the project needs an outlet pointing to the <code>UITableViewController</code> instance. To accomplish this, simply add the following to the primary view's header (<code>TableTestViewController.h</code>):</p>
<pre><code>#import "TableTestTableViewController.h"
</code></pre>
<p>and</p>
<pre><code>IBOutlet TableTestTableViewController *myTableViewController;
</code></pre>
<p>Then, in Interface Builder, connect the new outlet from File's Owner to <code>TableTestTableViewController</code> in the main IB window. No changes are necessary in the UI part of the XIB. Simply having this outlet in place, even though no user code directly uses it, resolves the problem completely. Thanks to those who've helped and credit goes to BaldEagle on the iPhone Developer Forums for finding the solution.</p>
|
[
{
"answer_id": 254813,
"author": "keremk",
"author_id": 29475,
"author_profile": "https://Stackoverflow.com/users/29475",
"pm_score": 2,
"selected": false,
"text": "tableView UITableViewController IBOutlet UITableView tableView IBOutlet UITableViewController's UITableView UITableView"
},
{
"answer_id": 255874,
"author": "keremk",
"author_id": 29475,
"author_profile": "https://Stackoverflow.com/users/29475",
"pm_score": 6,
"selected": true,
"text": "tableView TableTestTableViewController UITableView IBOutlet tableView IBOutlet @interface TableTestTableViewController : UITableViewController {\n UITableView *tableView;\n}\n\n@property (nonatomic, retain) IBOutlet UITableView *tableView;\n TableTestTableViewController TableTestViewController TableTestTableViewController @interface TableTestViewController : UIViewController {\n TableTestTableViewController *tableViewController;\n}\n\n@property (nonatomic, retain) IBOutlet TableTestTableViewController *tableViewController;\n TableTestTableViewController UITableViewController UITableView UITableView UILabels UIImages UIView UITableView"
},
{
"answer_id": 621320,
"author": "Pat Niemeyer",
"author_id": 74975,
"author_profile": "https://Stackoverflow.com/users/74975",
"pm_score": 2,
"selected": false,
"text": "UITableView UITableViewController UITableView IBOutlet tableView viewDidLoad uitableview uitableviewcontroller"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33164/"
] |
254,385
|
<p>I want to simplify my execution of a Groovy script that makes calls to an Oracle database. How do I add the ojdbc jar to the default classpath so that I can run:</p>
<pre><code>groovy RunScript.groovy
</code></pre>
<p>instead of:</p>
<pre><code>groovy -cp ojdbc5.jar RunScript.groovy
</code></pre>
|
[
{
"answer_id": 254431,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 1,
"selected": false,
"text": "groovy"
},
{
"answer_id": 254443,
"author": "Joey Gibson",
"author_id": 6645,
"author_profile": "https://Stackoverflow.com/users/6645",
"pm_score": 3,
"selected": false,
"text": "this.class.classLoader.rootLoader.addURL(new URL(\"file:///path to file\"))\n"
},
{
"answer_id": 254448,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 5,
"selected": true,
"text": ".groovy/lib load !{user.home}/.groovy/lib/*.jar .groovy/lib"
},
{
"answer_id": 42890203,
"author": "bonh",
"author_id": 2068738,
"author_profile": "https://Stackoverflow.com/users/2068738",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env groovy -cp ojdbc5.jar\n chmod u+x RunScript.groovy\n ./RunScript.groovy\n"
},
{
"answer_id": 61104823,
"author": "Cristi B.",
"author_id": 2064134,
"author_profile": "https://Stackoverflow.com/users/2064134",
"pm_score": 2,
"selected": false,
"text": " @GrabConfig(systemClassLoader=true)\n @Grab('com.oracle:ojdbc6:12.1.0.2.0')\n Class.forName(\"oracle.jdbc.OracleDriver\").newInstance()\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6013/"
] |
254,388
|
<p>How does one go about converting an image to black and white in PHP?</p>
<p>Not just turning it into greyscale but every pixel made black or white?</p>
|
[
{
"answer_id": 254427,
"author": "Jasper Bekkers",
"author_id": 31486,
"author_profile": "https://Stackoverflow.com/users/31486",
"pm_score": 5,
"selected": true,
"text": "float gray = (r + g + b) / 3\nif(gray > 0x7F) return 0xFF;\nreturn 0x00;\n"
},
{
"answer_id": 254776,
"author": "Joel Wietelmann",
"author_id": 28340,
"author_profile": "https://Stackoverflow.com/users/28340",
"pm_score": 5,
"selected": false,
"text": "imagefilter($im, IMG_FILTER_GRAYSCALE);\nimagefilter($im, IMG_FILTER_CONTRAST, -100);\n"
},
{
"answer_id": 10313995,
"author": "KEL",
"author_id": 1355937,
"author_profile": "https://Stackoverflow.com/users/1355937",
"pm_score": 1,
"selected": false,
"text": "$rgb = imagecolorat($original, $x, $y);\n $r = ($rgb >> 16) & 0xFF;\n $g = ($rgb >> 8 ) & 0xFF;\n $b = $rgb & 0xFF;\n\n $gray = $r + $g + $b/3;\n if ($gray >0xFF) {$grey = 0xFFFFFF;}\n else { $grey=0x000000;}\n"
},
{
"answer_id": 14289672,
"author": "Amed",
"author_id": 1065166,
"author_profile": "https://Stackoverflow.com/users/1065166",
"pm_score": 1,
"selected": false,
"text": " public function ImageToBlackAndWhite($im) {\n\n for ($x = imagesx($im); $x--;) {\n for ($y = imagesy($im); $y--;) {\n $rgb = imagecolorat($im, $x, $y);\n $r = ($rgb >> 16) & 0xFF;\n $g = ($rgb >> 8 ) & 0xFF;\n $b = $rgb & 0xFF;\n $gray = ($r + $g + $b) / 3;\n if ($gray < 0xFF) {\n\n imagesetpixel($im, $x, $y, 0xFFFFFF);\n }else\n imagesetpixel($im, $x, $y, 0x000000);\n }\n }\n\n imagefilter($im, IMG_FILTER_NEGATE);\n\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118/"
] |
254,397
|
<p>I'm extracting a folder from a tarball, and I see these zero-byte files showing up in the result (where they are not in the source.) Setup (all on OS X):</p>
<p>On machine one, I have a directory /My/Stuff/Goes/Here/ containing several hundred files.
I build it like this</p>
<pre><code>tar -cZf mystuff.tgz /My/Stuff/Goes/Here/
</code></pre>
<p>On machine two, I scp the tgz file to my local directory, then unpack it.</p>
<pre><code>tar -xZf mystuff.tgz
</code></pre>
<p>It creates ~scott/My/Stuff/Goes/, but then under Goes, I see two files:</p>
<pre><code>Here/ - a directory,
Here.bGd - a zero byte file.
</code></pre>
<p>The "Here.bGd" zero-byte file has a random 3-character suffix, mixed upper and lower-case characters. It has the same name as the lowest-level directory mentioned in the tar-creation command. It only appears at the lowest level directory named. Anybody know where these come from, and how I can adjust my tar creation to get rid of them?</p>
<p><strong>Update:</strong> I checked the table of contents on the files using tar tZvf: toc does not list the zero-byte files, so I'm leaning toward the suggestion that the uncompress machine is at fault. OS X is version 10.5.5 on the unzip machine (not sure how to check the filesystem type). Tar is GNU tar 1.15.1, and it came with the machine.</p>
|
[
{
"answer_id": 254417,
"author": "Rich",
"author_id": 22003,
"author_profile": "https://Stackoverflow.com/users/22003",
"pm_score": -1,
"selected": false,
"text": "tar Z compress tar"
},
{
"answer_id": 254422,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "tar tZvf mystuff.tgz"
},
{
"answer_id": 254484,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 0,
"selected": false,
"text": "COPYFILE_DISABLE=y"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
254,407
|
<p>I want to create a string that spans multiple lines to assign to a Label Caption property. How is this done in Delphi?</p>
|
[
{
"answer_id": 254412,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 5,
"selected": false,
"text": "my_string := 'Hello,' + #13#10 + 'world!'; #13#10"
},
{
"answer_id": 254465,
"author": "Zartog",
"author_id": 9467,
"author_profile": "https://Stackoverflow.com/users/9467",
"pm_score": 5,
"selected": false,
"text": "my_string := 'Hello,'#13#10' world!';\n"
},
{
"answer_id": 254668,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 3,
"selected": false,
"text": "Label1.Caption := Memo1.Lines.Text;\n"
},
{
"answer_id": 254820,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 4,
"selected": false,
"text": "MyString := 'Hello,' + ^M + ^J + 'world!';\n"
},
{
"answer_id": 254997,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 9,
"selected": true,
"text": "const\n sLineBreak = {$IFDEF LINUX} AnsiChar(#10) {$ENDIF} \n {$IFDEF MSWINDOWS} AnsiString(#13#10) {$ENDIF};\n label1.Caption := 'Line one'+sLineBreak+'Line two';\n"
},
{
"answer_id": 734576,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "ShowMessage('Hello'+Chr(10)+'World');\n"
},
{
"answer_id": 24833814,
"author": "Jessé Catrinck",
"author_id": 3625217,
"author_profile": "https://Stackoverflow.com/users/3625217",
"pm_score": 2,
"selected": false,
"text": "var\n stlst: TStringList;\nbegin\n Label1.Caption := 'Hello,'+sLineBreak+'world!';\n\n Label2.Caption := 'Hello,'#13#10'world!';\n\n Label3.Caption := 'Hello,' + chr(13) + chr(10) + 'world!';\n\n stlst := TStringList.Create;\n stlst.Add('Hello,');\n stlst.Add('world!');\n Label4.Caption := stlst.Text;\n\n Label5.WordWrap := True; //Multi-line Caption\n Label5.Caption := 'Hello,'^M^J'world!';\n\n Label6.Caption := AdjustLineBreaks('Hello,'#10'world!');\n {http://delphi.about.com/library/rtl/blrtlAdjustLineBreaks.htm}\nend;\n"
},
{
"answer_id": 46758569,
"author": "boodyman28",
"author_id": 8111869,
"author_profile": "https://Stackoverflow.com/users/8111869",
"pm_score": -1,
"selected": false,
"text": " private\n { Private declarations }\n {declare a variable like this}\n NewLine : string; // ok\n // in next event handler assign a value to that variable (NewLine)\n // like the code down\nprocedure TMainForm.FormCreate(Sender: TObject);\nbegin`enter code here`\n NewLine := #10;\n {Next Code To show NewLine In action}\n //ShowMessage('Hello to programming with Delphi' + NewLine + 'Print New Lin now !!!!');\nend;\n"
},
{
"answer_id": 67011494,
"author": "Samuel Cruz",
"author_id": 11515709,
"author_profile": "https://Stackoverflow.com/users/11515709",
"pm_score": 1,
"selected": false,
"text": "const sLineBreak System.pas unit TForm1.btnInfoClick(Sender: TObject);\nbegin\n ShowMessage ('My name is Jhon' + sLineBreak\n 'Profession: Hollywood actor');\nend;\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199/"
] |
254,419
|
<p>I have an aspx page which will upload images to server harddisk from client pc</p>
<p>But now i need to change my program in such a way that it would allow me to resize the image while uploading.</p>
<p>Does anyone has any idea on this ? I couldnt not find such properties/methods with Input file server control</p>
<p>Any one there to guide me ?</p>
|
[
{
"answer_id": 254430,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 3,
"selected": false,
"text": " ''' <summary>\n ''' Resize image with GDI+ so that image is nice and clear with required size.\n ''' </summary>\n ''' <param name=\"SourceImage\">Image to resize</param>\n ''' <param name=\"NewHeight\">New height to resize to.</param>\n ''' <param name=\"NewWidth\">New width to resize to.</param>\n ''' <returns>Image object resized to new dimensions.</returns>\n ''' <remarks></remarks>\n Public Shared Function ImageResize(ByVal SourceImage As Image, ByVal NewHeight As Int32, ByVal NewWidth As Int32) As Image\n\n Dim bitmap As System.Drawing.Bitmap = New System.Drawing.Bitmap(NewWidth, NewHeight, SourceImage.PixelFormat)\n\n If bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format4bppIndexed Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format8bppIndexed Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Undefined Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.DontCare Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppArgb1555 Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppGrayScale Then\n Throw New NotSupportedException(\"Pixel format of the image is not supported.\")\n End If\n\n Dim graphicsImage As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmap)\n\n graphicsImage.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality\n graphicsImage.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic\n graphicsImage.DrawImage(SourceImage, 0, 0, bitmap.Width, bitmap.Height)\n graphicsImage.Dispose()\n Return bitmap\n\n End Function\n"
},
{
"answer_id": 254460,
"author": "JPrescottSanders",
"author_id": 19444,
"author_profile": "https://Stackoverflow.com/users/19444",
"pm_score": 4,
"selected": false,
"text": "public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)\n{\n\n System.Drawing.Bitmap bmpOut = null;\n\n try\n {\n Bitmap loBMP = new Bitmap(lcFilename);\n ImageFormat loFormat = loBMP.RawFormat;\n\n decimal lnRatio;\n int lnNewWidth = 0;\n int lnNewHeight = 0;\n\n if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)\n return loBMP;\n\n if (loBMP.Width > loBMP.Height)\n {\n lnRatio = (decimal)lnWidth / loBMP.Width;\n lnNewWidth = lnWidth;\n decimal lnTemp = loBMP.Height * lnRatio;\n lnNewHeight = (int)lnTemp;\n }\n else\n {\n lnRatio = (decimal)lnHeight / loBMP.Height;\n lnNewHeight = lnHeight;\n decimal lnTemp = loBMP.Width * lnRatio;\n lnNewWidth = (int)lnTemp;\n }\n\n\n bmpOut = new Bitmap(lnNewWidth, lnNewHeight);\n Graphics g = Graphics.FromImage(bmpOut);\n g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;\n g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;\n g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;\n g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);\n g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);\n\n loBMP.Dispose();\n }\n catch\n {\n return null;\n }\n return bmpOut;\n}\n"
},
{
"answer_id": 254510,
"author": "Sean",
"author_id": 29941,
"author_profile": "https://Stackoverflow.com/users/29941",
"pm_score": 0,
"selected": false,
"text": "using System.IO;\nusing System.Drawing;\nusing System.Drawing.Imaging;\n\npublic partial class admin_AddPhoto : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n string reportPath = Server.MapPath(\"../picnic\");\n\n if (!Directory.Exists(reportPath))\n {\n Directory.CreateDirectory(Server.MapPath(\"../picnic\"));\n }\n }\n\n protected void PhotoForm_ItemInserting(object sender, FormViewInsertEventArgs e)\n {\n FormView uploadForm = sender as FormView;\n FileUpload uploadedFile = uploadForm.FindControl(\"uploadedFile\") as FileUpload;\n\n if (uploadedFile != null)\n {\n string fileName = uploadedFile.PostedFile.FileName;\n string pathFile = System.IO.Path.GetFileName(fileName);\n\n try\n {\n uploadedFile.SaveAs(Server.MapPath(\"../picnic/\") + pathFile);\n }\n catch (Exception exp)\n {\n //catch exception here\n }\n\n try\n {\n Bitmap uploadedimage = new Bitmap(uploadedFile.PostedFile.InputStream);\n\n e.Values[\"ImageWidth\"] = uploadedimage.Width.ToString();\n e.Values[\"ImageHeight\"] = uploadedimage.Height.ToString();\n // Make output File Name\n char[] splitter = { '.' };\n string[] splitFile = pathFile.Split(splitter);\n string OutputFilename = splitFile[0] + \"s\";\n\n System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);\n System.Drawing.Image thumbImage = uploadedimage.GetThumbnailImage(74, 54, myCallback, IntPtr.Zero);\n thumbImage.Save(Server.MapPath(\"../picnic/\") + OutputFilename + \".jpg\");\n e.Values[\"Thumbnail\"] = \"./picnic/\" + OutputFilename + \".jpg\";\n }\n catch (Exception ex)\n {\n //catch exception here\n }\n\n e.Values[\"Pic\"] = \"./picnic/\" + pathFile;\n e.Values[\"Url\"] = \"./picnic/\" + pathFile;\n e.Values[\"dateEntered\"] = DateTime.Now.ToString();\n }\n }\n\n public bool ThumbnailCallback()\n {\n return false;\n }\n}\n uploadedimage.GetThumbnailImage(W, H, myCallback, IntPtr.Zero);\n"
},
{
"answer_id": 518597,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "//Here is another WAY fox!!! i have actually modify the code from You all. HIHI\n//First, add one textBox and one FileUpload Control, and a button\n\n//paste this in your code behind file... after public partial class admin : System.Web.UI.Page\n\n string OriPath;\n string ImageName;\n\npublic Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)\n {\n Size NewSize;\n double tempval;\n\n if (OriginalHeight > FormatSize && OriginalWidth > FormatSize)\n {\n if (OriginalHeight > OriginalWidth)\n tempval = FormatSize / Convert.ToDouble(OriginalHeight);\n else\n tempval = FormatSize / Convert.ToDouble(OriginalWidth);\n\n NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));\n }\n else\n NewSize = new Size(OriginalWidth, OriginalHeight); return NewSize;\n } \n\n\n\n//Now, On Button click add the folwing code.\n\nif (FileUpload1.PostedFile != null)\n {\n ImageName = TextBox1.Text+\".jpg\";\n\n\n OriPath = Server.MapPath(\"pix\\\\\") + ImageName;\n\n //Gets the Full Path using Filecontrol1 which points to actual location in the hardisk :)\n\n using (System.Drawing.Image Img = System.Drawing.Image.FromFile(System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName)))\n {\n Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 800);\n\n using (System.Drawing.Image ImgThnail = new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))\n {\n ImgThnail.Save(OriPath, Img.RawFormat);\n ImgThnail.Dispose();\n }\n Img.Dispose();\n }\n}\n\n\n//Enjoy. If any problem,, mail me at izacmail@gmail.com \n"
},
{
"answer_id": 591108,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " bmpOut = new Bitmap(lnNewWidth, lnNewHeight, **System.Drawing.Imaging.PixelFormat.Format24bppRgb**);\n\n Graphics g = Graphics.FromImage(bmpOut);\n bmpOut.Save(PathImage, System.Drawing.Imaging.ImageFormat.Jpeg);\n"
},
{
"answer_id": 2312783,
"author": "Tim Meers",
"author_id": 90764,
"author_profile": "https://Stackoverflow.com/users/90764",
"pm_score": 1,
"selected": false,
"text": "byte[] public static byte[] ResizeImageFile(byte[] imageFile, int targetSize) \n{ \n using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile))) \n { \n Size newSize = CalculateDimensions(oldImage.Size, targetSize); \n\n using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) \n { \n newImage.SetResolution(oldImage.HorizontalResolution, oldImage.VerticalResolution); \n using (Graphics canvas = Graphics.FromImage(newImage)) \n { \n canvas.SmoothingMode = SmoothingMode.AntiAlias; \n canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; \n canvas.PixelOffsetMode = PixelOffsetMode.HighQuality; \n canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize)); \n MemoryStream m = new MemoryStream(); \n newImage.Save(m, ImageFormat.Jpeg); \n return m.GetBuffer(); \n } \n } \n\n } \n} \n\nprivate static Size CalculateDimensions(Size oldSize, int targetSize) \n{ \n Size newSize = new Size(); \n if (oldSize.Width > oldSize.Height) \n { \n newSize.Width = targetSize; \n newSize.Height = (int)(oldSize.Height * (float)targetSize / (float)oldSize.Width); \n } \n else \n { \n newSize.Width = (int)(oldSize.Width * (float)targetSize / (float)oldSize.Height); \n newSize.Height = targetSize; \n } \n return newSize; \n} \n"
},
{
"answer_id": 9289380,
"author": "Deepak Sahu",
"author_id": 1210688,
"author_profile": "https://Stackoverflow.com/users/1210688",
"pm_score": -1,
"selected": false,
"text": "private void ResizeImage(FileUpload fileUpload)\n{\n // First we check to see if the user has selected a file\n if (fileUpload.HasFile)\n {\n // Find the fileUpload control\n string filename = fileUpload.FileName;\n\n // Check if the directory we want the image uploaded to actually exists or not\n if (!Directory.Exists(MapPath(@\"Uploaded-Files\")))\n {\n // If it doesn't then we just create it before going any further\n Directory.CreateDirectory(MapPath(@\"Uploaded-Files\"));\n }\n // Specify the upload directory\n string directory = Server.MapPath(@\"Uploaded-Files\\\");\n\n // Create a bitmap of the content of the fileUpload control in memory\n Bitmap originalBMP = new Bitmap(fileUpload.FileContent);\n\n // Calculate the new image dimensions\n int origWidth = originalBMP.Width;\n int origHeight = originalBMP.Height;\n int sngRatio = origWidth / origHeight;\n int newWidth = 100;\n int newHeight = newWidth / sngRatio;\n\n // Create a new bitmap which will hold the previous resized bitmap\n Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);\n\n // Create a graphic based on the new bitmap\n Graphics oGraphics = Graphics.FromImage(newBMP);\n // Set the properties for the new graphic file\n oGraphics.SmoothingMode = SmoothingMode.AntiAlias; \n oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;\n\n // Draw the new graphic based on the resized bitmap\n oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);\n // Save the new graphic file to the server\n newBMP.Save(directory + \"tn_\" + filename);\n\n // Once finished with the bitmap objects, we deallocate them.\n originalBMP.Dispose();\n newBMP.Dispose();\n oGraphics.Dispose();\n\n // Write a message to inform the user all is OK\n label.Text = \"File Name: <b style='color: red;'>\" + filename + \"</b><br>\";\n label.Text += \"Content Type: <b style='color: red;'>\" + fileUpload.PostedFile.ContentType + \"</b><br>\";\n label.Text += \"File Size: <b style='color: red;'>\" + fileUpload.PostedFile.ContentLength.ToString() + \"</b>\";\n\n // Display the image to the user\n Image1.Visible = true;\n Image1.ImageUrl = @\"Uploaded-Files/tn_\" + filename;\n }\n else\n {\n label.Text = \"No file uploaded!\";\n }\n}\n"
},
{
"answer_id": 12001997,
"author": "Satinder singh",
"author_id": 1192188,
"author_profile": "https://Stackoverflow.com/users/1192188",
"pm_score": 2,
"selected": false,
"text": " public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)\n {\n var ratio = (double)maxHeight / image.Height;\n \n var newWidth = (int)(image.Width * ratio);\n var newHeight = (int)(image.Height * ratio);\n \n var newImage = new Bitmap(newWidth, newHeight);\n using (var g = Graphics.FromImage(newImage))\n {\n g.DrawImage(image, 0, 0, newWidth, newHeight);\n }\n return newImage;\n }\n protected void Button1_Click(object sender, EventArgs e)\n{\n lblmsg.Text=\"\";\n if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))\n {\n Guid uid = Guid.NewGuid();\n string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);\n string SaveLocation = Server.MapPath(\"LogoImagesFolder\") + \"\\\\\" + uid+fn;\n try\n {\n string fileExtention = File1.PostedFile.ContentType;\n int fileLenght = File1.PostedFile.ContentLength;\n if (fileExtention == \"image/png\" || fileExtention == \"image/jpeg\" || fileExtention == \"image/x-png\")\n {\n if (fileLenght <= 1048576)\n {\n System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);\n System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);\n objImage.Save(SaveLocation,ImageFormat.Png);\n lblmsg.Text = \"The file has been uploaded.\";\n lblmsg.Style.Add(\"Color\", \"Green\");\n }\n else \n {\n lblmsg.Text = \"Image size cannot be more then 1 MB.\";\n lblmsg.Style.Add(\"Color\", \"Red\");\n }\n }\n else {\n lblmsg.Text = \"Invaild Format!\";\n lblmsg.Style.Add(\"Color\", \"Red\");\n }\n }\n catch (Exception ex)\n {\n lblmsg.Text= \"Error: \" + ex.Message;\n lblmsg.Style.Add(\"Color\", \"Red\");\n }\n }\n }\n"
},
{
"answer_id": 21814242,
"author": "Rajib Chy",
"author_id": 3301985,
"author_profile": "https://Stackoverflow.com/users/3301985",
"pm_score": 2,
"selected": false,
"text": " <asp:FileUpload ID=\"ProductImage\" runat=\"server\"/>\n <asp:Button ID=\"Button1\" runat=\"server\" OnClick=\"Button1_Click\" Text=\"Upload\" />\n <asp:TextBox runat=\"server\" ID=\"txtProductName\" CssClass=\"form-control\" />\n <asp:RequiredFieldValidator runat=\"server\" ControlToValidate=\"txtProductName\" ErrorMessage=\"The Product name field is required.\" />\n /// <summary>\n/// Created By Rajib Chowdhury Mob. 01766-306306; Web: http://onlineshoping.somee.com/\n/// Complete This Page Coding On January 05, 2014\n/// Programing C# By Visual Studio 2013 For Web\n/// Dot Net Version 4.5\n/// Database Virsion MSSQL Server 2005\n/// </summary>\n public bool ResizeImageAndUpload(System.IO.FileStream newFile, string folderPathAndFilenameNoExtension, double maxHeight, double maxWidth)\n {\n try\n {\n // Declare variable for the conversion\n float ratio;\n // Create variable to hold the image\n System.Drawing.Image thisImage = System.Drawing.Image.FromStream(newFile);\n // Get height and width of current image\n int width = (int)thisImage.Width;\n int height = (int)thisImage.Height;\n // Ratio and conversion for new size\n if (width > maxWidth)\n {\n ratio = (float)width / (float)maxWidth;\n width = (int)(width / ratio);\n height = (int)(height / ratio);\n }\n // Ratio and conversion for new size\n if (height > maxHeight)\n {\n ratio = (float)height / (float)maxHeight;\n height = (int)(height / ratio);\n width = (int)(width / ratio);\n }\n // Create \"blank\" image for drawing new image\n Bitmap outImage = new Bitmap(width, height);\n Graphics outGraphics = Graphics.FromImage(outImage);\n SolidBrush sb = new SolidBrush(System.Drawing.Color.White);\n // Fill \"blank\" with new sized image\n outGraphics.FillRectangle(sb, 0, 0, outImage.Width, outImage.Height);\n outGraphics.DrawImage(thisImage, 0, 0, outImage.Width, outImage.Height);\n sb.Dispose();\n outGraphics.Dispose();\n thisImage.Dispose();\n // Save new image as jpg\n outImage.Save(Server.MapPath(folderPathAndFilenameNoExtension + \".jpg\"), System.Drawing.Imaging.ImageFormat.Jpeg);\n outImage.Dispose();\n return true;\n }\n catch (Exception)\n {\n return false;\n }\n }\n string filePath = \"~\\\\Image\\\\\";//your normal image path\n if (Page.IsValid)\n {\n HttpPostedFile myFile = ProductImage.PostedFile;//Get Slected Image\n int nFileLen = myFile.ContentLength;//Get slected Image Size\n string myimag = txtProductName.Text;//Get user input image name\n Guid ImageName = Guid.NewGuid();//get unique id\n if ((myFile != null) && (nFileLen > 1048576))\n {\n LabelAddStatus.Text = \"minimum size exceed\"; //If file image size 1 MB above\n }\n else\n {\n try\n {\n if (ProductImage.HasFile)\n {\n String fileExtension = System.IO.Path.GetExtension(ProductImage.FileName).ToLower();\n String[] allowedExtensions = { \".jpg\" };//Declare For Allowed Extension\n for (int i = 0; i < allowedExtensions.Length; i++)\n {\n if (fileExtension == allowedExtensions[i])\n {\n // Read file into a data stream\n byte[] myData = new Byte[nFileLen];\n myFile.InputStream.Read(myData, 0, nFileLen);\n myFile.InputStream.Dispose();\n // Save the stream to disk as temporary file. make sure the path is unique!\n System.IO.FileStream newFile\n = new System.IO.FileStream(Server.MapPath(filePath + \"_temp.jpg\"),\n System.IO.FileMode.Create);\n newFile.Write(myData, 0, myData.Length);\n bool success = ResizeImageAndUpload(newFile, filePath + (\"thumbs\"+myimag + ImageName), 100, 100);//Save image your thumb image path\n success = ResizeImageAndUpload(newFile, filePath + (myimag + ImageName), 768, 1024);//Save image your normal image path\n //delete the temp file.\n newFile.Close();\n System.IO.File.Delete(Server.MapPath(filePath + \"_temp.jpg\"));\n LabelAddStatus.Text = \"File uploaded.\";\n }\n else\n {\n LabelAddStatus.Text = \"Unable to accept file type..\";\n }\n }\n }\n }\n catch (Exception)\n {\n //No Exception Message\n }\n }\n }\n"
},
{
"answer_id": 33045949,
"author": "Loai Tayem",
"author_id": 4718109,
"author_profile": "https://Stackoverflow.com/users/4718109",
"pm_score": 0,
"selected": false,
"text": "public string ResizeImageAndSave(int Width, int Height, string imageUrl, string destPath)\n {\n System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(imageUrl);\n double widthRatio = (double)fullSizeImg.Width / (double)Width;\n double heightRatio = (double)fullSizeImg.Height / (double)Height;\n double ratio = Math.Max(widthRatio, heightRatio);\n int newWidth = (int)(fullSizeImg.Width / ratio);\n int newHeight = (int)(fullSizeImg.Height / ratio);\n //System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);\n System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);\n //DateTime MyDate = DateTime.Now;\n //String MyString = MyDate.ToString(\"ddMMyyhhmmss\") + imageUrl.Substring(imageUrl.LastIndexOf(\".\"));\n thumbNailImg.Save(destPath, ImageFormat.Jpeg);\n thumbNailImg.Dispose();\n return \"\";\n }\n public bool ThumbnailCallback() { return false; }\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29982/"
] |
254,441
|
<p>I'm having problems with Iterator.remove() called on a HashSet.</p>
<p>I've a Set of time stamped objects. Before adding a new item to the Set, I loop through the set, identify an old version of that data object and remove it (before adding the new object). the timestamp is included in hashCode and equals(), but not equalsData().</p>
<pre><code>for (Iterator<DataResult> i = allResults.iterator(); i.hasNext();)
{
DataResult oldData = i.next();
if (data.equalsData(oldData))
{
i.remove();
break;
}
}
allResults.add(data)
</code></pre>
<p>The odd thing is that i.remove() silently fails (no exception) for some of the items in the set. I've verified</p>
<ul>
<li><p>The line i.remove() is actually called. I can call it from the debugger directly at the breakpoint in Eclipse and it still fails to change the state of Set</p></li>
<li><p>DataResult is an immutable object so it can't have changed after being added to the set originally.</p></li>
<li><p>The equals and hashCode() methods use @Override to ensure they are the correct methods. Unit tests verify these work. </p></li>
<li><p>This also fails if I just use a for statement and Set.remove instead. (e.g. loop through the items, find the item in the list, then call Set.remove(oldData) after the loop).</p></li>
<li><p>I've tested in JDK 5 and JDK 6.</p></li>
</ul>
<p>I thought I must be missing something basic, but after spending some significant time on this my colleague and I are stumped. Any suggestions for things to check?</p>
<p>EDIT:</p>
<p>There have been questions - is DataResult truly immutable. Yes. There are no setters. And when the Date object is retrieved (which is a mutable object), it is done by creating a copy.</p>
<pre><code>public Date getEntryTime()
{
return DateUtil.copyDate(entryTime);
}
public static Date copyDate(Date date)
{
return (date == null) ? null : new Date(date.getTime());
}
</code></pre>
<p>FURTHER EDIT (some time later):
For the record -- DataResult was not immutable! It referenced an object which had a hashcode which changed when persisted to the database (bad practice, I know). It turned out that if a DataResult was created with a transient subobject, and the subobject was persisted, the DataResult hashcode was changed.</p>
<p>Very subtle -- I looked at this many times and didn't notice the lack of immutability.</p>
|
[
{
"answer_id": 254480,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "boolean removed = allResults.remove(oldData)\nif (!removed) // COMPLAIN BITTERLY!\n Iterator hashCode equals equalsData"
},
{
"answer_id": 255490,
"author": "Jack Leow",
"author_id": 31506,
"author_profile": "https://Stackoverflow.com/users/31506",
"pm_score": 2,
"selected": false,
"text": "java.util.Date java.util.Date Date timestamp = new Date();\nDataResult d = new DataResult(timestamp);\nSystem.out.println(d.getTimestamp());\ntimestamp.setTime(System.currentTimeMillis());\nSystem.out.println(d.getTimestamp());\n"
},
{
"answer_id": 256105,
"author": "Will Glass",
"author_id": 32978,
"author_profile": "https://Stackoverflow.com/users/32978",
"pm_score": 2,
"selected": false,
"text": " Set<DataResult> tempResults = new HashSet<DataResult>();\n CollectionUtils.select(allResults, \n new Predicate()\n {\n public boolean evaluate(Object oldData)\n {\n return !data.equalsData((DataResult) oldData);\n }\n }\n , tempResults);\n allResults = tempResults;\n"
},
{
"answer_id": 256247,
"author": "Jack Leow",
"author_id": 31506,
"author_profile": "https://Stackoverflow.com/users/31506",
"pm_score": 7,
"selected": true,
"text": "import java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class HashCodeTest {\n private int hashCode = 0;\n\n @Override public int hashCode() {\n return hashCode ++;\n }\n\n public static void main(String[] args) {\n Set<HashCodeTest> set = new HashSet<HashCodeTest>();\n\n set.add(new HashCodeTest());\n System.out.println(set.size());\n for (Iterator<HashCodeTest> iter = set.iterator();\n iter.hasNext();) {\n iter.next();\n iter.remove();\n }\n System.out.println(set.size());\n }\n}\n 1\n1\n"
},
{
"answer_id": 28787298,
"author": "Tomer Shalev",
"author_id": 2779007,
"author_profile": "https://Stackoverflow.com/users/2779007",
"pm_score": 2,
"selected": false,
"text": "HashSet<HashSet<?>> or HashSet<AbstaractSet<?>> or HashMap variant:\n HashSet<HashSet<String>> coll = new HashSet<HashSet<String>>();\nHashSet<String> set1 = new HashSet<String>();\nset1.add(\"1\");\ncoll.add(set1);\nprint(set1.hashCode()); //---> will output X\nset1.add(\"2\");\nprint(set1.hashCode()); //---> will output Y\ncoll.remove(set1) // WILL FAIL TO REMOVE (SILENTLY)\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32978/"
] |
254,449
|
<p>I'm building a .net application with windows forms. I'm pondering on the following problem: If I specify fonts in my application that are available only in Vista and Office 07, what will happen when the application tries to run in a machine without these ?</p>
<p>I suppose the system won't be able to fall back to a font of it's family, since they are initialized internally using strings (eg "Segoe UI").</p>
<p>What's the best practice to follow, such that I will still be able to specify fonts through the forms designer and not worry about things like this breaking ?</p>
|
[
{
"answer_id": 254583,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 3,
"selected": true,
"text": "System.Drawing.SystemFonts.MessageBoxFont"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/354645/"
] |
254,451
|
<p>By default, objects (tables, stored procedures, etc) are set up with the dbo owner/schema (I think ms sql 2000 calls it owner, while ms sql 2005 calls it schema)</p>
<p>The owner/schema is really a role or user in the database. I've always left the default of dbo, but I've recently seen some examples in microsoft training books where some of their tables & stored procedures had different owners/schemas. When is it beneficial to do this and why?</p>
|
[
{
"answer_id": 254493,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 3,
"selected": false,
"text": "[Person].[Address] [Company].[Address] [dbo].[PersonAddress]"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
254,458
|
<p><strong>Update</strong></p>
<p><em>Got it! See my solution (fifth comment)</em></p>
<p>Here is my problem:</p>
<p>I have created a small binary called "jail" and in /etc/password I have made it the default shell for a test user.</p>
<p>Here is the -- simplified -- source code:</p>
<pre><code>#define HOME "/home/user"
#define SHELL "/bin/bash"
...
if(chdir(HOME) || chroot(HOME)) return -1;
...
char *shellargv[] = { SHELL, "-login", "-rcfile", "/bin/myscript", 0 };
execvp(SHELL, shellargv);
</code></pre>
<p>Well, no matter how hard I try, it seems that, when my test user logs in, <em>/bin/myscript</em> will never be sourced. Similarly, if I drop a <code>.bashrc</code> file in user's home directory, it will be ignored as well.</p>
<p>Why would bash snob these guys?</p>
<p>--</p>
<p>Some precisions, not necessarily relevant, but to clear out some of the points made in the comments:</p>
<ul>
<li>The 'jail' binary is actually suid, thus allowing it to chroot() successfully. </li>
<li>I have used 'ln' to make the appropriate binaries available - my jail cell is nicely padded :)</li>
<li>The issue does not seem to be with chrooting the user...something else is remiss.</li>
</ul>
|
[
{
"answer_id": 254529,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "-i char *shellargv[] = { SHELL, \"-i\", \"-login\", ... };\nexecvp(SHELL, shellargv);\n ARGV[0] char *shellargv[] = {\"-\"SHELL, \"-i\", ...};\nexecvp(SHELL, shellargv);\n /dev/*"
},
{
"answer_id": 254549,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "chroot() ls"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6253/"
] |
254,461
|
<p>I have a method with an out parameter that tries to do a type conversion. Basically:</p>
<pre><code>public void GetParameterValue(out object destination)
{
object paramVal = "I want to return this. could be any type, not just string.";
destination = null; // default out param to null
destination = Convert.ChangeType(paramVal, destination.GetType());
}
</code></pre>
<p>The problem is that usually someone would call this like:</p>
<pre><code>string output;
GetParameterValue(output);
</code></pre>
<p>This will fail because of:</p>
<pre><code>destination.GetType()
</code></pre>
<p>destination is null, so we can't call <code>.GetType()</code> on it. We also can not call:</p>
<pre><code>typeof(destination)
</code></pre>
<p>because destination is a variable name not a type name.</p>
<p>So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.</p>
<hr>
<p>Just to give a bit more info, I am trying to make a utility method that will grab the output parameters of an Oracle stored procedure. The issue is that <code>DbParameter.Value</code> is of type object.</p>
<p>What would be ideal would be for the developers to do something like:</p>
<pre><code>string val = GetParameterValue("parameterName");
</code></pre>
<p>The notable thing is that there is no casting of types. In practice, you don't know the lparam of the "equals", so I went with:</p>
<pre><code>string val;
GetParameterValue("parameterName", out val);
</code></pre>
<p>And figured within the method, I would know the destination type of the output variable. I guess that was a bad assumption. As an alternative, I also wrote the method:</p>
<pre><code>public T GetParameterValue<T>(string paramName)
</code></pre>
<p>So the developers can do:</p>
<pre><code>string val = GetParameterValue<string>("parameterName");
</code></pre>
<p>I find the explicit "string" declaration to be repetitive, especially since in practice, the destination if probably an object property and the oracle data type could change (think ORM):</p>
<pre><code>MyObj.SomeProp = GetParameterValue<MyObj.SomeProp.GetType()>("parameterName");
</code></pre>
<p>But again, if MyObj.SomeProp is null, that <code>.GetType()</code> call fails. The VM has to know the type of <code>MyObj.SomeProp</code>, even when its null, right? or else how would it catch cast exceptions?</p>
<hr>
<p>To partially solve my own problem, I can do:</p>
<pre><code>MyObj.SomeProp = GetParameterValue<typeof(MyObj).GetField("SomeProp").GetType()>("parameterName");
</code></pre>
<p>The whole idea was to not have to explicitly use the Type in more than one place, so that if the data type changes, it only has to be changed in the destination object (<code>MyObj.SomeProp</code>) and in the DB. There has to be a better way...</p>
|
[
{
"answer_id": 254464,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "System.Object"
},
{
"answer_id": 254483,
"author": "dub",
"author_id": 30022,
"author_profile": "https://Stackoverflow.com/users/30022",
"pm_score": 2,
"selected": false,
"text": "System.Object Convert.ChangeType(paramVal, System.Object).\n"
},
{
"answer_id": 254485,
"author": "Jelon",
"author_id": 2326,
"author_profile": "https://Stackoverflow.com/users/2326",
"pm_score": 2,
"selected": false,
"text": "public void GetParameterValue<T>(out T destination)\n{\n ...\n}\n"
},
{
"answer_id": 254488,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 6,
"selected": true,
"text": "object null public void GetParameterValue<T>(out T destination)\n{\n object paramVal = \"Blah\";\n destination = default(T);\n destination = Convert.ChangeType(paramVal, typeof(T));\n}\n T"
},
{
"answer_id": 254495,
"author": "Ryan",
"author_id": 29762,
"author_profile": "https://Stackoverflow.com/users/29762",
"pm_score": 0,
"selected": false,
"text": "public void GetParameterValue(Type sourceType, out object destination) { //... }\n"
},
{
"answer_id": 254496,
"author": "Damian Powell",
"author_id": 30321,
"author_profile": "https://Stackoverflow.com/users/30321",
"pm_score": 4,
"selected": false,
"text": "class Program\n{\n public static void GetParameterValue<T>(out T destination)\n {\n Console.WriteLine(\"typeof(T)=\" + typeof(T).Name);\n destination = default(T);\n }\n static void Main(string[] args)\n {\n string s;\n GetParameterValue(out s);\n int i;\n GetParameterValue(out i);\n }\n}\n"
},
{
"answer_id": 254644,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "string val;\nGetParameterValue(\"parameterName\", out val);\n void GetParameterValue<T>(string parameterName, out T val) { }\n T GetParameterValue<T>(string parameterName, T ununsed) { }\n MyObj.SomeProp = GetParameterValue(\"parameterName\", MyObj.SomeProp);\n class ParameterHelper\n{\n private object value;\n public ParameterHelper(object value) { this.value = value; }\n\n public static implicit operator int(ParameterHelper v)\n { return (int) v.value; }\n\n}\nParameterHelper GetParameterValue( string parameterName);\n\nMyObj.SomeProp = GetParameterValue(\"parameterName\");\n"
},
{
"answer_id": 254764,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 0,
"selected": false,
"text": "string val = GetParameterValue<string>(\"parameterName\");\n var val = GetParameterValue<string>(\"parameterName\");\n"
},
{
"answer_id": 1187134,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "//**The working answer**\n\n//**based on your discussion eheheheheeh**\n\npublic void s<T>(out T varName)\n{\n if (typeof (T) == typeof(HtmlTable)) \n { \n ////////// \n }\n\n}\n\nprotected void Page_Load(object sender, EventArgs e) \n{\n HtmlTable obj=null ;\n s(out obj); \n}\n"
},
{
"answer_id": 9513472,
"author": "Observer",
"author_id": 1242244,
"author_profile": "https://Stackoverflow.com/users/1242244",
"pm_score": -1,
"selected": false,
"text": "private Hashtable propertyTable = new Hashtable();\n\npublic void LoadPropertyTypes()\n{\n Type t = this.GetType();\n\n System.Reflection.MemberInfo[] memberInfo = t.GetMembers();\n\n foreach (System.Reflection.MemberInfo mInfo in memberInfo)\n {\n string[] prop = mInfo.ToString().Split(Convert.ToChar(\" \"));\n propertyTable.Add(prop[1], prop[0]);\n }\n}\npublic string GetMemberType(string propName)\n{\n if (propertyTable.ContainsKey(propName))\n {\n return Convert.ToString(propertyTable[propName]);\n }\n else{\n return \"N/A\";\n }\n}\n"
},
{
"answer_id": 11803825,
"author": "John Beyer",
"author_id": 1575257,
"author_profile": "https://Stackoverflow.com/users/1575257",
"pm_score": 3,
"selected": false,
"text": "using System;\n\nnamespace MyNamespace\n{\n public static class Extensions\n {\n /// <summary>\n /// Gets the declared type of the specified object.\n /// </summary>\n /// <typeparam name=\"T\">The type of the object.</typeparam>\n /// <param name=\"obj\">The object.</param>\n /// <returns>\n /// A <see cref=\"Type\"/> object representing type \n /// <typeparamref name=\"T\"/>; i.e., the type of <paramref name=\"obj\"/> \n /// as it was declared. Note that the contents of \n /// <paramref name=\"obj\"/> are irrelevant; if <paramref name=\"obj\"/> \n /// contains an object whose class is derived from \n /// <typeparamref name=\"T\"/>, then <typeparamref name=\"T\"/> is \n /// returned, not the derived type.\n /// </returns>\n public static Type GetDeclaredType<T>(\n this T obj )\n {\n return typeof( T );\n }\n }\n}\n string myString = \"abc\";\nobject myObj = myString;\nType myObjType = myObj.GetDeclaredType();\n\nstring myNullString = null;\nobject myNullObj = myNullString;\nType myNullObjType = myNullObj.GetDeclaredType();\n myObjType myNullObjType return return (obj != null) ? obj.GetType() : typeof( T );\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28278/"
] |
254,469
|
<p>What solutions have people come up with to develop their web applications offline when they made the decision to use OpenId for site membership?</p>
<p>Couple of ideas:</p>
<ol>
<li>Create two login pages one for OpenId and one for ASP.NET Membership</li>
<li>Create local OpenId provider with test accounts</li>
</ol>
<p>Any thoughts?</p>
|
[
{
"answer_id": 373675,
"author": "Andrew Arnott",
"author_id": 46926,
"author_profile": "https://Stackoverflow.com/users/46926",
"pm_score": 1,
"selected": false,
"text": "FormsAuthentication.RedirectFromLoginPage(\"http://blog.nerdbank.net/\")\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132/"
] |
254,486
|
<p>Some of my MS SQL stored procedures produce messages using the 'print' command. In my Delphi 2007 application, which connects to MS SQL using TADOConnection, how can I view the output of those 'print' commands?</p>
<p>Key requirements:
1) I can't run the query more than once; it might be updating things.
2) I need to see the 'print' results even if datasets are returned.</p>
|
[
{
"answer_id": 255311,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 4,
"selected": true,
"text": "SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nIF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FG_TEST]') AND type in (N'P', N'PC'))\n DROP PROCEDURE [dbo].[FG_TEST]\nGO\n-- =============================================\n-- Author: François\n-- Description: test multi ADO with info\n-- =============================================\nCREATE PROCEDURE FG_TEST\nAS\nBEGIN\n -- SET NOCOUNT ON absolutely NEEDED\n SET NOCOUNT ON;\n\n PRINT '*** start ***'\n\n SELECT 'one' as Set1Field1\n\n PRINT '*** done once ***'\n\n SELECT 'two' as Set2Field2\n\n PRINT '*** done again ***'\n\n SELECT 'three' as Set3Field3\n\n PRINT '***finish ***'\nEND\nGO\n object ADOConnection1: TADOConnection\n ConnectionString = \n 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security In' +\n 'fo=False;Initial Catalog=xxxYOURxxxDBxxx;Data Source=xxxYOURxxxSERVERxxx'\n CursorLocation = clUseServer\n LoginPrompt = False\n Provider = 'SQLOLEDB.1'\n OnInfoMessage = ADOConnection1InfoMessage\n Left = 24\n Top = 216\nend\nobject ADOStoredProc1: TADOStoredProc\n Connection = ADOConnection1\n CursorLocation = clUseServer\n ProcedureName = 'FG_TEST;1'\n Parameters = <>\n Left = 24\n Top = 264\nend\n Memo1.Lines.Add(Error.Description);\n procedure TForm1.Button1Click(Sender: TObject);\nconst\n adStateOpen = $00000001; // or defined in ADOInt\nvar\n I: Integer;\n ARecordSet: _Recordset;\nbegin\n Memo1.Lines.Add('==========================');\n\n ADOStoredProc1.Open; // not ExecProc !!!!!\n\n ARecordSet := ADOStoredProc1.Recordset;\n while Assigned(ARecordSet) do\n begin\n // do whatever with current RecordSet\n while not ADOStoredProc1.Eof do\n begin\n Memo1.Lines.Add(ADOStoredProc1.Fields[0].FieldName + ': ' + ADOStoredProc1.Fields[0].Value);\n ADOStoredProc1.Next;\n end;\n // switch to subsequent RecordSet if any\n ARecordSet := ADOStoredProc1.NextRecordset(I);\n if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) <> 0) then\n ADOStoredProc1.Recordset := ARecordSet\n else\n Break;\n end;\n\n ADOStoredProc1.Close;\nend;\n"
},
{
"answer_id": 13145530,
"author": "Freddie bell",
"author_id": 1441618,
"author_profile": "https://Stackoverflow.com/users/1441618",
"pm_score": 0,
"selected": false,
"text": "procedure TForm1.ADOConnection1InfoMessage(Connection: TADOConnection;\n const Error: Error; var EventStatus: TEventStatus);\nvar\n i: integer;\nbegin\n // show ALL print statements\n for i := 0 to AdoConnection1.Errors.Count - 1 do\n begin\n // was: cxMemo1.Lines.Add(Error.Description);\n cxMemo1.Lines.Add(\n ADOConnection1.Errors.Item[i].Description);\n end;\nend;\n\nprocedure TForm1.cxButton1Click(Sender: TObject);\nconst\n adStateOpen = $00000001; // or uses ADOInt\nvar\n records: Integer;\n ARecordSet: _RecordSet;\nbegin\n cxMemo1.Lines.Add('==========================');\n\n ADOStoredProc1.Open;\n\n try\n ARecordSet := ADOStoredProc1.RecordSet; // initial fetch\n while Assigned(ARecordSet) do\n begin\n // assign the recordset to a DataSets recordset to traverse\n AdoDataSet1.Recordset := ARecordSet;\n // do whatever with current ARecordSet\n while not ADODataSet1.eof do\n begin\n cxMemo1.Lines.Add(ADODataSet1.Fields[0].FieldName + \n ': ' + ADODataSet1.Fields[0].Value);\n AdoDataSet1.Next;\n end;\n // fetch next recordset if there is one\n ARecordSet := ADOStoredProc1.NextRecordSet(records);\n if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) <> 0) then\n ADOStoredProc1.Recordset := ARecordSet\n else\n Break;\n end;\n finally\n ADOStoredProc1.Close;\n end;\n\nend;\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42219/"
] |
254,494
|
<p>I've been struggling coming up with a good solution to separate my testing data from unit
tests (hard coded values). Until it dawned on me that I could create beans with spring
and use those beans to hold my data. </p>
<p>Are there any draw backs to coding my unit tests this way? Albeit they run a bit slower
seeing as how spring has to configure all the beans and what not.</p>
|
[
{
"answer_id": 255311,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 4,
"selected": true,
"text": "SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nIF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FG_TEST]') AND type in (N'P', N'PC'))\n DROP PROCEDURE [dbo].[FG_TEST]\nGO\n-- =============================================\n-- Author: François\n-- Description: test multi ADO with info\n-- =============================================\nCREATE PROCEDURE FG_TEST\nAS\nBEGIN\n -- SET NOCOUNT ON absolutely NEEDED\n SET NOCOUNT ON;\n\n PRINT '*** start ***'\n\n SELECT 'one' as Set1Field1\n\n PRINT '*** done once ***'\n\n SELECT 'two' as Set2Field2\n\n PRINT '*** done again ***'\n\n SELECT 'three' as Set3Field3\n\n PRINT '***finish ***'\nEND\nGO\n object ADOConnection1: TADOConnection\n ConnectionString = \n 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security In' +\n 'fo=False;Initial Catalog=xxxYOURxxxDBxxx;Data Source=xxxYOURxxxSERVERxxx'\n CursorLocation = clUseServer\n LoginPrompt = False\n Provider = 'SQLOLEDB.1'\n OnInfoMessage = ADOConnection1InfoMessage\n Left = 24\n Top = 216\nend\nobject ADOStoredProc1: TADOStoredProc\n Connection = ADOConnection1\n CursorLocation = clUseServer\n ProcedureName = 'FG_TEST;1'\n Parameters = <>\n Left = 24\n Top = 264\nend\n Memo1.Lines.Add(Error.Description);\n procedure TForm1.Button1Click(Sender: TObject);\nconst\n adStateOpen = $00000001; // or defined in ADOInt\nvar\n I: Integer;\n ARecordSet: _Recordset;\nbegin\n Memo1.Lines.Add('==========================');\n\n ADOStoredProc1.Open; // not ExecProc !!!!!\n\n ARecordSet := ADOStoredProc1.Recordset;\n while Assigned(ARecordSet) do\n begin\n // do whatever with current RecordSet\n while not ADOStoredProc1.Eof do\n begin\n Memo1.Lines.Add(ADOStoredProc1.Fields[0].FieldName + ': ' + ADOStoredProc1.Fields[0].Value);\n ADOStoredProc1.Next;\n end;\n // switch to subsequent RecordSet if any\n ARecordSet := ADOStoredProc1.NextRecordset(I);\n if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) <> 0) then\n ADOStoredProc1.Recordset := ARecordSet\n else\n Break;\n end;\n\n ADOStoredProc1.Close;\nend;\n"
},
{
"answer_id": 13145530,
"author": "Freddie bell",
"author_id": 1441618,
"author_profile": "https://Stackoverflow.com/users/1441618",
"pm_score": 0,
"selected": false,
"text": "procedure TForm1.ADOConnection1InfoMessage(Connection: TADOConnection;\n const Error: Error; var EventStatus: TEventStatus);\nvar\n i: integer;\nbegin\n // show ALL print statements\n for i := 0 to AdoConnection1.Errors.Count - 1 do\n begin\n // was: cxMemo1.Lines.Add(Error.Description);\n cxMemo1.Lines.Add(\n ADOConnection1.Errors.Item[i].Description);\n end;\nend;\n\nprocedure TForm1.cxButton1Click(Sender: TObject);\nconst\n adStateOpen = $00000001; // or uses ADOInt\nvar\n records: Integer;\n ARecordSet: _RecordSet;\nbegin\n cxMemo1.Lines.Add('==========================');\n\n ADOStoredProc1.Open;\n\n try\n ARecordSet := ADOStoredProc1.RecordSet; // initial fetch\n while Assigned(ARecordSet) do\n begin\n // assign the recordset to a DataSets recordset to traverse\n AdoDataSet1.Recordset := ARecordSet;\n // do whatever with current ARecordSet\n while not ADODataSet1.eof do\n begin\n cxMemo1.Lines.Add(ADODataSet1.Fields[0].FieldName + \n ': ' + ADODataSet1.Fields[0].Value);\n AdoDataSet1.Next;\n end;\n // fetch next recordset if there is one\n ARecordSet := ADOStoredProc1.NextRecordSet(records);\n if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) <> 0) then\n ADOStoredProc1.Recordset := ARecordSet\n else\n Break;\n end;\n finally\n ADOStoredProc1.Close;\n end;\n\nend;\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17337/"
] |
254,509
|
<p>I need to leave some instructional comments for other developers on a page/user control. Is there a better way to do this besides the below?</p>
<pre><code> <% /* DO NOT rename control IDs here, because blah blah blah... */ %>
</code></pre>
|
[
{
"answer_id": 254525,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": " <!-- Renders to ClientOutput too -->\n <% /* Your original idea */ %>\n"
},
{
"answer_id": 254538,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 4,
"selected": true,
"text": "<%-- Comment Here --%>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22303/"
] |
254,514
|
<p>I know that PHP doesn't yet have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto-completion features could understand.</p>
<p>Constants do the trick, but there's the namespace collision problem and (or actually <em>because</em>) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely know how to autofill their keys without additional static analysis annotations or attributes.</p>
<p>Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enumerations?</p>
|
[
{
"answer_id": 254528,
"author": "andy.gurin",
"author_id": 22388,
"author_profile": "https://Stackoverflow.com/users/22388",
"pm_score": 5,
"selected": false,
"text": "class Enum {\n const NAME = 'aaaa';\n const SOME_VALUE = 'bbbb';\n}\n\nprint Enum::NAME;\n"
},
{
"answer_id": 254532,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 6,
"selected": false,
"text": "<?php\n\nclass YourClass\n{\n const SOME_CONSTANT = 1;\n\n public function echoConstant()\n {\n echo self::SOME_CONSTANT;\n }\n}\n\necho YourClass::SOME_CONSTANT;\n\n$c = new YourClass;\n$c->echoConstant();\n"
},
{
"answer_id": 254543,
"author": "Brian Cline",
"author_id": 32536,
"author_profile": "https://Stackoverflow.com/users/32536",
"pm_score": 12,
"selected": true,
"text": "abstract class DaysOfWeek\n{\n const Sunday = 0;\n const Monday = 1;\n // etc.\n}\n\n$today = DaysOfWeek::Sunday;\n abstract class BasicEnum {\n private static $constCacheArray = NULL;\n\n private static function getConstants() {\n if (self::$constCacheArray == NULL) {\n self::$constCacheArray = [];\n }\n $calledClass = get_called_class();\n if (!array_key_exists($calledClass, self::$constCacheArray)) {\n $reflect = new ReflectionClass($calledClass);\n self::$constCacheArray[$calledClass] = $reflect->getConstants();\n }\n return self::$constCacheArray[$calledClass];\n }\n\n public static function isValidName($name, $strict = false) {\n $constants = self::getConstants();\n\n if ($strict) {\n return array_key_exists($name, $constants);\n }\n\n $keys = array_map('strtolower', array_keys($constants));\n return in_array(strtolower($name), $keys);\n }\n\n public static function isValidValue($value, $strict = true) {\n $values = array_values(self::getConstants());\n return in_array($value, $values, $strict);\n }\n}\n abstract class DaysOfWeek extends BasicEnum {\n const Sunday = 0;\n const Monday = 1;\n const Tuesday = 2;\n const Wednesday = 3;\n const Thursday = 4;\n const Friday = 5;\n const Saturday = 6;\n}\n\nDaysOfWeek::isValidName('Humpday'); // false\nDaysOfWeek::isValidName('Monday'); // true\nDaysOfWeek::isValidName('monday'); // true\nDaysOfWeek::isValidName('monday', $strict = true); // false\nDaysOfWeek::isValidName(0); // false\n\nDaysOfWeek::isValidValue(0); // true\nDaysOfWeek::isValidValue(5); // true\nDaysOfWeek::isValidValue(7); // false\nDaysOfWeek::isValidValue('Friday'); // false\n SplEnum BasicEnum DaysOfWeek"
},
{
"answer_id": 3539340,
"author": "Christopher Fox",
"author_id": 427340,
"author_profile": "https://Stackoverflow.com/users/427340",
"pm_score": 3,
"selected": false,
"text": "<?php\n\n/**\n * Class Enum\n * \n * @author Christopher Fox <christopher.fox@gmx.de>\n *\n * @version 1.0\n *\n * This class provides the function of an enumeration.\n * The values of Enum elements are unique (even between different Enums)\n * as you would expect them to be.\n *\n * Constructing a new Enum:\n * ========================\n *\n * In the following example we construct an enum called \"UserState\"\n * with the elements \"inactive\", \"active\", \"banned\" and \"deleted\".\n * \n * <code>\n * Enum::Create('UserState', 'inactive', 'active', 'banned', 'deleted');\n * </code>\n *\n * Using Enums:\n * ============\n *\n * The following example demonstrates how to compare two Enum elements\n *\n * <code>\n * var_dump(UserState::inactive == UserState::banned); // result: false\n * var_dump(UserState::active == UserState::active); // result: true\n * </code>\n *\n * Special Enum methods:\n * =====================\n *\n * Get the number of elements in an Enum:\n *\n * <code>\n * echo UserState::CountEntries(); // result: 4\n * </code>\n *\n * Get a list with all elements of the Enum:\n *\n * <code>\n * $allUserStates = UserState::GetEntries();\n * </code>\n *\n * Get a name of an element:\n *\n * <code>\n * echo UserState::GetName(UserState::deleted); // result: deleted\n * </code>\n *\n * Get an integer ID for an element (e.g. to store as a value in a database table):\n * This is simply the index of the element (beginning with 1).\n * Note that this ID is only unique for this Enum but now between different Enums.\n *\n * <code>\n * echo UserState::GetDatabaseID(UserState::active); // result: 2\n * </code>\n */\nclass Enum\n{\n\n /**\n * @var Enum $instance The only instance of Enum (Singleton)\n */\n private static $instance;\n\n /**\n * @var array $enums An array of all enums with Enum names as keys\n * and arrays of element names as values\n */\n private $enums;\n\n /**\n * Constructs (the only) Enum instance\n */\n private function __construct()\n {\n $this->enums = array();\n }\n\n /**\n * Constructs a new enum\n *\n * @param string $name The class name for the enum\n * @param mixed $_ A list of strings to use as names for enum entries\n */\n public static function Create($name, $_)\n {\n // Create (the only) Enum instance if this hasn't happened yet\n if (self::$instance===null)\n {\n self::$instance = new Enum();\n }\n\n // Fetch the arguments of the function\n $args = func_get_args();\n // Exclude the \"name\" argument from the array of function arguments,\n // so only the enum element names remain in the array\n array_shift($args);\n self::$instance->add($name, $args);\n }\n\n /**\n * Creates an enumeration if this hasn't happened yet\n * \n * @param string $name The class name for the enum\n * @param array $fields The names of the enum elements\n */\n private function add($name, $fields)\n {\n if (!array_key_exists($name, $this->enums))\n {\n $this->enums[$name] = array();\n\n // Generate the code of the class for this enumeration\n $classDeclaration = \"class \" . $name . \" {\\n\"\n . \"private static \\$name = '\" . $name . \"';\\n\"\n . $this->getClassConstants($name, $fields)\n . $this->getFunctionGetEntries($name)\n . $this->getFunctionCountEntries($name)\n . $this->getFunctionGetDatabaseID()\n . $this->getFunctionGetName()\n . \"}\";\n\n // Create the class for this enumeration\n eval($classDeclaration);\n }\n }\n\n /**\n * Returns the code of the class constants\n * for an enumeration. These are the representations\n * of the elements.\n * \n * @param string $name The class name for the enum\n * @param array $fields The names of the enum elements\n *\n * @return string The code of the class constants\n */\n private function getClassConstants($name, $fields)\n {\n $constants = '';\n\n foreach ($fields as $field)\n {\n // Create a unique ID for the Enum element\n // This ID is unique because class and variables\n // names can't contain a semicolon. Therefore we\n // can use the semicolon as a separator here.\n $uniqueID = $name . \";\" . $field;\n $constants .= \"const \" . $field . \" = '\". $uniqueID . \"';\\n\";\n // Store the unique ID\n array_push($this->enums[$name], $uniqueID);\n }\n\n return $constants;\n }\n\n /**\n * Returns the code of the function \"GetEntries()\"\n * for an enumeration\n * \n * @param string $name The class name for the enum\n *\n * @return string The code of the function \"GetEntries()\"\n */\n private function getFunctionGetEntries($name) \n {\n $entryList = ''; \n\n // Put the unique element IDs in single quotes and\n // separate them with commas\n foreach ($this->enums[$name] as $key => $entry)\n {\n if ($key > 0) $entryList .= ',';\n $entryList .= \"'\" . $entry . \"'\";\n }\n\n return \"public static function GetEntries() { \\n\"\n . \" return array(\" . $entryList . \");\\n\"\n . \"}\\n\";\n }\n\n /**\n * Returns the code of the function \"CountEntries()\"\n * for an enumeration\n * \n * @param string $name The class name for the enum\n *\n * @return string The code of the function \"CountEntries()\"\n */\n private function getFunctionCountEntries($name) \n {\n // This function will simply return a constant number (e.g. return 5;)\n return \"public static function CountEntries() { \\n\"\n . \" return \" . count($this->enums[$name]) . \";\\n\"\n . \"}\\n\";\n }\n\n /**\n * Returns the code of the function \"GetDatabaseID()\"\n * for an enumeration\n * \n * @return string The code of the function \"GetDatabaseID()\"\n */\n private function getFunctionGetDatabaseID()\n {\n // Check for the index of this element inside of the array\n // of elements and add +1\n return \"public static function GetDatabaseID(\\$entry) { \\n\"\n . \"\\$key = array_search(\\$entry, self::GetEntries());\\n\"\n . \" return \\$key + 1;\\n\"\n . \"}\\n\";\n }\n\n /**\n * Returns the code of the function \"GetName()\"\n * for an enumeration\n *\n * @return string The code of the function \"GetName()\"\n */\n private function getFunctionGetName()\n {\n // Remove the class name from the unique ID \n // and return this value (which is the element name)\n return \"public static function GetName(\\$entry) { \\n\"\n . \"return substr(\\$entry, strlen(self::\\$name) + 1 , strlen(\\$entry));\\n\"\n . \"}\\n\";\n }\n\n}\n\n\n?>\n"
},
{
"answer_id": 3985626,
"author": "zanshine",
"author_id": 482734,
"author_profile": "https://Stackoverflow.com/users/482734",
"pm_score": 3,
"selected": false,
"text": "<?php\n//require the library\nrequire_once __DIR__ . '/src/Enum.func.php';\n\n//if you don't have a cache directory, create one\n@mkdir(__DIR__ . '/cache');\nEnumGenerator::setDefaultCachedClassesDir(__DIR__ . '/cache');\n\n//Class definition is evaluated on the fly:\nEnum('FruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'));\n\n//Class definition is cached in the cache directory for later usage:\nEnum('CachedFruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'), '\\my\\company\\name\\space', true);\n\necho 'FruitsEnum::APPLE() == FruitsEnum::APPLE(): ';\nvar_dump(FruitsEnum::APPLE() == FruitsEnum::APPLE()) . \"\\n\";\n\necho 'FruitsEnum::APPLE() == FruitsEnum::ORANGE(): ';\nvar_dump(FruitsEnum::APPLE() == FruitsEnum::ORANGE()) . \"\\n\";\n\necho 'FruitsEnum::APPLE() instanceof Enum: ';\nvar_dump(FruitsEnum::APPLE() instanceof Enum) . \"\\n\";\n\necho 'FruitsEnum::APPLE() instanceof FruitsEnum: ';\nvar_dump(FruitsEnum::APPLE() instanceof FruitsEnum) . \"\\n\";\n\necho \"->getName()\\n\";\nforeach (FruitsEnum::iterator() as $enum)\n{\n echo \" \" . $enum->getName() . \"\\n\";\n}\n\necho \"->getValue()\\n\";\nforeach (FruitsEnum::iterator() as $enum)\n{\n echo \" \" . $enum->getValue() . \"\\n\";\n}\n\necho \"->getOrdinal()\\n\";\nforeach (CachedFruitsEnum::iterator() as $enum)\n{\n echo \" \" . $enum->getOrdinal() . \"\\n\";\n}\n\necho \"->getBinary()\\n\";\nforeach (CachedFruitsEnum::iterator() as $enum)\n{\n echo \" \" . $enum->getBinary() . \"\\n\";\n}\n FruitsEnum::APPLE() == FruitsEnum::APPLE(): bool(true)\nFruitsEnum::APPLE() == FruitsEnum::ORANGE(): bool(false)\nFruitsEnum::APPLE() instanceof Enum: bool(true)\nFruitsEnum::APPLE() instanceof FruitsEnum: bool(true)\n->getName()\n APPLE\n ORANGE\n RASBERRY\n BANNANA\n->getValue()\n apple\n orange\n rasberry\n bannana\n->getValue() when values have been specified\n pig\n dog\n cat\n bird\n->getOrdinal()\n 1\n 2\n 3\n 4\n->getBinary()\n 1\n 2\n 4\n 8\n"
},
{
"answer_id": 4522078,
"author": "aelg",
"author_id": 552764,
"author_profile": "https://Stackoverflow.com/users/552764",
"pm_score": 5,
"selected": false,
"text": "class SomeTypeName {\n private static $enum = array(1 => \"Read\", 2 => \"Write\");\n\n public function toOrdinal($name) {\n return array_search($name, self::$enum);\n }\n\n public function toString($ordinal) {\n return self::$enum[$ordinal];\n }\n}\n SomeTypeName::toOrdinal(\"Read\");\nSomeTypeName::toString(1);\n"
},
{
"answer_id": 5051786,
"author": "arturgspb",
"author_id": 614999,
"author_profile": "https://Stackoverflow.com/users/614999",
"pm_score": 1,
"selected": false,
"text": "final class EnumException extends Exception{}\n\nabstract class Enum\n{\n /**\n * @var array ReflectionClass\n */\n protected static $reflectorInstances = array();\n /**\n * Массив конфигурированного объекта-константы enum\n * @var array\n */\n protected static $enumInstances = array();\n /**\n * Массив соответствий значение->ключ используется для проверки - \n * если ли константа с таким значением\n * @var array\n */\n protected static $foundNameValueLink = array();\n\n protected $constName;\n protected $constValue;\n\n /**\n * Реализует паттерн \"Одиночка\"\n * Возвращает объект константы, но но как объект его использовать не стоит, \n * т.к. для него реализован \"волшебный метод\" __toString()\n * Это должно использоваться только для типизачии его как параметра\n * @paradm Node\n */\n final public static function get($value)\n {\n // Это остается здесь для увеличения производительности (по замерам ~10%)\n $name = self::getName($value);\n if ($name === false)\n throw new EnumException(\"Неизвестая константа\");\n $className = get_called_class(); \n if (!isset(self::$enumInstances[$className][$name]))\n {\n $value = constant($className.'::'.$name);\n self::$enumInstances[$className][$name] = new $className($name, $value);\n }\n\n return self::$enumInstances[$className][$name];\n }\n\n /**\n * Возвращает массив констант пар ключ-значение всего перечисления\n * @return array \n */\n final public static function toArray()\n {\n $classConstantsArray = self::getReflectorInstance()->getConstants();\n foreach ($classConstantsArray as $k => $v)\n $classConstantsArray[$k] = (string)$v;\n return $classConstantsArray;\n }\n\n /**\n * Для последующего использования в toArray для получения массива констант ключ->значение \n * @return ReflectionClass\n */\n final private static function getReflectorInstance()\n {\n $className = get_called_class();\n if (!isset(self::$reflectorInstances[$className]))\n {\n self::$reflectorInstances[$className] = new ReflectionClass($className);\n }\n return self::$reflectorInstances[$className];\n }\n\n /**\n * Получает имя константы по её значению\n * @param string $value\n */\n final public static function getName($value)\n {\n $className = (string)get_called_class();\n\n $value = (string)$value;\n if (!isset(self::$foundNameValueLink[$className][$value]))\n {\n $constantName = array_search($value, self::toArray(), true);\n self::$foundNameValueLink[$className][$value] = $constantName;\n }\n return self::$foundNameValueLink[$className][$value];\n }\n\n /**\n * Используется ли такое имя константы в перечислении\n * @param string $name\n */\n final public static function isExistName($name)\n {\n $constArray = self::toArray();\n return isset($constArray[$name]);\n }\n\n /**\n * Используется ли такое значение константы в перечислении\n * @param string $value\n */\n final public static function isExistValue($value)\n {\n return self::getName($value) === false ? false : true;\n } \n\n\n final private function __clone(){}\n\n final private function __construct($name, $value)\n {\n $this->constName = $name;\n $this->constValue = $value;\n }\n\n final public function __toString()\n {\n return (string)$this->constValue;\n }\n}\n class enumWorkType extends Enum\n{\n const FULL = 0;\n const SHORT = 1;\n}\n"
},
{
"answer_id": 5647348,
"author": "user667540",
"author_id": 667540,
"author_profile": "https://Stackoverflow.com/users/667540",
"pm_score": 3,
"selected": false,
"text": "\nclass FruitsEnum {\n\n static $APPLE = null;\n static $ORANGE = null;\n\n private $value = null;\n\n public static $map;\n\n public function __construct($value) {\n $this->value = $value;\n }\n\n public static function init () {\n self::$APPLE = new FruitsEnum(\"Apple\");\n self::$ORANGE = new FruitsEnum(\"Orange\");\n //static map to get object by name - example Enum::get(\"INIT\") - returns Enum::$INIT object;\n self::$map = array (\n \"Apple\" => self::$APPLE,\n \"Orange\" => self::$ORANGE\n );\n }\n\n public static function get($element) {\n if($element == null)\n return null;\n return self::$map[$element];\n }\n\n public function getValue() {\n return $this->value;\n }\n\n public function equals(FruitsEnum $element) {\n return $element->getValue() == $this->getValue();\n }\n\n public function __toString () {\n return $this->value;\n }\n}\nFruitsEnum::init();\n\nvar_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$APPLE)); //true\nvar_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$ORANGE)); //false\nvar_dump(FruitsEnum::$APPLE instanceof FruitsEnum); //true\nvar_dump(FruitsEnum::get(\"Apple\")->equals(FruitsEnum::$APPLE)); //true - enum from string\nvar_dump(FruitsEnum::get(\"Apple\")->equals(FruitsEnum::get(\"Orange\"))); //false\n\n"
},
{
"answer_id": 5655491,
"author": "Anders",
"author_id": 526696,
"author_profile": "https://Stackoverflow.com/users/526696",
"pm_score": 2,
"selected": false,
"text": "$value = \"concert\";\n$Enumvalue = EnumCategory::enum($value);\n//$EnumValue = 1\n\nclass EnumCategory{\n const concert = 1;\n const festival = 2;\n const sport = 3;\n const nightlife = 4;\n const theatre = 5;\n const musical = 6;\n const cinema = 7;\n const charity = 8;\n const museum = 9;\n const other = 10;\n\n public function enum($string){\n return constant('EnumCategory::'.$string);\n }\n}\n class EnumCategory {\n\n static $concert = 1;\n static $festival = 2;\n static $sport = 3;\n static $nightlife = 4;\n static $theatre = 5;\n static $musical = 6;\n static $cinema = 7;\n static $charity = 8;\n static $museum = 9;\n static $other = 10;\n\n}\n EnumCategory::${$category};\n"
},
{
"answer_id": 8258912,
"author": "Andi T",
"author_id": 399996,
"author_profile": "https://Stackoverflow.com/users/399996",
"pm_score": 5,
"selected": false,
"text": "interface class interface DaysOfWeek\n{\n const Sunday = 0;\n const Monday = 1;\n // etc.\n}\n\nvar $today = DaysOfWeek::Sunday;\n"
},
{
"answer_id": 8659707,
"author": "Tiddo",
"author_id": 532901,
"author_profile": "https://Stackoverflow.com/users/532901",
"pm_score": 2,
"selected": false,
"text": "/**\n * A base class for enums. \n * \n * This class can be used as a base class for enums. \n * It can be used to create regular enums (incremental indices), but it can also be used to create binary flag values.\n * To create an enum class you can simply extend this class, and make a call to <yourEnumClass>::init() before you use the enum.\n * Preferably this call is made directly after the class declaration. \n * Example usages:\n * DaysOfTheWeek.class.php\n * abstract class DaysOfTheWeek extends Enum{\n * static $MONDAY = 1;\n * static $TUESDAY;\n * static $WEDNESDAY;\n * static $THURSDAY;\n * static $FRIDAY;\n * static $SATURDAY;\n * static $SUNDAY;\n * }\n * DaysOfTheWeek::init();\n * \n * example.php\n * require_once(\"DaysOfTheWeek.class.php\");\n * $today = date('N');\n * if ($today == DaysOfTheWeek::$SUNDAY || $today == DaysOfTheWeek::$SATURDAY)\n * echo \"It's weekend!\";\n * \n * Flags.class.php\n * abstract class Flags extends Enum{\n * static $FLAG_1;\n * static $FLAG_2;\n * static $FLAG_3;\n * }\n * Flags::init(Enum::$BINARY_FLAG);\n * \n * example2.php\n * require_once(\"Flags.class.php\");\n * $flags = Flags::$FLAG_1 | Flags::$FLAG_2;\n * if ($flags & Flags::$FLAG_1)\n * echo \"Flag_1 is set\";\n * \n * @author Tiddo Langerak\n */\nabstract class Enum{\n\n static $BINARY_FLAG = 1;\n /**\n * This function must be called to initialize the enumeration!\n * \n * @param bool $flags If the USE_BINARY flag is provided, the enum values will be binary flag values. Default: no flags set.\n */ \n public static function init($flags = 0){\n //First, we want to get a list of all static properties of the enum class. We'll use the ReflectionClass for this.\n $enum = get_called_class();\n $ref = new ReflectionClass($enum);\n $items = $ref->getStaticProperties();\n //Now we can start assigning values to the items. \n if ($flags & self::$BINARY_FLAG){\n //If we want binary flag values, our first value should be 1.\n $value = 1;\n //Now we can set the values for all items.\n foreach ($items as $key=>$item){\n if (!isset($item)){ \n //If no value is set manually, we should set it.\n $enum::$$key = $value;\n //And we need to calculate the new value\n $value *= 2;\n } else {\n //If there was already a value set, we will continue starting from that value, but only if that was a valid binary flag value.\n //Otherwise, we will just skip this item.\n if ($key != 0 && ($key & ($key - 1) == 0))\n $value = 2 * $item;\n }\n }\n } else {\n //If we want to use regular indices, we'll start with index 0.\n $value = 0;\n //Now we can set the values for all items.\n foreach ($items as $key=>$item){\n if (!isset($item)){\n //If no value is set manually, we should set it, and increment the value for the next item.\n $enum::$$key = $value;\n $value++;\n } else {\n //If a value was already set, we'll continue from that value.\n $value = $item+1;\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 10428012,
"author": "Weke",
"author_id": 1371979,
"author_profile": "https://Stackoverflow.com/users/1371979",
"pm_score": -1,
"selected": false,
"text": "<?php \n define(\"OPTION_1\", \"1\");\n define(\"OPTION_2\", OPTION_1 + 1);\n define(\"OPTION_3\", OPTION_2 + 1);\n\n // Some function...\n switch($Val){\n case OPTION_1:{ Perform_1();}break;\n case OPTION_2:{ Perform_2();}break;\n ...\n }\n?>\n"
},
{
"answer_id": 12150762,
"author": "KDog",
"author_id": 1628906,
"author_profile": "https://Stackoverflow.com/users/1628906",
"pm_score": 1,
"selected": false,
"text": "class ProtocolsEnum {\n\n const HTTP = '1';\n const HTTPS = '2';\n const FTP = '3';\n\n /**\n * Retrieve an enum value\n * @param string $name\n * @return string\n */\n public static function getValueByName($name) {\n return constant('self::'. $name);\n } \n\n /**\n * Retrieve an enum key name\n * @param string $code\n * @return string\n */\n public static function getNameByValue($code) {\n foreach(get_class_constants() as $key => $val) {\n if($val == $code) {\n return $key;\n }\n }\n }\n\n /**\n * Retrieve associate array of all constants (used for creating droplist options)\n * @return multitype:\n */\n public static function toArray() { \n return array_flip(self::get_class_constants());\n }\n\n private static function get_class_constants()\n {\n $reflect = new ReflectionClass(__CLASS__);\n return $reflect->getConstants();\n }\n}\n"
},
{
"answer_id": 13621724,
"author": "Vincent Pazeller",
"author_id": 811120,
"author_profile": "https://Stackoverflow.com/users/811120",
"pm_score": 2,
"selected": false,
"text": "class DaysOfWeek{\n const Sunday = 0;\n const Monday = 1;\n // etc.\n\n private $intVal;\n private function __construct($intVal){\n $this->intVal = $intVal;\n }\n\n //static instantiation methods\n public static function MONDAY(){\n return new self(self::Monday);\n }\n //etc.\n}\n\n//function using type checking\nfunction printDayOfWeek(DaysOfWeek $d){ //compiler can now use type checking\n // to something with $d...\n}\n\n//calling the function is safe!\nprintDayOfWeek(DaysOfWeek::MONDAY());\n printDayOfWeek(DaysOfWeek::Monday); //triggers a compiler error.\n class DaysOfWeeks{\n\n private static $monday = 1;\n //etc.\n\n private $intVal;\n //private constructor\n private function __construct($intVal){\n $this->intVal = $intVal;\n }\n\n //public instantiation methods\n public static function MONDAY(){\n return new self(self::$monday);\n }\n //etc.\n\n\n //convert an instance to its integer value\n public function intVal(){\n return $this->intVal;\n }\n\n}\n"
},
{
"answer_id": 13665128,
"author": "Brian Fisher",
"author_id": 43816,
"author_profile": "https://Stackoverflow.com/users/43816",
"pm_score": 3,
"selected": false,
"text": "[extended class name]::enumerate(); abstract class Enum {\n\n private $_value;\n\n protected function __construct($value) {\n $this->_value = $value;\n }\n\n public function __toString() {\n return (string) $this->_value;\n }\n\n public static function enumerate() {\n $class = get_called_class();\n $ref = new ReflectionClass($class);\n $statics = $ref->getStaticProperties();\n foreach ($statics as $name => $value) {\n $ref->setStaticPropertyValue($name, new $class($value));\n }\n }\n}\n\nclass DaysOfWeek extends Enum {\n public static $MONDAY = 0;\n public static $SUNDAY = 1;\n // etc.\n}\nDaysOfWeek::enumerate();\n\nfunction isMonday(DaysOfWeek $d) {\n if ($d == DaysOfWeek::$MONDAY) {\n return true;\n } else {\n return false;\n }\n}\n\n$day = DaysOfWeek::$MONDAY;\necho (isMonday($day) ? \"bummer it's monday\" : \"Yay! it's not monday\");\n"
},
{
"answer_id": 14330126,
"author": "Hervé Labas",
"author_id": 1092480,
"author_profile": "https://Stackoverflow.com/users/1092480",
"pm_score": 2,
"selected": false,
"text": "class TestEnum extends Enum\n{\n public static $TEST1;\n public static $TEST2;\n}\nTestEnum::init(); // Automatically initializes enum values\n class Enum\n{\n public static function parse($enum)\n {\n $class = get_called_class();\n $vars = get_class_vars($class);\n if (array_key_exists($enum, $vars)) {\n return $vars[$enum];\n }\n return null;\n }\n\n public static function init()\n {\n $className = get_called_class();\n $consts = get_class_vars($className);\n foreach ($consts as $constant => $value) {\n if (is_null($className::$$constant)) {\n $constantValue = $constant;\n $constantValueName = $className . '::' . $constant . '_VALUE';\n if (defined($constantValueName)) {\n $constantValue = constant($constantValueName);\n }\n $className::$$constant = new $className($constantValue);\n }\n }\n }\n\n public function __construct($value)\n {\n $this->value = $value;\n }\n}\n TestEnum::$TEST1 === TestEnum::parse('TEST1') // true statement"
},
{
"answer_id": 15010599,
"author": "Dan King",
"author_id": 1490986,
"author_profile": "https://Stackoverflow.com/users/1490986",
"pm_score": 2,
"selected": false,
"text": "<?php\n\nabstract class AbstractEnum\n{\n /** @var array cache of all enum instances by class name and integer value */\n private static $allEnumMembers = array();\n\n /** @var mixed */\n private $code;\n\n /** @var string */\n private $description;\n\n /**\n * Return an enum instance of the concrete type on which this static method is called, assuming an instance\n * exists for the passed in value. Otherwise an exception is thrown.\n *\n * @param $code\n * @return AbstractEnum\n * @throws Exception\n */\n public static function getByCode($code)\n {\n $concreteMembers = &self::getConcreteMembers();\n\n if (array_key_exists($code, $concreteMembers)) {\n return $concreteMembers[$code];\n }\n\n throw new Exception(\"Value '$code' does not exist for enum '\".get_called_class().\"'\");\n }\n\n public static function getAllMembers()\n {\n return self::getConcreteMembers();\n }\n\n /**\n * Create, cache and return an instance of the concrete enum type for the supplied primitive value.\n *\n * @param mixed $code code to uniquely identify this enum\n * @param string $description\n * @throws Exception\n * @return AbstractEnum\n */\n protected static function enum($code, $description)\n {\n $concreteMembers = &self::getConcreteMembers();\n\n if (array_key_exists($code, $concreteMembers)) {\n throw new Exception(\"Value '$code' has already been added to enum '\".get_called_class().\"'\");\n }\n\n $concreteMembers[$code] = $concreteEnumInstance = new static($code, $description);\n\n return $concreteEnumInstance;\n }\n\n /**\n * @return AbstractEnum[]\n */\n private static function &getConcreteMembers() {\n $thisClassName = get_called_class();\n\n if (!array_key_exists($thisClassName, self::$allEnumMembers)) {\n $concreteMembers = array();\n self::$allEnumMembers[$thisClassName] = $concreteMembers;\n }\n\n return self::$allEnumMembers[$thisClassName];\n }\n\n private function __construct($code, $description)\n {\n $this->code = $code;\n $this->description = $description;\n }\n\n public function getCode()\n {\n return $this->code;\n }\n\n public function getDescription()\n {\n return $this->description;\n }\n}\n <?php\n\nrequire('AbstractEnum.php');\n\nclass EMyEnum extends AbstractEnum\n{\n /** @var EMyEnum */\n public static $MY_FIRST_VALUE;\n /** @var EMyEnum */\n public static $MY_SECOND_VALUE;\n /** @var EMyEnum */\n public static $MY_THIRD_VALUE;\n\n public static function _init()\n {\n self::$MY_FIRST_VALUE = self::enum(1, 'My first value');\n self::$MY_SECOND_VALUE = self::enum(2, 'My second value');\n self::$MY_THIRD_VALUE = self::enum(3, 'My third value');\n }\n}\n\nEMyEnum::_init();\n <?php\n\nrequire('EMyEnum.php');\n\necho EMyEnum::$MY_FIRST_VALUE->getCode().' : '.EMyEnum::$MY_FIRST_VALUE->getDescription().PHP_EOL.PHP_EOL;\n\nvar_dump(EMyEnum::getAllMembers());\n\necho PHP_EOL.EMyEnum::getByCode(2)->getDescription().PHP_EOL;\n array(3) { \n [1]=> \n object(EMyEnum)#1 (2) { \n [\"code\":\"AbstractEnum\":private]=> \n int(1) \n [\"description\":\"AbstractEnum\":private]=> \n string(14) \"My first value\" \n } \n [2]=> \n object(EMyEnum)#2 (2) { \n [\"code\":\"AbstractEnum\":private]=> \n int(2) \n [\"description\":\"AbstractEnum\":private]=> \n string(15) \"My second value\" \n } \n [3]=> \n object(EMyEnum)#3 (2) { \n [\"code\":\"AbstractEnum\":private]=> \n int(3) \n [\"description\":\"AbstractEnum\":private]=> \n string(14) \"My third value\" \n } \n}\n"
},
{
"answer_id": 16102873,
"author": "jglatre",
"author_id": 974355,
"author_profile": "https://Stackoverflow.com/users/974355",
"pm_score": 3,
"selected": false,
"text": "abstract class Enumeration\n{\n public static function enum() \n {\n $reflect = new ReflectionClass( get_called_class() );\n return $reflect->getConstants();\n }\n}\n\n\nclass Test extends Enumeration\n{\n const A = 'a';\n const B = 'b'; \n}\n\n\nforeach (Test::enum() as $key => $value) {\n echo \"$key -> $value<br>\";\n}\n"
},
{
"answer_id": 17045081,
"author": "Dan Lugg",
"author_id": 409279,
"author_profile": "https://Stackoverflow.com/users/409279",
"pm_score": 5,
"selected": false,
"text": "const abstract class Enum\n{\n\n const NONE = null;\n\n final private function __construct()\n {\n throw new NotSupportedException(); // \n }\n\n final private function __clone()\n {\n throw new NotSupportedException();\n }\n\n final public static function toArray()\n {\n return (new ReflectionClass(static::class))->getConstants();\n }\n\n final public static function isValid($value)\n {\n return in_array($value, static::toArray());\n }\n\n}\n final class ResponseStatusCode extends Enum\n{\n\n const OK = 200;\n const CREATED = 201;\n const ACCEPTED = 202;\n // ...\n const SERVICE_UNAVAILABLE = 503;\n const GATEWAY_TIME_OUT = 504;\n const HTTP_VERSION_NOT_SUPPORTED = 505;\n\n}\n Enum toArray isValid __getStatic __equals final class TestEnum\n{\n\n private static $_values = [\n 'FOO' => 1,\n 'BAR' => 2,\n 'QUX' => 3,\n ];\n private static $_instances = [];\n\n public static function __getStatic($name)\n {\n if (isset(static::$_values[$name]))\n {\n if (empty(static::$_instances[$name]))\n {\n static::$_instances[$name] = new static($name);\n }\n return static::$_instances[$name];\n }\n throw new Exception(sprintf('Invalid enumeration value, \"%s\"', $name));\n }\n\n private $_value;\n\n public function __construct($name)\n {\n $this->_value = static::$_values[$name];\n }\n\n public function __equals($object)\n {\n if ($object instanceof static)\n {\n return $object->_value === $this->_value;\n }\n return $object === $this->_value;\n }\n\n}\n\n$foo = TestEnum::$FOO; // object(TestEnum)#1 (1) {\n // [\"_value\":\"TestEnum\":private]=>\n // int(1)\n // }\n\n$zap = TestEnum::$ZAP; // Uncaught exception 'Exception' with message\n // 'Invalid enumeration member, \"ZAP\"'\n\n$qux = TestEnum::$QUX;\nTestEnum::$QUX == $qux; // true\n'hello world!' == $qux; // false\n"
},
{
"answer_id": 18168706,
"author": "Songo",
"author_id": 636342,
"author_profile": "https://Stackoverflow.com/users/636342",
"pm_score": 3,
"selected": false,
"text": "function setAction(Action $action) { format parse final <?php\nuse MyCLabs\\Enum\\Enum;\n\n/**\n * Action enum\n */\nclass Action extends Enum\n{\n const VIEW = 'view';\n const EDIT = 'edit';\n}\n <?php\n$action = new Action(Action::VIEW);\n\n// or\n$action = Action::VIEW();\n <?php\nfunction setAction(Action $action) {\n // ...\n}\n"
},
{
"answer_id": 21536800,
"author": "Neil Townsend",
"author_id": 1242380,
"author_profile": "https://Stackoverflow.com/users/1242380",
"pm_score": 5,
"selected": false,
"text": "extend private static $constCacheArray = null;\n\nprivate static function getConstants() {\n if (self::$constCacheArray === null) self::$constCacheArray = array();\n\n $calledClass = get_called_class();\n if (!array_key_exists($calledClass, self::$constCacheArray)) {\n $reflect = new \\ReflectionClass($calledClass);\n self::$constCacheArray[$calledClass] = $reflect->getConstants();\n }\n\n return self::$constCacheArray[$calledClass];\n}\n"
},
{
"answer_id": 25526473,
"author": "Buck Fixing",
"author_id": 2451283,
"author_profile": "https://Stackoverflow.com/users/2451283",
"pm_score": 4,
"selected": false,
"text": "abstract class TypedEnum\n{\n private static $_instancedValues;\n\n private $_value;\n private $_name;\n\n private function __construct($value, $name)\n {\n $this->_value = $value;\n $this->_name = $name;\n }\n\n private static function _fromGetter($getter, $value)\n {\n $reflectionClass = new ReflectionClass(get_called_class());\n $methods = $reflectionClass->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_PUBLIC); \n $className = get_called_class();\n\n foreach($methods as $method)\n {\n if ($method->class === $className)\n {\n $enumItem = $method->invoke(null);\n\n if ($enumItem instanceof $className && $enumItem->$getter() === $value)\n {\n return $enumItem;\n }\n }\n }\n\n throw new OutOfRangeException();\n }\n\n protected static function _create($value)\n {\n if (self::$_instancedValues === null)\n {\n self::$_instancedValues = array();\n }\n\n $className = get_called_class();\n\n if (!isset(self::$_instancedValues[$className]))\n {\n self::$_instancedValues[$className] = array();\n }\n\n if (!isset(self::$_instancedValues[$className][$value]))\n {\n $debugTrace = debug_backtrace();\n $lastCaller = array_shift($debugTrace);\n\n while ($lastCaller['class'] !== $className && count($debugTrace) > 0)\n {\n $lastCaller = array_shift($debugTrace);\n }\n\n self::$_instancedValues[$className][$value] = new static($value, $lastCaller['function']);\n }\n\n return self::$_instancedValues[$className][$value];\n }\n\n public static function fromValue($value)\n {\n return self::_fromGetter('getValue', $value);\n }\n\n public static function fromName($value)\n {\n return self::_fromGetter('getName', $value);\n }\n\n public function getValue()\n {\n return $this->_value;\n }\n\n public function getName()\n {\n return $this->_name;\n }\n}\n final class DaysOfWeek extends TypedEnum\n{\n public static function Sunday() { return self::_create(0); } \n public static function Monday() { return self::_create(1); }\n public static function Tuesday() { return self::_create(2); } \n public static function Wednesday() { return self::_create(3); }\n public static function Thursday() { return self::_create(4); } \n public static function Friday() { return self::_create(5); }\n public static function Saturday() { return self::_create(6); } \n}\n function saveEvent(DaysOfWeek $weekDay, $comment)\n{\n // store week day numeric value and comment:\n $myDatabase->save('myeventtable', \n array('weekday_id' => $weekDay->getValue()),\n array('comment' => $comment));\n}\n\n// call the function, note: DaysOfWeek::Monday() returns an object of type DaysOfWeek\nsaveEvent(DaysOfWeek::Monday(), 'some comment');\n $monday1 = DaysOfWeek::Monday();\n$monday2 = DaysOfWeek::Monday();\n$monday1 === $monday2; // true\n function getGermanWeekDayName(DaysOfWeek $weekDay)\n{\n switch ($weekDay)\n {\n case DaysOfWeek::Monday(): return 'Montag';\n case DaysOfWeek::Tuesday(): return 'Dienstag';\n // ...\n}\n $monday = DaysOfWeek::fromValue(2);\n$tuesday = DaysOfWeek::fromName('Tuesday');\n $wednesday = DaysOfWeek::Wednesday()\necho $wednesDay->getName(); // Wednesday\n"
},
{
"answer_id": 27941072,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "// My Enumeration Class\nclass Enum\n{\n protected $m_actions = array();\n\n public function __construct($actions)\n {\n $this->init($actions);\n }\n\n public function init($actions)\n {\n $this->m_actions = array();\n for($i = 0; $i < count($actions); ++$i)\n {\n $this->m_actions[$actions[$i]] = ($i + 1); \n define($actions[$i], ($i + 1));\n }\n }\n\n public function toString($index)\n {\n $keys = array_keys($this->m_actions);\n for($i = 0; $i < count($keys); ++$i)\n {\n if($this->m_actions[$keys[$i]] == $index)\n {\n return $keys[$i];\n }\n }\n\n return \"undefined\";\n }\n\n public function fromString($str)\n {\n return $this->m_actions[$str];\n }\n}\n\n// Enumeration creation\n$actions = new Enum(array(\"CREATE\", \"READ\", \"UPDATE\", \"DELETE\"));\n\n// Examples\nprint($action_objects->toString(DELETE));\nprint($action_objects->fromString(\"DELETE\"));\n\nif($action_objects->fromString($_POST[\"myAction\"]) == CREATE)\n{\n print(\"CREATE\");\n}\n"
},
{
"answer_id": 28747652,
"author": "Torge",
"author_id": 2075537,
"author_profile": "https://Stackoverflow.com/users/2075537",
"pm_score": 3,
"selected": false,
"text": "class Fruit extends Enum {\n static public $APPLE = 1;\n static public $ORANGE = 2;\n}\nFruit::initialize(); //Can also be called in autoloader\n $myFruit = Fruit::$APPLE;\n\nswitch ($myFruit) {\n case Fruit::$APPLE : echo \"I like apples\\n\"; break;\n case Fruit::$ORANGE : echo \"I hate oranges\\n\"; break;\n}\n\n>> I like apples\n /** Function only accepts Fruit enums as input**/\nfunction echoFruit(Fruit $fruit) {\n echo $fruit->getName().\": \".$fruit->getValue().\"\\n\";\n}\n\n/** Call function with each Enum value that Fruit has */\nforeach (Fruit::getList() as $fruit) {\n echoFruit($fruit);\n}\n\n//Call function with Apple enum\nechoFruit(Fruit::$APPLE)\n\n//Will produce an error. This solution is strongly typed\nechoFruit(2);\n\n>> APPLE: 1\n>> ORANGE: 2\n>> APPLE: 1\n>> Argument 1 passed to echoFruit() must be an instance of Fruit, integer given\n echo \"I have an $myFruit\\n\";\n\n>> I have an APPLE\n $myFruit = Fruit::getByValue(2);\n\necho \"Now I have an $myFruit\\n\";\n\n>> Now I have an ORANGE\n $myFruit = Fruit::getByName(\"APPLE\");\n\necho \"But I definitely prefer an $myFruit\\n\\n\";\n\n>> But I definitely prefer an APPLE\n /**\n * @author Torge Kummerow\n */\nclass Enum {\n\n /**\n * Holds the values for each type of Enum\n */\n static private $list = array();\n\n /**\n * Initializes the enum values by replacing the number with an instance of itself\n * using reflection\n */\n static public function initialize() {\n $className = get_called_class();\n $class = new ReflectionClass($className);\n $staticProperties = $class->getStaticProperties();\n\n self::$list[$className] = array();\n\n foreach ($staticProperties as $propertyName => &$value) {\n if ($propertyName == 'list')\n continue;\n\n $enum = new $className($propertyName, $value);\n $class->setStaticPropertyValue($propertyName, $enum);\n self::$list[$className][$propertyName] = $enum;\n } unset($value);\n }\n\n\n /**\n * Gets the enum for the given value\n *\n * @param integer $value\n * @throws Exception\n *\n * @return Enum\n */\n static public function getByValue($value) {\n $className = get_called_class();\n foreach (self::$list[$className] as $propertyName=>&$enum) {\n /* @var $enum Enum */\n if ($enum->value == $value)\n return $enum;\n } unset($enum);\n\n throw new Exception(\"No such enum with value=$value of type \".get_called_class());\n }\n\n /**\n * Gets the enum for the given name\n *\n * @param string $name\n * @throws Exception\n *\n * @return Enum\n */\n static public function getByName($name) {\n $className = get_called_class();\n if (array_key_exists($name, static::$list[$className]))\n return self::$list[$className][$name];\n\n throw new Exception(\"No such enum \".get_called_class().\"::\\$$name\");\n }\n\n\n /**\n * Returns the list of all enum variants\n * @return Array of Enum\n */\n static public function getList() {\n $className = get_called_class();\n return self::$list[$className];\n }\n\n\n private $name;\n private $value;\n\n public function __construct($name, $value) {\n $this->name = $name;\n $this->value = $value;\n }\n\n public function __toString() {\n return $this->name;\n }\n\n public function getValue() {\n return $this->value;\n }\n\n public function getName() {\n return $this->name;\n }\n\n}\n class Fruit extends Enum {\n\n /**\n * This comment is for autocomplete support in common IDEs\n * @var Fruit A yummy apple\n */\n static public $APPLE = 1;\n\n /**\n * This comment is for autocomplete support in common IDEs\n * @var Fruit A sour orange\n */\n static public $ORANGE = 2;\n}\n\n//This can also go to the autoloader if available.\nFruit::initialize();\n"
},
{
"answer_id": 28789884,
"author": "Jesse",
"author_id": 268083,
"author_profile": "https://Stackoverflow.com/users/268083",
"pm_score": 2,
"selected": false,
"text": "class DayOfWeek {\n static $values = array(\n self::MONDAY,\n self::TUESDAY,\n // ...\n );\n\n const MONDAY = 0;\n const TUESDAY = 1;\n // ...\n}\n\n$today = DayOfWeek::MONDAY;\n\n// If you want to check if a value is valid\nassert( in_array( $today, DayOfWeek::$values ) );\n"
},
{
"answer_id": 29358610,
"author": "Chris Middleton",
"author_id": 2407870,
"author_profile": "https://Stackoverflow.com/users/2407870",
"pm_score": 2,
"selected": false,
"text": "abstract class ShirtSize {\n public const SMALL = 1;\n public const MEDIUM = 2;\n public const LARGE = 3;\n}\n ShirtSize::SMALL int ShirtSize class ShirtSize {\n private $size;\n private function __construct ($size) {\n $this->size = $size;\n }\n public function equals (ShirtSize $s) {\n return $this->size === $s->size;\n }\n public static function SMALL () { return new self(1); }\n public static function MEDIUM () { return new self(2); }\n public static function LARGE () { return new self(3); }\n}\n ShirtSize function sizeIsAvailable ($productId, ShirtSize $size) {\n // business magic\n}\nif(sizeIsAvailable($_GET[\"id\"], ShirtSize::LARGE())) {\n echo \"Available\";\n} else {\n echo \"Out of stock.\";\n}\n$s2 = ShirtSize::SMALL();\n$s3 = ShirtSize::MEDIUM();\necho $s2->equals($s3) ? \"SMALL == MEDIUM\" : \"SMALL != MEDIUM\";\n () === == equals == ==="
},
{
"answer_id": 29924814,
"author": "Mark Manning",
"author_id": 928121,
"author_profile": "https://Stackoverflow.com/users/928121",
"pm_score": 3,
"selected": false,
"text": "__call() enums __call() enums $c->RED_LIGHT();\n$c->YELLOW_LIGHT();\n$c->GREEN_LIGHT();\n echo $c->RED_LIGHT();\necho $c->YELLOW_LIGHT();\necho $c->GREEN_LIGHT();\n __get() __set() $c->RED_LIGHT;\n$c->YELLOW_LIGHT;\n$c->GREEN_LIGHT;\n __get() $c->RED_LIGHT = 85;\n __set() <?php\n################################################################################\n# Class ENUMS\n#\n# Original code by Mark Manning.\n# Copyrighted (c) 2015 by Mark Manning.\n# All rights reserved.\n#\n# This set of code is hereby placed into the free software universe\n# via the GNU greater license thus placing it under the Copyleft\n# rules and regulations with the following modifications:\n#\n# 1. You may use this work in any other work. Commercial or otherwise.\n# 2. You may make as much money as you can with it.\n# 3. You owe me nothing except to give me a small blurb somewhere in\n# your program or maybe have pity on me and donate a dollar to\n# sim_sales@paypal.com. :-)\n#\n# Blurb:\n#\n# PHP Class Enums by Mark Manning (markem-AT-sim1-DOT-us).\n# Used with permission.\n#\n# Notes:\n#\n# VIM formatting. Set tabs to four(4) spaces.\n#\n################################################################################\nclass enums\n{\n private $enums;\n private $clear_flag;\n private $last_value;\n\n################################################################################\n# __construct(). Construction function. Optionally pass in your enums.\n################################################################################\nfunction __construct()\n{\n $this->enums = array();\n $this->clear_flag = false;\n $this->last_value = 0;\n\n if( func_num_args() > 0 ){\n return $this->put( func_get_args() );\n }\n\n return true;\n}\n################################################################################\n# put(). Insert one or more enums.\n################################################################################\nfunction put()\n{\n $args = func_get_args();\n#\n# Did they send us an array of enums?\n# Ex: $c->put( array( \"a\"=>0, \"b\"=>1,...) );\n# OR $c->put( array( \"a\", \"b\", \"c\",... ) );\n#\n if( is_array($args[0]) ){\n#\n# Add them all in\n#\n foreach( $args[0] as $k=>$v ){\n#\n# Don't let them change it once it is set.\n# Remove the IF statement if you want to be able to modify the enums.\n#\n if( !isset($this->enums[$k]) ){\n#\n# If they sent an array of enums like this: \"a\",\"b\",\"c\",... then we have to\n# change that to be \"A\"=>#. Where \"#\" is the current count of the enums.\n#\n if( is_numeric($k) ){\n $this->enums[$v] = $this->last_value++;\n }\n#\n# Else - they sent \"a\"=>\"A\", \"b\"=>\"B\", \"c\"=>\"C\"...\n#\n else {\n $this->last_value = $v + 1;\n $this->enums[$k] = $v;\n }\n }\n }\n }\n#\n# Nope! Did they just sent us one enum?\n#\n else {\n#\n# Is this just a default declaration?\n# Ex: $c->put( \"a\" );\n#\n if( count($args) < 2 ){\n#\n# Again - remove the IF statement if you want to be able to change the enums.\n#\n if( !isset($this->enums[$args[0]]) ){\n $this->enums[$args[0]] = $this->last_value++;\n }\n#\n# No - they sent us a regular enum\n# Ex: $c->put( \"a\", \"This is the first enum\" );\n#\n else {\n#\n# Again - remove the IF statement if you want to be able to change the enums.\n#\n if( !isset($this->enums[$args[0]]) ){\n $this->last_value = $args[1] + 1;\n $this->enums[$args[0]] = $args[1];\n }\n }\n }\n }\n\n return true;\n}\n################################################################################\n# get(). Get one or more enums.\n################################################################################\nfunction get()\n{\n $num = func_num_args();\n $args = func_get_args();\n#\n# Is this an array of enums request? (ie: $c->get(array(\"a\",\"b\",\"c\"...)) )\n#\n if( is_array($args[0]) ){\n $ary = array();\n foreach( $args[0] as $k=>$v ){\n $ary[$v] = $this->enums[$v];\n }\n\n return $ary;\n }\n#\n# Is it just ONE enum they want? (ie: $c->get(\"a\") )\n#\n else if( ($num > 0) && ($num < 2) ){\n return $this->enums[$args[0]];\n }\n#\n# Is it a list of enums they want? (ie: $c->get( \"a\", \"b\", \"c\"...) )\n#\n else if( $num > 1 ){\n $ary = array();\n foreach( $args as $k=>$v ){\n $ary[$v] = $this->enums[$v];\n }\n\n return $ary;\n }\n#\n# They either sent something funky or nothing at all.\n#\n return false;\n}\n################################################################################\n# clear(). Clear out the enum array.\n# Optional. Set the flag in the __construct function.\n# After all, ENUMS are supposed to be constant.\n################################################################################\nfunction clear()\n{\n if( $clear_flag ){\n unset( $this->enums );\n $this->enums = array();\n }\n\n return true;\n}\n################################################################################\n# __call(). In case someone tries to blow up the class.\n################################################################################\nfunction __call( $name, $arguments )\n{\n if( isset($this->enums[$name]) ){ return $this->enums[$name]; }\n else if( !isset($this->enums[$name]) && (count($arguments) > 0) ){\n $this->last_value = $arguments[0] + 1;\n $this->enums[$name] = $arguments[0];\n return true;\n }\n else if( !isset($this->enums[$name]) && (count($arguments) < 1) ){\n $this->enums[$name] = $this->last_value++;\n return true;\n }\n\n return false;\n}\n################################################################################\n# __get(). Gets the value.\n################################################################################\nfunction __get($name)\n{\n if( isset($this->enums[$name]) ){ return $this->enums[$name]; }\n else if( !isset($this->enums[$name]) ){\n $this->enums[$name] = $this->last_value++;\n return true;\n }\n\n return false;\n}\n################################################################################\n# __set(). Sets the value.\n################################################################################\nfunction __set( $name, $value=null )\n{\n if( isset($this->enums[$name]) ){ return false; }\n else if( !isset($this->enums[$name]) && !is_null($value) ){\n $this->last_value = $value + 1;\n $this->enums[$name] = $value;\n return true;\n }\n else if( !isset($this->enums[$name]) && is_null($value) ){\n $this->enums[$name] = $this->last_value++;\n return true;\n }\n\n return false;\n}\n################################################################################\n# __destruct(). Deconstruct the class. Remove the list of enums.\n################################################################################\nfunction __destruct()\n{\n unset( $this->enums );\n $this->enums = null;\n\n return true;\n}\n\n}\n#\n# Test code\n#\n# $c = new enums();\n# $c->RED_LIGHT(85);\n# $c->YELLOW_LIGHT = 23;\n# $c->GREEN_LIGHT;\n#\n# echo $c->RED_LIGHT . \"\\n\";\n# echo $c->YELLOW_LIGHT . \"\\n\";\n# echo $c->GREEN_LIGHT . \"\\n\";\n\n?>\n"
},
{
"answer_id": 30507927,
"author": "mykhal",
"author_id": 234248,
"author_profile": "https://Stackoverflow.com/users/234248",
"pm_score": 3,
"selected": false,
"text": "enum DaysOfWeek {\n Sunday,\n Monday,\n // ...\n}\n"
},
{
"answer_id": 33041402,
"author": "Loupax",
"author_id": 208271,
"author_profile": "https://Stackoverflow.com/users/208271",
"pm_score": 2,
"selected": false,
"text": "<?php \n/**\n * A class that simulates Enums behaviour\n * <code>\n * class Season extends Enum{\n * const Spring = 0;\n * const Summer = 1;\n * const Autumn = 2;\n * const Winter = 3;\n * }\n * \n * $currentSeason = new Season(Season::Spring);\n * $nextYearSeason = new Season(Season::Spring);\n * $winter = new Season(Season::Winter);\n * $whatever = new Season(-1); // Throws InvalidArgumentException\n * echo $currentSeason.is(Season::Spring); // True\n * echo $currentSeason.getName(); // 'Spring'\n * echo $currentSeason.is($nextYearSeason); // True\n * echo $currentSeason.is(Season::Winter); // False\n * echo $currentSeason.is(Season::Spring); // True\n * echo $currentSeason.is($winter); // False\n * </code>\n * \n * Class Enum\n * \n * PHP Version 5.5\n */\nabstract class Enum\n{\n /**\n * Will contain all the constants of every enum that gets created to \n * avoid expensive ReflectionClass usage\n * @var array\n */\n private static $_constCacheArray = [];\n /**\n * The value that separates this instance from the rest of the same class\n * @var mixed\n */\n private $_value;\n /**\n * The label of the Enum instance. Will take the string name of the \n * constant provided, used for logging and human readable messages\n * @var string\n */\n private $_name;\n /**\n * Creates an enum instance, while makes sure that the value given to the \n * enum is a valid one\n * \n * @param mixed $value The value of the current\n * \n * @throws \\InvalidArgumentException\n */\n public final function __construct($value)\n {\n $constants = self::_getConstants();\n if (count($constants) !== count(array_unique($constants))) {\n throw new \\InvalidArgumentException('Enums cannot contain duplicate constant values');\n }\n if ($name = array_search($value, $constants)) {\n $this->_value = $value;\n $this->_name = $name;\n } else {\n throw new \\InvalidArgumentException('Invalid enum value provided');\n }\n }\n /**\n * Returns the constant name of the current enum instance\n * \n * @return string\n */\n public function getName()\n {\n return $this->_name;\n }\n /**\n * Returns the value of the current enum instance\n * \n * @return mixed\n */\n public function getValue()\n {\n return $this->_value;\n }\n /**\n * Checks whether this enum instance matches with the provided one.\n * This function should be used to compare Enums at all times instead\n * of an identity comparison \n * <code>\n * // Assuming EnumObject and EnumObject2 both extend the Enum class\n * // and constants with such values are defined\n * $var = new EnumObject('test'); \n * $var2 = new EnumObject('test');\n * $var3 = new EnumObject2('test');\n * $var4 = new EnumObject2('test2');\n * echo $var->is($var2); // true\n * echo $var->is('test'); // true\n * echo $var->is($var3); // false\n * echo $var3->is($var4); // false\n * </code>\n * \n * @param mixed|Enum $enum The value we are comparing this enum object against\n * If the value is instance of the Enum class makes\n * sure they are instances of the same class as well, \n * otherwise just ensures they have the same value\n * \n * @return bool\n */\n public final function is($enum)\n {\n // If we are comparing enums, just make\n // sure they have the same toString value\n if (is_subclass_of($enum, __CLASS__)) {\n return get_class($this) === get_class($enum) \n && $this->getValue() === $enum->getValue();\n } else {\n // Otherwise assume $enum is the value we are comparing against\n // and do an exact comparison\n return $this->getValue() === $enum; \n }\n }\n\n /**\n * Returns the constants that are set for the current Enum instance\n * \n * @return array\n */\n private static function _getConstants()\n {\n if (self::$_constCacheArray == null) {\n self::$_constCacheArray = [];\n }\n $calledClass = get_called_class();\n if (!array_key_exists($calledClass, self::$_constCacheArray)) {\n $reflect = new \\ReflectionClass($calledClass);\n self::$_constCacheArray[$calledClass] = $reflect->getConstants();\n }\n return self::$_constCacheArray[$calledClass];\n }\n}\n"
},
{
"answer_id": 43825552,
"author": "Ismaelj",
"author_id": 392484,
"author_profile": "https://Stackoverflow.com/users/392484",
"pm_score": 0,
"selected": false,
"text": "abstract class enum {\n private function __construct() {}\n static function has($const) {\n $name = get_called_class();\n return defined(\"$name::$const\");\n }\n static function value($const) {\n $name = get_called_class();\n return defined(\"$name::$const\")? constant(\"$name::$const\") : false;\n }\n}\n class requestFormat extends enum { const HTML = 1; const JSON = 2; const XML = 3; const FORM = 4; }\n\necho requestFormat::value('JSON'); // 2\necho requestFormat::has('JSON'); // true\n"
},
{
"answer_id": 48402367,
"author": "user986730",
"author_id": 986730,
"author_profile": "https://Stackoverflow.com/users/986730",
"pm_score": 0,
"selected": false,
"text": "abstract class DaysOfWeekEnum{\n public function __construct(string $value){\n $this->value = $value; \n }\n public function __toString(){\n return $this->value;\n }\n\n}\nclass Monday extends DaysOfWeekEnum{\n public function __construct(){\n parent::__construct(\"Monday\");\n }\n}\n\nclass Tuesday extends DaysOfWeekEnum{\n public function __construct(){\n parent::__construct(\"Tuesday\");\n }\n}\n function printWeekDay(DaysOfWeek $day){\n echo \"Today is $day.\";\n}\n\nprintWeekDay(new Monday());\n"
},
{
"answer_id": 50545442,
"author": "Krishnadas PC",
"author_id": 2295484,
"author_profile": "https://Stackoverflow.com/users/2295484",
"pm_score": 2,
"selected": false,
"text": "<?php\nclass Month extends SplEnum {\n const __default = self::January;\n\n const January = 1;\n const February = 2;\n const March = 3;\n const April = 4;\n const May = 5;\n const June = 6;\n const July = 7;\n const August = 8;\n const September = 9;\n const October = 10;\n const November = 11;\n const December = 12;\n}\n\necho new Month(Month::June) . PHP_EOL;\n\ntry {\n new Month(13);\n} catch (UnexpectedValueException $uve) {\n echo $uve->getMessage() . PHP_EOL;\n}\n?>\n"
},
{
"answer_id": 52268643,
"author": "Anthony Rutledge",
"author_id": 2495645,
"author_profile": "https://Stackoverflow.com/users/2495645",
"pm_score": 3,
"selected": false,
"text": "/**\n * An interface that groups HTTP Accept: header Media Types in one place.\n */\ninterface MediaTypes\n{\n /**\n * Now, if you have to use these same constants with another class, you can\n * without creating funky inheritance / is-a relationships.\n * Also, this gets around the single inheritance limitation.\n */\n\n public const HTML = 'text/html';\n public const JSON = 'application/json';\n public const XML = 'application/xml';\n public const TEXT = 'text/plain';\n}\n\n/**\n * An generic request class.\n */\nabstract class Request\n{\n // Why not put the constants here?\n // 1) The logical reuse issue.\n // 2) Single Inheritance.\n // 3) Overriding is possible.\n\n // Why put class constants here?\n // 1) The constant value will not be necessary in other class families.\n}\n\n/**\n * An incoming / server-side HTTP request class.\n */\nclass HttpRequest extends Request implements MediaTypes\n{\n // This class can implement groups of constants as necessary.\n}\n protected private Interface public"
},
{
"answer_id": 59597159,
"author": "the liquid metal",
"author_id": 442388,
"author_profile": "https://Stackoverflow.com/users/442388",
"pm_score": 2,
"selected": false,
"text": "abstract class Enum {\n protected $val;\n\n protected function __construct($arg) {\n $this->val = $arg;\n }\n\n public function __toString() {\n return $this->val;\n }\n\n public function __set($arg1, $arg2) {\n throw new Exception(\"enum does not have property\");\n }\n\n public function __get($arg1) {\n throw new Exception(\"enum does not have property\");\n }\n\n // not really needed\n public function __call($arg1, $arg2) {\n throw new Exception(\"enum does not have method\");\n }\n\n // not really needed\n static public function __callStatic($arg1, $arg2) {\n throw new Exception(\"enum does not have static method\");\n }\n}\n final class MyEnum extends Enum {\n static public function val1() {\n return new self(\"val1\");\n }\n\n static public function val2() {\n return new self(\"val2\");\n }\n\n static public function val3() {\n return new self(\"val3\");\n }\n}\n $a = MyEnum::val1();\necho \"1.the enum value is '$a'\\n\";\n\nfunction consumeMyEnum(MyEnum $arg) {\n return \"2.the return value is '$arg'\\n\";\n}\n\necho consumeMyEnum($a);\n$version = explode(\".\", PHP_VERSION);\nif ($version[0] >= 7) {\n try {\n echo consumeMyEnum(\"val1\");\n } catch (TypeError $e) {\n echo \"3.passing argument error happens (PHP 7.0 and above)\\n\";\n }\n}\n\necho ($a == MyEnum::val1()) ? \"4.same\\n\" : \"4.different\\n\";\necho ($a == MyEnum::val2()) ? \"5.same\\n\" : \"5.different\\n\";\n\n$b = MyEnum::val1();\necho ($a == $b) ? \"6.same\\n\" : \"6.different\\n\";\necho ($a === $b) ? \"7.same\\n\" : \"7.different\\n\";\n\n$c = MyEnum::val2();\necho ($a == $c) ? \"8.same\\n\" : \"8.different\\n\";\necho ($a === $c) ? \"9.same\\n\" : \"9.different\\n\";\n\nswitch ($c) {\n case MyEnum::val1(): echo \"10.case of 1st\\n\"; break;\n case MyEnum::val2(): echo \"11.case of 2nd\\n\"; break;\n case MyEnum::val3(): echo \"12.case of 3rd\\n\"; break;\n}\n\ntry {\n $a->prop = 10;\n} catch (Exception $e) {\n echo \"13.set property error happens\\n\";\n}\n\ntry {\n echo $a->prop;\n} catch (Exception $e) {\n echo \"14.get property error happens\\n\";\n}\n\ntry {\n echo $a->meth();\n} catch (Exception $e) {\n echo \"15.method call error happens\\n\";\n}\n\ntry {\n echo MyEnum::meth();\n} catch (Exception $e) {\n echo \"16.static method call error happens\\n\";\n}\n\nclass Ordinary {}\necho $a instanceof MyEnum ? \"17.MyEnum instance\\n\" : \"17.not MyEnum instance\\n\";\necho $a instanceof Enum ? \"18.Enum instance\\n\" : \"18.not Enum instance\\n\";\necho $a instanceof Ordinary ? \"19.Ordinary instance\\n\" : \"19.not Ordinary instance\\n\";\n"
},
{
"answer_id": 66208862,
"author": "yivi",
"author_id": 1426539,
"author_profile": "https://Stackoverflow.com/users/1426539",
"pm_score": 7,
"selected": false,
"text": "enum TransportMode {\n case Bicycle;\n case Car;\n case Ship;\n case Plane;\n case Feet;\n}\n function travelCost(TransportMode $mode, int $distance): int\n{ /* implementation */ } \n\n$mode = TransportMode::Boat;\n\n$bikeCost = travelCost(TransportMode::Bicycle, 90);\n$boatCost = travelCost($mode, 90);\n\n// this one would fail: (Enums are singletons, not scalars)\n$failCost = travelCost('Car', 90);\n TransportMode::Bicycle 0 > < $foo = TransportMode::Car;\n$bar = TransportMode::Car;\n$baz = TransportMode::Bicycle;\n\n$foo === $bar; // true\n$bar === $baz; // false\n\n$foo instanceof TransportMode; // true\n\n$foo > $bar || $foo < $bar; // false either way\n int string enum Metal: int {\n case Gold = 1932;\n case Silver = 1049;\n case Lead = 1134;\n case Uranium = 1905;\n case Copper = 894;\n}\n value Metal::Gold->value BackedEnum from(int|string): self tryFrom(int|string): ?self null // usage example:\n\n$metal_1 = Metal::tryFrom(1932); // $metal_1 === Metal::Gold;\n$metal_2 = Metal::tryFrom(1000); // $metal_2 === null;\n\n$metal_3 = Metal::from(9999); // throws Exception\n interface TravelCapable\n{\n public function travelCost(int $distance): int;\n public function requiresFuel(): bool;\n}\n\nenum TransportMode: int implements TravelCapable{\n case Bicycle = 10;\n case Car = 1000 ;\n case Ship = 800 ;\n case Plane = 2000;\n case Feet = 5;\n \n public function travelCost(int $distance): int\n {\n return $this->value * $distance;\n }\n \n public function requiresFuel(): bool {\n return match($this) {\n TransportMode::Car, TransportMode::Ship, TransportMode::Plane => true,\n TransportMode::Bicycle, TransportMode::Feet => false\n }\n }\n}\n\n$mode = TransportMode::Car;\n\n$carConsumesFuel = $mode->requiresFuel(); // true\n$carTravelCost = $mode->travelCost(800); // 800000\n UnitEnum UnitEnum::cases() $modes = TransportMode::cases();\n $modes [\n TransportMode::Bicycle,\n TransportMode::Car,\n TransportMode::Ship,\n TransportMode::Plane\n TransportMode::Feet\n]\n static"
},
{
"answer_id": 68683590,
"author": "Alexander Behling",
"author_id": 9271344,
"author_profile": "https://Stackoverflow.com/users/9271344",
"pm_score": -1,
"selected": false,
"text": "class Human{\n private $gender;\n\n public function __set($key, $value){\n if($key == 'day' && !in_array($value, array('Man', 'Woman')){\n new Exception('Wrong value for '.__CLASS__.'->'.$key);\n }\n else{\n $this->$key = $value;\n }\n ...\n }\n}\n"
},
{
"answer_id": 69155570,
"author": "Kwaadpepper",
"author_id": 4355295,
"author_profile": "https://Stackoverflow.com/users/4355295",
"pm_score": 0,
"selected": false,
"text": "$enum = BasicEnum::someValue();\necho $enum->equals(BasicEnum::someValue()) ? 'true' : 'false'; // true\necho $enum->value; // 'someValue' or the value you have defined\necho $enum->label; // 'someValue' or the label you have defined\necho $enum; // 'someValue' or the value you have defined\necho json_encode($enum); // {\"label\": \"someValue\", \"value: \"someValue\" }\n /**\n * @method static self post()\n * @method static self about()\n * @method static self contact()\n */\nclass PostType extends BaseEnum\n{\n protected static function values(): array\n {\n return [\n 'post' => 0,\n 'about' => 1,\n 'contact' => 2\n ];\n }\n\n protected static function labels(): array\n {\n return [\n 'post' => 'Regular posts',\n 'about' => 'The about page',\n 'contact' => 'The contact page'\n ];\n }\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] |
254,526
|
<p>My application links against libsamplerate.a. I am doing this to make distributing the final binary easier.</p>
<p>I am worried that perhaps the code inside the .a file depends on some other libraries I also will need to distribute.</p>
<p>But if it doesn't I am worried I am bloating up my application too much by including multiple copies of eg. libc.</p>
<p>What exactly will be inside libsamplerate.a? Just libsamperate's bytecode? Or more?</p>
|
[
{
"answer_id": 254587,
"author": "Tim Robinson",
"author_id": 32133,
"author_profile": "https://Stackoverflow.com/users/32133",
"pm_score": 3,
"selected": false,
"text": "ar ar -t libsamplerate.a\n ar -r tim.a *.txt\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6444/"
] |
254,544
|
<p>What do I put in my order by?? I want to order by Name. I have moved the orderby after the distinct because I read that it needs to be done last.</p>
<pre><code> var result = (from r in db.RecordDocs
where r.RecordID == recordID
select new
{
DocTypeID = r.Document.DocType.DocTypeID,
Name = r.Document.DocType.Name,
Number = r.Document.DocType.Number
}
).Distinct().OrderBy( );
</code></pre>
|
[
{
"answer_id": 254547,
"author": "Jacob Carpenter",
"author_id": 26627,
"author_profile": "https://Stackoverflow.com/users/26627",
"pm_score": 5,
"selected": true,
"text": ".OrderBy(doc => doc.Name)\n"
},
{
"answer_id": 254624,
"author": "Jacob Carpenter",
"author_id": 26627,
"author_profile": "https://Stackoverflow.com/users/26627",
"pm_score": 2,
"selected": false,
"text": "var query = from r in db.RecordDocs\n where r.RecordID == recordID\n select new\n {\n DocTypeID = r.Document.DocType.DocTypeID,\n Name = r.Document.DocType.Name,\n Number = r.Document.DocType.Number\n };\n\nquery = query.Disctinct();\nquery = from doc in query orderby doc.Name select doc;\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
254,573
|
<p>Is there a way to use a <code>foreach</code> loop to iterate through a collection backwards or in a completely random order?</p>
|
[
{
"answer_id": 254601,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "for (int i=col.count-1; i>0; i--){ \n DoSomething ( col.item[i]) ;\n}\n collection c = originalCollection;\n while (c.count > 0) {\n int i = randomNumber(seed) mod c.count\n element d = c[i];\n c.remove(d);\n DoSomething(d);\n}\n"
},
{
"answer_id": 254604,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "as good yield return Reverse OrderBy Reverse() IEnumerable<T> yield return foreach(var myThing in myCollection.Reverse()) yield return"
},
{
"answer_id": 254605,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 4,
"selected": false,
"text": "System.Linq // List<...> list;\nforeach (var i in list.Reverse())\n{\n}\n list.OrderBy var rnd = new Random();\nvar randomlyOrdered = list.OrderBy(i => rnd.Next());\nforeach (var i in randomlyOrdered)\n{\n}\n"
},
{
"answer_id": 254664,
"author": "Jacob Carpenter",
"author_id": 26627,
"author_profile": "https://Stackoverflow.com/users/26627",
"pm_score": 5,
"selected": true,
"text": "Reverse() public static IEnumerable<T> OrderRandomly<T>(this IEnumerable<T> sequence)\n{\n Random random = new Random();\n List<T> copy = sequence.ToList();\n\n while (copy.Count > 0)\n {\n int index = random.Next(copy.Count);\n yield return copy[index];\n copy.RemoveAt(index);\n }\n}\n foreach (int n in Enumerable.Range(1, 10).OrderRandomly())\n Console.WriteLine(n);\n"
},
{
"answer_id": 254698,
"author": "Zote",
"author_id": 20683,
"author_profile": "https://Stackoverflow.com/users/20683",
"pm_score": 0,
"selected": false,
"text": "Random rand = new Random(Environment.TickCount);\n\ntest.Sort((string v1, string v2) => {\n if (v1.Equals(v2))\n {\n return 0;\n }\n\n int x = rand.Next();\n int y = rand.Next();\n\n if (x == y)\n {\n return 0;\n }\n else if (x > y)\n {\n return 1;\n }\n\n return -1; \n });\n\nfor (string item in test)\n{\n Console.WriteLn(item);\n}\n// Note that test is List<string>;\n"
},
{
"answer_id": 254783,
"author": "TheCodeJunkie",
"author_id": 25319,
"author_profile": "https://Stackoverflow.com/users/25319",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n List<int> ints = \n new List<int> { 1,2,3,4,5,6,7,8,9,10};\n\n Console.WriteLine(\"Iterating over Odd numbers only.\");\n foreach (int i in ints.Odd())\n {\n Console.WriteLine(i);\n }\n\n Console.WriteLine(\"Iterating over Even numbers only.\");\n foreach (int i in ints.Even())\n {\n Console.WriteLine(i);\n }\n\n Console.WriteLine(\"Iterating over the list in reversed order.\");\n foreach (int i in ints.Reversed())\n {\n Console.WriteLine(i);\n }\n\n Console.WriteLine(\"Iterating over the list in random order.\");\n foreach (int i in ints.Random())\n {\n Console.WriteLine(i);\n }\n\n Console.ReadLine();\n }\n }\n\n public static class ListExtensions\n {\n /// <summary>\n /// Iterates over the list only returns even numbers\n /// </summary>\n /// <param name=\"list\"></param>\n public static IEnumerable<int> Even(this List<int> list)\n {\n foreach (var i in list)\n {\n if (i % 2 == 0)\n {\n yield return i;\n }\n }\n }\n\n /// <summary>\n /// Iterates over the list only returns odd numbers\n /// </summary>\n public static IEnumerable<int> Odd(this List<int> list)\n {\n foreach (var i in list)\n {\n if (i % 2 != 0)\n {\n yield return i;\n }\n }\n }\n\n /// <summary>\n /// Iterates over the list in reversed order\n /// </summary>\n public static IEnumerable<int> Reversed(this List<int> list)\n {\n for (int i = list.Count; i >= 0; i--)\n {\n yield return i;\n }\n }\n\n /// <summary>\n /// Iterates over the list in random order\n /// </summary>\n public static IEnumerable<int> Random(this List<int> list)\n {\n // Initialize a random number generator with a seed.\n System.Random rnd =\n new Random((int)DateTime.Now.Ticks);\n\n // Create a list to keep track of which indexes we've\n // already returned\n List<int> visited =\n new List<int>();\n\n // loop until we've returned the value of all indexes\n // in the list\n while (visited.Count < list.Count)\n {\n int index =\n rnd.Next(0, list.Count);\n\n // Make sure we've not returned it already\n if (!visited.Contains(index))\n {\n visited.Add(index);\n yield return list[index];\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 254917,
"author": "TheCodeJunkie",
"author_id": 25319,
"author_profile": "https://Stackoverflow.com/users/25319",
"pm_score": 1,
"selected": false,
"text": "// Even\nforeach (var i in ints.FindAll(number => number % 2 == 0))\n{\n Console.WriteLine(i);\n}\n\n// Odd\nforeach (var i in ints.FindAll(number => number % 2 != 0))\n{\n Console.WriteLine(i);\n}\n"
},
{
"answer_id": 254947,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 1,
"selected": false,
"text": "IList<T> foreach (var i in list.Reverse())\n{\n}\n Shuffle() var listClone = (IList<T>) list.Clone();\nlistClone.Shuffle();\nforeach (var i in listClone)\n{\n}\n"
},
{
"answer_id": 308742,
"author": "Ramesh Soni",
"author_id": 191,
"author_profile": "https://Stackoverflow.com/users/191",
"pm_score": 0,
"selected": false,
"text": "List<Employee> list = new List<Employee>();\n\nlist.Add(new Employee { Id = 1, Name = \"Davolio Nancy\" });\nlist.Add(new Employee { Id = 2, Name = \"Fuller Andrew\" });\nlist.Add(new Employee { Id = 3, Name = \"Leverling Janet\" });\nlist.Add(new Employee { Id = 4, Name = \"Peacock Margaret\" });\nlist.Add(new Employee { Id = 5, Name = \"Buchanan Steven\" });\nlist.Add(new Employee { Id = 6, Name = \"Suyama Michael\" });\nlist.Add(new Employee { Id = 7, Name = \"King Robert\" });\nlist.Add(new Employee { Id = 8, Name = \"Callahan Laura\" });\nlist.Add(new Employee { Id = 9, Name = \"Dodsworth Anne\" });\n\nlist = list.OrderBy(emp => Guid.NewGuid()).ToList();\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] |
254,613
|
<p>When a web site is licensed under Creative Commons, I use the <a href="http://microformats.org/wiki/rel-license" rel="noreferrer">rel-license microformat</a>. When a web site is licensed under regular copyright, I have a boring paragraph element.</p>
<pre><code><p id="copyright">&copy; 2008 Example Corporation</p>
</code></pre>
<p>That id attribute on there is just for CSS styling purposes. I'm wondering if there's some better way to markup a copyright notice that is more semantic. Is this a job for Dublin Core metadata? If so, how do I go about it? (I've never used Dublin Core before.)</p>
<p>Some web sites advocate using a meta tag in the head element:</p>
<pre><code><meta name="copyright" content="name of owner">
</code></pre>
<p>Which might be seen by search engines, but doesn't replace the user-visible notice on the page itself.</p>
|
[
{
"answer_id": 254666,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "<dl id=\"copyright\">\n <dt title=\"Copyright\">©</dt>\n <dd>2008 Example Corporation</dd>\n</dl>\n"
},
{
"answer_id": 254710,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": false,
"text": "// RDFa recomendation and rel=license microformat\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/3.0/\">\n a Creative Commons License\n</a>\n"
},
{
"answer_id": 254836,
"author": "Scott",
"author_id": 6126,
"author_profile": "https://Stackoverflow.com/users/6126",
"pm_score": 5,
"selected": true,
"text": "<div id=\"footer\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<p id=\"copyright\" property=\"dc:rights\">©\n <span property=\"dc:dateCopyrighted\">2008</span>\n <span property=\"dc:publisher\">Example Corporation</span>\n</p>\n</div>\n <meta name=\"copyright\" content=\"© 2008 Example Corporation\" />\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6126/"
] |
254,616
|
<p>I am wondering how I can break up my index.php homepage to multiple php pages (i.e. header.php, footer.php) and build a working index.php page using those separate php pages. I know WordPress uses this with different functions like:</p>
<pre><code>GetHeader();
GetFoodter();
</code></pre>
<p>But when I tried to use those functions, it errors. I am guessing they are not native functions to PHP.</p>
<p>What would I need to do to get this functionality?</p>
|
[
{
"answer_id": 254622,
"author": "Scott",
"author_id": 6126,
"author_profile": "https://Stackoverflow.com/users/6126",
"pm_score": 4,
"selected": true,
"text": "include 'header.php';\n\ninclude 'footer.php';\n"
},
{
"answer_id": 254626,
"author": "Tigraine",
"author_id": 21699,
"author_profile": "https://Stackoverflow.com/users/21699",
"pm_score": -1,
"selected": false,
"text": "include '[filename]'\n"
},
{
"answer_id": 254629,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 1,
"selected": false,
"text": "<?php\n include('header.php');\n // Template Processing Code\n include('footer.php');\n?>\n"
},
{
"answer_id": 254659,
"author": "belunch",
"author_id": 32867,
"author_profile": "https://Stackoverflow.com/users/32867",
"pm_score": 1,
"selected": false,
"text": "<?php\ninclude(\"1.php\"); include(\"2.php\"); include(\"3.php\");\n?>\n"
},
{
"answer_id": 395736,
"author": "EroSan",
"author_id": 48540,
"author_profile": "https://Stackoverflow.com/users/48540",
"pm_score": 1,
"selected": false,
"text": "<?php\nrequire('filename');\n?>\n"
},
{
"answer_id": 1982094,
"author": "AgentConundrum",
"author_id": 1588,
"author_profile": "https://Stackoverflow.com/users/1588",
"pm_score": 0,
"selected": false,
"text": "include 'file.php'; 'header.php' 'footer.php' 'menu.php'"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33194/"
] |
254,639
|
<p>currently i have jdbc code with the following basic stucture:</p>
<p>get Connection</p>
<p>(do the next 4 lines several times, never closing statement)<br>
get statement<br>
get result set<br>
process result set<br>
close result set </p>
<p>close connection </p>
<p>It occurred to me after writing this code that i need to close the statement.<br>
1 what are the effects of not closing the statement.<br>
2 will the following work, this si will closing the statement prevent me from processing the result set as normal?</p>
<p>get Connection</p>
<p>(do the next 5 lines several times)<br>
get statement<br>
get result set<br>
close statement<br>
process result set<br>
close result set </p>
<p>close connection</p>
|
[
{
"answer_id": 279101,
"author": "asalamon74",
"author_id": 21348,
"author_profile": "https://Stackoverflow.com/users/21348",
"pm_score": 1,
"selected": false,
"text": "ORA-01000: maximum open cursors exceeded\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] |
254,669
|
<p>I've been working with some C# legacy code and I've been seeing a lot of @ symbols in front of variable names. What does this signify or do?</p>
<p>Currently I'm seeing it a lot in front of variables with common names that aren't reserved. E.g.:</p>
<pre><code>MyProcedure(@step.LoadInstanceId, @step.ResultCode, @step.StatusCode);
</code></pre>
<p>Given that step isn't a reserved word, is there any reason that they should be escaped?</p>
|
[
{
"answer_id": 254674,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 9,
"selected": true,
"text": "void Foo(int @string)\n"
},
{
"answer_id": 254683,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "string @public = \"foo\";\n"
},
{
"answer_id": 254684,
"author": "Gabe Hollombe",
"author_id": 30632,
"author_profile": "https://Stackoverflow.com/users/30632",
"pm_score": 4,
"selected": false,
"text": "@\"c:\\Docs\\Source\\a.txt\" // rather than \"c:\\\\Docs\\\\Source\\\\a.txt\"\n @\"\"\"Ahoy!\"\" cried the captain.\" // \"Ahoy!\" cried the captain.\n"
},
{
"answer_id": 8575886,
"author": "mklein",
"author_id": 487371,
"author_profile": "https://Stackoverflow.com/users/487371",
"pm_score": 2,
"selected": false,
"text": "step"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7756/"
] |
254,673
|
<p>I have an abstract base class which acts as an interface.</p>
<p>I have two "sets" of derived classes, which implement half of the abstract class. ( one "set" defines the abstract virtual methods related to initialization, the other "set" defines those related to the actual "work". )</p>
<p>I then have derived classes which use multiple inheritance to construct fully defined classes ( and does not add anything itself ).</p>
<p>So: ( bad pseudocode )</p>
<pre><code>class AbsBase {
virtual void init() = 0;
virtual void work() = 0;
}
class AbsInit : public AbsBase {
void init() { do_this(); }
// work() still abs
}
class AbsWork : public AbsBase {
void work() { do_this(); }
// init() still abs
}
class NotAbsTotal : public AbsInit, public AbsWork {
// Nothing, both should be defined
}
</code></pre>
<p>First of all, can I do this? Can I inherit from two classes which are both derived from the same Base? (I hope so).</p>
<p>Here is the "real problem", though (I lied a bit above to simplify the example).</p>
<p>What I have really gone and done is add non abstract accessors methods to the base class:</p>
<pre><code>class AbsBase {
public:
void init() { init_impl(); }
void work() { work_impl(); }
private:
virtual void init_impl() = 0;
virtual void work_impl() = 0;
}
</code></pre>
<p>Because, a common idiom is to make all virtual methods private.</p>
<p>Unfortunately, now both AbsInit, and AbsWork inherit these methods, and so NotAbsTotal inherits "two of each" ( I realize I may be butchering what is really happening at compile time ).</p>
<p>Anyway, g++ complains that: "request for member init() is ambiguous" when trying to use the class.</p>
<p>I assume that, had I used my AbsBase class as a pure interface, this would have been avoided ( assuming that the top example is valid ).</p>
<p>So:
- Am I way off with my implementation?
- Is this a limitation of the idiom of making virtual methods private?
- How do I refactor my code to do what I want? ( Provide one common interface, but allow a way to swap out implementations for "sets" of member functions )</p>
<p>Edit:</p>
<p>Seems I am not the first one:
<a href="http://en.wikipedia.org/wiki/Diamond_problem" rel="noreferrer">http://en.wikipedia.org/wiki/Diamond_problem</a></p>
<p>Seems Virtual Inheritance is the solution here. I have heard of virtual inheritance before, but I have not wrapped my head around it. I am still open to suggestions.</p>
|
[
{
"answer_id": 254696,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "class AbsInit: public virtual AbsBase {...};\nclass AbsWork: public virtual AbsBase {...};\nclass NotAbsTotal: public AbsInit, public AbsWork {...};\n NotAbsTotal::work()\n{\n AbsInit::work_impl();\n}\n"
},
{
"answer_id": 254704,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 1,
"selected": false,
"text": "struct AbsBase {\n virtual void init() = 0;\n virtual void work() = 0;\n};\n\nstruct AbsInit : virtual public AbsBase {\n void init() { }\n};\n\nstruct AbsWork : virtual public AbsBase {\n void work() { }\n};\n\nstruct NotAbsTotal : virtual public AbsInit, virtual public AbsWork {\n};\n\nvoid f(NotAbsTotal *p)\n{\n p->init();\n}\n\nNotAbsTotal x;\n"
},
{
"answer_id": 254713,
"author": "comingstorm",
"author_id": 210211,
"author_profile": "https://Stackoverflow.com/users/210211",
"pm_score": 6,
"selected": true,
"text": "\nclass AbsBase {...};\nclass AbsInit: public virtual AbsBase {...};\nclass AbsWork: public virtual AbsBase {...};\nclass NotAbsTotal: public AbsInit, public AbsWork {...};\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29701/"
] |
254,694
|
<p>I see little functional difference between using a property</p>
<pre><code>public readonly property foo as string
get
return bar
end get
end property
</code></pre>
<p>or a function</p>
<pre><code>public function foo() as string
return bar
end function
</code></pre>
<p>Why would I want to use one form over the other?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 254707,
"author": "Corey Gaudin",
"author_id": 31195,
"author_profile": "https://Stackoverflow.com/users/31195",
"pm_score": 1,
"selected": false,
"text": "person.Address.Street;\n person.Address().Street();\n ()"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736623/"
] |
254,695
|
<p>I have a login page where I authenticate the user. When the authentication pass, I then redirect the user to another page via Response.Redirect with the url defined in login control's destinationpageurl.</p>
<p>It work fine in firefox but when i test it with IE. It just redirect the user back to the login page.</p>
<p>does anyone know what's going on here?</p>
|
[
{
"answer_id": 254707,
"author": "Corey Gaudin",
"author_id": 31195,
"author_profile": "https://Stackoverflow.com/users/31195",
"pm_score": 1,
"selected": false,
"text": "person.Address.Street;\n person.Address().Street();\n ()"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
254,697
|
<p>I'm running a PL/SQL block that is supposed to be calling a stored procedure who's output parameters are supposed to be populating variables in the PL/SQL block.</p>
<p>The procedure compiles, and the PL/SQL block runs successfully. But I'd like to check the values of the variables populated by the procedure. Is there a way to output these values?</p>
<p>I'm using Free TOAD if that helps. </p>
<p>Thanks,</p>
|
[
{
"answer_id": 254727,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "dbms_output.put_line(varHere);\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
254,712
|
<p>Can I somehow disable spell-checking on HTML textfields (as seen in e.g. Safari)?</p>
|
[
{
"answer_id": 254716,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 10,
"selected": true,
"text": "<tag autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\"/>\n"
},
{
"answer_id": 1245570,
"author": "Ms2ger",
"author_id": 33466,
"author_profile": "https://Stackoverflow.com/users/33466",
"pm_score": 8,
"selected": false,
"text": "spellcheck=\"false\" <textarea spellcheck=\"false\">\n ...\n</textarea>\n"
},
{
"answer_id": 50301368,
"author": "sensor",
"author_id": 567897,
"author_profile": "https://Stackoverflow.com/users/567897",
"pm_score": 4,
"selected": false,
"text": "<textarea data-gramm=\"false\" />\n"
},
{
"answer_id": 53021984,
"author": "Artur INTECH",
"author_id": 2987689,
"author_profile": "https://Stackoverflow.com/users/2987689",
"pm_score": 2,
"selected": false,
"text": "textarea input[type=text] (function () {\n function disableSpellCheck() {\n let selector = 'input[type=text], textarea';\n let textFields = document.querySelectorAll(selector);\n\n textFields.forEach(\n function (field, _currentIndex, _listObj) {\n field.spellcheck = false;\n }\n );\n }\n\n disableSpellCheck();\n})();\n"
},
{
"answer_id": 64810105,
"author": "Mac",
"author_id": 2158270,
"author_profile": "https://Stackoverflow.com/users/2158270",
"pm_score": 1,
"selected": false,
"text": "<textarea id=\"my-ta\" spellcheck=\"whatever\">abcd dcba</textarea>\n function setSpellCheck( mode ) {\n var myTextArea = document.getElementById( \"my-ta\" )\n , myTextAreaValue = myTextArea.value\n ;\n myTextArea.value = '';\n myTextArea.setAttribute( \"spellcheck\", String( mode ) );\n myTextArea.value = myTextAreaValue;\n myTextArea.focus();\n}\n setSpellCheck( true );\nsetSpellCheck( 'false' );\n"
},
{
"answer_id": 66101648,
"author": "Fom",
"author_id": 6151750,
"author_profile": "https://Stackoverflow.com/users/6151750",
"pm_score": 0,
"selected": false,
"text": "elem.contentEditable false \"false\" elem.spellcheck elem.spellcheck = false;\n elem.setAttribute(\"spellcheck\", \"false\"); // Both string and boolean work here. \n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136/"
] |
254,719
|
<p>I'm <em>extremely new</em> to Java, and have mostly just been teaching myself as I go, so I've started building an applet. I'd like to make one that can select a file from the local disk and upload it as a multipart/form-data POST request but <strong>with a progress bar</strong>. Obviously the user has to grant permission to the Java applet to access the hard drive. Now I've already got the first part working: the user can select a file using a <code>JFileChooser</code> object, which conveniently returns a <code>File</code> object. But I'm wondering what comes next. I know that <code>File.length()</code> will give me the total size in bytes of the file, but how do I send the selected <code>File</code> to the web, and how do I monitor how many bytes have been sent? Thanks in advance.</p>
|
[
{
"answer_id": 255079,
"author": "el_eduardo",
"author_id": 13469,
"author_profile": "https://Stackoverflow.com/users/13469",
"pm_score": 2,
"selected": false,
"text": "\nDiskFileUpload upload = new DiskFileUpload();\nupload.setHeaderEncoding(ConsoleConstants.UTF8_ENCODING);\n\nupload.setSizeMax(1000000);\nupload.setSizeThreshold(1000000);\n\nIterator it = upload.parseRequest((HttpServletRequest) request).iterator();\nFileItem item;\nwhile(it.hasNext()){\n item = (FileItem) it.next();\n if (item.getFieldName(\"UPLOAD FIELD\"){\n String fileName = item.getString(ConsoleConstants.UTF8_ENCODING);\n byte[] fileBytes = item.get();\n }\n}\n"
},
{
"answer_id": 470047,
"author": "tuler",
"author_id": 54623,
"author_profile": "https://Stackoverflow.com/users/54623",
"pm_score": 5,
"selected": false,
"text": "import java.io.FilterOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport org.apache.commons.httpclient.methods.RequestEntity;\n\npublic class CountingMultipartRequestEntity implements RequestEntity {\n private final RequestEntity delegate;\n\n private final ProgressListener listener;\n\n public CountingMultipartRequestEntity(final RequestEntity entity,\n final ProgressListener listener) {\n super();\n this.delegate = entity;\n this.listener = listener;\n }\n\n public long getContentLength() {\n return this.delegate.getContentLength();\n }\n\n public String getContentType() {\n return this.delegate.getContentType();\n }\n\n public boolean isRepeatable() {\n return this.delegate.isRepeatable();\n }\n\n public void writeRequest(final OutputStream out) throws IOException {\n this.delegate.writeRequest(new CountingOutputStream(out, this.listener));\n }\n\n public static interface ProgressListener {\n void transferred(long num);\n }\n\n public static class CountingOutputStream extends FilterOutputStream {\n\n private final ProgressListener listener;\n\n private long transferred;\n\n public CountingOutputStream(final OutputStream out,\n final ProgressListener listener) {\n super(out);\n this.listener = listener;\n this.transferred = 0;\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n out.write(b, off, len);\n this.transferred += len;\n this.listener.transferred(this.transferred);\n }\n\n public void write(int b) throws IOException {\n out.write(b);\n this.transferred++;\n this.listener.transferred(this.transferred);\n }\n }\n}\n"
},
{
"answer_id": 3154929,
"author": "Hamy",
"author_id": 119592,
"author_profile": "https://Stackoverflow.com/users/119592",
"pm_score": 2,
"selected": false,
"text": "CountingOutputStream MultipartEntity import java.io.FilterOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\n\nimport org.apache.http.entity.mime.HttpMultipartMode;\nimport org.apache.http.entity.mime.MultipartEntity;\n\npublic class CountingMultiPartEntity extends MultipartEntity {\n\n private UploadProgressListener listener_;\n private CountingOutputStream outputStream_;\n private OutputStream lastOutputStream_;\n\n // the parameter is the same as the ProgressListener class in tuler's answer\n public CountingMultiPartEntity(UploadProgressListener listener) {\n super(HttpMultipartMode.BROWSER_COMPATIBLE);\n listener_ = listener;\n }\n\n @Override\n public void writeTo(OutputStream out) throws IOException {\n // If we have yet to create the CountingOutputStream, or the\n // OutputStream being passed in is different from the OutputStream used\n // to create the current CountingOutputStream\n if ((lastOutputStream_ == null) || (lastOutputStream_ != out)) {\n lastOutputStream_ = out;\n outputStream_ = new CountingOutputStream(out);\n }\n\n super.writeTo(outputStream_);\n }\n\n private class CountingOutputStream extends FilterOutputStream {\n\n private long transferred = 0;\n private OutputStream wrappedOutputStream_;\n\n public CountingOutputStream(final OutputStream out) {\n super(out);\n wrappedOutputStream_ = out;\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n wrappedOutputStream_.write(b,off,len);\n ++transferred;\n listener_.transferred(transferred);\n }\n\n public void write(int b) throws IOException {\n super.write(b);\n }\n }\n}\n"
},
{
"answer_id": 7319110,
"author": "ankostis",
"author_id": 548792,
"author_profile": "https://Stackoverflow.com/users/548792",
"pm_score": 4,
"selected": false,
"text": "HttpEntityWrapped package gr.phaistos.android.util;\n\nimport java.io.FilterOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\n\nimport org.apache.http.HttpEntity;\nimport org.apache.http.entity.HttpEntityWrapper;\n\npublic class CountingHttpEntity extends HttpEntityWrapper {\n\n public static interface ProgressListener {\n void transferred(long transferedBytes);\n }\n\n\n static class CountingOutputStream extends FilterOutputStream {\n\n private final ProgressListener listener;\n private long transferred;\n\n CountingOutputStream(final OutputStream out, final ProgressListener listener) {\n super(out);\n this.listener = listener;\n this.transferred = 0;\n }\n\n @Override\n public void write(final byte[] b, final int off, final int len) throws IOException {\n //// NO, double-counting, as super.write(byte[], int, int) delegates to write(int).\n //super.write(b, off, len);\n out.write(b, off, len);\n this.transferred += len;\n this.listener.transferred(this.transferred);\n }\n\n @Override\n public void write(final int b) throws IOException {\n out.write(b);\n this.transferred++;\n this.listener.transferred(this.transferred);\n }\n\n }\n\n\n private final ProgressListener listener;\n\n public CountingHttpEntity(final HttpEntity entity, final ProgressListener listener) {\n super(entity);\n this.listener = listener;\n }\n\n @Override\n public void writeTo(final OutputStream out) throws IOException {\n this.wrappedEntity.writeTo(out instanceof CountingOutputStream? out: new CountingOutputStream(out, this.listener));\n }\n}\n"
},
{
"answer_id": 10330512,
"author": "douggynix",
"author_id": 1358259,
"author_profile": "https://Stackoverflow.com/users/1358259",
"pm_score": 3,
"selected": false,
"text": "transferred++ transferred=len ContentLength CountingMultiPartEntity.this.getContentLength(); public void write(byte[] b, int off, int len) throws IOException {\n wrappedOutputStream_.write(b,off,len);\n transferred=len;\n listener_.transferred(transferred);\n}\n"
},
{
"answer_id": 36385256,
"author": "user3502626",
"author_id": 3502626,
"author_profile": "https://Stackoverflow.com/users/3502626",
"pm_score": 1,
"selected": false,
"text": "AbstractHttpEntity public void writeTo(OutputStream outstream) FileEntity FileEntity fileEntity = new FileEntity(new File(\"img.jpg\")){\n @Override\n public void writeTo(OutputStream outstream) throws IOException {\n super.writeTo(new BufferedOutputStream(outstream){\n int writedBytes = 0;\n\n @Override\n public synchronized void write(byte[] b, int off, int len) throws IOException {\n super.write(b, off, len);\n\n writedBytes+=len;\n System.out.println(\"wrote: \"+writedBytes+\"/\"+getContentLength()); //Or anything you want [using other threads]\n }\n });\n }\n\n};\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5454/"
] |
254,726
|
<p>I've been told that code such as:</p>
<pre><code>for (int i = 0; i < x.length(); i++) {
// blah
}
</code></pre>
<p>is actually O(n^2) because of the repeated calls to <code>x.length()</code>. Instead I should use:</p>
<pre><code>int l = x.length();
for (int i = 0; i < l; i++) {
// blah
}
</code></pre>
<p>Is this true? Is string length stored as a private integer attribute of the String class? Or does <code>String.length()</code> really walk the whole string just to determine its length?</p>
|
[
{
"answer_id": 254742,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 0,
"selected": false,
"text": "String#length #length()"
},
{
"answer_id": 255307,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 4,
"selected": false,
"text": "String.length() String String.length String.length()"
},
{
"answer_id": 255412,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 2,
"selected": false,
"text": "length()"
},
{
"answer_id": 255471,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 3,
"selected": false,
"text": "for (int i = 0, l = x.length(); i < l; i++) {\n // Blah\n}\n l"
},
{
"answer_id": 69908415,
"author": "Revanth Reddy Datla",
"author_id": 17373861,
"author_profile": "https://Stackoverflow.com/users/17373861",
"pm_score": 0,
"selected": false,
"text": "public int length() {\n return value.length >> coder();\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8913/"
] |
254,732
|
<p>Is it possible to determine whether my web site is being accessed as a trusted site? In <a href="https://stackoverflow.com/questions/251696/best-way-to-readset-ie-options">another question</a> we determined that, in general, it is not prudent to have visibility to client IE settings. Would this qualify as an exception?</p>
<p>The reason I'd like to do this is that some functions won't work unless the site is being accessed as a trusted site (e.g. client-side sendmail -- don't ask), and I'd like to be able to warn users. Despite many warnings in the pages, many users still don't read, and send us nastygrams. We'd like to reduce the email volume by detecting this condition and flashing a big warning that basically says "<strong>You didn't read the warnings, and what you're trying to do won't work until you change your settings!</strong>" Any ideas are welcome.</p>
<p>EDIT: In our shop, client-side sendmail only works if the site is trusted, and I can't change that due to security requirements, nor can I switch to server-side sendmail. However, this is not the only reason that client-side sendmail will fail, so I can't simply catch a sendmail error to determine this. Also, I don't want this to degrade to a sendmail discussion.</p>
|
[
{
"answer_id": 254913,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 2,
"selected": false,
"text": "function isTrustedIE(){\n try{\n var test=new ActiveXObject(\"Scripting.FileSystemObject\");\n }\n catch(e){\n return false;\n }\n\n return true;\n}\n"
},
{
"answer_id": 259736,
"author": "luiscubal",
"author_id": 32775,
"author_profile": "https://Stackoverflow.com/users/32775",
"pm_score": 0,
"selected": false,
"text": "a.innerHTML = \"abc\"; \n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26671/"
] |
254,733
|
<p>The vast majority of applications does not handle "disk full" scenarios properly. </p>
<p>Example: an installer doesn't see that the disk is full, ignores all errors, and finally happily announces "installation complete!", or an email program is unaware that the message it has just downloaded could not be saved, and tells the server to delete the original.</p>
<p>What techniques are there to handle this situation gracefully? Do you use them? Do you test them?</p>
|
[
{
"answer_id": 275261,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 4,
"selected": true,
"text": "#2"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31615/"
] |
254,737
|
<p>In JSP I can reference a bean's property by using the tag
${object.property}</p>
<p>Is there some way to deal with properties that might not exist? I have a JSP page that needs to deal with different types. Example:</p>
<pre><code>public class Person {
public String getName()
}
public class Employee extends Person {
public float getSalary()
}
</code></pre>
<p>In JSP I want to display a table of people with columns of name and salary. If the person is not an employee then salary should be blank. The row HTML might look like:</p>
<pre><code><tr>
<td><c:out value="${person.name}"></td>
<td><c:out value="${person.salary}"></td>
</tr>
</code></pre>
<p>Unfortunately if person is not an employee then it can't find salary and an error occurs. How would I solve this in JSP?</p>
<p>Edit: Is there an <strong>instanceof</strong> check in JSP tag language?</p>
|
[
{
"answer_id": 254769,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "public class Person {\n public String getType() { return \"Person\"; }\n public String getName()\n}\npublic class Employee extends Person {\n public String getType() { return \"Employee\"; }\n public float getSalary()\n}\n <tr>\n <td><c:out value=\"${person.name}\"></td>\n <td><c:if test=\"'Employee' eq person.type\"><c:out value=\"${person.salary}\"></c:if></td>\n</tr>\n <tr>\n <td><c:out value=\"${person.name}\"></td>\n <td><c:if test=\"'Employee' eq person.class.simpleName\"><c:out value=\"${person.salary}\"></c:if></td>\n</tr>\n"
},
{
"answer_id": 254781,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "Person Employee JSP Employee <% \n String salary\n if (person instanceof Employee) {\n salary = person.salary\n } else {\n salary = \"\" // or ' '\n }\n%>\n<td><c:out value=\"${salary}\"></td>\n"
},
{
"answer_id": 254795,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 4,
"selected": true,
"text": "<c:catch var=\"err\">\n <c:out value=\"${employee.salary}\"/>\n</c:catch>\n"
},
{
"answer_id": 254955,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 2,
"selected": false,
"text": "${person.class} ${person.class.name eq 'my.package.PersonClass'} <c:out value='${person.salary}' default=\"Null Value\" />\n"
},
{
"answer_id": 356082,
"author": "Adeel Ansari",
"author_id": 42769,
"author_profile": "https://Stackoverflow.com/users/42769",
"pm_score": 2,
"selected": false,
"text": "<tr>\n <td>${person.name}</td> \n <td>${person.class.simpleName == 'Employee' ? person.salary : ''}</td>\n</tr>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
254,753
|
<p>What format do I use for Date/Time when writing to an XML file using .NET? Do I simply use <code>DateTime.ToString()</code>, or do I have to use a specific format?</p>
|
[
{
"answer_id": 254768,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 6,
"selected": false,
"text": "dateTime.ToUniversalTime().ToString(\"s\");\n <xs:element name=\"startdate\" type=\"xs:dateTime\"/>\n <startdate>2002-05-30T09:00:00</startdate>\n"
},
{
"answer_id": 254782,
"author": "chilltemp",
"author_id": 28736,
"author_profile": "https://Stackoverflow.com/users/28736",
"pm_score": 3,
"selected": false,
"text": "var.ToUniversalTime().ToString(\"yyyy-MM-dd'T'HH:mm:ss.fffffffZ\"));"
},
{
"answer_id": 254803,
"author": "Ryan",
"author_id": 29762,
"author_profile": "https://Stackoverflow.com/users/29762",
"pm_score": 8,
"selected": true,
"text": "2008-10-31T15:07:38.6875000-05:00 date.ToString(\"o\") date.ToString(\"yyyy-MM-dd HH:mm:ss\");"
},
{
"answer_id": 25543786,
"author": "Starnuto di topo",
"author_id": 1288109,
"author_profile": "https://Stackoverflow.com/users/1288109",
"pm_score": 0,
"selected": false,
"text": "XmlConvert"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27414/"
] |
254,765
|
<p>How can I detect whether or not an input box is currently a jQuery UI autocomplete? There doesn't seem to be a native method for this, but I'm hoping there is something simple like this:</p>
<pre><code>if ($("#q").autocomplete)
{
//Do something
}
</code></pre>
<p>That conditional, however, seems to always return true.</p>
|
[
{
"answer_id": 255115,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 5,
"selected": true,
"text": "if ($(\"#q\").hasClass(\"ac_input\")) {\n // do something\n}\n if ($(\"#q\").hasClass(\"ui-autocomplete-input\")) {\n // do something\n}\n"
},
{
"answer_id": 2713570,
"author": "CreativeNotice",
"author_id": 241633,
"author_profile": "https://Stackoverflow.com/users/241633",
"pm_score": 2,
"selected": false,
"text": "if( $.isFunction( $.fn.autocomplete ) ){ }\n"
},
{
"answer_id": 6370280,
"author": "Matloob Ali",
"author_id": 373624,
"author_profile": "https://Stackoverflow.com/users/373624",
"pm_score": 3,
"selected": false,
"text": "if ($('Selector').data('autocomplete')) {\n}\n"
},
{
"answer_id": 46068669,
"author": "Robin",
"author_id": 416740,
"author_profile": "https://Stackoverflow.com/users/416740",
"pm_score": 3,
"selected": false,
"text": "if ($(\"#q\").autocomplete(\"instance\")) {\n console.log(\"autocomplete already setup for #q\");\n} else {\n console.log(\"NO autocomplete for #q\");\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] |
254,784
|
<p>I have two objects, let's call them <strong><code>Input</code></strong> and <strong><code>Output</code></strong></p>
<p><strong><code>Input</code></strong> has properties <em><code>Input_ID</code></em>, <em><code>Label</code></em>, and <em><code>Input_Amt</code></em><br>
<strong><code>Output</code></strong> has properties <em><code>Output_ID</code></em> and <em><code>Output_Amt</code></em></p>
<p>I want to perform the equivalent SQL statement in LINQ:</p>
<pre><code>SELECT Label, Sum(Added_Amount) as Amount FROM
(SELECT I.Label, I.Input_Amt + ISNULL(O.Output_Amt, 0) as Added_Amount
FROM Input I LEFT OUTER JOIN Output O ON I.Input_ID = O.Output_ID)
GROUP BY Label
</code></pre>
<p>For the inner query, I'm writing something like:</p>
<pre><code>var InnerQuery = from i in input
join o in output
on i.Input_ID equals o.Output_ID into joined
from leftjoin in joined.DefaultIfEmpty()
select new
{
Label = i.Label,
AddedAmount = (i.Input_Amt + leftjoin.Output_Amt)
};
</code></pre>
<p>In testing, however, the statement returns null. What gives? </p>
<p>Also, how can I continue the desired query and perform the group after I've added my amounts together, all within a single LINQ statement?</p>
|
[
{
"answer_id": 254908,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "var InnerQuery = from i in input\n join o in output\n on i.Input_ID equals o.Output_ID into joined\n from leftjoin in joined.DefaultIfEmpty()\n select new\n {\n Label = i.Label,\n AddedAmount = (i.Input_Amt + (leftjoin == null ? 0 : leftjoin.Output_Amt))\n };\n"
},
{
"answer_id": 603490,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "var labelsAndAmounts = input\n .GroupJoin\n (\n output,\n i => i.InputId,\n o => o.OutputId,\n (i, os) => new\n {\n i,\n oAmount = os.Any() ? os.Select(o => o.OutputAmt).Sum() : 0\n }\n )\n .GroupBy(x => x.i.Label)\n .Select(g => new\n {\n Label = g.Key,\n Amount = g.Select(x => x.i.InputAmt + x.oAmount).Sum()\n }\n );\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373/"
] |
254,809
|
<p>The following code fails at runtime…</p>
<pre>
Dim Id As Guid = CType(e.CommandArgument, Guid)
</pre>
<p>It throws this exception…</p>
<pre>
System.InvalidCastException was unhandled by user code
Specified cast is not valid
</pre>
<p>Why can't I cast <strong><em>e.CommandArgument</em></strong> as a Guid?</p>
|
[
{
"answer_id": 254826,
"author": "Jonathan S.",
"author_id": 2034,
"author_profile": "https://Stackoverflow.com/users/2034",
"pm_score": 3,
"selected": true,
"text": "Dim DeleteId As Guid = New Guid(Convert.ToString(e.CommandArgument))\n"
},
{
"answer_id": 254847,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": " Guid DeleteId new Guid(e.CommandArgument);\n Dim DeleteId As Guid = New Guid(e.CommandArgument);\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
254,810
|
<p>I have a .Net CF 2.0 application and am using log4net to log errors. I get a stack trace, but it doesn't have any line numbers. I noticed that it doesn't appear to deploy the pdb file to the device, so I tried to manually place it in the same directory as the exe. But that didn't help.</p>
|
[
{
"answer_id": 254906,
"author": "Oscar Cabrero",
"author_id": 14440,
"author_profile": "https://Stackoverflow.com/users/14440",
"pm_score": 0,
"selected": false,
"text": "try {\n //code..\n\n }\n catch\n { \n throw;\n }\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30469/"
] |
254,811
|
<p>My app crashes when I do the following in the applicationDidFinishLaunching event in the app delegate:</p>
<pre><code>_textures[mytex] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"a.png"]];
</code></pre>
<p>However when I replace <code>@"a.png"</code> with</p>
<pre><code>@"/Users/MyUserName/Desktop/MyProjectFolder/a.png"
</code></pre>
<p>everything works fine. I've experimented with the relative path stuff for the <code>a.png</code> resource... but none of it has worked. How can I fix this? I'd like to just say <code>@"a.png"</code> for all the image resources (esp. since I did this in another app... where I was working directly with sample code).</p>
<p>So what is that magical setting?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 255209,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 4,
"selected": true,
"text": "+[UIImage imageNamed:] a.png"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
] |
254,821
|
<p>I want to be able to load a serialized xml class to a Soap Envelope. I am starting so I am not filling the innards so it appears like:
<br /> </p>
<pre><code><Envelope
xmlns="http://schemas.xmlsoap.org/soap/envelope/" />
</code></pre>
<p>I want it to appear like: <br/></p>
<pre><code><Envelope
xmlns="http://schemas.xmlsoap.org/soap/envelope/" ></Envelope>`
</code></pre>
<p><br /></p>
<p>The class I wrote is this:
<br/></p>
<pre><code>[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/",ElementName="Envelope", IsNullable = true)]
public class TestXmlEnvelope
{
[System.Xml.Serialization.XmlElement(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public System.Collections.ArrayList Body = new System.Collections.ArrayList();
} //class TestXmlEnvelope`
</code></pre>
<p>I am using this as an example since other people might want it in an individual element. I am sure this must be simple but sadly I don't know the right keyword for this.</p>
<p>As always thanks for your help.</p>
<p>[Edit] The error comes when I try to use this instruction</p>
<pre><code>System.Xml.Serialization.XmlSerializer xmlout = new System.Xml.Serialization.XmlSerializer(typeof(TestXmlEnvelope));
System.IO.MemoryStream memOut = new System.IO.MemoryStream();
xmlout.Serialize(memOut, envelope, namespc);
Microsoft.Web.Services.SoapEnvelope soapEnv = new Microsoft.Web.Services.SoapEnvelope();
soapEnv.Load(memOut);
</code></pre>
<p>It gives me error "Root Element not found". </p>
<p>[Edit] I fixed the error the problem was that after I serialized the object I didn't set the memOut.Position = 0. Still I hope this question helps other people that may want to do this.</p>
|
[
{
"answer_id": 254894,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 5,
"selected": true,
"text": "XmlSerializer WriteEndElement() XmlWriter <tag/> WriteFullEndElement() XmlTextWriter serializer XmlSerializer public class XmlTextWriterFull : XmlTextWriter\n{\n public XmlTextWriterFull(TextWriter sink) : base(sink) { }\n\n public override void WriteEndElement()\n {\n base.WriteFullEndElement();\n }\n}\n\n...\n\nvar writer = new XmlTextWriterFull(innerwriter);\nserializer.Serialize(writer, obj);\n public XmlTextWriterFull(Stream stream, Encoding enc) : base(stream, enc) { }\npublic XmlTextWriterFull(String str, Encoding enc) : base(str, enc) { }\n System.IO.MemoryStream memOut = new System.IO.MemoryStream();\nXmlTextWriterFull writer = new XmlTextWriterFull(memOut, Encoding.UTF8Encoding); //Or the encoding of your choice\nxmlout.Serialize(writer, envelope, namespc);\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12924/"
] |
254,823
|
<p>I've got a form that's a few pages long. To traverse the form all I'm doing is showing and hiding container divs. The last page is a confirmation page before submitting. It takes the contents of the form and lays it out so the user can see what he/she just filled out. If they click on one of these it'll take them back to the page they were on (#nav1~3), focus on that field, and let them type in a new value if they need to.</p>
<p>Using jQuery, I made variables for EVERY field/radio/check/select/textarea/whatever. If my method seems silly please pwn me but basically, and this method works ok already, but I'm trying to <strong>scale</strong> it and I don't have any idea how because I don't really know what I'm doing. Thoughts?</p>
<pre>
var field1 = '<a href="#"
onclick="$(\'#nav1\').click();$(\'input#field-1\').focus();"
title="Click to edit">' +
$('input#field-1').val() + '</a>';
$('#field1-confirm').html(field1);
var field2 = '<a href="#"
onclick="$(\'#nav1\').click();$(\'input#field-2\').focus();"
title="Click to edit">' +
$('input#field-2').val() + '</a>';
$('#field2-confirm').html(field2);
</pre>
<p>And so on, with field3, 4, 5 ~ 25, etc.</p>
<p>If you could help out explaining in non-programmer terms, I'd love you forever.</p>
|
[
{
"answer_id": 254865,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 3,
"selected": true,
"text": "function valField(fieldName,navName) {\n var output = '<a href=\"javascript://\" onclick=\"$(\\''+navName+'\\').click();$(\\'input#'+fieldName+'\\').focus();\" title=\"Click to edit\">' + $('input#'+fieldName).val() + '</a>';\n $('#'+fieldName+'-confirm').html(output);\n}\n\nvalField(\"field-1\",\"nav1\")\nvalField(\"field-2\",\"nav1\")\nvalField(\"field-293\",\"nav3\")\n $(\\''+navName+'\\').click();\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
254,844
|
<p>I was reading an article on MSDN Magazine about using the <a href="http://msdn.microsoft.com/en-us/magazine/cc700332.aspx" rel="noreferrer">Enumerable class in LINQ</a> to generate a random array. The article uses VB.NET and I'm not immediately sure what the equivalent is in C#:</p>
<pre><code>Dim rnd As New System.Random()
Dim numbers = Enumerable.Range(1, 100). _
OrderBy(Function() rnd.Next)
</code></pre>
|
[
{
"answer_id": 254860,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "Random rnd = new Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());\n"
},
{
"answer_id": 254861,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 5,
"selected": true,
"text": "System.Random rnd = new System.Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());\n"
},
{
"answer_id": 254875,
"author": "Adam Alexander",
"author_id": 33164,
"author_profile": "https://Stackoverflow.com/users/33164",
"pm_score": 1,
"selected": false,
"text": "System.Random rnd = New System.Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(rnd => rnd.Next);\n"
},
{
"answer_id": 254919,
"author": "Daniel Plaisted",
"author_id": 1509,
"author_profile": "https://Stackoverflow.com/users/1509",
"pm_score": 3,
"selected": false,
"text": "int timesCalled = 0;\nRandom rnd = new Random();\n\nList<int> numbers = Enumerable.Range(1, 100).OrderBy(r =>\n {\n timesCalled++;\n return rnd.Next();\n }\n).ToList();\n\nAssert.AreEqual(timesCalled, 100);\n"
},
{
"answer_id": 254957,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 1,
"selected": false,
"text": "Shuffle() IList<int> numbers = new ArrayList<int>(Enumerable.Range(1,100));\nnumbers.Shuffle();\n"
},
{
"answer_id": 3189638,
"author": "FouZ",
"author_id": 300141,
"author_profile": "https://Stackoverflow.com/users/300141",
"pm_score": 2,
"selected": false,
"text": "Enumerable.Range(1, 100).OrderBy(c=> Guid.NewGuid().ToString())\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29762/"
] |
254,849
|
<p>I have an MSBuild project where within it I have a task that calls multiple projects where I set BuildInParallel = "true"</p>
<p>Example:</p>
<p></p>
<pre><code> <Message Text="MSBuild project list = @(ProjList)" />
<!-- Compile in parallel -->
<MSBuild Projects="@(ProjList)"
Targets="Build"
Properties="Configuration=$(Configuration)"
BuildInParallel="true" />
</code></pre>
<p></p>
<p>These sub-projects actually invoke a command-line tool to do the actual 'building' - call it compile.exe. Doing crude profiling (thank you taskmgr.exe) of the build process has the following results:</p>
<p>based on the /m setting - I see that exact number of MSBuild.exe processes started which is expected of course - the total available concurrent build processes.</p>
<p>However what I expect to see is around that many number of processes of compile.exe. Basically each MSBuild process will just turn around and invoke compile.exe. What I see is that a number of compile.exe's are started, then they slowly finish until I just see one sole compile.exe still around. The tasks that each compile.exe take a different amount of time, so it's expected that one of them takes a lot longer than the others.</p>
<p>However no other compile.exe's are spawned until the first 'batch' of them are finished. In other words if I have /m:4 - I will see 4 compile.exe's until all finish, then another 4 will be spawned.</p>
<p>This isn't exactly completely parallel to me. Has anyone else seen this behavior. Am I just misunderstanding something?</p>
|
[
{
"answer_id": 254860,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "Random rnd = new Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());\n"
},
{
"answer_id": 254861,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 5,
"selected": true,
"text": "System.Random rnd = new System.Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());\n"
},
{
"answer_id": 254875,
"author": "Adam Alexander",
"author_id": 33164,
"author_profile": "https://Stackoverflow.com/users/33164",
"pm_score": 1,
"selected": false,
"text": "System.Random rnd = New System.Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(rnd => rnd.Next);\n"
},
{
"answer_id": 254919,
"author": "Daniel Plaisted",
"author_id": 1509,
"author_profile": "https://Stackoverflow.com/users/1509",
"pm_score": 3,
"selected": false,
"text": "int timesCalled = 0;\nRandom rnd = new Random();\n\nList<int> numbers = Enumerable.Range(1, 100).OrderBy(r =>\n {\n timesCalled++;\n return rnd.Next();\n }\n).ToList();\n\nAssert.AreEqual(timesCalled, 100);\n"
},
{
"answer_id": 254957,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 1,
"selected": false,
"text": "Shuffle() IList<int> numbers = new ArrayList<int>(Enumerable.Range(1,100));\nnumbers.Shuffle();\n"
},
{
"answer_id": 3189638,
"author": "FouZ",
"author_id": 300141,
"author_profile": "https://Stackoverflow.com/users/300141",
"pm_score": 2,
"selected": false,
"text": "Enumerable.Range(1, 100).OrderBy(c=> Guid.NewGuid().ToString())\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] |
254,859
|
<p>I am creating an integration server for the first time, and although I have two projects in my cruisecontrol config file, only the first one seems to be executing. My config file is pasted below.</p>
<pre><code><cruisecontrol>
<project name="cc-config">
<triggers>
<intervalTrigger seconds="60" />
</triggers>
<sourcecontrol type="svn">
<trunkUrl></trunkUrl>
<workingDirectory>C:\Program Files (x86)\CruiseControl.NET\server\config</workingDirectory>
</sourcecontrol>
</project>
<project name="stable_trunk">
<workingDirectoy>C:\working</workingDirectory>
<artifactDirectory>C:\artifact</artifactDirectory>
<triggers>
<intervalTrigger name="continuous" seconds="60"/>
</triggers>
<sourcecontrol type="svn">
<trunkUrl></trunkUrl>
<workingDirectory>C:\projects\security\trunk</workingDirectory>
</sourcecontrol>
<tasks>
<nant>
<executable>C:\projects\security\trunk\tools\nant-0.86-nightly-2008-08-18\bin\nant.exe</executable>
<buildFile>C:\projects\security\trunk\security.build</buildFile>
</nant>
</tasks>
<externalLinks>
<externalLink name="proj" url="projURL">
</externalLinks>
</project>
</cruisecontrol>
</code></pre>
<p>Can anybody help me?
thanks
Carter</p>
<p>Additional Information:</p>
<ul>
<li>The log file has no errors and no mention of the second project</li>
<li>The web interface only shows the first project</li>
</ul>
<p>It's as if the second project doesn't even exist.</p>
<p>The problem was a typo, and I missed the error in the log file. The WorkingDirectory tag was missing the last 'r'.</p>
|
[
{
"answer_id": 255247,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 0,
"selected": false,
"text": "<triggers>\n <intervalTrigger name=\"continuous\" buildCondition=\"ForceBuild\" seconds=\"60\"/>\n</triggers>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26527/"
] |
254,864
|
<p>So I know it's considered somewhat good practice to always include curly braces for if, for, etc even though they're optional if there is only one following statement, for the reason that it's easier to accidentally do something like:</p>
<pre><code>if(something == true)
DoSomething();
DoSomethingElse();
</code></pre>
<p>when quickly editing code if you don't put the braces.</p>
<p>What about something like this though:</p>
<pre><code>if(something == true)
{ DoSomething(); }
</code></pre>
<p>That way you still take up fewer lines (which IMO increases readability) but still make it unlikely to accidentally make the mistake from above?</p>
<p>I ask because I don't believe I've ever seen this style before for if or loops, but I do see it used for getter and setter in C# properties like:</p>
<pre><code>public string Name
{get;set;}
</code></pre>
<p>Not asking what's best since that's too subjective, but rather just whether this would be considered acceptable style and if not, why not.</p>
|
[
{
"answer_id": 254866,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 3,
"selected": false,
"text": "if(something == true)\n{ DoSomething(); }\n if(something == true) { DoSomething(); }\n"
},
{
"answer_id": 254867,
"author": "Stephen Walcher",
"author_id": 25375,
"author_profile": "https://Stackoverflow.com/users/25375",
"pm_score": 5,
"selected": true,
"text": "if (something == true) DoSomething();\n"
},
{
"answer_id": 254870,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 0,
"selected": false,
"text": "if(something == true) { DoSomething(); }\n if(something == true) DoSomething(); \n"
},
{
"answer_id": 254871,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 3,
"selected": false,
"text": "if(foo)\n DoSomething();\n if(foo) DoSomething();\n"
},
{
"answer_id": 254876,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": " if (something== true) {\n DoSomething();\n }\n if (something)\n if (!something)\n if (something== true) \n if (something== false) \n"
},
{
"answer_id": 254881,
"author": "Maxime Rouiller",
"author_id": 24975,
"author_profile": "https://Stackoverflow.com/users/24975",
"pm_score": 0,
"selected": false,
"text": "if(something) { DoSomething(); }\n if( param1 == null ) throw new ArgumentNullException(\"param1\");\n"
},
{
"answer_id": 254890,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "if (something == true) \n DoSomething();\n DoSomething() if (something == true) \n print(\"debug message\");\n DoSomething();\n if DoSomething() if (something == true) {\n print(\"debug message\");\n DoSomething();\n}\n"
},
{
"answer_id": 254905,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": false,
"text": "if (condition)\n{\n statement;\n statement;\n}\n if (condition)\n statement;\n statement;\n if (condition)\n statement;\n"
},
{
"answer_id": 254938,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 3,
"selected": false,
"text": "if if if (a==b) { Foo(); }\n"
},
{
"answer_id": 254954,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "if (something)\n{\n DoSomething();\n}\n public string MyProperty { get; set; }\n"
},
{
"answer_id": 255033,
"author": "Cybis",
"author_id": 32998,
"author_profile": "https://Stackoverflow.com/users/32998",
"pm_score": 0,
"selected": false,
"text": "if (something == true)\nif (something == false)\n if (something)\nif (!something)\n if something:\nif not something:\n"
},
{
"answer_id": 255034,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 0,
"selected": false,
"text": "if(obj != null) obj.method();\n public executeMethodOn(String cmd) {\n CommandObject co;\n\n if(\"CmdObject1\".equals(cmd)) co=new CmdObject1();\n if(\"CmdObject2\".equals(cmd)) co=new CmdObjec21();\n\n co.executeMethod();\n}\n"
},
{
"answer_id": 255038,
"author": "Berserk",
"author_id": 26313,
"author_profile": "https://Stackoverflow.com/users/26313",
"pm_score": 0,
"selected": false,
"text": "if($something) {\n do_something();\n}\n THING:\nfor my $thing (1 .. 10) {\n next THING if $thing % 3 == 0;\n}\n"
},
{
"answer_id": 1035872,
"author": "Stan Graves",
"author_id": 1715896,
"author_profile": "https://Stackoverflow.com/users/1715896",
"pm_score": 0,
"selected": false,
"text": "if (true == something) {\n doSomething1();\n}\n if (-1 == doSomething()) {\n doSomethingElse();\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23822/"
] |
254,887
|
<p>I am looking for a clear, complete example of programmatically deleting all documents from a specific document library, via the Sharepoint object model. The doclib does not contain folders. I am looking to delete the documents completely (ie I don't want them in the Recycle Bin).</p>
<p>I know of SPWeb.ProcessBatchData, but somehow it never seems to work for me.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 254918,
"author": "Maxime Rouiller",
"author_id": 24975,
"author_profile": "https://Stackoverflow.com/users/24975",
"pm_score": 1,
"selected": false,
"text": "foreach(SPListItem item in SPContext.Current.Web.Lists[\"YourDocLibName\"].Items)\n{\n //TODO: Verify that the file is not checked-out before deleting\n item.File.Delete();\n}\n"
},
{
"answer_id": 255897,
"author": "Daniel McPherson",
"author_id": 897,
"author_profile": "https://Stackoverflow.com/users/897",
"pm_score": 4,
"selected": true,
"text": "for (int i = SPItems.Length - 1; i >= 0; i--)\n{\n SPListItem item = SPItems[i];\n item.File.Delete();\n}\n"
},
{
"answer_id": 7207839,
"author": "Richard Gear",
"author_id": 900948,
"author_profile": "https://Stackoverflow.com/users/900948",
"pm_score": 0,
"selected": false,
"text": "function ProcessFolder {\n param($folderUrl)\n $folder = $web.GetFolder($folderUrl)\n foreach ($file in $folder.Files) {\n #Ensure destination directory\n $destinationfolder = $destination + \"/\" + $folder.Url \n if (!(Test-Path -path $destinationfolder))\n {\n $dest = New-Item $destinationfolder -type directory \n }\n #Delete file by deleting parent SPListItem\n $list.Items.DeleteItemById($file.Item.Id)\n }\n}\n\n#Delete root Files\nProcessFolder($list.RootFolder.Url)\n\n#Delete files from Folders or Document Sets\nforeach ($folder in $list.Folders) {\n ProcessFolder($folder.Url)\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5782/"
] |
254,895
|
<p>How do I embed a tag within a <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url" rel="nofollow noreferrer" title="url templatetag">url templatetag</a> in a django template?</p>
<p>Django 1.0 , Python 2.5.2</p>
<p>In views.py</p>
<pre><code>def home_page_view(request):
NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"}
variables = RequestContext(request, {'NUP':NUP})
return render_to_response('home_page.html', variables)
</code></pre>
<p>In home_page.html, the following</p>
<pre><code>NUP.HOMEPAGE = {{ NUP.HOMEPAGE }}
</code></pre>
<p>is displayed as </p>
<pre><code>NUP.HOMEPAGE = named-url-pattern-string-for-my-home-page-view
</code></pre>
<p>and the following url named pattern works ( as expected ),</p>
<pre><code>url template tag for NUP.HOMEPAGE = {% url named-url-pattern-string-for-my-home-page-view %}
</code></pre>
<p>and is displayed as </p>
<pre><code>url template tag for NUP.HOMEPAGE = /myhomepage/
</code></pre>
<p>but when <code>{{ NUP.HOMEPAGE }}</code> is embedded within a <code>{% url ... %}</code> as follows</p>
<pre><code>url template tag for NUP.HOMEPAGE = {% url {{ NUP.HOMEPAGE }} %}
</code></pre>
<p>this results in a template syntax error</p>
<pre><code>TemplateSyntaxError at /myhomepage/
Could not parse the remainder: '}}' from '}}'
Request Method: GET
Request URL: http://localhost:8000/myhomepage/
Exception Type: TemplateSyntaxError
Exception Value:
Could not parse the remainder: '}}' from '}}'
Exception Location: C:\Python25\Lib\site-packages\django\template\__init__.py in __init__, line 529
Python Executable: C:\Python25\python.exe
Python Version: 2.5.2
</code></pre>
<p>I was expecting <code>{% url {{ NUP.HOMEPAGE }} %}</code> to resolve to <code>{% url named-url-pattern-string-for-my-home-page-view %}</code> at runtime and be displayed as <code>/myhomepage/</code>.</p>
<p>Are embedded tags not supported in django? </p>
<p>is it possible to write a custom url template tag with embedded tags support to make this work?</p>
<p><code>{% url {{ NUP.HOMEPAGE }} %}</code></p>
|
[
{
"answer_id": 254942,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "{% url named-url-pattern-string-for-my-home-page-view %}\n {% if tagoption1 %}<a href=\"{% url named-url-1 %}\">Text</a>{% endif %}\n"
},
{
"answer_id": 254948,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 3,
"selected": true,
"text": "from django.core.urlresolvers import reverse\n\ndef home_page_view(request):\n NUP={\"HOMEPAGE\": reverse('named-url-pattern-string-for-my-home-page-view')} \n variables = RequestContext(request, {'NUP':NUP})\n return render_to_response('home_page.html', variables)\n NUP.HOMEPAGE"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11452/"
] |
254,901
|
<p>does anybody know how could I get the TWO most largest values from the third column on the following array?</p>
<pre><code>$ar = array(array(1, 1, 7.50, 'Hello'),
array(1, 2, 18.90, 'Hello'),
array(3, 5, 11.50, 'Hello'),
array(2, 4, 15.90, 'Hello'));
</code></pre>
<p>Output should be:</p>
<pre><code>15.90
18.90
</code></pre>
<p>Thanks in advance</p>
|
[
{
"answer_id": 254920,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": true,
"text": "usort function cmp($a, $b) {\n $a = $a[2];\n $b = $b[2];\n return $a == $b ? 0 : $a < $b ? 1 : -1;\n}\n\nusort($ar, 'cmp');\n"
},
{
"answer_id": 254949,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "first = array[0][2]\nsecond = array[1][2]\nif second > first\n first, second = second, first\nfor tuple in array[2:n]\n if tuple[2] > second\n second = tuple[2]\n if second > first\n first, second = second, first\n"
},
{
"answer_id": 254986,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "def maxN(list, n):\n result = []\n curmin = 0\n for number in list:\n if number > curmin:\n binary insert number into result. #O(log n)\n if len(result) > n: \n truncate last element #O(1)\n curmin = new minimum in result list #O(1) since list is sorted\n\n return result\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
254,912
|
<p>Given that these two examples are equivalent, which do you think is preferrable?</p>
<p><strong>Without explicit modifier</strong></p>
<pre><code>public class MyClass
{
string name = "james";
public string Name {
get { return name; }
set { name = value; }
}
void SomeMethod() { ... }
}
</code></pre>
<p><strong>With explicit modifier</strong></p>
<pre><code>public class MyClass
{
private string name = "james";
public string Name {
get { return name; }
set { name = value; }
}
private void SomeMethod() { ... }
}
</code></pre>
<hr>
<p>I've always used the latter, but recently I've started adopting the former style. The private is redundant as that's the default accessor modifier, so doesn't it make sense to exclude it?</p>
|
[
{
"answer_id": 254931,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 2,
"selected": false,
"text": "public private internal"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4590/"
] |
254,929
|
<p>I'm trying to figure out how to restrict access to a page unless the page is navigated to from a specific "gate" page. Essentially I want the page to be unaccessible unless you're coming from the page that comes before it in my sitemap. I'm not certain this is even possible. If possible, can you limit your suggestions to using either html or javascript?</p>
|
[
{
"answer_id": 254939,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "REFERER mod_rewrite RewriteEngine On\nRewriteCond %{HTTP_REFERER} !^http://www\\.example\\.com/.*\nRewriteRule /* http://www.example.com/access-denied.html [R,L]\n"
},
{
"answer_id": 254967,
"author": "Stephen Walcher",
"author_id": 25375,
"author_profile": "https://Stackoverflow.com/users/25375",
"pm_score": 2,
"selected": true,
"text": "<a href=\"restricted.php?pass=eERadWRWE3ad=\">Go!</a>\n"
},
{
"answer_id": 254999,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 3,
"selected": false,
"text": "Referer <?php\nsession_start();\n$_SESSION['allowed_access'] = true;\n?><a href=\"protected_page.php\">Protected area</a>\n <?php\nsession_start();\nif (!$_SESSION['allowed_access']) {\n header('Location: gate_page.php');\n echo 'Go through the <a href=\"gate_page.php\">entry page</a> first.';\n exit();\n}\n\n// whatever happens to be at the protected page\n"
},
{
"answer_id": 280989,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "document.history.previous"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27171/"
] |
254,930
|
<p>I'm currently working on an application which requires transmission of speech encoded to a specific audio format.</p>
<pre><code>System.Speech.AudioFormat.SpeechAudioFormatInfo synthFormat =
new System.Speech.AudioFormat.SpeechAudioFormatInfo(System.Speech.AudioFormat.EncodingFormat.Pcm,
8000, 16, 1, 16000, 2, null);
</code></pre>
<p>This states that the audio is in PCM format, 8000 samples per second, 16 bits per sample, mono, 16000 average bytes per second, block alignment of 2.</p>
<p>When I attempt to execute the following code there is nothing written to my MemoryStream instance; however when I change from 8000 samples per second up to 11025 the audio data is written successfully.</p>
<pre><code>SpeechSynthesizer synthesizer = new SpeechSynthesizer();
waveStream = new MemoryStream();
PromptBuilder pbuilder = new PromptBuilder();
PromptStyle pStyle = new PromptStyle();
pStyle.Emphasis = PromptEmphasis.None;
pStyle.Rate = PromptRate.Fast;
pStyle.Volume = PromptVolume.ExtraLoud;
pbuilder.StartStyle(pStyle);
pbuilder.StartParagraph();
pbuilder.StartVoice(VoiceGender.Male, VoiceAge.Teen, 2);
pbuilder.StartSentence();
pbuilder.AppendText("This is some text.");
pbuilder.EndSentence();
pbuilder.EndVoice();
pbuilder.EndParagraph();
pbuilder.EndStyle();
synthesizer.SetOutputToAudioStream(waveStream, synthFormat);
synthesizer.Speak(pbuilder);
synthesizer.SetOutputToNull();
</code></pre>
<p>There are no exceptions or errors recorded when using a sample rate of 8000 and I couldn't find anything useful in the documentation regarding SetOutputToAudioStream and why it succeeds at 11025 samples per second and not 8000. I have a workaround involving a wav file that I generated and converted to the correct sample rate using some sound editing tools, but I would like to generate the audio from within the application if I can.</p>
<p>One particular point of interest was that the SpeechRecognitionEngine accepts that audio format and successfully recognized the speech in my synthesized wave file...</p>
<p>Update: Recently discovered that this audio format succeeds for certain installed voices, but fails for others. It fails specifically for LH Michael and LH Michelle, and failure varies for certain voice settings defined in the PromptBuilder.</p>
|
[
{
"answer_id": 336940,
"author": "Mark Heath",
"author_id": 7532,
"author_profile": "https://Stackoverflow.com/users/7532",
"pm_score": 1,
"selected": false,
"text": "WaveFormatConversionStream ResamplerDMO"
},
{
"answer_id": 14016962,
"author": "user1925922",
"author_id": 1925922,
"author_profile": "https://Stackoverflow.com/users/1925922",
"pm_score": 1,
"selected": false,
"text": "SpeechAudioFormatInfo synthFormat = new SpeechAudioFormatInfo(EncodingFormat.Pcm, 88200, 16, 1, 16000, 2, null);\nsynth.SetOutputToAudioStream(streamAudio, synthFormat);\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24695/"
] |
254,969
|
<p>I work in C#, and I've been pretty lax about using <code>using</code> blocks to declare objects that implement <code>IDisposable</code>, which you're apparently always supposed to do. However, I don't see an easy way of knowing when I'm slipping up. Visual Studio doesn't seem to indicate this in any way (am I just missing something?). Am I just supposed to check help every time I declare anything, and gradually build up an encyclopedic memory for which objects are and which are not disposable? Seems unnecessary, painful, and error-prone.</p>
<p>How do <em>you</em> handle this?</p>
<p><strong>EDIT:</strong></p>
<p>Looking at the related questions sidebar, I found <a href="https://stackoverflow.com/questions/2785/setting-objects-to-nullnothing-after-use-in-dot-net">another question</a> which made it clear that <code>Dispose()</code> is supposed to be called by the object's finalizer anyway. So even if you never call it yourself, it should eventually happen, meaning you won't have a memory leak if you don't use <code>using</code> (which is what I suppose I was really worried about all along). The only caveat is that the garbage collector doesn't know how much extra memory is being held by the object as unmanaged stuff, so it won't have an accurate idea how much memory will be freed by collecting the object. This will result in less-ideal-than-usual performance by the garbage collector.</p>
<p>In short, it's not the end of the world if I miss a <code>using</code>. I just wish something would generate at least a warning for it.</p>
<p>(Off-topic: why is there no special markdown for linking to another question?)</p>
<p><strong>EDIT:</strong></p>
<p>Ok, fine, stop clamoring. It's super duper all-fired <a href="http://www.youtube.com/watch?v=a1Y73sPHKxw" rel="nofollow noreferrer">dramatic-chipmunk</a>-level <strong><em>important</em></strong> to call <code>Dispose()</code> or we'll all <em>die</em>.</p>
<p>Now. Given that, why is it so easy — hell, why is it even <em>allowed</em> — to do it wrong? You have to go out of your way to do it right. Doing it like everything else results in armageddon (apparently). So much for encapsulation, huh?</p>
<p>[Stalks off, disgusted]</p>
|
[
{
"answer_id": 254971,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "IDisposable .D using using (int i = 5) {}\n\nError 1 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable' \n"
},
{
"answer_id": 255494,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 4,
"selected": false,
"text": "IDisposable using Dispose() Dispose() Dispose() Dispose() Dispose() IDisposable Dispose() Close() IDisposable Open() Close() using Dispose()"
},
{
"answer_id": 257057,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 2,
"selected": false,
"text": "using IDisposable IDisposable IDispose"
},
{
"answer_id": 663274,
"author": "GrahamS",
"author_id": 79591,
"author_profile": "https://Stackoverflow.com/users/79591",
"pm_score": 2,
"selected": false,
"text": "using Dispose using"
},
{
"answer_id": 4737240,
"author": "usr-local-ΕΨΗΕΛΩΝ",
"author_id": 471213,
"author_profile": "https://Stackoverflow.com/users/471213",
"pm_score": -1,
"selected": false,
"text": "IDisposable public MyClass: IDisposable\n{\n\n private bool _disposed = false;\n\n //Destructor\n ~MyClass()\n { Dispose(false); }\n\n public void Dispose()\n { Dispose(true); }\n\n private void Dispose(bool disposing)\n {\n if (_disposed) return;\n GC.SuppressFinalize(this);\n\n /* actions to always perform */\n\n if (disposing) { /* actions to be performed when Dispose() is called */ }\n\n _disposed=true;\n}\n using"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33219/"
] |
254,976
|
<p>I'm trying to create classes to read from my config file using ConfigurationSection and ConfigurationElementCollection but am having a hard time.</p>
<p>As an example of the config:</p>
<pre><code>
<PaymentMethodSettings>
<PaymentMethods>
<PaymentMethod name="blah blah" code="1"/>
<PaymentMethod name="blah blah" code="42"/>
<PaymentMethod name="blah blah" code="43"/>
<Paymentmethod name="Base blah">
<SubPaymentMethod name="blah blah" code="18"/>
<SubPaymentMethod name="blah blah" code="28"/>
<SubPaymentMethod name="blah blah" code="38"/>
</Paymentmethod>
</PaymentMethods>
</PaymentMethodSettings>
</code></pre>
|
[
{
"answer_id": 255030,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": true,
"text": "public class PaymentSection : ConfigurationSection\n{\n // Simple One\n [ConfigurationProperty(\"name\")]]\n public String name\n {\n get { return this[\"name\"]; }\n set { this[\"name\"] = value; }\n }\n\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25951/"
] |
254,979
|
<p>I have 3 points (A, B and X) and a distance (d). I need to make a function that tests if point X is closer than distance d to any point on the line segment AB. </p>
<p>The question is firstly, is my solution correct and then to come up with a better (faster) solution.</p>
<p>My first pass is as follows</p>
<pre><code>AX = X-A
BX = X-B
AB = A-B
// closer than d to A (done squared to avoid needing to compute the sqrt in mag)
If d^2 > AX.mag^2 return true
// closer than d to B
If d^2 > BX.mag^2 return true
// "beyond" B
If (dot(BX,AB) < 0) return false
// "beyond" A
If (dot(AX,AB) > 0) return false
// find component of BX perpendicular to AB
Return (BX.mag)^2 - (dot(AB,BX)/AB.mag)^2 < d^2
</code></pre>
<p>This code will end up being run for a large set of P's and a large set of A/B/d triplets with the intent of finding all P's that pass for at least one A/B/d so I suspect that there is a way to reduce overall the cost based on that but I haven't looked into that yet.</p>
<p>(BTW: I am aware that some reordering, some temporary values and some algebraic identities could decrease the cost of the above. I just omitted them for clarity.)</p>
<hr>
<p><em>EDIT: this is a 2D problem (but solution that generalizes to 3D would be cool</em></p>
<p>Edit: On further reflection, I expect the hit rate to be around 50%. The X point can be formed in a nested hierarchy so I expect to be able to prune large subtrees as all-pass and all-fail. The A/B/d limiting the triplets will be more of a trick.</p>
<p>Edit: d is in the same order of magnitude as AB.</p>
<hr>
<p>edit: Artelius posted a nice solution. I'm not sure I understand exactly what he's getting at as I got off on a tangent before I fully understood it. Anyway another thought came to mind as a result:</p>
<ul>
<li>First Artelius' bit, pre-cacluate a matrix that will place AB centered ate the origin and aligned with the X-axis. (2 adds, 4 muls and 2 adds)</li>
<li>fold it all into the 1st quadrant (2 abs)</li>
<li>scale in X&Y to make the central portion of the zone into a unit square (2 mul)</li>
<li>test if the point is in that square (2 test) is so quit</li>
<li>test the end cap (go back to the unscaled values
<ul>
<li>translate in x to place the end at the origin (1 add)</li>
<li>square and add (2 mul, 1 add)</li>
<li>compare to d^2 (1 cmp)</li>
</ul></li>
</ul>
<p>I'm fairly sure this beats my solution.</p>
<p>(if nothing better comes along sone Artelius gets the "prize" :)</p>
|
[
{
"answer_id": 255120,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 1,
"selected": false,
"text": " ...... .....\n ........... ...........\n ...........................\n.......A-------------B.......\n ...........................\n ........... ...........\n ..... .....\n If d^2 > AX.mag^2 return true\nIf d^2 > BX.mag^2 return true\n"
},
{
"answer_id": 255219,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 2,
"selected": false,
"text": "origin + distance * direction AB+ Vector v = X - A\nVector d = normalise(B - A) // unit direction vector of AB\ndouble b = dot(v, B - A)\ndouble discrim = b^2 - dot(v, v) + d^2\nif (discrim < 0)\n return false // definitely no intersection\n discrim = sqrt(discrim)\ndouble t2 = b + discrim\nif (t2 <= 0)\n return false // intersection is before A\n\ndouble t1 = b - discrim\n\nresult = (t1 < length(AB) || (t2 < length(AB))\n"
},
{
"answer_id": 255235,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 3,
"selected": true,
"text": "trans = - ((A + B) / 2) // translate midpoint of AB to origin\n\nrot.col1 = AB / AB.mag // unit vector in AB direction\n\n 0 -1 \nrot.col2 = rot.col1 * ( ) // unit vector perp to AB\n 1 0 \n\nrot = rot.inverse() // but it needs to be done in reverse\n rot * (X + trans) y < d && x < AB.mag/2 //\"along\" the line segment\n|| (x - AB.mag/2)^2 + y^2 < d^2 // the \"end cap\".\n AB.mag/2 y < 2*d/AB.mag && x < 1\n|| (x - 1)^2 + y^2 < (2*d/AB.mag)^2\n 2*d/AB.mag (2*d/AB.mag)^2"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
254,980
|
<p>As a follow-up to <a href="https://stackoverflow.com/questions/199518/how-to-programatically-add-mapped-network-passwords-winxp">this</a> question I am hoping someone can help with the <a href="http://msdn.microsoft.com/en-us/library/aa374794(VS.85).aspx" rel="nofollow noreferrer">CredEnumerate</a> API. </p>
<p>As I understand from the documentation the PCREDENTIALS out parameter is a "pointer to an array of pointers to credentials". I am able to successfully call the CredEnumerate API using C# but I am not sure of how to convert the PCREDENTIALS into something useful (like a list of credentials).</p>
<p>Edit: Here's the code I am using:</p>
<pre><code> int count = 0;
IntPtr pCredentials = IntPtr.Zero;
bool ret = false;
ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
IntPtr[] credentials = new IntPtr[count];
IntPtr p = pCredentials;
for (int i = 0; i < count; i++)
{
p = new IntPtr(p.ToInt32() + i);
credentials[i] = Marshal.ReadIntPtr(p);
}
List<Credential> creds = new List<Credential>(credentials.Length);
foreach (IntPtr ptr in credentials)
{
creds.Add((Credential)Marshal.PtrToStructure(ptr, typeof(Credential)));
}
}
</code></pre>
<p>Unfortunately, while this works for the first credential in the array—it gets generated and added to the list correctly—subsequent array items bomb at Marshal.PtrToStructure with the following error:</p>
<p><em>Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</em></p>
<p>Any ideas? Anyone? Bueller?</p>
|
[
{
"answer_id": 255073,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 4,
"selected": true,
"text": "PCREDENTIALS [DllImport(\"advapi32\", SetLastError = true, CharSet=CharSet.Unicode)]\nstatic extern bool CredEnumerate(string filter, int flag, out int count, out IntPtr\npCredentials);\n int count = 0;\nIntPtr pCredentials = IntPtr.Zero;\nIntPtr[] credentials = null;\nbool ret = CredEnumerate(null, 0, out count, out pCredentials);\nif (ret != false)\n{\n credentials = new IntPtr[count];\n IntPtr p = pCredentials;\n for (int n = 0; n < count; n++)\n {\n credentials[n] = Marshal.ReadIntPtr(pCredentials,\n n * Marshal.SizeOf(typeof(IntPtr)));\n }\n} \nelse\n// failed....\n Marshal.PtrToStructure PCREDENTIALS PCREDENTIALS // assuming you have declared struct PCREDENTIALS\nvar creds = new List<PCREDENTIALS>(credentials.Length);\nforeach (var ptr in credentials)\n{\n creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));\n}\n PtrToStructure"
},
{
"answer_id": 4815173,
"author": "Luis",
"author_id": 591994,
"author_profile": "https://Stackoverflow.com/users/591994",
"pm_score": 1,
"selected": false,
"text": "int count;\nIntPtr pCredentials;\n\nif (CredEnumerate(filter, 0, out count, out pCredentials) != 0)\n{\n m_list = new List<PCREDENTIALS >(count);\n int sz = Marshal.SizeOf(pCredentials);\n\n for (int index = 0; index < count; index++)\n {\n IntPtr p = new IntPtr((sz == 4 ? pCredentials.ToInt32() : pCredentials.ToInt64()) + index * sz);\n m_list.Add((PCREDENTIALS)Marshal.PtrToStructure(p, typeof(PCREDENTIALS)));\n }\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12842/"
] |
254,985
|
<p>The company I work for has a large webapp written in C++ as an ISAPI extension (not a filter). We're currently enhancing our system to integrate with several 3rd party tools that have SOAP interfaces. Rather than roll our own, I think it would probably be best if we used some SOAP library. Ideally, it would be free and open source, but have a license compatible with closed-source commercial software. We also need to support SSL for both incoming and outgoing SOAP messages.</p>
<p>One of the biggest concerns I have is that every SOAP library that I've looked at seems to have 2 modes of operation: standalone server and server module (either Apache module or ISAPI filter). Obviously, we can't use the standalone server. It seems to me that if it is running as a module, it won't be part of my app -- it won't have access to the rest of my code, so it won't be able to share data structures, etc. Is that a correct assumption? Each HTTP request processed by our app is handled by a separate thread (we manage our own thread pool), but we have lots of persistent data that is shared between those threads. I think the type of integration I'm looking for is to add some code to my app that looks at the request URL, sees that it is trying to access a SOAP service, and calls some function like soapService.handleRequest(). I'm not aware of anything that offers this sort of integration. We must be able to utilize data structures from our main app in the SOAP handler functions.</p>
<p>In addition to handling incoming SOAP requests, we're also going to be generating them (bi-directional communication with the 3rd parties). I assume pretty much any SOAP library will fulfill that purpose, right?</p>
<p>Can anyone suggest a SOAP library that is capable of this, or offer a suggestion on how to use a different paradigm? I've already looked at Apache Axis2, gSOAP and AlchemySOAP, but perhaps there's some feature of these that I overlooked. Thanks.</p>
|
[
{
"answer_id": 255073,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 4,
"selected": true,
"text": "PCREDENTIALS [DllImport(\"advapi32\", SetLastError = true, CharSet=CharSet.Unicode)]\nstatic extern bool CredEnumerate(string filter, int flag, out int count, out IntPtr\npCredentials);\n int count = 0;\nIntPtr pCredentials = IntPtr.Zero;\nIntPtr[] credentials = null;\nbool ret = CredEnumerate(null, 0, out count, out pCredentials);\nif (ret != false)\n{\n credentials = new IntPtr[count];\n IntPtr p = pCredentials;\n for (int n = 0; n < count; n++)\n {\n credentials[n] = Marshal.ReadIntPtr(pCredentials,\n n * Marshal.SizeOf(typeof(IntPtr)));\n }\n} \nelse\n// failed....\n Marshal.PtrToStructure PCREDENTIALS PCREDENTIALS // assuming you have declared struct PCREDENTIALS\nvar creds = new List<PCREDENTIALS>(credentials.Length);\nforeach (var ptr in credentials)\n{\n creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));\n}\n PtrToStructure"
},
{
"answer_id": 4815173,
"author": "Luis",
"author_id": 591994,
"author_profile": "https://Stackoverflow.com/users/591994",
"pm_score": 1,
"selected": false,
"text": "int count;\nIntPtr pCredentials;\n\nif (CredEnumerate(filter, 0, out count, out pCredentials) != 0)\n{\n m_list = new List<PCREDENTIALS >(count);\n int sz = Marshal.SizeOf(pCredentials);\n\n for (int index = 0; index < count; index++)\n {\n IntPtr p = new IntPtr((sz == 4 ? pCredentials.ToInt32() : pCredentials.ToInt64()) + index * sz);\n m_list.Add((PCREDENTIALS)Marshal.PtrToStructure(p, typeof(PCREDENTIALS)));\n }\n}\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10861/"
] |
254,992
|
<p>I've got some RadioButtons in my XAML...</p>
<pre><code><StackPanel>
<RadioButton Name="RadioButton1" GroupName="Buttons" Click="ButtonsChecked" IsChecked="True">One</RadioButton>
<RadioButton Name="RadioButton2" GroupName="Buttons" Click="ButtonsChecked">Two</RadioButton>
<RadioButton Name="RadioButton3" GroupName="Buttons" Click="ButtonsChecked">Three</RadioButton>
</StackPanel>
</code></pre>
<p>And I can handle their click events in the Visual Basic code. This works...</p>
<pre>
Private Sub ButtonsChecked(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Select Case CType(sender, RadioButton).Name
Case "RadioButton1"
'Do something one
Exit Select
Case "RadioButton2"
'Do something two
Exit Select
Case "RadioButton3"
'Do something three
Exit Select
End Select
End Sub
</pre>
<p>But, I'd like to improve it. This code fails...</p>
<pre><code><StackPanel>
<RadioButton Name="RadioButton1" GroupName="Buttons" Click="ButtonsChecked" Command="one" IsChecked="True">One</RadioButton>
<RadioButton Name="RadioButton2" GroupName="Buttons" Click="ButtonsChecked" Command="two">Two</RadioButton>
<RadioButton Name="RadioButton3" GroupName="Buttons" Click="ButtonsChecked" Command="three">Three</RadioButton>
</StackPanel>
</code></pre>
<pre>
Private Sub ButtonsChecked(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Select Case CType(sender, RadioButton).Command
Case "one"
'Do something one
Exit Select
Case "two"
'Do something two
Exit Select
Case "three"
'Do something three
Exit Select
End Select
End Sub
</pre>
<p>In my XAML I get a blue squiggly underline on the <strong>Command=</strong> attributes and this tip... </p>
<pre>'CommandValueSerializer' ValueSerializer cannot convert from 'System.String'.</pre>
<p>In my VB I get a green squiggly underline on the <strong>Select Case</strong> line and this warning...</p>
<pre>Runtime errors might occur when converting 'System.Windows.Input.ICommand' to 'String'.</pre>
<p>Even better would be to use Enum type commands with full Intellisense and compile errors rather than runtime errors in case of typos. How can I improve this?</p>
|
[
{
"answer_id": 255225,
"author": "Ian Oakes",
"author_id": 21606,
"author_profile": "https://Stackoverflow.com/users/21606",
"pm_score": 5,
"selected": true,
"text": "<Window \n x:Class=\"RadioButtonCommandSample.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:RadioButtonCommandSample\"\n Title=\"Window1\" \n Height=\"300\" \n Width=\"300\"\n >\n <Window.CommandBindings>\n <CommandBinding Command=\"{x:Static local:Window1.CommandOne}\" Executed=\"CommandBinding_Executed\"/>\n <CommandBinding Command=\"{x:Static local:Window1.CommandTwo}\" Executed=\"CommandBinding_Executed\"/>\n <CommandBinding Command=\"{x:Static local:Window1.CommandThree}\" Executed=\"CommandBinding_Executed\"/>\n </Window.CommandBindings>\n <StackPanel>\n <RadioButton Name=\"RadioButton1\" GroupName=\"Buttons\" Command=\"{x:Static local:Window1.CommandOne}\" IsChecked=\"True\">One</RadioButton>\n <RadioButton Name=\"RadioButton2\" GroupName=\"Buttons\" Command=\"{x:Static local:Window1.CommandTwo}\">Two</RadioButton>\n <RadioButton Name=\"RadioButton3\" GroupName=\"Buttons\" Command=\"{x:Static local:Window1.CommandThree}\">Three</RadioButton>\n </StackPanel>\n</Window>\n\npublic partial class Window1 : Window\n{\n public static readonly RoutedCommand CommandOne = new RoutedCommand();\n public static readonly RoutedCommand CommandTwo = new RoutedCommand();\n public static readonly RoutedCommand CommandThree = new RoutedCommand();\n\n public Window1()\n {\n InitializeComponent();\n }\n\n private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)\n {\n if (e.Command == CommandOne)\n {\n MessageBox.Show(\"CommandOne\");\n }\n else if (e.Command == CommandTwo)\n {\n MessageBox.Show(\"CommandTwo\");\n }\n else if (e.Command == CommandThree)\n {\n MessageBox.Show(\"CommandThree\");\n }\n }\n}\n"
},
{
"answer_id": 39902417,
"author": "Sridhar Ganapathy",
"author_id": 4437729,
"author_profile": "https://Stackoverflow.com/users/4437729",
"pm_score": 0,
"selected": false,
"text": "XAML Code:\n<RadioButton Content=\"On\" IsEnabled=\"True\" IsChecked=\"{Binding OnJob}\"/>\n<RadioButton Content=\"Off\" IsEnabled=\"True\" IsChecked=\"{Binding OffJob}\"/>\n Private _OffJob As Boolean = False\nPrivate _OnJob As Boolean = False\n\nPublic Property OnJob As Boolean\n Get\n Return _OnJob\n End Get\n Set(value As Boolean)\n Me._OnJob = value\n End Set\nEnd Property\n\nPublic Property OffJob As Boolean\n Get\n Return _OffJob\n End Get\n Set(value As Boolean)\n Me._OffJob = value\n End Set\nEnd Property\n\nPrivate Sub FindCheckedItem()\n If(Me.OnJob = True)\n MessageBox.show(\"You have checked On\")\n End If\nIf(Me.OffJob = False)\n MessageBox.Show(\"You have checked Off\")\nEnd sub\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
254,993
|
<p>In one of my projects I need to build an ASP.NET page and some of the controls need to be created dynamically. These controls are added to the page by the code-behind class and they have some event-handlers added to them. Upon the PostBacks these event-handlers have a lot to do with what controls are then shown on the page. To cut the story short, this doesn't work for me and I don't seem to be able to figure this out.</p>
<p>So, as my project is quite involved, I decided to create a short example that doesn't work either but if you can tweak it so that it works, that would be great and I would then be able to apply your solution to my original problem.</p>
<p>The following example should dynamically create three buttons on a panel. When one of the buttons is pressed all of the buttons should be dynamically re-created except for the button that was pressed. In other words, just hide the button that the user presses and show the other two.</p>
<p>For your solution to be helpful you can't statically create the buttons and then use the Visible property (or drastically change the example in other ways) - you have to re-create all the button controls dynamically upon every PostBack (not necessarily in the event-handler though). This is not a trick-question - I really don't know how to do this. Thank you very much for your effort. Here is my short example:</p>
<h2>From the Default.aspx file:</h2>
<pre><code><body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="ButtonsPanel" runat="server"></asp:Panel>
</div>
</form>
</body>
</code></pre>
<h2>From the Default.aspx.cs code-behind file:</h2>
<pre><code>using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DynamicControls
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
AddButtons();
}
protected void AddButtons()
{
var lastClick = (string) Session["ClickedButton"] ?? "";
ButtonsPanel.Controls.Clear();
if (!lastClick.Equals("1")) AddButtonControl("1");
if (!lastClick.Equals("2")) AddButtonControl("2");
if (!lastClick.Equals("3")) AddButtonControl("3");
}
protected void AddButtonControl(String id)
{
var button = new Button {Text = id};
button.Click += button_Click;
ButtonsPanel.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
Session["ClickedButton"] = ((Button) sender).Text;
AddButtons();
}
}
}
</code></pre>
<p>My example shows the three buttons and when I click one of the buttons, the pressed button gets hidden. Seems to work; but after this first click, I have to click each button <strong>TWICE</strong> for it to get hidden. !?</p>
|
[
{
"answer_id": 255017,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "Page_Load() button_Click() Page_Load() if (!IsPostBack) if (!IsPostBack)\n{\n AddButtons();\n}\n"
},
{
"answer_id": 255037,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": true,
"text": "AddButtonControl var button = new Button { Text = id , ID = id };\n public partial class _Default : Page\n{\n protected override void OnPreInit(EventArgs e)\n {\n base.OnPreInit(e);\n AddButtons();\n }\n\n protected void AddButtons()\n {\n AddButtonControl(\"btn1\", \"1\");\n AddButtonControl(\"btn2\", \"2\");\n AddButtonControl(\"btn3\", \"3\");\n }\n\n protected void AddButtonControl(string id, string text)\n {\n var button = new Button { Text = text, ID = id };\n button.Click += button_Click;\n ButtonsPanel.Controls.Add(button);\n }\n\n private void button_Click(object sender, EventArgs e)\n {\n foreach (Control control in ButtonsPanel.Controls)\n control.Visible = !control.Equals(sender);\n }\n}\n"
},
{
"answer_id": 255055,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "Pre_Init Page_Load !IsPostBack"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3379/"
] |
255,006
|
<p>Is it possible to automatically launch an application from a USB flash drive (bypassing windows prompt asking user what he wants to do)? on windows XP or vista.</p>
<p>I looked into "autorun.inf" and "open" entry seems to work only for CD drives for Windows XP SP2+ and Vista. Is it possible to launch program automatically on all windows versions?</p>
<p>I don't care if autorun is disabled by user in Windows settings.</p>
|
[
{
"answer_id": 255067,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 5,
"selected": false,
"text": "[Autorun]\nOpen=PStart.exe\nAction=Start portable apps\nIcon=diskicon.ico\n PStart.exe Open= autorun.inf Icon= Action="
},
{
"answer_id": 352784,
"author": "berlindev",
"author_id": 44276,
"author_profile": "https://Stackoverflow.com/users/44276",
"pm_score": 2,
"selected": false,
"text": "\n[Autorun]\nShellExecute=System\\something.exe\nUseAutoplay=1 \n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19124/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.