qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
195,262
<p>I'm playing around with the <a href="http://developer.mozilla.org/en/HTML/Canvas" rel="noreferrer"><code>&lt;canvas&gt;</code></a> element, drawing lines and such.</p> <p>I've noticed that my diagonal lines are antialiased. I'd prefer the jaggy look for what I'm doing - is there any way of turning this feature off?</p>
[ { "answer_id": 195575, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 7, "selected": true, "text": "context.imageSmoothingEnabled = false getImageData putImageData" }, { "answer_id": 3279863, "author": "allan", "author_id": 176779, "author_profile": "https://Stackoverflow.com/users/176779", "pm_score": 6, "selected": false, "text": "1-pixel ctx.lineTo(10.5, 10.5) (10, 10) 1 9.5 10.5 0.5 ctx.translate(0.5, 0.5)" }, { "answer_id": 5676157, "author": "francholi", "author_id": 709735, "author_profile": "https://Stackoverflow.com/users/709735", "pm_score": 5, "selected": false, "text": "contextXYZ.mozImageSmoothingEnabled = false;\n" }, { "answer_id": 22745066, "author": "retepaskab", "author_id": 2874723, "author_profile": "https://Stackoverflow.com/users/2874723", "pm_score": 3, "selected": false, "text": "ctx.translate(0.5, 0.5);\nctx.lineWidth = .5;\n" }, { "answer_id": 32798277, "author": "eri0o", "author_id": 965638, "author_profile": "https://Stackoverflow.com/users/965638", "pm_score": 3, "selected": false, "text": "function setpixelated(context){\n context['imageSmoothingEnabled'] = false; /* standard */\n context['mozImageSmoothingEnabled'] = false; /* Firefox */\n context['oImageSmoothingEnabled'] = false; /* Opera */\n context['webkitImageSmoothingEnabled'] = false; /* Safari */\n context['msImageSmoothingEnabled'] = false; /* IE */\n}\n var canvas = document.getElementById('mycanvas')\nsetpixelated(canvas.getContext('2d'))\n" }, { "answer_id": 46532835, "author": "StashOfCode", "author_id": 8710484, "author_profile": "https://Stackoverflow.com/users/8710484", "pm_score": 3, "selected": false, "text": "imageData = context2d.getImageData (0, 0, g.width, g.height);\nfor (i = 0; i != imageData.data.length; i ++) {\n if (imageData.data[i] != 0x00)\n imageData.data[i] = 0xFF;\n}\ncontext2d.putImageData (imageData, 0, 0);\n" }, { "answer_id": 52935345, "author": "Matías Moreno", "author_id": 4508391, "author_profile": "https://Stackoverflow.com/users/4508391", "pm_score": 0, "selected": false, "text": "#FFFFFF imageData.data[i] = (imageData.data[i] >> 7) * 0xFF\n" }, { "answer_id": 60732516, "author": "Jaewon.A.C", "author_id": 8455221, "author_profile": "https://Stackoverflow.com/users/8455221", "pm_score": 1, "selected": false, "text": "ctx.beginPath();\nctx.moveTo(some_x, some_y);\nctx.lineTo(some_x, some_y);\n...\nctx.closePath();\nctx.fill();\nctx.stroke();\n\nlet image = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height)\nfor(let x=0; x < ctx.canvas.width; x++) {\n for(let y=0; y < ctx.canvas.height; y++) {\n if(image.data[x*image.height + y] < 128) {\n image.data[x*image.height + y] = 0;\n } else {\n image.data[x*image.height + y] = 255;\n }\n }\n}\n x*image.height*number_channel + y*number_channel + channel\n" }, { "answer_id": 60807581, "author": "elliottdehn", "author_id": 12670507, "author_profile": "https://Stackoverflow.com/users/12670507", "pm_score": 2, "selected": false, "text": " function range(f=0, l) {\n var list = [];\n const lower = Math.min(f, l);\n const higher = Math.max(f, l);\n for (var i = lower; i <= higher; i++) {\n list.push(i);\n }\n return list;\n }\n\n //Don't ask me.\n //https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm\n function bresenhamLinePoints(start, end) {\n\n let points = [];\n\n if(start.x === end.x) {\n return range(f=start.y, l=end.y)\n .map(yIdx => {\n return {x: start.x, y: yIdx};\n });\n } else if (start.y === end.y) {\n return range(f=start.x, l=end.x)\n .map(xIdx => {\n return {x: xIdx, y: start.y};\n });\n }\n\n let dx = Math.abs(end.x - start.x);\n let sx = start.x < end.x ? 1 : -1;\n let dy = -1*Math.abs(end.y - start.y);\n let sy = start.y < end.y ? 1 : - 1;\n let err = dx + dy;\n\n let currX = start.x;\n let currY = start.y;\n\n while(true) {\n points.push({x: currX, y: currY});\n if(currX === end.x && currY === end.y) break;\n let e2 = 2*err;\n if (e2 >= dy) {\n err += dy;\n currX += sx;\n }\n if(e2 <= dx) {\n err += dx;\n currY += sy;\n }\n }\n\n return points;\n\n }\n" }, { "answer_id": 65420940, "author": "soshimee", "author_id": 12530359, "author_profile": "https://Stackoverflow.com/users/12530359", "pm_score": 4, "selected": false, "text": "canvas { image-rendering: pixelated; } const canvas = document.querySelector(\"canvas\");\nconst ctx = canvas.getContext(\"2d\");\n\nctx.fillRect(4, 4, 2, 2); canvas {\n image-rendering: pixelated;\n width: 100px;\n height: 100px; /* Scale 10x */\n} <html>\n <head></head>\n <body>\n <canvas width=\"10\" height=\"10\">Canvas unsupported</canvas>\n </body>\n</html>" }, { "answer_id": 67800821, "author": "Max Weber", "author_id": 4737357, "author_profile": "https://Stackoverflow.com/users/4737357", "pm_score": 3, "selected": false, "text": "image-rendering: pixelated; image-rendering: crisp-edges;\n" }, { "answer_id": 68372384, "author": "Codesmith", "author_id": 586652, "author_profile": "https://Stackoverflow.com/users/586652", "pm_score": 3, "selected": false, "text": "filter ctx = canvas.getContext('2d');\n\n// make canvas context render without antialiasing\nctx.filter = \"url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxmaWx0ZXIgaWQ9ImZpbHRlciIgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj48ZmVDb21wb25lbnRUcmFuc2Zlcj48ZmVGdW5jUiB0eXBlPSJpZGVudGl0eSIvPjxmZUZ1bmNHIHR5cGU9ImlkZW50aXR5Ii8+PGZlRnVuY0IgdHlwZT0iaWRlbnRpdHkiLz48ZmVGdW5jQSB0eXBlPSJkaXNjcmV0ZSIgdGFibGVWYWx1ZXM9IjAgMSIvPjwvZmVDb21wb25lbnRUcmFuc2Zlcj48L2ZpbHRlcj48L3N2Zz4=#filter)\";\n <svg xmlns=\"http://www.w3.org/2000/svg\">\n <filter id=\"filter\" x=\"0\" y=\"0\" width=\"100%\" height=\"100%\" color-interpolation-filters=\"sRGB\">\n <feComponentTransfer>\n <feFuncR type=\"identity\"/>\n <feFuncG type=\"identity\"/>\n <feFuncB type=\"identity\"/>\n <feFuncA type=\"discrete\" tableValues=\"0 1\"/>\n </feComponentTransfer>\n </filter>\n</svg>\n #filter \"url(data:image/svg+...Zz4=#filter)\";\n ...\n<feFuncA type=\"discrete\" tableValues=\"0 0 0.25 0.75 1\"/>\n...\n lineWidth filter ctx.filter = \"url(data:image/svg+xml;base64,...#filter)\";\n\nctx.beginPath();\nctx.moveTo(10,10);\nctx.lineTo(20,20);\nctx.strokeStyle = 'black';\nctx.lineWidth = 2;\nctx.stroke();\n\nctx.filter = \"none\";\n ctx.filter = \"url(data:image/svg+xml;base64,...#filter)\";\nsetTimeout(() => {\n ctx.beginPath();\n ctx.moveTo(10,10);\n ctx.lineTo(20,20);\n ctx.strokeStyle = 'black';\n ctx.lineWidth = 2;\n ctx.stroke();\n\n ctx.filter = \"none\";\n}, 0);\n" }, { "answer_id": 69718616, "author": "Kaiido", "author_id": 3702797, "author_profile": "https://Stackoverflow.com/users/3702797", "pm_score": 3, "selected": false, "text": "shapeSmoothingEnabled shapeSmoothingQuality .filter <feComponentTransfer> const canvas = document.getElementById(\"canvas\");\nconst ctx = canvas.getContext(\"2d\");\nctx.fillStyle = \"#ABEDBE\";\nctx.fillRect(0,0,canvas.width,canvas.height);\nctx.fillStyle = \"black\";\nctx.font = \"14px sans-serif\";\nctx.textAlign = \"center\";\n\n// first without filter\nctx.fillText(\"no filter\", 60, 20);\ndrawArc();\ndrawTriangle();\n// then with filter\nctx.setTransform(1, 0, 0, 1, 120, 0);\nctx.filter = \"url(#remove-alpha)\";\n// and do the same ops\nctx.fillText(\"no alpha\", 60, 20);\ndrawArc();\ndrawTriangle();\n\n// to remove the filter\nctx.filter = \"none\";\n\n\nfunction drawArc() {\n ctx.beginPath();\n ctx.arc(60, 80, 50, 0, Math.PI * 2);\n ctx.stroke();\n}\n\nfunction drawTriangle() {\n ctx.beginPath();\n ctx.moveTo(60, 150);\n ctx.lineTo(110, 230);\n ctx.lineTo(10, 230);\n ctx.closePath();\n ctx.stroke();\n}\n// unrelated\n// simply to show a zoomed-in version\nconst zoomed = document.getElementById(\"zoomed\");\nconst zCtx = zoomed.getContext(\"2d\");\nzCtx.imageSmoothingEnabled = false;\ncanvas.onmousemove = function drawToZoommed(e) {\n const\n x = e.pageX - this.offsetLeft,\n y = e.pageY - this.offsetTop,\n w = this.width,\n h = this.height;\n \n zCtx.clearRect(0,0,w,h);\n zCtx.drawImage(this, x-w/6,y-h/6,w, h, 0,0,w*3, h*3);\n} <svg width=\"0\" height=\"0\" style=\"position:absolute;z-index:-1;\">\n <defs>\n <filter id=\"remove-alpha\" x=\"0\" y=\"0\" width=\"100%\" height=\"100%\">\n <feComponentTransfer>\n <feFuncA type=\"discrete\" tableValues=\"0 1\"></feFuncA>\n </feComponentTransfer>\n </filter>\n </defs>\n</svg>\n\n<canvas id=\"canvas\" width=\"250\" height=\"250\" ></canvas>\n<canvas id=\"zoomed\" width=\"250\" height=\"250\" ></canvas> <svg> if (!(\"CanvasFilter\" in globalThis)) {\n throw new Error(\"Not Supported\", \"Please enable experimental web platform features, or wait a bit\");\n}\n\nconst canvas = document.getElementById(\"canvas\");\nconst ctx = canvas.getContext(\"2d\");\nctx.fillStyle = \"#ABEDBE\";\nctx.fillRect(0,0,canvas.width,canvas.height);\nctx.fillStyle = \"black\";\nctx.font = \"14px sans-serif\";\nctx.textAlign = \"center\";\n\n// first without filter\nctx.fillText(\"no filter\", 60, 20);\ndrawArc();\ndrawTriangle();\n// then with filter\nctx.setTransform(1, 0, 0, 1, 120, 0);\nctx.filter = new CanvasFilter([\n {\n filter: \"componentTransfer\",\n funcA: {\n type: \"discrete\",\n tableValues: [ 0, 1 ]\n }\n }\n]);\n// and do the same ops\nctx.fillText(\"no alpha\", 60, 20);\ndrawArc();\ndrawTriangle();\n\n// to remove the filter\nctx.filter = \"none\";\n\n\nfunction drawArc() {\n ctx.beginPath();\n ctx.arc(60, 80, 50, 0, Math.PI * 2);\n ctx.stroke();\n}\n\nfunction drawTriangle() {\n ctx.beginPath();\n ctx.moveTo(60, 150);\n ctx.lineTo(110, 230);\n ctx.lineTo(10, 230);\n ctx.closePath();\n ctx.stroke();\n}\n// unrelated\n// simply to show a zoomed-in version\nconst zoomed = document.getElementById(\"zoomed\");\nconst zCtx = zoomed.getContext(\"2d\");\nzCtx.imageSmoothingEnabled = false;\ncanvas.onmousemove = function drawToZoommed(e) {\n const\n x = e.pageX - this.offsetLeft,\n y = e.pageY - this.offsetTop,\n w = this.width,\n h = this.height;\n \n zCtx.clearRect(0,0,w,h);\n zCtx.drawImage(this, x-w/6,y-h/6,w, h, 0,0,w*3, h*3);\n}; <canvas id=\"canvas\" width=\"250\" height=\"250\" ></canvas>\n<canvas id=\"zoomed\" width=\"250\" height=\"250\" ></canvas> filter path/to/svg_file.svg#remove-alpha" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
195,267
<p>I'm trying to use the Windows API to set the primary monitor. It doesn't seem to work - my screen just flicks and nothing happens.</p> <pre><code> public const int DM_ORIENTATION = 0x00000001; public const int DM_PAPERSIZE = 0x00000002; public const int DM_PAPERLENGTH = 0x00000004; public const int DM_PAPERWIDTH = 0x00000008; public const int DM_SCALE = 0x00000010; public const int DM_POSITION = 0x00000020; public const int DM_NUP = 0x00000040; public const int DM_DISPLAYORIENTATION = 0x00000080; public const int DM_COPIES = 0x00000100; public const int DM_DEFAULTSOURCE = 0x00000200; public const int DM_PRINTQUALITY = 0x00000400; public const int DM_COLOR = 0x00000800; public const int DM_DUPLEX = 0x00001000; public const int DM_YRESOLUTION = 0x00002000; public const int DM_TTOPTION = 0x00004000; public const int DM_COLLATE = 0x00008000; public const int DM_FORMNAME = 0x00010000; public const int DM_LOGPIXELS = 0x00020000; public const int DM_BITSPERPEL = 0x00040000; public const int DM_PELSWIDTH = 0x00080000; public const int DM_PELSHEIGHT = 0x00100000; public const int DM_DISPLAYFLAGS = 0x00200000; public const int DM_DISPLAYFREQUENCY = 0x00400000; public const int DM_ICMMETHOD = 0x00800000; public const int DM_ICMINTENT = 0x01000000; public const int DM_MEDIATYPE = 0x02000000; public const int DM_DITHERTYPE = 0x04000000; public const int DM_PANNINGWIDTH = 0x08000000; public const int DM_PANNINGHEIGHT = 0x10000000; public const int DM_DISPLAYFIXEDOUTPUT = 0x20000000; public const int ENUM_CURRENT_SETTINGS = -1; public const int CDS_UPDATEREGISTRY = 0x01; public const int CDS_TEST = 0x02; public const int CDS_SET_PRIMARY = 0x00000010; public const long DISP_CHANGE_SUCCESSFUL = 0; public const long DISP_CHANGE_RESTART = 1; public const long DISP_CHANGE_FAILED = -1; public const long DISP_CHANGE_BADMODE = -2; public const long DISP_CHANGE_NOTUPDATED = -3; public const long DISP_CHANGE_BADFLAGS = -4; public const long DISP_CHANGE_BADPARAM = -5; public const long DISP_CHANGE_BADDUALVIEW = -6; public static void SetPrimary(Screen screen) { DISPLAY_DEVICE d = new DISPLAY_DEVICE(); DEVMODE dm = new DEVMODE(); d.cb = Marshal.SizeOf(d); uint deviceID = 1; User_32.EnumDisplayDevices(null, deviceID, ref d, 0); // User_32.EnumDisplaySettings(d.DeviceName, 0, ref dm); dm.dmPelsWidth = 2560; dm.dmPelsHeight = 1600; dm.dmPositionX = screen.Bounds.Right; dm.dmFields = DM_POSITION | DM_PELSWIDTH | DM_PELSHEIGHT; User_32.ChangeDisplaySettingsEx(d.DeviceName, ref dm, IntPtr.Zero, CDS_SET_PRIMARY, IntPtr.Zero); } </code></pre> <p>I call the method like this:</p> <pre><code>SetPrimary(Screen.AllScreens[1]) </code></pre> <p>Any ideas?</p>
[ { "answer_id": 195319, "author": "tobsen", "author_id": 27083, "author_profile": "https://Stackoverflow.com/users/27083", "pm_score": 2, "selected": false, "text": "rundll32.exe NvCpl.dll,dtcfg primary 2" }, { "answer_id": 23044185, "author": "ADBailey", "author_id": 3410046, "author_profile": "https://Stackoverflow.com/users/3410046", "pm_score": 3, "selected": false, "text": " public static void SetAsPrimaryMonitor(uint id)\n {\n var device = new DISPLAY_DEVICE();\n var deviceMode = new DEVMODE();\n device.cb = Marshal.SizeOf(device);\n\n NativeMethods.EnumDisplayDevices(null, id, ref device, 0);\n NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref deviceMode);\n var offsetx = deviceMode.dmPosition.x;\n var offsety = deviceMode.dmPosition.y;\n deviceMode.dmPosition.x = 0;\n deviceMode.dmPosition.y = 0;\n\n NativeMethods.ChangeDisplaySettingsEx(\n device.DeviceName, \n ref deviceMode, \n (IntPtr)null, \n (ChangeDisplaySettingsFlags.CDS_SET_PRIMARY | ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET), \n IntPtr.Zero);\n\n device = new DISPLAY_DEVICE();\n device.cb = Marshal.SizeOf(device);\n\n // Update remaining devices\n for (uint otherid = 0; NativeMethods.EnumDisplayDevices(null, otherid, ref device, 0); otherid++)\n {\n if (device.StateFlags.HasFlag(DisplayDeviceStateFlags.AttachedToDesktop) && otherid != id)\n {\n device.cb = Marshal.SizeOf(device);\n var otherDeviceMode = new DEVMODE();\n\n NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref otherDeviceMode);\n\n otherDeviceMode.dmPosition.x -= offsetx;\n otherDeviceMode.dmPosition.y -= offsety;\n\n NativeMethods.ChangeDisplaySettingsEx(\n device.DeviceName,\n ref otherDeviceMode,\n (IntPtr)null,\n (ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET),\n IntPtr.Zero);\n\n }\n\n device.cb = Marshal.SizeOf(device);\n }\n\n // Apply settings\n NativeMethods.ChangeDisplaySettingsEx(null, IntPtr.Zero, (IntPtr)null, ChangeDisplaySettingsFlags.CDS_NONE, (IntPtr)null);\n }\n [DllImport(\"user32.dll\")]\n public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, IntPtr lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);\n" }, { "answer_id": 36968861, "author": "Vladimir", "author_id": 1266849, "author_profile": "https://Stackoverflow.com/users/1266849", "pm_score": 3, "selected": false, "text": "public class MonitorChanger\n{\n public static void SetAsPrimaryMonitor(uint id)\n {\n var device = new DISPLAY_DEVICE();\n var deviceMode = new DEVMODE();\n device.cb = Marshal.SizeOf(device);\n\n NativeMethods.EnumDisplayDevices(null, id, ref device, 0);\n NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref deviceMode);\n var offsetx = deviceMode.dmPosition.x;\n var offsety = deviceMode.dmPosition.y;\n deviceMode.dmPosition.x = 0;\n deviceMode.dmPosition.y = 0;\n\n NativeMethods.ChangeDisplaySettingsEx(\n device.DeviceName,\n ref deviceMode,\n (IntPtr)null,\n (ChangeDisplaySettingsFlags.CDS_SET_PRIMARY | ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET),\n IntPtr.Zero);\n\n device = new DISPLAY_DEVICE();\n device.cb = Marshal.SizeOf(device);\n\n // Update remaining devices\n for (uint otherid = 0; NativeMethods.EnumDisplayDevices(null, otherid, ref device, 0); otherid++)\n {\n if (device.StateFlags.HasFlag(DisplayDeviceStateFlags.AttachedToDesktop) && otherid != id)\n {\n device.cb = Marshal.SizeOf(device);\n var otherDeviceMode = new DEVMODE();\n\n NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref otherDeviceMode);\n\n otherDeviceMode.dmPosition.x -= offsetx;\n otherDeviceMode.dmPosition.y -= offsety;\n\n NativeMethods.ChangeDisplaySettingsEx(\n device.DeviceName,\n ref otherDeviceMode,\n (IntPtr)null,\n (ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET),\n IntPtr.Zero);\n\n }\n\n device.cb = Marshal.SizeOf(device);\n }\n\n // Apply settings\n NativeMethods.ChangeDisplaySettingsEx(null, IntPtr.Zero, (IntPtr)null, ChangeDisplaySettingsFlags.CDS_NONE, (IntPtr)null);\n }\n}\n\n[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]\npublic struct DEVMODE\n{\n public const int CCHDEVICENAME = 32;\n public const int CCHFORMNAME = 32;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]\n [System.Runtime.InteropServices.FieldOffset(0)]\n public string dmDeviceName;\n [System.Runtime.InteropServices.FieldOffset(32)]\n public Int16 dmSpecVersion;\n [System.Runtime.InteropServices.FieldOffset(34)]\n public Int16 dmDriverVersion;\n [System.Runtime.InteropServices.FieldOffset(36)]\n public Int16 dmSize;\n [System.Runtime.InteropServices.FieldOffset(38)]\n public Int16 dmDriverExtra;\n [System.Runtime.InteropServices.FieldOffset(40)]\n public UInt32 dmFields;\n\n [System.Runtime.InteropServices.FieldOffset(44)]\n Int16 dmOrientation;\n [System.Runtime.InteropServices.FieldOffset(46)]\n Int16 dmPaperSize;\n [System.Runtime.InteropServices.FieldOffset(48)]\n Int16 dmPaperLength;\n [System.Runtime.InteropServices.FieldOffset(50)]\n Int16 dmPaperWidth;\n [System.Runtime.InteropServices.FieldOffset(52)]\n Int16 dmScale;\n [System.Runtime.InteropServices.FieldOffset(54)]\n Int16 dmCopies;\n [System.Runtime.InteropServices.FieldOffset(56)]\n Int16 dmDefaultSource;\n [System.Runtime.InteropServices.FieldOffset(58)]\n Int16 dmPrintQuality;\n\n [System.Runtime.InteropServices.FieldOffset(44)]\n public POINTL dmPosition;\n [System.Runtime.InteropServices.FieldOffset(52)]\n public Int32 dmDisplayOrientation;\n [System.Runtime.InteropServices.FieldOffset(56)]\n public Int32 dmDisplayFixedOutput;\n\n [System.Runtime.InteropServices.FieldOffset(60)]\n public short dmColor; // See note below!\n [System.Runtime.InteropServices.FieldOffset(62)]\n public short dmDuplex; // See note below!\n [System.Runtime.InteropServices.FieldOffset(64)]\n public short dmYResolution;\n [System.Runtime.InteropServices.FieldOffset(66)]\n public short dmTTOption;\n [System.Runtime.InteropServices.FieldOffset(68)]\n public short dmCollate; // See note below!\n [System.Runtime.InteropServices.FieldOffset(72)]\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)]\n public string dmFormName;\n [System.Runtime.InteropServices.FieldOffset(102)]\n public Int16 dmLogPixels;\n [System.Runtime.InteropServices.FieldOffset(104)]\n public Int32 dmBitsPerPel;\n [System.Runtime.InteropServices.FieldOffset(108)]\n public Int32 dmPelsWidth;\n [System.Runtime.InteropServices.FieldOffset(112)]\n public Int32 dmPelsHeight;\n [System.Runtime.InteropServices.FieldOffset(116)]\n public Int32 dmDisplayFlags;\n [System.Runtime.InteropServices.FieldOffset(116)]\n public Int32 dmNup;\n [System.Runtime.InteropServices.FieldOffset(120)]\n public Int32 dmDisplayFrequency;\n}\n\npublic enum DISP_CHANGE : int\n{\n Successful = 0,\n Restart = 1,\n Failed = -1,\n BadMode = -2,\n NotUpdated = -3,\n BadFlags = -4,\n BadParam = -5,\n BadDualView = -6\n}\n\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic struct DISPLAY_DEVICE\n{\n [MarshalAs(UnmanagedType.U4)]\n public int cb;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n public string DeviceName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceString;\n [MarshalAs(UnmanagedType.U4)]\n public DisplayDeviceStateFlags StateFlags;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceID;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceKey;\n}\n\n[Flags()]\npublic enum DisplayDeviceStateFlags : int\n{\n /// <summary>The device is part of the desktop.</summary>\n AttachedToDesktop = 0x1,\n MultiDriver = 0x2,\n /// <summary>The device is part of the desktop.</summary>\n PrimaryDevice = 0x4,\n /// <summary>Represents a pseudo device used to mirror application drawing for remoting or other purposes.</summary>\n MirroringDriver = 0x8,\n /// <summary>The device is VGA compatible.</summary>\n VGACompatible = 0x10,\n /// <summary>The device is removable; it cannot be the primary display.</summary>\n Removable = 0x20,\n /// <summary>The device has more display modes than its output devices support.</summary>\n ModesPruned = 0x8000000,\n Remote = 0x4000000,\n Disconnect = 0x2000000,\n}\n\n[Flags()]\npublic enum ChangeDisplaySettingsFlags : uint\n{\n CDS_NONE = 0,\n CDS_UPDATEREGISTRY = 0x00000001,\n CDS_TEST = 0x00000002,\n CDS_FULLSCREEN = 0x00000004,\n CDS_GLOBAL = 0x00000008,\n CDS_SET_PRIMARY = 0x00000010,\n CDS_VIDEOPARAMETERS = 0x00000020,\n CDS_ENABLE_UNSAFE_MODES = 0x00000100,\n CDS_DISABLE_UNSAFE_MODES = 0x00000200,\n CDS_RESET = 0x40000000,\n CDS_RESET_EX = 0x20000000,\n CDS_NORESET = 0x10000000\n}\n\npublic class NativeMethods\n{\n [DllImport(\"user32.dll\")]\n public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n // A signature for ChangeDisplaySettingsEx with a DEVMODE struct as the second parameter won't allow you to pass in IntPtr.Zero, so create an overload\n public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, IntPtr lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n public static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);\n\n [DllImport(\"user32.dll\")]\n public static extern bool EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE devMode);\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct POINTL\n{\n public int x;\n public int y;\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2972/" ]
195,270
<p>Are there any <strong>professional</strong> Combobox controls (dropdown list with autosuggestion) based on the jQuery library?</p> <p>It should be able to handle <strong>large datasets</strong> and have some <strong>skinning</strong> options. A <strong>multi-column result list</strong> would be great too. I'm working with ASP.NET, but it's a not a problem if I had to write a wrapper for it.</p> <p><img src="https://i.stack.imgur.com/ilhvD.png" alt="alt text"></p> <p><em>I'm already using a third-party control, but I ran into some compatibilty issues between two vendor's controls. Well, I want to get rid of this kind of dependencies.</em></p>
[ { "answer_id": 5609429, "author": "Danny W. Adair", "author_id": 640759, "author_profile": "https://Stackoverflow.com/users/640759", "pm_score": 5, "selected": false, "text": "<select id=\"combo4\" style=\"width: 200px;\"\n onchange=\"$('input#text4').val($(this).val());\">\n <option>option 1</option>\n <option>option 2</option>\n <option>option 3</option>\n</select>\n<input id=\"text4\"\n style=\"margin-left: -203px; width: 180px; height: 1.2em; border: 0;\" />\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
195,287
<p>I'd like to get all the permutations of swapped characters pairs of a string. For example:</p> <p>Base string: <code>abcd</code></p> <p>Combinations:</p> <ol> <li><code>bacd</code></li> <li><code>acbd</code></li> <li><code>abdc</code></li> </ol> <p>etc.</p> <h3>Edit</h3> <p>I want to swap only letters that are next to each other. Like first with second, second with third, but not third with sixth.</p> <p>What's the best way to do this?</p> <h3>Edit</h3> <p>Just for fun: there are three or four solutions, could somebody post a speed test of those so we could compare which is fastest?</p> <h3>Speed test</h3> <p>I made speed test of nickf's code and mine, and results are that mine is beating the nickf's at four letters (0.08 and 0.06 for 10K times) but nickf's is beating it at 10 letters (nick's 0.24 and mine 0.37)</p>
[ { "answer_id": 195295, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": true, "text": "$input = \"abcd\";\n$len = strlen($input);\n$output = array();\n\nfor ($i = 0; $i < $len - 1; ++$i) {\n $output[] = substr($input, 0, $i)\n . substr($input, $i + 1, 1)\n . substr($input, $i, 1)\n . substr($input, $i + 2);\n}\nprint_r($output);\n" }, { "answer_id": 195313, "author": "Chris", "author_id": 27186, "author_profile": "https://Stackoverflow.com/users/27186", "pm_score": 1, "selected": false, "text": " $arr=array(0=>'a',1=>'b',2=>'c',3=>'d');\n for($i=0;$i<count($arr)-1;$i++){\n $swapped=\"\";\n //Make normal before swapped\n for($z=0;$z<$i;$z++){\n $swapped.=$arr[$z];\n }\n //Create swapped\n $i1=$i+1;\n $swapped.=$arr[$i1].$arr[$i];\n\n //Make normal after swapped. \n for($y=$z+2;$y<count($arr);$y++){\n $swapped.=$arr[$y];\n\n }\n$arrayswapped[$i]=$swapped;\n}\nvar_dump($arrayswapped);\n" }, { "answer_id": 195337, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 0, "selected": false, "text": "function swap($s, $i)\n{\n $t = $s[$i];\n $s[$i] = $s[$i+1];\n $s[$i+1] = $t;\n\n return $s;\n}\n\n$s = \"abcd\";\n$l = strlen($s);\nfor ($i=0; $i<$l-1; ++$i)\n{\n print swap($s,$i).\"\\n\";\n}\n" }, { "answer_id": 195738, "author": "Czimi", "author_id": 3906, "author_profile": "https://Stackoverflow.com/users/3906", "pm_score": 0, "selected": false, "text": "function swapcharpairs($input = \"abcd\") {\n $pre = \"\";\n $a=\"\";\n $b = $input[0];\n $post = substr($input, 1);\n while($post!='') {\n $pre.=$a;\n $a=$b;\n $b=$post[0];\n $post=substr($post,1);\n $swaps[] = $pre.$b.$a.$post;\n };\n return $swaps;\n}\n\nprint_R(swapcharpairs());\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27186/" ]
195,288
<p>I'm working on an ASP.NET website where I am using an asp:repeater with paging done through a VB.NET code-behind file. I'm having trouble with the database connection though. As far as I can tell, the paging is working, but I can't get the data to be certain.</p> <p>The database is a Microsoft Access database. The function that should be accessing the database is:</p> <pre><code>Dim pagedData As New PagedDataSource Sub Page_Load(ByVal obj As Object, ByVal e As EventArgs) doPaging() End Sub Function getTheData() As DataTable Dim DS As New DataSet() Dim strConnect As New OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;Data Source=App_Data/ArtDatabase.mdb") Dim objOleDBAdapter As New OleDbDataAdapter("SELECT ArtID, FileLocation, Title, UserName, ArtDate FROM Art ORDER BY Art.ArtDate DESC", strConnect) objOleDBAdapter.Fill(DS, "Art") Return DS.Tables("Art").Copy End Function Sub doPaging() pagedData.DataSource = getTheData().DefaultView pagedData.AllowPaging = True pagedData.PageSize = 2 Try pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString() Catch ex As Exception pagedData.CurrentPageIndex = 0 End Try btnPrev.Visible = (Not pagedData.IsFirstPage) btnNext.Visible = (Not pagedData.IsLastPage) pageNumber.Text = (pagedData.CurrentPageIndex + 1) &amp; " of " &amp; pagedData.PageCount ArtRepeater.DataSource = pagedData ArtRepeater.DataBind() End Sub </code></pre> <p>The ASP.NET is:</p> <pre><code>&lt;asp:Repeater ID="ArtRepeater" runat="server"&gt; &lt;HeaderTemplate&gt; &lt;h2&gt;Items in Selected Category:&lt;/h2&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;li&gt; &lt;asp:HyperLink runat="server" ID="HyperLink" NavigateUrl='&lt;%# Eval("ArtID", "ArtPiece.aspx?ArtID={0}") %&gt;'&gt; &lt;img src="&lt;%# Eval("FileLocation") %&gt;" alt="&lt;%# DataBinder.Eval(Container.DataItem, "Title") %&gt;t"/&gt; &lt;br /&gt; &lt;%# DataBinder.Eval(Container.DataItem, "Title") %&gt; &lt;/asp:HyperLink&gt; &lt;/li&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre>
[ { "answer_id": 201365, "author": "Matt", "author_id": 17020, "author_profile": "https://Stackoverflow.com/users/17020", "pm_score": 1, "selected": true, "text": "Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n doPaging()\nEnd Sub\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17020/" ]
195,317
<p>I am tryiing to create an "add to cart" button for each item that is displayed by an XSLT file. The button must be run at server (VB) and I need to pass parameters into the onlick, so that the requested item is added to the cart. Is this possible, and if so, how should I go about it?</p> <p>When I try</p> <pre><code>&lt;asp:Button id="Button123" Text="Add to Cart" CommandName="AddToCart" CommandArgument="123" OnCommand="CommandBtn_Click" runat="server"/&gt; </code></pre> <p>I get "'asp' is an undeclared namespace"</p> <p>I've also tried</p> <pre><code>&lt;asp&gt; &lt;xsl:attribute name="Button"&gt;id="BtnAddToCart"&lt;/xsl:attribute&gt; &lt;xsl:attribute name="text"&gt;Add to cart&lt;/xsl:attribute&gt; &lt;xsl:attribute name="CommandName"&gt;AddToCart&lt;/xsl:attribute&gt; &lt;xsl:attribute name="CommandArgument"&gt;123&lt;/xsl:attribute&gt; &lt;xsl:attribute name="Command"&gt;CommandBtn_Click&lt;/xsl:attribute&gt; &lt;xsl:attribute name="runat"&gt;server"&lt;/xsl:attribute&gt; &lt;/asp&gt; </code></pre> <p>Which doesn't give any errors, but doesn't do anything at all</p> <p>I need to use XSLT directly for displaying my products, as it is for an assignment, although what I am trying to do here is beyond the scope of the assignment.</p>
[ { "answer_id": 195384, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 2, "selected": false, "text": "<asp:Button id=\"Button123\"\n Text=\"Add to Cart\"\n CommandName=\"AddToCart\"\n CommandArgument=\"123\"\n OnCommand=\"CommandBtn_Click\" \n runat=\"server\"/>\n <xsl:for-each select=\"Item\">\n ...\n <asp:Button id=\"Button{@Id}\"\n Text=\"Add To Cart\"\n CommandName=\"AddToCart\"\n CommandArgument=\"{@Id}\"\n OnCommand=\"CommandBtn_Click\" \n runat=\"server\"/>\n</xsl:foreach>\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
195,321
<p><a href="https://stackoverflow.com/users/9931/ryan-delucchi">Ryan Delucchi</a> asked <a href="https://stackoverflow.com/questions/194698/how-to-load-a-jar-file-at-runtime#194712">here</a> in comment #3 to <a href="https://stackoverflow.com/users/4725/tom-hawtin-tackline">Tom Hawtin</a>'s answer:</p> <blockquote> <p>why is Class.newInstance() "evil"?</p> </blockquote> <p>this in response to the code sample:</p> <pre><code>// Avoid Class.newInstance, for it is evil. Constructor&lt;? extends Runnable&gt; ctor = runClass.getConstructor(); Runnable doRun = ctor.newInstance(); </code></pre> <p>so, why is it Evil?</p>
[ { "answer_id": 195328, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 7, "selected": true, "text": "Constructor.newInstance InvocationTargetException" }, { "answer_id": 53014482, "author": "Eugene", "author_id": 1059372, "author_profile": "https://Stackoverflow.com/users/1059372", "pm_score": 4, "selected": false, "text": "Constructor::newInstance Class::newInstance static class Foo {\n public Foo() throws IOException {\n throw new IOException();\n }\n}\n Class::newInstance Class<Foo> clazz = ...\n\n try {\n clazz.newInstance();\n } catch (InstantiationException e) {\n // handle 1\n } catch (IllegalAccessException e) {\n // handle 2\n }\n IOException handle 1 handle 2 Constructor Constructor<Foo> constructor = null;\n try {\n constructor = clazz.getConstructor();\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n }\n\n try {\n Foo foo = constructor.newInstance();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n System.out.println(\"handle 3 called\");\n e.printStackTrace();\n }\n Class::newInstance" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11813/" ]
195,323
<p>I'd like to read whole content of a text file to a <code>std::string</code> object with c++. </p> <p>With Python, I can write:</p> <pre><code>text = open("text.txt", "rt").read() </code></pre> <p>It is very simple and elegant. I hate ugly stuff, so I'd like to know - what is the most elegant way to read a text file with C++? Thanks.</p>
[ { "answer_id": 195350, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 8, "selected": true, "text": "ifstream file (\"file.txt\", ios::in|ios::binary|ios::ate);\nif (file.is_open())\n{\n file.seekg(0, ios::end);\n size = file.tellg();\n char *contents = new char [size];\n file.seekg (0, ios::beg);\n file.read (contents, size);\n file.close();\n //... do something with it\n delete [] contents;\n}\n std::ifstream in(\"file.txt\");\nstd::string contents((std::istreambuf_iterator<char>(in)), \n std::istreambuf_iterator<char>());\n std::ifstream in(\"file.txt\");\nstd::vector<char> contents((std::istreambuf_iterator<char>(in)),\n std::istreambuf_iterator<char>());\n std::ifstream in(\"file.txt\");\nstd::stringstream buffer;\nbuffer << in.rdbuf();\nstd::string contents(buffer.str());\n" }, { "answer_id": 195545, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 0, "selected": false, "text": "\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <cstdlib>\nusing namespace std;\n\nstring& getfile(const string& filename, string& buffer) {\n ifstream in(filename.c_str(), ios_base::binary | ios_base::ate);\n in.exceptions(ios_base::badbit | ios_base::failbit | ios_base::eofbit);\n buffer.resize(in.tellg());\n in.seekg(0, ios_base::beg);\n in.read(&buffer[0], buffer.size());\n return buffer;\n}\n\nint main(int argc, char* argv[]) {\n if (argc != 2) {\n cerr << \"Usage: this_executable file_to_read\\n\";\n return EXIT_FAILURE;\n }\n string buffer;\n cout << getfile(argv[1], buffer).size() << \"\\n\";\n}\n \n#include <iostream>\n#include <string>\n#include <fstream>\n#include <cstdlib>\nusing namespace std;\n\nstring getfile(const string& filename) {\n ifstream in(filename.c_str(), ios_base::binary);\n in.exceptions(ios_base::badbit | ios_base::failbit | ios_base::eofbit);\n return string(istreambuf_iterator<char>(in), istreambuf_iterator<char>());\n}\n\nint main(int argc, char* argv[]) {\n if (argc != 2) {\n cerr << \"Usage: this_executable file_to_read\\n\";\n return EXIT_FAILURE;\n }\n cout << getfile(argv[1]).size() << \"\\n\";\n}\n" }, { "answer_id": 195558, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "string str((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());\n string str(static_cast<stringstream const&>(stringstream() << ifs.rdbuf()).str());\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25077/" ]
195,332
<p>What are the possibilities of a programmer to handle data that are rarely used but cannot be simply deleted because at least reporting still requires it?</p> <p>Some examples I am thinking of:</p> <ul> <li>Discountinued funding types of older years of a university</li> <li>Unused currencies (e.g. Italian lira)</li> <li>Names of disappeared countries (e.g. Austro-Hungary, USSR)</li> </ul> <p>Some partial solutions are activity flags, activity periods, priorities of visualization but each of them means a case by case decision and it is hard to know what types of entities need this special handling.</p> <p>May be there is a design pattern for this problem.</p> <p><strong>Conclusions:</strong> (based on the answers so far)</p> <ul> <li><p>If old data makes everyday work difficult on a huge database, partitioning would be helpful. Oracle's description on this subject is <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/partiti.htm" rel="noreferrer">here</a>.</p></li> <li><p>From the point of view of the designer the taxonomy of <a href="http://en.wikipedia.org/wiki/Slowly_changing_dimension" rel="noreferrer">Slowly changing dimension</a> gives some background information. </p></li> </ul>
[ { "answer_id": 195431, "author": "Andrew not the Saint", "author_id": 23670, "author_profile": "https://Stackoverflow.com/users/23670", "pm_score": 2, "selected": false, "text": "CREATE TABLE Currency (CurrencyID NUMBER, CurrencyStartDate DATETIME, CurrentEndDate DATETIME)\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21047/" ]
195,363
<p>In IE when I insert text into a <code>&lt;pre&gt;</code> tag the newlines are ignored:</p> <pre><code>&lt;pre id="putItHere"&gt;&lt;/pre&gt; &lt;script&gt; function putText() { document.getElementById("putItHere").innerHTML = "first line\nsecond line"; } &lt;/script&gt; </code></pre> <p>Using <code>\r\n</code> instead of a plain <code>\n</code> does not work. </p> <p><code>&lt;br/&gt;</code> does work but inserts an extra blank line in FF, which is not acceptable for my purposes.</p>
[ { "answer_id": 195370, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 2, "selected": false, "text": "<br/> document.getElementById(\"putItHere\").innerHTML = \"first line<br/>second line\";\n" }, { "answer_id": 195385, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "document.getElementById(\"putItHere\")\n .appendChild(document.createTextNode(\"first line\\nsecond line\"));\n" }, { "answer_id": 195399, "author": "Samuel Kim", "author_id": 437435, "author_profile": "https://Stackoverflow.com/users/437435", "pm_score": 2, "selected": false, "text": "<pre> <pre> <pre> document.getElementById(\"putItHere\").innerText = \"first line\\nsecond line\";\n" }, { "answer_id": 195407, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var newline;\nif ( document.all ) newline = '\\r\\n';\nelse newline = '\\n';\n\nvar data = 'firstline' + newline + 'second line';\ndocument.getElementById(\"putItHere\").appendChild(document.createTextNode(data));\n var br = ed.dom.select('pre br');\n for (var i = 0; i < br.length; i++) {\n var nlChar;\n if (tinymce.isIE)\n nlChar = '\\r\\n';\n else\n nlChar = '\\n';\n\n var nl = ed.getDoc().createTextNode(nlChar);\n ed.dom.insertAfter(nl, br[i]);\n ed.dom.remove(br[i]);\n }\n" }, { "answer_id": 363188, "author": "Edward Wilde", "author_id": 5182, "author_profile": "https://Stackoverflow.com/users/5182", "pm_score": 3, "selected": false, "text": "if (elem.tagName == \"PRE\" && \"outerHTML\" in elem)\n{\n elem.outerHTML = \"<PRE>\" + str + \"</PRE>\";\n}\nelse\n{\n elem.innerHTML = str;\n}\n" }, { "answer_id": 613542, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if (typeof div2.innerText == 'undefined')\n div2.innerHTML = value;\nelse\n div2.innerText = value;\n" }, { "answer_id": 825098, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "document.getElementById('pre_id').firstChild.nodeValue=' white space \\r\\n ad new line';\n" }, { "answer_id": 2720402, "author": "Vivek Jani", "author_id": 326768, "author_profile": "https://Stackoverflow.com/users/326768", "pm_score": 1, "selected": false, "text": " if(isIE)\n document.getElementById(\"putItHere\").innerHTML = \"<pre>\" + content+\"</pre>\";\n else\n document.getElementById(\"putItHere\").innerHTML = content;\n" }, { "answer_id": 5263220, "author": "Drew", "author_id": 160755, "author_profile": "https://Stackoverflow.com/users/160755", "pm_score": 2, "selected": false, "text": "var t = document.createElement(elem.tagName);\nt.innerHTML = \"\\n\";\n\nif( t.innerHTML === \"\\n\" ){\n elem.innerHTML = str;\n}\nelse if(\"outerHTML\" in elem)\n{\n elem.outerHTML = \"<\"+elem.tagName+\">\" + str + \"</\"+elem.tagName+\">\";\n}\nelse {\n // fallback of your choice, probably do the first one.\n}\n" }, { "answer_id": 8402133, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "if (elem.tagName == \"PRE\" && \"outerHTML\" in elem) {\n var outer = elem.outerHTML;\n elem.outerHTML = outer.substring(0, outer.indexOf('>') + 1) + str + \"</PRE>\";\n}\nelse {\n elem.innerHTML = str;\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27198/" ]
195,368
<p>How is it possible for this to be true</p> <pre><code>XmlDocument d = BuildReportXML(schema); DataSet ds = new DataSet(); ds.ReadXmlSchema(schema); ds.ReadXml(new XmlNodeReader(d)); </code></pre> <p>Schema is the schema location that I apply to the XmlDocument before I start setting data, assuring that all the columns are of the correct type. Then I set the schema to the DataSet, and read the document into it. When I do this it throws an "Input string was not in a correct format." I have a few decimal variables in the Xml, and I assume this is the error. All of the information is obviously of the correct format, else the XmlDocument would have had errors. What can I do?</p>
[ { "answer_id": 195370, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 2, "selected": false, "text": "<br/> document.getElementById(\"putItHere\").innerHTML = \"first line<br/>second line\";\n" }, { "answer_id": 195385, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "document.getElementById(\"putItHere\")\n .appendChild(document.createTextNode(\"first line\\nsecond line\"));\n" }, { "answer_id": 195399, "author": "Samuel Kim", "author_id": 437435, "author_profile": "https://Stackoverflow.com/users/437435", "pm_score": 2, "selected": false, "text": "<pre> <pre> <pre> document.getElementById(\"putItHere\").innerText = \"first line\\nsecond line\";\n" }, { "answer_id": 195407, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var newline;\nif ( document.all ) newline = '\\r\\n';\nelse newline = '\\n';\n\nvar data = 'firstline' + newline + 'second line';\ndocument.getElementById(\"putItHere\").appendChild(document.createTextNode(data));\n var br = ed.dom.select('pre br');\n for (var i = 0; i < br.length; i++) {\n var nlChar;\n if (tinymce.isIE)\n nlChar = '\\r\\n';\n else\n nlChar = '\\n';\n\n var nl = ed.getDoc().createTextNode(nlChar);\n ed.dom.insertAfter(nl, br[i]);\n ed.dom.remove(br[i]);\n }\n" }, { "answer_id": 363188, "author": "Edward Wilde", "author_id": 5182, "author_profile": "https://Stackoverflow.com/users/5182", "pm_score": 3, "selected": false, "text": "if (elem.tagName == \"PRE\" && \"outerHTML\" in elem)\n{\n elem.outerHTML = \"<PRE>\" + str + \"</PRE>\";\n}\nelse\n{\n elem.innerHTML = str;\n}\n" }, { "answer_id": 613542, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if (typeof div2.innerText == 'undefined')\n div2.innerHTML = value;\nelse\n div2.innerText = value;\n" }, { "answer_id": 825098, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "document.getElementById('pre_id').firstChild.nodeValue=' white space \\r\\n ad new line';\n" }, { "answer_id": 2720402, "author": "Vivek Jani", "author_id": 326768, "author_profile": "https://Stackoverflow.com/users/326768", "pm_score": 1, "selected": false, "text": " if(isIE)\n document.getElementById(\"putItHere\").innerHTML = \"<pre>\" + content+\"</pre>\";\n else\n document.getElementById(\"putItHere\").innerHTML = content;\n" }, { "answer_id": 5263220, "author": "Drew", "author_id": 160755, "author_profile": "https://Stackoverflow.com/users/160755", "pm_score": 2, "selected": false, "text": "var t = document.createElement(elem.tagName);\nt.innerHTML = \"\\n\";\n\nif( t.innerHTML === \"\\n\" ){\n elem.innerHTML = str;\n}\nelse if(\"outerHTML\" in elem)\n{\n elem.outerHTML = \"<\"+elem.tagName+\">\" + str + \"</\"+elem.tagName+\">\";\n}\nelse {\n // fallback of your choice, probably do the first one.\n}\n" }, { "answer_id": 8402133, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "if (elem.tagName == \"PRE\" && \"outerHTML\" in elem) {\n var outer = elem.outerHTML;\n elem.outerHTML = outer.substring(0, outer.indexOf('>') + 1) + str + \"</PRE>\";\n}\nelse {\n elem.innerHTML = str;\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11137/" ]
195,408
<p>I'm looking for a technique (javascript, CSS, whatever ???) that will let me control the amount of a string that is displayed. The string is the result of a search (and therefore not initially known). A simple Character count approach is trivial, but not acceptable, as it needs to handle proportional fonts. In otherwords if I want to limit to say 70 pixels then the examples below show different character counts (9 and 15) both measuring the same:-</p> <p>Welcome M...<br> Hi Iain if I've ...</p> <p>If you look at Yahoo search results they are able to limit the length of title strings and add ellipsis on the end of long strings to indicate more. (try site:loot.com wireless+keyboard+and+mouse to see an example of Yahoo achieving this)</p> <p>Any Ideas?</p>
[ { "answer_id": 195413, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": true, "text": "overflow: hidden; width" }, { "answer_id": 195435, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 0, "selected": false, "text": "overflow: hidden overflow:hidden; W (char_count * width_of_w) > desired_width text-wrap: none;" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27200/" ]
195,410
<p>I am interested in what methods of logging is frequent in an Oracle database. Our method is the following:</p> <p>We create a log table for the table to be logged. The log table contains all the columns of the original table plus some special fields including timestamp, modification type (insert, update, delete), modifier's id. A trigger on the original table creates one log row for each insertion and deletion, and two rows for a modification. Log rows contain the data before and after the alteration of the original one.</p> <p>Although state of the records can be mined back in time using this method, it has some drawbacks:</p> <ul> <li>Introduction of a new column in the original table does not automatically involves log modification.</li> <li>Log modification affects log table and trigger and it is easy to mess up.</li> <li>State of a record at a specific past time cannot be determined in a straightforward way.</li> <li>...</li> </ul> <p>What other possibilities exist? What kind of tools can be used to solve this problem?</p> <p>I only know of <a href="http://log4plsql.sourceforge.net/" rel="noreferrer">log4plsql</a>. What are the pros/cons of this tool?</p> <p>Edit: Based on Brian's answer I have found the following <a href="http://www.oracle-base.com/articles/10g/Auditing_10gR2.php" rel="noreferrer">reference</a> that explains standard and fine grain auditing.</p>
[ { "answer_id": 196454, "author": "Salamander2007", "author_id": 10629, "author_profile": "https://Stackoverflow.com/users/10629", "pm_score": 2, "selected": false, "text": "+----------------------------------------------------------------------------+\n| Column Name | Function |\n+----------------------------------------------------------------------------+\n| Id | PRIMARY_KEY value of the SOURCE table |\n| TimeStamp | Time stamp of the action |\n| User | User who make the action |\n| ActionType | INSERT, UPDATE, or DELETE |\n| OldValues | All fields value from source table, seperated by '|' |\n| Newvalues | All fields value from source table, seperated by '|' |\n+----------------------------------------------------------------------------+\n" }, { "answer_id": 196630, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 4, "selected": true, "text": "audit UPDATE on SCOTT.EMP by access;\n begin\n dbms_fga.add_policy (\n object_schema=>'BANK',\n object_name=>'ACCOUNTS',\n policy_name=>'ACCOUNTS_ACCESS'\n );\nend;\n select * from bank.accounts; \n select timestamp, \n db_user,\n os_user,\n object_schema,\n object_name,\n sql_text\nfrom dba_fga_audit_trail;\n\nTIMESTAMP DB_USER OS_USER OBJECT_ OBJECT_N SQL_TEXT\n--------- ------- ------- ------- -------- ----------------------\n22-OCT-08 BANK ananda BANK ACCOUNTS select * from accounts\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21047/" ]
195,420
<p>I have read (or perhaps heard from a colleague) that in .NET, TransactionScope can hit its timeout and then VoteCommit (as opposed to VoteRollback). Is this accurate or hearsay? I couldn't track down information on the web that talked about this issue (if it IS an issue), so I wonder if anyone has any direct experience with it and can shed some light?</p>
[ { "answer_id": 195427, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "Transaction Binding=Explicit Unbind; TransactionScope" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20971/" ]
195,434
<p>I know its possible to get the top terms within a Lucene Index, but is there a way to get the top terms based on a subset of a Lucene index?</p> <p>I.e. What are the top terms in the Index for documents within a certain date range?</p>
[ { "answer_id": 224131, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 3, "selected": false, "text": "Query Filter IndexSearcher.search(Query, Filter, HitCollector) HitCollector IndexReader.getTermFreqVector TermVectorMapper map term frequency frequency TermVectorMapper getTermFreqVector isIgnoringPositions() isIgnoringOffsets() true TermVectorMapper setExpectations HitCollector getTermFreqVector" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1982/" ]
195,437
<p>Would it be possible to execute a JSP page and capture its output outside of a web application? Mode specifically, in my case there still exists a usual web application, but it loads JSP pages not from its classpath, but from an arbitrary source. It seems like I cannot simply get RequestDispatcher and point it to a JSP file on disk. </p>
[ { "answer_id": 195503, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 2, "selected": false, "text": "<jsp-config>\n <jsp-property-group>\n <url-pattern>*.jsp</url-pattern>\n <scripting-invalid>true</scripting-invalid>\n </jsp-property-group>\n</jsp-config>\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6954/" ]
195,439
<p>Using web forms I know that you can only have one ASP.NET form on a page. I've done some implementations where I've used Javascript to add other forms to a page to support things like logon controls (that post back to Logon.aspx instead of the current page). I'm wondering if the single form per page is still present in ASP.NET MVC or if this restriction has been lifted.</p>
[ { "answer_id": 195479, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "runat=\"server\" runat='server' LiteralControl HtmlForm <%= code blocks %> <%= Html.Button() %>" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12950/" ]
195,450
<p>I'm considering building a framework for VB.NET, and using the My namespace to plug it into VB seems like a reasonable idea. What is &quot;My&quot; used for?</p>
[ { "answer_id": 195467, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 2, "selected": false, "text": "My Environment.SpecialFolder Temp My.Computer.FileSystem.SpecialDirectories Path.GetTempPath() My My My" }, { "answer_id": 195563, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "My My.Computer" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18426/" ]
195,451
<p>I use <code>public boolean mouseDown(Event ev, int x, int y)</code> to detect a click of the mouse.<br> I can distinguish between the right mouse button (ev.metaDown() is true) and the left and middle.</p> <p>How can i differentiate the left from the middle button? Or if it is impossible with mouseDown, what should i use?</p>
[ { "answer_id": 270373, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 2, "selected": true, "text": "if (ev.modifiers & Event.ALT_MASK != 0) {\n // middle button was pressed\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12860/" ]
195,454
<p>How can I <strong>protect a ClickOnce deployed application with a password</strong>? Do I have to change the IIS settings of the web or is there a way to do it programmatically? I'm using Visual Studio 2005 (.NET 2.0).</p> <p>If I have to use web credentials, are auto-updates of the application still possible?</p> <p>Would be great if you could provide some sample code or detailed instructions for administering IIS.</p> <p>Thank you! </p>
[ { "answer_id": 215100, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 5, "selected": true, "text": "http://servername.adatum.com/WindowsApp1.application?username=joeuser\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
195,455
<p>I am writing a compiler in F# and I want to be able to access the <a href="http://msdn.microsoft.com/en-us/library/ms404384.aspx" rel="nofollow noreferrer">unmanaged metadata COM interfaces</a> in the .net runtime. Before anybody mentions it, <em>Reflection.Emit is not suitable for my purposes</em>, nor do I want to use any other method than the metadata COM interfaces.</p> <p>I've imported mscoree.tlb but it doesn't seem to include the interfaces I need.</p> <p>The interfaces I'm interested in include <a href="http://msdn.microsoft.com/en-us/library/ms230877.aspx" rel="nofollow noreferrer">IMetaDataEmit</a>. Any sample code relating to this would be very useful, though I've not been able to find any so far.</p> <p>C# samples would be fine as I can easily convert them to F#.</p> <p>Thanks in advance to anybody who can help me with this rather cryptic query!</p> <p><strong>Update:</strong> I have now got this sorted by writing explicit COM references using the interface GUIDs!</p>
[ { "answer_id": 215100, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 5, "selected": true, "text": "http://servername.adatum.com/WindowsApp1.application?username=joeuser\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394/" ]
195,468
<p>Basically, I have a class with 2 methods: one to serialize an object into an XML file and another to read an object from XML. Here is an example of synchronized part from the method that restores an object:</p> <pre><code> public T restore(String from) throws Exception { // variables declaration synchronized (from) { try { decoder = new XMLDecoder(new BufferedInputStream( new FileInputStream(from))); restoredItem = decoder.readObject(); decoder.close(); } catch (Exception e) { logger.warning("file not found or smth: " + from); throw new Exception(e); } } // try to cast it } </code></pre> <p>A similar approach is taken when serializing an object. Now, when I create a unit test which in turn creates 10 threads with each thread trying to serialize and instantly read either a Boolean or a String it would fail showing that ClassCastExceptions occur. This makes me think that I get serialization wrong (everything's ok in a single-threaded environment). If you've stayed with me down to this point :), here are the 2 issues I need your help on:</p> <ol> <li>does it make sense to synchronize on a string argument passed to method (considering there's a string pool in java)? BTW, I've tried synchronizing on the XMLSerializer class itself with result staying the same.</li> <li>how do i correctly synchronize io operations on a single file?</li> </ol>
[ { "answer_id": 195796, "author": "Ran Biron", "author_id": 931, "author_profile": "https://Stackoverflow.com/users/931", "pm_score": 4, "selected": true, "text": "StringBuffer sb = new StringBuffer(); sb.append(\"a\").append(\"b\");\nString a = new String(sb.toString());\nString b = new String(sb.toString());\na == b; //false\na.equals(b); //true\na.intern() == b.intern(); //true\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15187/" ]
195,483
<p>Is there an easy way of programmatically checking if a serial COM port is already open/being used?</p> <p>Normally I would use:</p> <pre><code>try { // open port } catch (Exception ex) { // handle the exception } </code></pre> <p>However, I would like to programatically check so I can attempt to use another COM port or some such.</p>
[ { "answer_id": 195493, "author": "Fionn", "author_id": 21566, "author_profile": "https://Stackoverflow.com/users/21566", "pm_score": 5, "selected": true, "text": "var portNames = SerialPort.GetPortNames();\n\nforeach(var port in portNames) {\n //Try for every portName and break on the first working\n}\n" }, { "answer_id": 195494, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "using System;\nusing System.IO.Ports;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace SerPort1\n{\nclass Program\n{\n static private SerialPort MyPort;\n static void Main(string[] args)\n {\n MyPort = new SerialPort(\"COM1\");\n OpenMyPort();\n Console.WriteLine(\"BaudRate {0}\", MyPort.BaudRate);\n OpenMyPort();\n MyPort.Close();\n Console.ReadLine();\n }\n\n private static void OpenMyPort()\n {\n try\n {\n MyPort.Open();\n }\n catch (Exception ex)\n {\n Console.WriteLine(\"Error opening my port: {0}\", ex.Message);\n }\n }\n }\n}\n" }, { "answer_id": 327593, "author": "Funky81", "author_id": 37509, "author_profile": "https://Stackoverflow.com/users/37509", "pm_score": -1, "selected": false, "text": "foreach (var portName in Serial.GetPortNames()\n{\n SerialPort port = new SerialPort(portName);\n if (port.IsOpen){\n /** do something **/\n }\n else {\n /** do something **/\n }\n}\n" }, { "answer_id": 5052499, "author": "Jeff", "author_id": 303284, "author_profile": "https://Stackoverflow.com/users/303284", "pm_score": 4, "selected": false, "text": " [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n internal static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr securityAttrs, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);\n int dwFlagsAndAttributes = 0x40000000;\n\n var portName = \"COM5\";\n\n var isValid = SerialPort.GetPortNames().Any(x => string.Compare(x, portName, true) == 0);\n if (!isValid)\n throw new System.IO.IOException(string.Format(\"{0} port was not found\", portName));\n\n //Borrowed from Microsoft's Serial Port Open Method :)\n SafeFileHandle hFile = CreateFile(@\"\\\\.\\\" + portName, -1073741824, 0, IntPtr.Zero, 3, dwFlagsAndAttributes, IntPtr.Zero);\n if (hFile.IsInvalid)\n throw new System.IO.IOException(string.Format(\"{0} port is already open\", portName));\n\n hFile.Close();\n\n\n using (var serialPort = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One))\n {\n serialPort.Open();\n }\n" }, { "answer_id": 59880011, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private string portName { get; set; } = string.Empty;\n\n /// <summary>\n /// Returns SerialPort Port State (Open / Closed)\n /// </summary>\n /// <returns></returns>\n internal bool HasOpenPort()\n {\n bool portState = false;\n\n if (portName != string.Empty)\n {\n using (SerialPort serialPort = new SerialPort(portName))\n {\n foreach (var itm in SerialPort.GetPortNames())\n {\n if (itm.Contains(serialPort.PortName))\n {\n if (serialPort.IsOpen) { portState = true; }\n else { portState = false; }\n }\n }\n }\n }\n\n else { System.Windows.Forms.MessageBox.Show(\"Error: No Port Specified.\"); }\n\n return portState;\n}\n" }, { "answer_id": 60986566, "author": "Farrukh Azad", "author_id": 11632237, "author_profile": "https://Stackoverflow.com/users/11632237", "pm_score": 0, "selected": false, "text": " public void MobileMessages(string ComNo, string MobileMessage, string MobileNo)\n {\n if (SerialPort.IsOpen )\n SerialPort.Close();\n try\n {\n SerialPort.PortName = ComNo;\n SerialPort.BaudRate = 9600;\n SerialPort.Parity = Parity.None;\n SerialPort.StopBits = StopBits.One;\n SerialPort.DataBits = 8;\n SerialPort.Handshake = Handshake.RequestToSend;\n SerialPort.DtrEnable = true;\n SerialPort.RtsEnable = true;\n SerialPort.NewLine = Constants.vbCrLf;\n string message;\n message = MobileMessage;\n\n SerialPort.Open();\n if (SerialPort.IsOpen )\n {\n SerialPort.Write(\"AT\" + Constants.vbCrLf);\n SerialPort.Write(\"AT+CMGF=1\" + Constants.vbCrLf);\n SerialPort.Write(\"AT+CMGS=\" + Strings.Chr(34) + MobileNo + Strings.Chr(34) + Constants.vbCrLf);\n SerialPort.Write(message + Strings.Chr(26));\n }\n else\n (\"Port not available\");\n SerialPort.Close();\n System.Threading.Thread.Sleep(5000);\n }\n catch (Exception ex)\n {\n\n message.show(\"The port \" + ComNo + \" does not exist, change port no \");\n }\n }\n" }, { "answer_id": 63306698, "author": "Tono Nam", "author_id": 637142, "author_profile": "https://Stackoverflow.com/users/637142", "pm_score": 1, "selected": false, "text": "SerialPort.GetPortNames(); .net framework C:\\Windows\\System32\\mode.com // Code that answers the question\n\nvar proc = new Process\n{\n StartInfo = new ProcessStartInfo\n {\n FileName = @\"C:\\Windows\\System32\\mode.com\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n CreateNoWindow = true\n }\n};\n\nproc.Start();\nproc.WaitForExit(4000); // wait up to 4 seconds. It usually takes less than a second\n\n// get ports being used\nvar output = proc.StandardOutput.ReadToEnd();\n List<string> comPortsBeingUsed = new List<string>();\nRegex.Replace(output, @\"(?xi) status [\\s\\w]+? (COM\\d) \\b \", regexCapture =>\n{\n comPortsBeingUsed.Add(regexCapture.Groups[1].Value);\n return null;\n});\n\nforeach(var item in comPortsBeingUsed)\n{\n Console.WriteLine($\"COM port {item} is in use\");\n}\n" }, { "answer_id": 66330471, "author": "Jack", "author_id": 10155902, "author_profile": "https://Stackoverflow.com/users/10155902", "pm_score": 1, "selected": false, "text": "private void GetPortNames()\n{\n comboBoxComPort.Items.Clear();\n foreach (string s in SerialPort.GetPortNames())\n {\n comboBoxComPort.Items.Add(s);\n }\n comboBoxComPort.SelectedIndex = 0;\n}\n\nprivate void OpenSerialPort()\n{\n try\n {\n serialPort1.PortName = comboBoxComPort.SelectedItem.ToString();\n serialPort1.Open();\n }\n catch (Exception ex)\n {\n int SelectedIndex = comboBoxComPort.SelectedIndex;\n if (comboBoxComPort.SelectedIndex >= comboBoxComPort.Items.Count - 1)\n {\n comboBoxComPort.SelectedIndex = 0;\n }\n else\n {\n comboBoxComPort.SelectedIndex++;\n }\n if (comboBoxComPort.SelectedIndex == SelectedIndex)\n {\n buttonOpenClose.Text = \"Open Port\";\n MessageBox.Show(\"Error accessing port.\" + Environment.NewLine + ex.Message, \"Port Error!!!\", MessageBoxButtons.OK);\n }\n else\n {\n OpenSerialPort();\n }\n }\n\n if (serialPort1.IsOpen)\n {\n StartAsyncSerialReading();\n }\n}\n" }, { "answer_id": 71442239, "author": "Mike", "author_id": 608583, "author_profile": "https://Stackoverflow.com/users/608583", "pm_score": 0, "selected": false, "text": " private void checkAndFillPortNameList()\n {\n SerialPort _testingSerialPort;\n\n\n AvailablePortNamesFound.Clear();\n List<string> availablePortNames = new List<string>();//mySerial.GetAvailablePortNames();\n\n foreach (string portName in SerialPortDataAccess.GetAvailablePortNames())\n {\n try\n {\n _testingSerialPort = new SerialPort(portName);\n _testingSerialPort.Open();\n\n if (_testingSerialPort.IsOpen)\n {\n availablePortNames.Add(portName);\n _testingSerialPort.Close();\n }\n }\n catch (Exception ex)\n {\n \n }\n }\n availablePortNames.Sort();\n AvailablePortNamesFound = new ObservableCollection<string>(availablePortNames);\n }\n\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
195,497
<p>I'm playing around with the locale and I18N stuff in c++ and have been looking for real world examples. I've read through the Josuttis chapter on I18N in his <a href="http://www.josuttis.com/libbook/" rel="noreferrer">book</a> (2nd Edition for C++11 to be released April 2012), and found it useful but with no real world examples to draw from I've no idea if I'm following best practices are committing beginner mistakes. What resources can StackOverflow point me towards both on the web and in print for doing I18N stuff in C++?</p> <p>Also what libraries are available for C++ that makes i18n easier? What's not in the standard library that needs to be? At first glance, it seems that UTF8 support doesn't exist in the standard library.</p> <p>Edit:</p> <p>After doing some more reading, it seems that C and C++ are both Unicode "agnostic". It also seems that for dealing with data encoded in Unicode/UTF8/16/32 one needs to use a third party library. The crux of this is that the standard library itself only thinks about ISO 8859 and related character pages, which change based on what you're locale is set to. That means I probably want to use the ICU library for strings rather than using <code>std::string</code> or even <code>std::wstring</code>.</p>
[ { "answer_id": 72341513, "author": "BullyWiiPlaza", "author_id": 3764804, "author_profile": "https://Stackoverflow.com/users/3764804", "pm_score": 0, "selected": false, "text": "Internationalization.hpp #pragma once\n\n#include <map>\n#include <string>\n\nenum class supported_language_t\n{\n english,\n chinese\n};\n\ninline std::string hello_world_map_key = \"hello-world\";\ninline std::string hello_map_key = \"hello\";\n\ninline supported_language_t supported_language = supported_language_t::chinese;\n\nstd::string get_translated_string(const std::string& key);\n Internationalization.cpp #include \"Internationalization.hpp\"\n#include <stdexcept>\n#include <magic_enum.hpp>\n\nstd::map<std::string, std::string> english_translations =\n{\n {hello_world_map_key, \"Hello, world!\"},\n {hello_map_key, \"Hello {}!\"}\n};\n\nstd::map<std::string, std::string> chinese_translations =\n{\n {hello_world_map_key, \"你好,世界!\"},\n {hello_map_key, \"你好 {}!\"}\n};\n\nstd::string get_translated_string(const std::string& key)\n{\n switch (supported_language)\n {\n case supported_language_t::chinese:\n return chinese_translations.at(key);\n\n case supported_language_t::english:\n return english_translations.at(key);\n\n default:\n throw std::runtime_error(\"Unsupported language: \" + std::string(magic_enum::enum_name(supported_language)));\n }\n}\n const auto hello_world_transated = get_translated_string(hello_world_map_key); // \"你好,世界!\"\nconst auto hello_translated = std::format(get_translated_string(hello_map_key), \"StackOverflow\"); // \"你好 StackOverflow!\"\n std::format" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14788/" ]
195,520
<p>Can you post a short example of real, overdone spaghetti code, possibly saying what it does? Can you show me a little debugger's nightmare?</p> <p>I don't mean <a href="http://www0.us.ioccc.org/main.html" rel="noreferrer">IOCCC</a> code, that is science fiction. I mean real life examples that happened to you...</p> <h3>Update</h3> <p>The focus has changed from "post some spaghetti code" to "what is <em>exactly</em> spaghetti code?". From a historical perspective, the current choices seem to be:</p> <ul> <li>old Fortran code using computed gotos massively</li> <li>old Cobol code using the ALTER statement</li> </ul>
[ { "answer_id": 195531, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": ".286\n.model tiny\n\ng4 equ 55-48 ; removed note-decoding !\na4 equ 57-48 ; now: storing midi-notes for octaves 0..2 and convert\nh4 equ 59-48 ; to 4..6 with a simple add 48.\n\nc5 equ 60-48\nd5 equ 62-48\ne5 equ 64-48\ng5 equ 67-48\nh5 equ 71-48\n\nc6 equ 72-48\nd6 equ 74-48\ne6 equ 76-48\ng6 equ 79-48 ; = 00011111b\n\npp equ 0 ; c4 is not used in the walz, using it as play-pause.\nEOM equ 1 ; c#4 is also available... End Of Music\n ; warning: experts only beyond this point !\n\npau1 equ 00100000b ; bitfield definitions for note-compression\npau2 equ 01000000b ; you can or a pau to each note!\npau3 equ 01100000b\n\n;rep1 equ 01000000b ; rep1 is history (only used once).\n;rep3 equ 11000000b ; rep3 was never used.\n\nrep2 equ 10000000b ; or a rep2 to a note to play it 3 times.\n\ndrumsize equ 5\n\n.code\norg 100h\n\nstart:\n mov ah,9\n mov dx,offset msg\n int 21h ; print our headerstring\n\n mov dx,0330h ; gus midi megaem -port\n mov si,offset music_code ; start of music data\n\nmainloop:\n\n ; get new note (melody)\n\n xor bp,bp ; bp= repeat-counter\n\n lodsb ; get a new note\n cmp al, EOM ; check for end\n jne continue\n ret\n\ncontinue:\n jns no_rep2 ; check for rep2-Bit\n inc bp\n inc bp ; \"build\" repeat-counter\n\nno_rep2:\n push ax ; save the note for pause\n\n ; \"convert\" to midi-note\n\n and al,00011111b\n jz skip_pp ; check pp, keep it 0\n add al,48 ; fix-up oktave\n\nskip_pp:\n xchg ax,bx ; bl= midi-note\n\nplay_again:\n mov cl,3\n push cx ; patch program (3= piano)\n push 0c8h ; program change, channel 9\n\n ; wait (cx:dx) times\n\n mov ah,86h ; wait a little bit\n int 15h\n\n ; prepare drums\n\n dec di ; get the current drum\n jns no_drum_underflow\n mov di,drumsize\n\nno_drum_underflow:\n\n ; play drum\n\n push dx ; volume drum\n push [word ptr drumtrk+di] ; note drum\n mov al,99h\n push ax ; play channel 10\n\n ; play melody\n\n push dx ; volume melody\n push bx ; note melody\n\n dec ax ; replaces dec al :)\n\n push ax ; play channel 9\n\n ; send data to midi-port\n\n mov cl,8 ; we have to send 8 bytes\n\nplay_loop:\n pop ax ; get the midi event\n out dx,al ; and send it\n loop play_loop\n\n ; repeat \"bp\" times\n\n dec bp ; repeat the note\n jns play_again\n\n ; check and \"play\" pause\n\n xor bx,bx ; clear the note, so we can hear\n ; a pause\n ; decode pause value\n\n pop ax\n test al,01100000b\n jz mainloop ; no pause, get next note\n\n ; decrement pause value and save on stack\n\n sub al,20h\n push ax\n jmp play_again ; and play next drum\n\n; don't change the order of the following data, it is heavily crosslinked !\nmusic_code db pp or rep2\n\n db g4 or rep2 or pau1\n db h4 or pau1, d5 or pau1, d5 or pau3\n db d6 or pau1, d6 or pau3, h5 or pau1, h5 or pau3\n\n db g4 or rep2 or pau1\n db h4 or pau1, d5 or pau1, d5 or pau3\n db d6 or pau1, d6 or pau3, c6 or pau1, c6 or pau3\n\n db a4 or rep2 or pau1\n db c5 or pau1, e5 or pau1, e5 or pau3\n db e6 or pau1, e6 or pau3, c6 or pau1, c6 or pau3\n\n db a4 or rep2 or pau1\n db c5 or pau1, e5 or pau1, e5 or pau3\n db e6 or pau1, e6 or pau3, h5 or pau1, h5 or pau3\n\n db g4 or rep2 or pau1\n db h4 or pau1, g5 or pau1, g5 or pau3\n db g6 or pau1, g6 or pau3, d6 or pau1, d6 or pau3\n\n db g4 or rep2 or pau1\n db h4 or pau1, g5 or pau1, g5 or pau3\n db g6 or pau1, g6 or pau3, e6 or pau1, e6 or pau3\n\n db a4 or rep2 or pau1\n db c5 or pau1, e5 or pau1, e5 or pau3, pp or pau3\n db c5 or pau1, e5 or pau1, h5 or pau3, pp or pau3, d5 or pau1\n\n db h4 or pau1, h4 or pau3\n db a4 or pau1, e5 or pau3\n db d5 or pau1, g4 or pau2\n\n; db g4 or rep1 or pau1\n; replace this last \"rep1\"-note with two (equal-sounding) notes\n db g4\n db g4 or pau1\n\nmsg db EOM, 'Docking Station',10,'doj&sub'\ndrumtrk db 36, 42, 38, 42, 38, 59 ; reversed order to save some bytes !\n\nend start\n" }, { "answer_id": 195559, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 4, "selected": false, "text": "wait_nomsg:\n if ((inb(tmport) & 0x04) != 0) {\n goto wait_nomsg;\n }\n outb(1, 0x80);\n udelay(100);\n for (n = 0; n < 0x30000; n++) {\n if ((inb(tmport) & 0x80) != 0) { /* bsy ? */\n goto wait_io;\n }\n }\n goto TCM_SYNC;\nwait_io:\n for (n = 0; n < 0x30000; n++) {\n if ((inb(tmport) & 0x81) == 0x0081) {\n goto wait_io1;\n }\n }\n goto TCM_SYNC;\nwait_io1:\n inb(0x80);\n val |= 0x8003; /* io,cd,db7 */\n outw(val, tmport);\n inb(0x80);\n val &= 0x00bf; /* no sel */\n outw(val, tmport);\n outb(2, 0x80);\nTCM_SYNC:\n/* ... */\nsmall_id:\n m = 1;\n m <<= k;\n if ((m & assignid_map) == 0) {\n goto G2Q_QUIN;\n }\n if (k > 0) {\n k--;\n goto small_id;\n }\nG2Q5: /* srch from max acceptable ID# */\n k = i; /* max acceptable ID# */\nG2Q_LP:\n m = 1;\n m <<= k;\n if ((m & assignid_map) == 0) {\n goto G2Q_QUIN;\n }\n if (k > 0) {\n k--;\n goto G2Q_LP;\n }\nG2Q_QUIN: /* k=binID#, */\n find /usr/src/linux -type f -name \\*.c | \nwhile read f\ndo \n echo -n \"$f \"\n sed -n 's/^.*goto *\\([^;]*\\);.*/\\1/p' $f | sort -u | wc -l\ndone | \nsort +1rn |\nhead\n kernel/fork.c 31\nfs/namei.c 35\ndrivers/infiniband/hw/mthca/mthca_main.c 36\nfs/cifs/cifssmb.c 45\nfs/ntfs/super.c 47\n" }, { "answer_id": 198276, "author": "Juan Pablo Califano", "author_id": 24170, "author_profile": "https://Stackoverflow.com/users/24170", "pm_score": 2, "selected": false, "text": "internal class EventContainerComparer : IComparer {\n\n int IComparer.Compare(object a, object b) {\n MIDIEventContainer evt1 = (MIDIEventContainer) a;\n MIDIEventContainer evt2 = (MIDIEventContainer) b;\n\n ChannelEvent chanEvt1;\n ChannelEvent chanEvt2;\n\n if (evt1.AbsoluteTime < evt2.AbsoluteTime) {\n return -1;\n } else if (evt1.AbsoluteTime > evt2.AbsoluteTime) {\n return 1;\n } else { \n // a iguar valor de AbsoluteTime, los channelEvent tienen prioridad\n if(evt1.MidiEvent is ChannelEvent && evt2.MidiEvent is MetaEvent) {\n return -1;\n } else if(evt1.MidiEvent is MetaEvent && evt2.MidiEvent is ChannelEvent){\n return 1;\n // si ambos son channelEvent, dar prioridad a NoteOn == 0 sobre NoteOn > 0\n } else if(evt1.MidiEvent is ChannelEvent && evt2.MidiEvent is ChannelEvent) {\n\n chanEvt1 = (ChannelEvent) evt1.MidiEvent;\n chanEvt2 = (ChannelEvent) evt2.MidiEvent;\n\n // si ambos son NoteOn\n if( chanEvt1.EventType == ChannelEventType.NoteOn \n && chanEvt2.EventType == ChannelEventType.NoteOn){\n\n // chanEvt1 en NoteOn(0) y el 2 es NoteOn(>0)\n if(chanEvt1.Arg1 == 0 && chanEvt2.Arg1 > 0) {\n return -1;\n // chanEvt1 en NoteOn(0) y el 2 es NoteOn(>0)\n } else if(chanEvt2.Arg1 == 0 && chanEvt1.Arg1 > 0) {\n return 1;\n } else {\n return 0;\n }\n // son 2 ChannelEvent, pero no son los 2 NoteOn, el orden es indistinto\n } else {\n return 0;\n }\n // son 2 MetaEvent, el orden es indistinto\n } else {\n return 0;\n }\n }\n }\n}\n" }, { "answer_id": 325775, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "int n = (count + 7) / 8;\nswitch (count % 8) {\ncase 0: do { *to = *from++;\ncase 7: *to = *from++;\ncase 6: *to = *from++;\ncase 5: *to = *from++;\ncase 4: *to = *from++;\ncase 3: *to = *from++;\ncase 2: *to = *from++;\ncase 1: *to = *from++;\n } while (--n > 0);\n}\n" }, { "answer_id": 3353499, "author": "Joe Smith", "author_id": 404580, "author_profile": "https://Stackoverflow.com/users/404580", "pm_score": 4, "selected": false, "text": "enum {\n a, b, c;\n} myenum;\n HashTable t;\nt[\"a\"] = 0;\nt[\"b\"] = 1;\nt[\"c\"] = 2;\n HashTableFactory *makeHashTableFactor();\n <enum>\n <item name=\"a\" value=\"0\"/>\n <item name=\"b\" value=\"1\"/>\n <item name=\"c\" value=\"2\"/>\n</enum>\n const char* myenumXML = [13, 32, 53 ....];\n void xmlToHashTable(char *xml, HashTable *h, HashTableFactory *f);\n HashTableFactory *factory = makeHashTableFactory();\nHashTable *t = facotry.make();\nxmlToHashTable(myenumXML, t, f);\n void printStuff(int c) {\n switch (c) {\n case a: print(\"a\");\n case b: print(\"b\");\n case c: print(\"c\");\n }\n}\n void stuff(char* str) {\n int c = charToEnum(str);\n printStuff(c);\n}\n void stuff(char *str) {\n printf(str);\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18770/" ]
195,530
<p>I accidentally coded <code>SELECT $FOO..</code> and got the error "Invalid pseudocolumn "$FOO".</p> <p>I can't find any documentation for them. Is it something I should know?</p> <p>Edit: this is a MS SQL Server specific question.</p>
[ { "answer_id": 195565, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "SELECT * FROM SomeTable SELECT ROWID, * FROM SomeTable *" }, { "answer_id": 4736433, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 1, "selected": false, "text": "output merge $action" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
195,537
<p>I am working on an implementation for RSS feeds for a collaboration platform. Say there are several thousands of different collaboration rooms where users can share information, and each needs to publish an RSS feed with news, changes, etc...</p> <p>Using a plain servlet (i.e. <a href="http://www.site.com/RSSServlet/?id=roomID" rel="nofollow noreferrer">http://www.site.com/RSSServlet/?id=roomID</a>) is costly, every time an RSS client is calling the servlet (and this will happen say every 10 minutes for each user registered to an RSS feed on one of the thousand of rooms) this will trigger the entire servlet lifecycle, which is costly.</p> <p>On the other hand, keeping a static XML file on the disk for each of the thousands of rooms is costly as well, in terms of hard disk space as well as IO operations...</p> <p>One more limitation - using already existing frameworks might not be an option...</p> <p>So, how would you implement RSS feeds in a Java envoronment?</p>
[ { "answer_id": 202044, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 4, "selected": true, "text": "doGet() doPost() doGet doPost doGet doPost public void doGet(HttpServletRequest request, HttpServletResponse response) {\n //build the objects you need for the RSS response\n Room room = getRoom(request.getParameter(\"roomid\"));\n //loadData();\n //moreMethodCalls();\n out.println( createRssContent(...) );\n}\n Map rssCache;\n\npublic void doGet(HttpServletRequest request, HttpServletResponse response) {\n\n //Map is initialized in the init() method or somewhere else \n String roomId = request.getParameter(\"roomid\");\n\n String rssDocument = rssCache.get(roomId);\n if (rssDocument == null) {\n\n //build the objects you need for the RSS response\n Room room = getRoom(roomId);\n //loadData();\n //moreMethodCalls();\n rssDocument = createRssContent(...);\n rssCache.put(roomId, rssDocument);\n }\n out.println( rssDocument );\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24545/" ]
195,548
<p>Due to company constraints out of my control, I have the following scenario:</p> <p>A COM library that defines the following interface (no CoClass, just the interface):</p> <pre><code>[ object, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx), dual, nonextensible, helpstring("IService Interface"), pointer_default(unique) ] IService : IDispatch { HRESULT DoSomething(); } [ object, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx), dual, nonextensible, helpstring("IProvider Interface"), pointer_default(unique) ] IServiceProvider : IDispatch { HRESULT Init( IDispatch *sink, VARIANT_BOOL * result ); HRESULT GetService( LONG serviceIndicator, IService ** result ); }; [ uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx), version(1.0), ] library ServiceLibrary { importlib("stdole2.tlb"); interface IService; interface IServiceProvider; }; </code></pre> <p>I have a COM (written w/ C++) that implements both interfaces and provides our application(s) with said service. All is fine, I think.</p> <p>I'm trying to build a new <code>IProvider</code> and <code>IService</code> in .NET (C#). </p> <p>I've built a Primary Interop Assembly for the COM library, and implemented the following C#:</p> <pre><code>[ComVisible( true )] [Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )] public interface INewService : IService { // adds a couple new properties } [ComVisible( true )] [Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )] public class NewService : INewService { // implement interface } [ComVisible( true )] [Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )] public interface INewProvider : IServiceProvider { // adds nothing, just implements } [ComVisible( true )] [Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )] public class NewProvider : INewProvider { // implement interface } </code></pre> <p>When I attempt to slip this into the existing runtime, I am able to create the <code>NewProvider</code> object from COM (C++), and <code>QueryInterface</code> for IServiceProvider. When I attempt to call a method on the IServiceProvider, a <code>System.ExecutionEngineException</code> is thrown. </p> <p>The only other thing I can find, is by looking at the .tlh files created by the #import, shows the legacy COM IExistingProvider class correctly shows that it is derived from IServiceProvider. However the .NET class shows a base of IDispatch. I'm not sure if this a sign, indication, helpful, something else.</p>
[ { "answer_id": 195885, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 4, "selected": true, "text": "Warning 65 warning C4192: automatically excluding 'IServiceProvider' while importing type library 'ServiceLibrary.dll'\n import \"oaidl.idl\";\n\n[\n object,\n uuid(9219CC5B-31CC-4868-A1DE-E18300F73C43),\n dual,\n nonextensible,\n helpstring(\"IService Interface\"),\n pointer_default(unique)\n]\ninterface IService : IDispatch\n{\n HRESULT DoSomething(void);\n}\n\n[\n object,\n uuid(9219CC5B-31CC-4868-A1DE-E18300F73C44),\n dual,\n nonextensible,\n helpstring(\"IProvider Interface\"),\n pointer_default(unique)\n]\ninterface IServiceProvider2 : IDispatch\n{\n HRESULT Init( IDispatch *sink, VARIANT_BOOL * result );\n HRESULT GetService( LONG serviceIndicator, IService ** result );\n};\n\n[\n uuid(9219CC5B-31CC-4868-A1DE-E18300F73C45),\n version(1.0),\n]\nlibrary ServiceLibrary\n{\n importlib(\"stdole2.tlb\");\n\n interface IService;\n interface IServiceProvider2;\n};\n using System.Runtime.InteropServices;\nusing System.Windows.Forms;\nusing ServiceLibrary;\nusing IServiceProvider=ServiceLibrary.IServiceProvider2;\n\nnamespace COMInterfaceTester\n{\n [ComVisible(true)]\n [Guid(\"2B9D06B9-EB59-435e-B3FF-B891C63108B2\")]\n public interface INewService : IService\n {\n string ServiceName { get; }\n }\n\n [ComVisible(true)]\n [Guid(\"2B9D06B9-EB59-435e-B3FF-B891C63108B3\")]\n public class NewService : INewService\n {\n public string _name;\n\n public NewService(string name)\n {\n _name = name;\n }\n\n // implement interface\n #region IService Members\n\n public void DoSomething()\n {\n MessageBox.Show(\"NewService.DoSomething\");\n }\n\n #endregion\n\n public string ServiceName\n {\n get { return _name; }\n }\n }\n\n [ComVisible(true)]\n [Guid(\"2B9D06B9-EB59-435e-B3FF-B891C63108B4\")]\n public interface INewProvider : IServiceProvider\n {\n // adds nothing, just implements\n }\n\n [ComVisible(true)]\n [Guid(\"2B9D06B9-EB59-435e-B3FF-B891C63108B5\")]\n public class NewProvider : INewProvider\n {\n // implement interface\n public void Init(object sink, ref bool result)\n {\n MessageBox.Show(\"NewProvider.Init\");\n }\n\n public void GetService(int serviceIndicator, ref IService result)\n {\n result = new NewService(\"FooBar\");\n MessageBox.Show(\"NewProvider.GetService\");\n }\n }\n} \n #include \"stdafx.h\"\n#include <iostream>\n#include <atlbase.h>\n#import \"COMInterfaceTester.tlb\" raw_interfaces_only\n#import \"ServiceLibrary.dll\" raw_interfaces_only\n\nusing std::cout;\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n CoInitialize(NULL); //Initialize all COM Components\n COMInterfaceTester::INewProviderPtr pNewProvider(__uuidof(COMInterfaceTester::NewProvider));\n ServiceLibrary::IServiceProvider2 *pNewProviderPtr;\n\n HRESULT hr = pNewProvider.QueryInterface(__uuidof(ServiceLibrary::IServiceProvider2), (void**)&pNewProviderPtr);\n\n if(SUCCEEDED(hr))\n { \n VARIANT_BOOL result = VARIANT_FALSE;\n int *p = NULL;\n\n hr = pNewProviderPtr->Init((IDispatch*)p, &result);\n\n if (FAILED(hr))\n {\n cout << \"Failed to call Init\";\n }\n\n ServiceLibrary::IService *pService = NULL;\n hr = pNewProviderPtr->GetService(0, &pService);\n\n if (FAILED(hr))\n {\n cout << \"Failed to call GetService\";\n }\n else\n {\n COMInterfaceTester::INewService* pNewService = NULL;\n hr = pService->QueryInterface(__uuidof(COMInterfaceTester::INewService), (void**)&pNewService);\n\n if (SUCCEEDED(hr))\n {\n CComBSTR serviceName;\n pNewService->get_ServiceName(&serviceName); \n\n if (serviceName == \"FooBar\")\n {\n pService->DoSomething();\n }\n else\n cout << \"Unexpected service\";\n\n pNewService->Release();\n\n }\n\n pService->Release();\n }\n\n pNewProviderPtr->Release();\n }\n else\n cout << \"Failed to query for IServiceProvider2\";\n\n pNewProvider.Release();\n CoUninitialize (); //DeInitialize all COM Components\n\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25565/" ]
195,549
<p>Here's a problem I keep running into:</p> <p>I have a lot of situations where I need to display some text with a styled container like so:</p> <pre><code>&lt;mx:Canvas&gt; &lt;mx:Text text="{text}" left="5" verticalCenter="0" right="5" /&gt; &lt;/mx:Canvas&gt; </code></pre> <p>As you can see - the text in constrained by the left and right margins of the canvas and I have not specified a height for the text control because I want it to grow vertically when I add text to it. Reason being - if there is one line of text I want it to display in the center of the canvas but if there are two or three lines of text I want the text control to show those two or three lines of text.</p> <p>What keeps happening however, is that it will only display one line of text - no matter how many times I call invalidateSize() on it or the container. What do I do?</p> <p>CAVEAT: The canvas height and width is set by the component that instantiates it (this is all wrapped up in a custom component) so I can't explicitly set the width or height of the text control...</p> <p>NOTE: Ok, maybe it's an easy fix because as I was typing this question I figured it out - but, here's a chance to answer an easy question!?</p>
[ { "answer_id": 195570, "author": "James Fassett", "author_id": 27081, "author_profile": "https://Stackoverflow.com/users/27081", "pm_score": 3, "selected": true, "text": "<mx:HBox \n width=\"500\"\n paddingLeft=\"5\"\n paddingRight=\"5\">\n <mx:Spacer width=\"100%\" />\n <mx:Text \n width=\"100%\"\n text=\"{text}\" />\n <mx:Spacer width=\"100%\" />\n</mx:HBox>\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
195,578
<p>I got a problem like this (this is html/css menu):</p> <p>Eshop | Another eshop | Another eshop</p> <p>Client wants it work like this:</p> <p>User comes to website, clicks on Eshop. Eshop changes to red color with red box outline. User decides to visit Another eshop, so Eshop will go back to normaln color without red box outline, and another eshop will do the red outline trick again.. </p> <p>I know there is A:visited but I don't want all visited menu links to be red with red box outline.</p> <p>Thx for any help :)</p>
[ { "answer_id": 195601, "author": "Georg Schölly", "author_id": 24587, "author_profile": "https://Stackoverflow.com/users/24587", "pm_score": 3, "selected": true, "text": ".red {\n outline-color:red;\n outline-width:10px;\n}\n $('.red').removeClass('red'); // removes class red from all items with class red\n$(this).addClass('red'); // adds class red to the clicked item\n" }, { "answer_id": 195603, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 1, "selected": false, "text": " <a href=\"#\">Eshop</a> | <a href=\"#\" class=\"selected\">Another eshop</a> | <a href=\"#\">Another eshop</a>\n .selected {\n font-weight:bold;\n color:#efefef;\n}\n <?php\n foreach(array('eshop' => '#','another eshop' => '#','yet another eshop' => '#') as $title => $url) {\n echo '<a href=\"' . $url . '\"' \n . ($url == $_SERVER['REQUEST_URI'] ? ' class=\"selected\"' : null) \n . '>' . $title . '</a>'; \n }\n" }, { "answer_id": 199282, "author": "Matthew M. Osborn", "author_id": 5235, "author_profile": "https://Stackoverflow.com/users/5235", "pm_score": 0, "selected": false, "text": "a[href^=\"http:\\\\www.EShop\"]:visted { color: red; }\n" }, { "answer_id": 199357, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 2, "selected": false, "text": "<!-- ... head, etc ... -->\n<body>\n\n<ul class=\"nav\">\n <li><a href=\"home.html\" class=\"nav-home\">Home</a></li>\n <li><a href=\"art.html\" class=\"nav-art\">Art</a></li>\n <li><a href=\"contact.html\" class=\"nav-contact\">Contact</a></li>\n</ul>\n\n<!-- ... more page ... -->\n\n</body>\n #NAV-HOME .nav-home,\n#NAV-ART .nav-art,\n#NAV-CONTACT .nav-contact { color:red; }\n <!-- The \"Art\" item will stand out. -->\n<body id=\"NAV-ART\">\n\n<ul class=\"nav\">\n <li><a href=\"home.html\" class=\"nav-home\">Home</a></li>\n <li><a href=\"art.html\" class=\"nav-art\">Art</a></li>\n <li><a href=\"contact.html\" class=\"nav-contact\">Contact</a></li>\n</ul>\n\n<!-- ... more page ... -->\n\n</body>\n" }, { "answer_id": 199379, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 0, "selected": false, "text": "<body id=\"eshop\">\n <ul>\n <li><a href=\"\" id=\"link-eshop\">Eshop</a></li>\n <li><a href=\"\" id=\"link-aeshop\">Another eshop</a></li>\n <li><a href=\"\" id=\"link-eshop-three\">Another eshop</a></li>\n </ul>\n</body>\n #eshop #link-eshop, #aeshop, #link-aeshop, #eshop-three #link-eshop-three\n{\n color: red;\n outline: 1px solid red;\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21209/" ]
195,582
<p>I am taking my first steps programming in Lua and get this error when I run my script:</p> <pre><code>attempt to index upvalue 'base' (a function value) </code></pre> <p>It's probably due to something very basic that I haven't grasped yet, but I can't find any good information about it when googling. Could someone explain to me what it means?</p>
[ { "answer_id": 195599, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "base base[5] base.somefield base" }, { "answer_id": 42890331, "author": "GoojajiGreg", "author_id": 3455883, "author_profile": "https://Stackoverflow.com/users/3455883", "pm_score": 3, "selected": false, "text": "local local nil local foo -- a forward declaration \n\n local function useFoo()\n print( foo.bar ) -- foo is an upvalue and this will produce the error in question\n -- not only is foo.bar == nil at this point, but so is foo\n end\n\n local function f()\n\n -- one LOCAL too many coming up...\n\n local foo = {} -- this is a **new** foo with function scope\n\n foo.bar = \"Hi!\"\n\n -- the local foo has been initialized to a table\n -- the upvalue (external local variable) foo declared above is not\n -- initialized\n\n useFoo()\n end \n\n f()\n local foo f() foo = {}\nfoo.bar = \"Hi!\"\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22283/" ]
195,587
<p>Got a class that serializes into xml with XMLEncoder nicely with all the variables there. Except for the one that holds <em>java.util.Locale</em>. What could be the trick?</p>
[ { "answer_id": 195693, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 4, "selected": true, "text": "public class MyBean implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private Locale locale;\n private String foo;\n\n public MyBean() {\n }\n\n public Locale getLocale() {\n return locale;\n }\n\n public void setLocale(Locale locale) {\n this.locale = locale;\n }\n\n public String getFoo() {\n return foo;\n }\n\n public void setFoo(String foo) {\n this.foo = foo;\n }\n\n}\n public class MyBeanTest {\n\n public static void main(String[] args) throws Exception {\n // quick and dirty test\n\n MyBean c = new MyBean();\n c.setLocale(Locale.CHINA);\n c.setFoo(\"foo\");\n\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n XMLEncoder encoder = new XMLEncoder(outputStream);\n encoder.setPersistenceDelegate(Locale.class, new PersistenceDelegate() {\n protected Expression instantiate(Object oldInstance, Encoder out) {\n Locale l = (Locale) oldInstance;\n return new Expression(oldInstance, oldInstance.getClass(),\n \"new\", new Object[] { l.getLanguage(), l.getCountry(),\n l.getVariant() });\n }\n });\n encoder.writeObject(c);\n encoder.flush();\n encoder.close();\n\n System.out.println(outputStream.toString(\"UTF-8\"));\n\n ByteArrayInputStream bain = new ByteArrayInputStream(outputStream\n .toByteArray());\n XMLDecoder decoder = new XMLDecoder(bain);\n\n c = (MyBean) decoder.readObject();\n\n System.out.println(\"===================\");\n System.out.println(c.getLocale());\n System.out.println(c.getFoo());\n }\n\n}\n new PersistenceDelegate() {\n protected Expression instantiate(Object oldInstance, Encoder out) {\n Locale l = (Locale) oldInstance;\n return new Expression(oldInstance, oldInstance.getClass(),\n \"new\", new Object[] { l.getLanguage(), l.getCountry(),\n l.getVariant() });\n }\n }\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15187/" ]
195,590
<p>Does anybody know how to determine the location of a file that's in one of the folders specified by the PATH environmental variable other than doing a dir filename.exe /s from the root folder?</p> <p>I know this is stretching the bounds of a programming question but this is useful for deployment-related issues, also I need to examine the dependencies of an executable. :-)</p>
[ { "answer_id": 195594, "author": "MvdD", "author_id": 18044, "author_profile": "https://Stackoverflow.com/users/18044", "pm_score": 7, "selected": true, "text": "where.exe C:\\Windows\\System32" }, { "answer_id": 195612, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 1, "selected": false, "text": "%WINDIR%\\system32\\where.exe <?php\nfunction Find( $file )\n{\n foreach( explode( ':', $_ENV( 'PATH' ) ) as $dir )\n {\n $command = sprintf( 'find -L %s -name \"%s\" -print', $dir, $file );\n $output = array();\n $result = -1;\n exec( $command, $output, $result );\n\n if ( count( $output ) == 1 )\n {\n return( $output[ 0 ] );\n }\n }\n return null;\n}\n?>\n" }, { "answer_id": 195624, "author": "Scott Weinstein", "author_id": 25201, "author_profile": "https://Stackoverflow.com/users/25201", "pm_score": -1, "selected": false, "text": " function PSwhere($file) { $env:Path.Split(\";\") | ? { test-path $_\\$file* } }\n" }, { "answer_id": 195649, "author": "Richard T", "author_id": 26976, "author_profile": "https://Stackoverflow.com/users/26976", "pm_score": 0, "selected": false, "text": "usage: findinpath [ -p <path> | -path <path> ] | [ -s | -system ] <file>\n or findinpath [ -h | -help ]\n\nwhere: <file> may be any file spec, including wild cards\n\n -h or -help returns this text\n\n -p or -path uses the specified path instead of the PATH environment variable.\n\n -s or -system searches the system disk, skipping /d /l/ /nfs and /users\n" }, { "answer_id": 197483, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 3, "selected": false, "text": "for %i in (file) do @echo %~dp$PATH:i\n file" }, { "answer_id": 48530937, "author": "ChadsTech", "author_id": 9073225, "author_profile": "https://Stackoverflow.com/users/9073225", "pm_score": 1, "selected": false, "text": "Function Get-ENVPathFolders {\n#.Synopsis Split $env:Path into an array\n#.Notes \n# - Handle 1) folders ending in a backslash 2) double-quoted folders 3) folders with semicolons 4) folders with spaces 5) double-semicolons i.e. blanks\n# - Example path: 'C:\\WINDOWS\\;\"C:\\Path with semicolon; in the middle\";\"E:\\Path with semicolon at the end;\";;C:\\Program Files;\n# - 2018/01/30 by Chad@ChadsTech.net - Created\n$NewPath = @()\n$env:Path.ToString().TrimEnd(';') -split '(?=[\"])' | ForEach-Object { #remove a trailing semicolon from the path then split it into an array using a double-quote as the delimeter keeping the delimeter\n If ($_ -eq '\";') { # throw away a blank line\n } ElseIf ($_.ToString().StartsWith('\";')) { # if line starts with \"; remove the \"; and any trailing backslash\n $NewPath += ($_.ToString().TrimStart('\";')).TrimEnd('\\')\n } ElseIf ($_.ToString().StartsWith('\"')) { # if line starts with \" remove the \" and any trailing backslash\n $NewPath += ($_.ToString().TrimStart('\"')).TrimEnd('\\') #$_ + '\"'\n } Else { # split by semicolon and remove any trailing backslash\n $_.ToString().Split(';') | ForEach-Object { If ($_.Length -gt 0) { $NewPath += $_.TrimEnd('\\') } }\n }\n}\nReturn $NewPath\n}\n\n$myFile = 'desktop.ini'\nGet-ENVPathFolders | ForEach-Object { If (Test-Path -Path $_\\$myFile) { Write-Output \"Found [$_\\$myFile]\" } } \n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394/" ]
195,593
<p>MessageBox.Show has forms like MessageBox.Show( ownerWindow, .... ).</p> <p>What do I gain by assigning a owner window?</p>
[ { "answer_id": 195614, "author": "jyoung", "author_id": 14841, "author_profile": "https://Stackoverflow.com/users/14841", "pm_score": 0, "selected": false, "text": "else if (owner == IntPtr.Zero)\n owner = UnsafeNativeMethods.GetActiveWindow();\n" }, { "answer_id": 25250001, "author": "binki", "author_id": 429091, "author_profile": "https://Stackoverflow.com/users/429091", "pm_score": 2, "selected": false, "text": "MessageBox.Show() MessageBox MessageBox owner MessageBox Form MessageBox MessageBox MessageBox MessageBox Owner ShowDialog() Form owner owner MessageBox.Show() Form this.Invoke() Form Form MessageBox.Show() button1_Click PerformClick() Button Timer.Tick Timer.Tick Invoke() owner owner Invoke() MessageBox.Show() Form.ShowDialog()" }, { "answer_id": 39184942, "author": "Felinis", "author_id": 2941664, "author_profile": "https://Stackoverflow.com/users/2941664", "pm_score": 1, "selected": false, "text": "MessageBox.Show(frmMain,\"a message\",\"a title\") TextDialog Application.OpenForms() btnOK_Click() frmMain.Close() Application.Exit()" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14841/" ]
195,625
<p>I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity? </p>
[ { "answer_id": 195647, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": "Pop() pop()" }, { "answer_id": 51576152, "author": "Pythoner", "author_id": 5117474, "author_profile": "https://Stackoverflow.com/users/5117474", "pm_score": 3, "selected": false, "text": "from timeit import timeit\nif __name__ == \"__main__\":\n L = range(100000)\n print timeit(\"L.pop(0)\", setup=\"from __main__ import L\", number=10000)\n L = range(100000)\n print timeit(\"L.pop(-1)\", setup=\"from __main__ import L\", number=10000)\n\n>>> 0.291752411828\n>>> 0.00161794329896\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21000/" ]
195,626
<p>I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
[ { "answer_id": 195739, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "class Proxy:\n @property\n def global_name(self):\n # calculate your global var here, enable cache if needed\n ...\n\n_proxy_object = Proxy()\nGLOBAL_NAME = _proxy_object.global_name\n class Data:\n GLOBAL_NAME = property(...)\n\ndata = Data()\n from some_module import data\n\nprint(data.GLOBAL_NAME)\n" }, { "answer_id": 195962, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 5, "selected": true, "text": "# Create dict with a million items:\nimport shelve\nd = shelve.open('path/to/my_persistant_dict')\nd.update(('key%d' % x, x) for x in xrange(1000000))\nd.close()\n >>> d = shelve.open('path/to/my_persistant_dict')\n>>> print d['key99999']\n99999\n" }, { "answer_id": 201077, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": "cPickle.dump(FD, protocol=2) cPickle.Pickler Protocol 0 is the\nonly protocol that can be written to a file opened in text\nmode and read back successfully. When using a protocol higher\nthan 0, make sure the file is opened in binary mode, both when\npickling and unpickling. \n" }, { "answer_id": 431452, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "try:\n FD\nexcept NameError:\n FD = FreqDist(word for word in brown.words())\n" }, { "answer_id": 1184838, "author": "Jacob", "author_id": 144563, "author_profile": "https://Stackoverflow.com/users/144563", "pm_score": 2, "selected": false, "text": "shelve" }, { "answer_id": 2213775, "author": "James", "author_id": 252253, "author_profile": "https://Stackoverflow.com/users/252253", "pm_score": 1, "selected": false, "text": "r = Redis()\nr.set(key, word)\n\nword = r.get(key)\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925263/" ]
195,632
<p>So, I can create an input button with an image using</p> <pre><code>&lt;INPUT type=&quot;image&quot; src=&quot;/images/Btn.PNG&quot; value=&quot;&quot;&gt; </code></pre> <p>But, I can't get the same behavior using CSS. For instance, I've tried</p> <pre><code>&lt;INPUT type=&quot;image&quot; class=&quot;myButton&quot; value=&quot;&quot;&gt; </code></pre> <p>where &quot;myButton&quot; is defined in the CSS file as</p> <pre><code>.myButton { background:url(/images/Btn.PNG) no-repeat; cursor:pointer; width: 200px; height: 100px; border: none; } </code></pre> <p>If that's all I wanted to do, I could use the original style, but I want to change the button's appearance on hover (using a <code>myButton:hover</code> class). I know the links are good, because I've been able to load them for a background image for other parts of the page (just as a check). I found examples on the web of how to do it using JavaScript, but I'm looking for a CSS solution.</p> <p>I'm using Firefox 3.0.3 if that makes a difference.</p>
[ { "answer_id": 195638, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 5, "selected": false, "text": "#replacement-1 {\n width: 100px;\n height: 55px;\n margin: 0;\n padding: 0;\n border: 0;\n background: transparent url(image.gif) no-repeat center top;\n text-indent: -1000em;\n cursor: pointer; /* hand-shaped cursor */\n cursor: hand; /* for IE 5.x */\n}\n\n#replacement-2 {\n width: 100px;\n height: 55px;\n padding: 55px 0 0;\n margin: 0;\n border: 0;\n background: transparent url(image.gif) no-repeat center top;\n overflow: hidden;\n cursor: pointer; /* hand-shaped cursor */\n cursor: hand; /* for IE 5.x */\n}\nform>#replacement-2 { /* For non-IE browsers*/\n height: 0px;\n}\n" }, { "answer_id": 195644, "author": "Dimitry", "author_id": 27073, "author_profile": "https://Stackoverflow.com/users/27073", "pm_score": 7, "selected": false, "text": "<button> type=\"submit\" <button type=\"submit\" style=\"border: 0; background: transparent\">\n <img src=\"https://i.imgur.com/tXLqhgC.png\" width=\"90\" height=\"90\" alt=\"submit\" />\n</button>" }, { "answer_id": 1193338, "author": "SI Web Design", "author_id": 146326, "author_profile": "https://Stackoverflow.com/users/146326", "pm_score": 6, "selected": false, "text": "div.myButton input {\n background: url(https://i.imgur.com/tXLqhgC.png) no-repeat;\n background-size: 90px;\n width: 90px;\n height: 90px;\n cursor: pointer;\n border: none;\n} <div class=\"myButton\">\n <INPUT type=\"submit\" name=\"\" value=\"\">\n</div>" }, { "answer_id": 4882160, "author": "philoye", "author_id": 109864, "author_profile": "https://Stackoverflow.com/users/109864", "pm_score": 4, "selected": false, "text": "<input type=\"submit\" value=\"Submit\">\n <style>\n input[type=\"submit\"] {\n border: 0;\n background: url('sprite.png') no-repeat -40px left;\n text-indent: -9999em;\n line-height:3000;\n width: 50px;\n height: 20px;\n }\n</style>\n" }, { "answer_id": 4971303, "author": "user545376", "author_id": 545376, "author_profile": "https://Stackoverflow.com/users/545376", "pm_score": 2, "selected": false, "text": ">#divbutton\n{\n position:relative;\n top:-64px;\n left:210px;\n background: transparent url(\"../../images/login_go.png\") no-repeat;\n line-height:3000;\n width:33px;\n height:32px;\n border:none;\n cursor:pointer;\n}\n" }, { "answer_id": 5517032, "author": "dafyk", "author_id": 688057, "author_profile": "https://Stackoverflow.com/users/688057", "pm_score": 2, "selected": false, "text": "<input type=\"image\" src=\"img/blank.gif\" class=\"button\">\n .button {border:0;background:transparent url(\"../img/button.png\") no-repeat 0 0;}\n.button:hover {background:transparent url(\"../img/button-hover.png\") no-repeat 0 0;}\n" }, { "answer_id": 5682333, "author": "Reed Richards", "author_id": 27943, "author_profile": "https://Stackoverflow.com/users/27943", "pm_score": 2, "selected": false, "text": "<div id=\"myButton\">\n <input id=\"myInputButton\" type=\"submit\" name=\"\" value=\"\">\n</div>\n\n#myButton {\n background: url(\"form_send_button.gif\") no-repeat;\n width: 62px;\n height: 24px;\n}\n\n#myInputButton {\n background: url(\"form_send_button.gif\") no-repeat;\n opacity: 0;\n -ms-filter: \"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)\";\n filter: alpha(opacity=0);\n width: 67px;\n height: 26px;\n cursor: pointer;\n cursor: hand;\n}\n" }, { "answer_id": 10286771, "author": "inf3rno", "author_id": 607033, "author_profile": "https://Stackoverflow.com/users/607033", "pm_score": 2, "selected": false, "text": ".edit-button {\n background-image: url(edit.png);\n background-size: 100%;\n background-repeat: no-repeat;\n width: 24px;\n height: 24px;\n}\n <input class=\"edit-button\" type=\"image\" src=\"transparent.png\" />\n" }, { "answer_id": 13481271, "author": "John", "author_id": 1833395, "author_profile": "https://Stackoverflow.com/users/1833395", "pm_score": 1, "selected": false, "text": "<input type=Submit class=continue_shopping_2\n name=Register title=\"Confirm Your Data!\"\n value=\"confirm your data\">\n .continue_shopping_2: hover {\n background-color: #FF9933;\n text-decoration: none;\n color: #FFFFFF;\n}\n\n\n.continue_shopping_2 {\n padding: 0 0 3px 0;\n cursor: pointer;\n background-color: #EC5500;\n display: block;\n text-align: center;\n margin-top: 8px;\n width: 174px;\n height: 21px;\n border-radius: 5px;\n border-width: 1px;\n border-style: solid;\n border-color: #919191;\n font-family: Verdana;\n font-size: 13px;\n font-style: normal;\n line-height: normal;\n font-weight: bold;\n color: #FFFFFF;\n}\n" }, { "answer_id": 60635900, "author": "Colin James Firth", "author_id": 1448603, "author_profile": "https://Stackoverflow.com/users/1448603", "pm_score": 0, "selected": false, "text": "#daft {\n height: 0;\n padding-top: 100px;\n width: 100px;\n background-image: url(clever.jpg);\n} <input type=\"image\" src=\"daft.jpg\" id=\"daft\">" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179/" ]
195,635
<p>I am trying to figure out Messagebox( ownerWindow, ... ).</p> <p>Using reflector I see that the ownerWindow defaults to the ActiveWindow for the thread.</p> <p>So the only time I need the ownerWindow parameter is to call Show from another thread. </p> <p>However when I try this, I get a cross threading exception.</p> <pre><code> private void button1_Click( object sender, EventArgs e ) { new Thread( () =&gt; MessageBox.Show( this, "Test" ) ).Start(); } </code></pre> <p>So it looks like the only time I need the explicitly state the owner window, I cann't use it!</p>
[ { "answer_id": 195640, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 2, "selected": false, "text": "private delegate void ThreadExecuteDelegate(object args);\n\npublic void StartThread\n{\n Thread thread = new Thread(new ParameterizedThreadStart(ThreadExecute));\n thread.Start((IWin32Window)this);\n}\n\nprivate void ThreadExecute(object args)\n{\n if(this.InvokeRequired)\n {\n this.BeginInvoke(new ThreadExecuteDelegate(ThreadExecute), args);\n return;\n } \n\n IWin32Window window = (IWin32Window)args;\n MessageBox.Show(window, \"Hello world\");\n}\n" }, { "answer_id": 195656, "author": "Scott Weinstein", "author_id": 25201, "author_profile": "https://Stackoverflow.com/users/25201", "pm_score": 0, "selected": false, "text": "ReportProgress" }, { "answer_id": 196111, "author": "jyoung", "author_id": 14841, "author_profile": "https://Stackoverflow.com/users/14841", "pm_score": 1, "selected": false, "text": " public class Win32Window :IWin32Window {\n IntPtr handle;\n public Win32Window( IWin32Window window ) {\n this.handle = window.Handle;\n }\n\n IntPtr IWin32Window.Handle {\n get { return handle; }\n }\n }\n\n private void button1_Click( object sender, EventArgs e ) {\n IWin32Window window = new Win32Window( this );\n new Thread( () => MessageBox.Show( window, \"Test\" ) ).Start();\n }\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14841/" ]
195,639
<p>I need a way to bind POJO objects to an external entity, that could be XML, YAML, structured text or anything easy to write and maintain in order to create Mock data for unit testing and TDD. Below are some libraries I tried, but the main problems with them were that I am stuck (for at least more 3 months) to Java 1.4. I'd like any insights on what I could use instead, with as low overhead and upfront setup (like using Schemas or DTDs, for instance) as possible and without complex XML. Here are the libraries I really like (but that apparently doesn't work with 1.4 or doesn't support constructors - you gotta have setters):</p> <p><b>RE-JAXB (or Really Easy Java XML Bindings)</b></p> <p><a href="http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html" rel="nofollow noreferrer"><a href="http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html" rel="nofollow noreferrer">http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html</a></a> <a href="http://sourceforge.net/projects/rejaxb/" rel="nofollow noreferrer"> <a href="http://sourceforge.net/projects/rejaxb/" rel="nofollow noreferrer">http://sourceforge.net/projects/rejaxb/</a></a></p> <p>Seamlessy binds this:</p> <pre><code>&lt;item&gt; &lt;title&gt;Astronauts' Dirty Laundry&lt;/title&gt; &lt;link&gt;http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp&lt;/link&gt; &lt;description&gt;Compared to earlier spacecraft, the International Space Station has many luxuries, but laundry facilities are not one of them. Instead, astronauts have other options.&lt;/description&gt; &lt;pubDate&gt;Tue, 20 May 2003 08:56:02 GMT&lt;/pubDate&gt; &lt;guid&gt;http://liftoff.msfc.nasa.gov/2003/05/20.html#item570&lt;/guid&gt; &lt;/item&gt; </code></pre> <p>To this:</p> <pre><code>@ClassXmlNodeName("item") public class Item { private String title; private String link; private String description; private String pubDate; private String guid; //getters and settings go here... } </code></pre> <p>Using:</p> <pre><code>Rss rss = new Rss(); XmlBinderFactory.newInstance().bind(rss, new File("Rss2Test.xml")); </code></pre> <p>Problem: It relies on annotations, so no good for Java 1.4</p> <p><b>jYaml</b> <a href="http://jyaml.sourceforge.net/" rel="nofollow noreferrer"><a href="http://jyaml.sourceforge.net/" rel="nofollow noreferrer">http://jyaml.sourceforge.net/</a></a></p> <p>Seamlessly binds this:</p> <pre><code>--- !user name: Felipe Coury password: felipe modules: - !module id: 1 name: Main Menu admin: !user name: Admin password: password </code></pre> <p>To this:</p> <pre><code>public class User { private String name; private String password; private List modules; } public class Module { private int id; private String name; private User admin; } </code></pre> <p>Using:</p> <pre><code>YamlReader reader = new YamlReader(new FileReader("example.yaml")); reader.getConfig().setClassTag("user", User.class); reader.getConfig().setClassTag("module", Module.class); User user = (User) reader.read(User.class); </code></pre> <p>Problem: It won't work with constructors (so no good for immutable objects). I'd have to either change my objects or write custom code por handling the YAML parsing.</p> <p>Remember that I would like to avoid - as much as I can - writing data descriptors, I'd like something that "just works".</p> <p>Do you have any suggestions?</p>
[ { "answer_id": 196243, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "import java.beans.XMLEncoder;\nimport java.beans.XMLDecoder;\nimport java.io.BufferedInputStream;\nimport java.io.BufferedOutputStream;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\n\npublic class ToXml {\n\n /**\n * Write an object to a file in XML format.\n * @param o - The object to serialize.\n * @param file - The file where to write the object.\n */\n public static void writeObject( Object o, String file ) {\n XMLEncoder e = null;\n try {\n\n e = new XMLEncoder( new BufferedOutputStream( new FileOutputStream(file)));\n\n e.writeObject(o);\n\n }catch( IOException ioe ) {\n throw new RuntimeException( ioe );\n }finally{\n if( e != null ) {\n e.close();\n }\n }\n }\n\n /**\n * Read a xml serialized object from the specified file.\n * @param file - The file where the serialized xml version of the object is.\n * @return The object represented by the xmlfile.\n */\n public static Object readObject( String file ){\n XMLDecoder d = null;\n try {\n\n d = new XMLDecoder( new BufferedInputStream( new FileInputStream(file)));\n\n return d.readObject();\n\n }catch( IOException ioe ) {\n throw new RuntimeException( ioe );\n }finally{\n if( d != null ) {\n d.close();\n }\n }\n }\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14540/" ]
195,641
<p>During the installation of Apache2 I got the following message into cmd window:</p> <blockquote> <p>Installing the Apache2.2 service The Apache2.2 service is successfully installed. Testing httpd.conf....</p> <p>Errors reported here must be corrected before the service can be started. httpd.exe: Could not reliably determine the server's fully qualified domain name , using 192.168.1.3 for ServerName (OS 10048)Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down Unable to open logs Note the errors or messages above, and press the key to exit. 24...</p> </blockquote> <p>and after installing everything look fine, but it isn't. If I try to start service I got the following message:</p> <blockquote> <p>Windows could not start the Apache2 on Local Computer. For more information, review the System Event Log. If this is a non-Micorsoft service, contact the service vendor, and refer to service-specific error code 1.</p> </blockquote> <p>Apach2 version is 2.2.9</p> <p>Does anyone have the same problem, or could help me.</p>
[ { "answer_id": 195654, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "Conexiones activas\n\n Proto Dirección local Dirección remota Estado PID\n TCP 127.0.0.1:1110 127.0.0.1:51373 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51379 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51381 ESTABLISHED 388\n TCP 127.0.0.1:1110 127.0.0.1:51382 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51479 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51481 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51483 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51485 ESTABLISHED 388\n TCP 127.0.0.1:1110 127.0.0.1:51487 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51489 ESTABLISHED 388\n TCP 127.0.0.1:51381 127.0.0.1:1110 ESTABLISHED 5168\n TCP 127.0.0.1:51485 127.0.0.1:1110 ESTABLISHED 5168\n TCP 127.0.0.1:51489 127.0.0.1:1110 ESTABLISHED 5168\n TCP 127.0.0.1:59264 127.0.0.1:59265 ESTABLISHED 5168\n TCP 127.0.0.1:59265 127.0.0.1:59264 ESTABLISHED 5168\n TCP 127.0.0.1:59268 127.0.0.1:59269 ESTABLISHED 5168\n TCP 127.0.0.1:59269 127.0.0.1:59268 ESTABLISHED 5168\n TCP 192.168.1.34:51278 192.168.1.33:445 ESTABLISHED 4\n TCP 192.168.1.34:51383 67.199.15.132:80 ESTABLISHED 388\n TCP 192.168.1.34:51486 66.102.9.18:80 ESTABLISHED 388\n TCP 192.168.1.34:51490 74.125.4.20:80 ESTABLISHED 388\n" }, { "answer_id": 20168079, "author": "Junior Mayhé", "author_id": 66708, "author_profile": "https://Stackoverflow.com/users/66708", "pm_score": 1, "selected": false, "text": "#if you have c:\\your-main-folder\\www\\\nDocumentRoot \"c:/your-main-folder/www/\" \n\n#if you have c:\\your-main-folder\\www\\sub-folder\\\nDocumentRoot \"c:/your-main-folder/www/sub-folder/\" \n DocumentRoot" }, { "answer_id": 29900265, "author": "John", "author_id": 606371, "author_profile": "https://Stackoverflow.com/users/606371", "pm_score": 2, "selected": false, "text": "error.log" }, { "answer_id": 37505142, "author": "PapaHotelPapa", "author_id": 2859605, "author_profile": "https://Stackoverflow.com/users/2859605", "pm_score": 0, "selected": false, "text": "httpd.conf" }, { "answer_id": 44534650, "author": "eddyparkinson", "author_id": 1378888, "author_profile": "https://Stackoverflow.com/users/1378888", "pm_score": 0, "selected": false, "text": "httpd.exe -k install\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16039/" ]
195,648
<p>What's an example of something dangerous that would not be caught by the code below?</p> <p>EDIT: After some of the comments I added another line, commented below. See Vinko's comment in David Grant's answer. So far only Vinko has answered the question, which asks for specific examples that would slip through this function. Vinko provided one, but I've edited the code to close that hole. If another of you can think of another specific example, you'll have my vote!</p> <pre><code>public static string strip_dangerous_tags(string text_with_tags) { string s = Regex.Replace(text_with_tags, @"&lt;script", "&lt;scrSAFEipt", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"&lt;/script", "&lt;/scrSAFEipt", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"&lt;object", "&lt;/objSAFEct", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"&lt;/object", "&lt;/obSAFEct", RegexOptions.IgnoreCase); // ADDED AFTER THIS QUESTION WAS POSTED s = Regex.Replace(s, @"javascript", "javaSAFEscript", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onabort", "onSAFEabort", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onblur", "onSAFEblur", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onchange", "onSAFEchange", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onclick", "onSAFEclick", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"ondblclick", "onSAFEdblclick", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onerror", "onSAFEerror", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onfocus", "onSAFEfocus", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onkeydown", "onSAFEkeydown", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onkeypress", "onSAFEkeypress", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onkeyup", "onSAFEkeyup", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onload", "onSAFEload", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onmousedown", "onSAFEmousedown", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onmousemove", "onSAFEmousemove", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onmouseout", "onSAFEmouseout", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onmouseup", "onSAFEmouseup", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onmouseup", "onSAFEmouseup", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onreset", "onSAFEresetK", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onresize", "onSAFEresize", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onselect", "onSAFEselect", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onsubmit", "onSAFEsubmit", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"onunload", "onSAFEunload", RegexOptions.IgnoreCase); return s; } </code></pre>
[ { "answer_id": 195662, "author": "David Grant", "author_id": 26829, "author_profile": "https://Stackoverflow.com/users/26829", "pm_score": 2, "selected": false, "text": "<a href=\"javascript:document.writeln('on' + 'unload' + ' and more malicious stuff here...');\">example</a>\n" }, { "answer_id": 195677, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 3, "selected": false, "text": "< &lt; > &gt;" }, { "answer_id": 195703, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 7, "selected": true, "text": "javascript: <embed> behavior expression < &lt; href" }, { "answer_id": 430133, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 2, "selected": false, "text": " <div style=\"color: expression('alert(4)')\">\n" }, { "answer_id": 11800969, "author": "mholly", "author_id": 1013424, "author_profile": "https://Stackoverflow.com/users/1013424", "pm_score": 2, "selected": false, "text": "patterns.put(\"xssAttack1\", Pattern.compile(\"<script\",Pattern.CASE_INSENSITIVE) );\npatterns.put(\"xssAttack2\", Pattern.compile(\"SRC=\",Pattern.CASE_INSENSITIVE) );\npatterns.put(\"xssAttack3\", Pattern.compile(\"pt:al\",Pattern.CASE_INSENSITIVE) );\npatterns.put(\"xssAttack4\", Pattern.compile(\"xss\",Pattern.CASE_INSENSITIVE) );\n\n<FRAMESET><FRAME SRC=\"javascript:alert('XSS');\"></FRAMESET>\n<DIV STYLE=\"width: expression(alert('XSS'));\">\n<LINK REL=\"stylesheet\" HREF=\"javascript:alert('XSS');\">\n<IMG SRC=\"jav ascript:alert('XSS');\"> // hmtl allows embedded tabs...\n<IMG SRC=\"jav&#x0A;ascript:alert('XSS');\"> // hmtl allows embedded newline...\n<IMG SRC=\"jav&#x0D;ascript:alert('XSS');\"> // hmtl allows embedded carriage return...\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
195,655
<p>Is it possible to copy a single file to multiple directories using the cp command ?</p> <p>I tried the following , which did not work: </p> <pre><code>cp file1 /foo/ /bar/ cp file1 {/foo/,/bar} </code></pre> <p>I know it's possible using a for loop, or find. But is it possible using the gnu cp command?</p>
[ { "answer_id": 195663, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 8, "selected": true, "text": "cp cp" }, { "answer_id": 195972, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 9, "selected": false, "text": "cp cp xargs echo dir1 dir2 dir3 | xargs -n 1 cp file1\n file1 dir1 dir2 dir3 xargs cp xargs" }, { "answer_id": 1374908, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "cat <source file> | tee <destination file 1> | tee <destination file 2> [...] > <last destination file>\n" }, { "answer_id": 4803535, "author": "Paul", "author_id": 590431, "author_profile": "https://Stackoverflow.com/users/590431", "pm_score": 6, "selected": false, "text": "echo ./fs*/* | xargs -n 1 cp test \n" }, { "answer_id": 6988966, "author": "Evgeny", "author_id": 876687, "author_profile": "https://Stackoverflow.com/users/876687", "pm_score": 4, "selected": false, "text": "ls | xargs -n 1 cp -i file.dat\n -i cp file.dat" }, { "answer_id": 9071256, "author": "deterb", "author_id": 15585, "author_profile": "https://Stackoverflow.com/users/15585", "pm_score": 4, "selected": false, "text": "cat tee cp cat inputfile | tee outfile1 outfile2 > /dev/null\n" }, { "answer_id": 13812788, "author": "Hedgehog", "author_id": 152860, "author_profile": "https://Stackoverflow.com/users/152860", "pm_score": -1, "selected": false, "text": "-maxdepth find . -mindepth 1 -maxdepth 1 -type d| xargs -n 1 cp -i index.html\n a find . -mindepth 1 -maxdepth 1 -type d| grep \\/a |xargs -n 1 cp -i index.html\n" }, { "answer_id": 18063738, "author": "ddavison", "author_id": 1695163, "author_profile": "https://Stackoverflow.com/users/1695163", "pm_score": 0, "selected": false, "text": "branch myfile dir1 dir2 dir3" }, { "answer_id": 21459130, "author": "Kristofer", "author_id": 259485, "author_profile": "https://Stackoverflow.com/users/259485", "pm_score": -1, "selected": false, "text": "find . | grep favicon\\.ico | xargs -n 1 cp -f /root/favicon.ico\n" }, { "answer_id": 21477075, "author": "thAAAnos", "author_id": 616698, "author_profile": "https://Stackoverflow.com/users/616698", "pm_score": 3, "selected": false, "text": "ls -db di*/subdir | xargs -n 1 cp File -b" }, { "answer_id": 22752248, "author": "Taywee", "author_id": 1362309, "author_profile": "https://Stackoverflow.com/users/1362309", "pm_score": 3, "selected": false, "text": "tee <inputfile file2 file3 file4 ... >/dev/null" }, { "answer_id": 23985038, "author": "alainv", "author_id": 3697704, "author_profile": "https://Stackoverflow.com/users/3697704", "pm_score": 2, "selected": false, "text": "parallel -q cp file1 ::: /foo/ /bar/\n parallel -q cp file1 ::: `find -mindepth 1 -type d`\n" }, { "answer_id": 26813325, "author": "Stace Fauske", "author_id": 4229261, "author_profile": "https://Stackoverflow.com/users/4229261", "pm_score": -1, "selected": false, "text": "cp file1 /foo/; cp file1 /bar/; cp file1 /foo2/; cp file1 /bar2/ cp -r dir1/ /foo/; cp -r dir1/ /bar/; cp -r dir1/ /foo2/; cp -r dir1/ /bar2/" }, { "answer_id": 29456982, "author": "Sj Lee", "author_id": 4751449, "author_profile": "https://Stackoverflow.com/users/4751449", "pm_score": 0, "selected": false, "text": "ls -d */ | xargs -iA cp file.txt A\n" }, { "answer_id": 36142701, "author": "Devendra Lattu", "author_id": 2889297, "author_profile": "https://Stackoverflow.com/users/2889297", "pm_score": 0, "selected": false, "text": "fileName.txt ls allFolders.txt ls > allFolders.txt\n xargs cat allFolders.txt | xargs -n 1 cp fileName.txt\n" }, { "answer_id": 37948571, "author": "oggust", "author_id": 6491685, "author_profile": "https://Stackoverflow.com/users/6491685", "pm_score": 3, "selected": false, "text": "$ tar cf - src | tee >( cd dest1 ; tar xf - ) >( cd dest2 ; tar xf - ) | ( cd dest3 ; tar xf - )\n" }, { "answer_id": 41433002, "author": "Waxrat", "author_id": 2102698, "author_profile": "https://Stackoverflow.com/users/2102698", "pm_score": 4, "selected": false, "text": "for i in /foo /bar; do cp \"$file1\" \"$i\"; done\n" }, { "answer_id": 45444089, "author": "MegaCookie", "author_id": 3801276, "author_profile": "https://Stackoverflow.com/users/3801276", "pm_score": 3, "selected": false, "text": "xargs find ./fs*/* -type d -print0 | xargs -0 -n 1 cp test \n test ./fs*/* -d -E" }, { "answer_id": 52121255, "author": "Patrick Manley", "author_id": 10301505, "author_profile": "https://Stackoverflow.com/users/10301505", "pm_score": 0, "selected": false, "text": "DESTINATIONPATH[0]=\"xxx/yyy\"\nDESTINATIONPATH[1]=\"aaa/bbb\"\n ..\nDESTINATIONPATH[5]=\"MainLine/USER\"\nNumberOfDestinations=6\n\nfor (( i=0; i<NumberOfDestinations; i++))\n do\n cp SourcePath/fileName.ext ${DESTINATIONPATH[$i]}\n\n done\nexit\n" }, { "answer_id": 56791292, "author": "Mig82", "author_id": 4124574, "author_profile": "https://Stackoverflow.com/users/4124574", "pm_score": -1, "selected": false, "text": "path/to find cp find ./path/to/* -type d -exec cp [file name] {} \\;\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
195,667
<p>I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).</p> <p>Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.</p> <p>Thanks</p>
[ { "answer_id": 195675, "author": "Dimitry", "author_id": 27073, "author_profile": "https://Stackoverflow.com/users/27073", "pm_score": 0, "selected": false, "text": "<!-- in the main page --->\nfunction showTable1() {}\n\n<!-- in the iframe -->\nwindow.onload = function () {\n parent.showTable1();\n}\n" }, { "answer_id": 195698, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " _tbRetry.style.display='none';\n _tbNext.style.display='none';\n\n var btnUpload = _ifrFile.contentWindow.document.getElementById('btnUpload');\n\n btnUpload.onclick = function(event)\n {\n var myFile = _ifrFile.contentWindow.document.getElementById('myFile');\n\n //Baisic validation\n _divUploadMessage.style.display = 'none';\n\n\n if (myFile.value.length == 0)\n {\n _divUploadMessage.innerHTML = '<span style=\\\"color:#ff0000\\\">Please select a file.</span>';\n _divUploadMessage.style.display = '';\n myFile.focus();\n return;\n }\n\n var regExp = /^(([a-zA-Z]:)|(\\\\{2}\\w+)\\$?)(\\\\(\\w[\\w].*))(.doc|.txt|.xls|.docx |.xlsx)$/;\n\n if (!regExp.test(myFile.value)) //Somehow the expression does not work in Opera\n {\n _divUploadMessage.innerHTML = '<span style=\\\"color:#ff0000\\\">Invalid file type. Only supports doc, txt, xls.</span>';\n _divUploadMessage.style.display = '';\n myFile.focus();\n return;\n }\n\n\n _ifrFile.contentWindow.document.getElementById('Upload').submit();\n _divFrame.style.display = 'none';\n\n\n }\n }\n clearUploadProgress();\n\n\n if (_UploadProgressTimer)\n {\n clearTimeout(_UploadProgressTimer);\n }\n\n _divUploadProgress.style.display = 'none';\n _divUploadMessage.style.display = 'none';\n _divFrame.style.display = 'none';\n _tbNext.style.display='';\n\n if (message.length)\n {\n var color = (isError) ? '#008000' : '#ff0000';\n\n _divUploadMessage.innerHTML = '<span style=\\\"color:' + color + '\\;font-weight:bold\">' + message + '</span>';\n _divUploadMessage.style.display = '';\n _tbNext.style.display='';\n _tbRetry.style.display='none';\n\n\n\n }\n }\n" }, { "answer_id": 213459, "author": "kentaromiura", "author_id": 27340, "author_profile": "https://Stackoverflow.com/users/27340", "pm_score": 1, "selected": false, "text": "mainpage.waitTillPostBack = true\nYourFunctionCausingPostBack();\n\n\n..\n\nonload=function(){\nif(!mainpage.waitTillPostBack){\nhideTables();\n}\nmainpage.waitTillPostBack = false;\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
195,682
<p>Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction. There's no reason for my mock class to actually create and close threads. But, to mock a class, I have inherit from it. When I create a new instance of my mock class, the base classes constructor is called, creating the thread. When my mock object is destroyed, the base classes destructor is called, attempting to close the thread. </p> <p>How does one mock an RAII class without having to deal with the actual resource?</p>
[ { "answer_id": 195747, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 5, "selected": true, "text": "class RAIIClass {\n public:\n RAIIClass(Foo* f);\n ~RAIIClass();\n bool DoOperation();\n\n private:\n ...\n};\n class MockableInterface {\n public:\n MockableInterface(Foo* f);\n virtual ~MockableInterface();\n virtual bool DoOperation() = 0;\n};\n" }, { "answer_id": 196116, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 0, "selected": false, "text": "class Base{\n protected:\n Base* decorated;\n public:\n virtual void method(void)=0;\n};\nclass Final: public Base{\n void method(void) { Thread athread; decorated->method(); } // I expect Final to do something with athread\n};\nclass TestBase: public Base{\n void method(void) { decorated->method(); }\n};\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23071/" ]
195,684
<p>On a CentOS LAMP box, trying to get require_once to work inside a script in PHP5. If the file to be included is not a in symlinked directory, it works fine, but if the file to be required is in a directory found via a symbolic link, it fails to find it.</p> <p>Is this a limitation of require_once and symbolic links?</p> <p>EDIT - Thanks for the input, all. I think it's most likely a permissions thing after reading those</p>
[ { "answer_id": 195801, "author": "Andy", "author_id": 26693, "author_profile": "https://Stackoverflow.com/users/26693", "pm_score": 2, "selected": false, "text": "\n if (is_link($path))\n {\n $path = readlink($path);\n }\n require_once($path);\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ]
195,688
<p>I have a string(char*), and i need to find its underlying datatype such as int, float, double, short, long, or just a character array containing alphabets with or with out digits(like varchar in SQL). For ex: </p> <pre><code> char* str1 = "12312" char* str2 = "231.342" char* str3 = "234234243234" char* str4 = "4323434.2432342" char* str5 = "i contain only alphabets" </code></pre> <p><strong>Given these strings, i need to find that the first string is of type int and typecast it to an int, and so on</strong> ex:</p> <pre><code>int no1 = atoi(str1) float no2 = atof(str2) long no3 = atol(str3) double no4 = strtod(str4) char* varchar1 = strdup(str5) </code></pre> <hr> <p>Clarifying a bit more... </p> <p>I have a string and its contents could be alphabets and/or digits and/or special characters. Right now, I am able to parse string and </p> <ol> <li>Identify if it contains only digits,<br> Here i convert the string into short or int or long, based on best fit. ( <strong>How do i know if the string can be converted to an short int or long?</strong>) </li> <li>Only alphabets, leave it as a string. </li> <li>Digits with a single decimal point.<br> Here i need to convert the string into float or double ( <strong>Same question here</strong>)</li> <li>other. leave it as a string</li> </ol>
[ { "answer_id": 195732, "author": "Pitarou", "author_id": 1260685, "author_profile": "https://Stackoverflow.com/users/1260685", "pm_score": 1, "selected": false, "text": "[+-]?\\d+" }, { "answer_id": 195775, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "<limits.h> <float.h>" }, { "answer_id": 195795, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 0, "selected": false, "text": "-?\\d*.\\d*([eE]?[+-]?\\d*.\\d*)? .e-. -?\\d+ 0x[0-9A-Fa-f]+ long long limits.h SHRT_MAX short unsigned short signed short unsigned short" }, { "answer_id": 195837, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": true, "text": "#include <stdlib.h>\n#include <stdio.h>\n#include <limits.h>\n#include <float.h>\n\n/* Now, we know the following values:\n INT_MAX, INT_MIN, SHRT_MAX, SHRT_MIN, CHAR_MAX, CHAR_MIN, etc. */\n\ntypedef union tagMyUnion\n{\n char TChar_ ; short TShort_ ; long TLong_ ; double TDouble_ ;\n} MyUnion ;\n\ntypedef enum tagMyEnum\n{\n TChar, TShort, TLong, TDouble, TNaN\n} MyEnum ;\n\nvoid whatIsTheValue(const char * string_, MyEnum * enum_, MyUnion * union_)\n{\n char * endptr ;\n long lValue ;\n double dValue ;\n\n *enum_ = TNaN ;\n\n /* integer value */\n lValue = strtol(string_, &endptr, 10) ;\n\n if(*endptr == 0) /* It is an integer value ! */\n {\n if((lValue >= CHAR_MIN) && (lValue <= CHAR_MAX)) /* is it a char ? */\n {\n *enum_ = TChar ;\n union_->TChar_ = (char) lValue ;\n }\n else if((lValue >= SHRT_MIN) && (lValue <= SHRT_MAX)) /* is it a short ? */\n {\n *enum_ = TShort ;\n union_->TShort_ = (short) lValue ;\n }\n else if((lValue >= LONG_MIN) && (lValue <= LONG_MAX)) /* is it a long ? */\n {\n *enum_ = TLong ;\n union_->TLong_ = (long) lValue ;\n }\n\n return ;\n }\n\n /* real value */\n dValue = strtod(string_, &endptr) ;\n\n if(*endptr == 0) /* It is an real value ! */\n {\n if((dValue >= -DBL_MAX) && (dValue <= DBL_MAX)) /* is it a double ? */\n {\n *enum_ = TDouble ;\n union_->TDouble_ = (double) dValue ;\n }\n\n return ;\n }\n\n return ;\n}\n\nvoid studyValue(const char * string_)\n{\n MyEnum enum_ ;\n MyUnion union_ ;\n\n whatIsTheValue(string_, &enum_, &union_) ;\n\n switch(enum_)\n {\n case TChar : printf(\"It is a char : %li\\n\", (long) union_.TChar_) ; break ;\n case TShort : printf(\"It is a short : %li\\n\", (long) union_.TShort_) ; break ;\n case TLong : printf(\"It is a long : %li\\n\", (long) union_.TLong_) ; break ;\n case TDouble : printf(\"It is a double : %f\\n\", (double) union_.TDouble_) ; break ;\n case TNaN : printf(\"It is a not a number : %s\\n\", string_) ; break ;\n default : printf(\"I really don't know : %s\\n\", string_) ; break ;\n }\n}\n\nint main(int argc, char **argv)\n{\n studyValue(\"25\") ;\n studyValue(\"-25\") ;\n studyValue(\"30000\") ;\n studyValue(\"-30000\") ;\n studyValue(\"300000\") ;\n studyValue(\"-300000\") ;\n studyValue(\"25.5\") ;\n studyValue(\"-25.5\") ;\n studyValue(\"25555555.55555555\") ;\n studyValue(\"-25555555.55555555\") ;\n studyValue(\"Hello World\") ;\n studyValue(\"555-55-55\") ;\n\n return 0;\n}\n [25] is a char : 25\n[-25] is a char : -25\n[30000] is a short : 30000\n[-30000] is a short : -30000\n[300000] is a long : 300000\n[-300000] is a long : -300000\n[25.5] is a double : 25.500000\n[-25.5] is a double : -25.500000\n[25555555.55555555] is a double : 25555555.555556\n[-25555555.55555555] is a double : -25555555.555556\n[Hello World] is a not a number\n[555-55-55] is a not a number\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27221/" ]
195,696
<p>While researching this issue, I found multiple mentions of the following scenario online, invariably as unanswered questions on programming forums. I hope that posting this here will at least serve to document my findings.</p> <p>First, the symptom: While running pretty standard code that uses waveOutWrite() to output PCM audio, I sometimes get this when running under the debugger:</p> <pre><code> ntdll.dll!_DbgBreakPoint@0() ntdll.dll!_RtlpBreakPointHeap@4() + 0x28 bytes ntdll.dll!_RtlpValidateHeapEntry@12() + 0x113 bytes ntdll.dll!_RtlDebugGetUserInfoHeap@20() + 0x96 bytes ntdll.dll!_RtlGetUserInfoHeap@20() + 0x32743 bytes kernel32.dll!_GlobalHandle@4() + 0x3a bytes wdmaud.drv!_waveCompleteHeader@4() + 0x40 bytes wdmaud.drv!_waveThread@4() + 0x9c bytes kernel32.dll!_BaseThreadStart@8() + 0x37 bytes </code></pre> <p>While the obvious suspect would be a heap corruption somewhere else in the code, I found out that that's not the case. Furthermore, I was able to reproduce this problem using the following code (this is part of a dialog based MFC application:)</p> <pre><code>void CwaveoutDlg::OnBnClickedButton1() { WAVEFORMATEX wfx; wfx.nSamplesPerSec = 44100; /* sample rate */ wfx.wBitsPerSample = 16; /* sample size */ wfx.nChannels = 2; wfx.cbSize = 0; /* size of _extra_ info */ wfx.wFormatTag = WAVE_FORMAT_PCM; wfx.nBlockAlign = (wfx.wBitsPerSample &gt;&gt; 3) * wfx.nChannels; wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec; waveOutOpen(&amp;hWaveOut, WAVE_MAPPER, &amp;wfx, (DWORD_PTR)m_hWnd, 0, CALLBACK_WINDOW ); ZeroMemory(&amp;header, sizeof(header)); header.dwBufferLength = 4608; header.lpData = (LPSTR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, 4608)); waveOutPrepareHeader(hWaveOut, &amp;header, sizeof(header)); waveOutWrite(hWaveOut, &amp;header, sizeof(header)); } afx_msg LRESULT CwaveoutDlg::OnWOMDone(WPARAM wParam, LPARAM lParam) { HWAVEOUT dev = (HWAVEOUT)wParam; WAVEHDR *hdr = (WAVEHDR*)lParam; waveOutUnprepareHeader(dev, hdr, sizeof(WAVEHDR)); GlobalFree(GlobalHandle(hdr-&gt;lpData)); ZeroMemory(hdr, sizeof(*hdr)); hdr-&gt;dwBufferLength = 4608; hdr-&gt;lpData = (LPSTR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, 4608)); waveOutPrepareHeader(hWaveOut, &amp;header, sizeof(WAVEHDR)); waveOutWrite(hWaveOut, hdr, sizeof(WAVEHDR)); return 0; } </code></pre> <p>Before anyone comments on this, yes - the sample code plays back uninitialized memory. Don't try this with your speakers turned all the way up.</p> <p>Some debugging revealed the following information: waveOutPrepareHeader() populates header.reserved with a pointer to what appears to be a structure containing at least two pointers as its first two members. The first pointer is set to NULL. After calling waveOutWrite(), this pointer is set to a pointer allocated on the global heap. In pseudo code, that would look something like this:</p> <pre><code>struct Undocumented { void *p1, *p2; } /* This might have more members */ MMRESULT waveOutPrepareHeader( handle, LPWAVEHDR hdr, ...) { hdr-&gt;reserved = (Undocumented*)calloc(sizeof(Undocumented)); /* Do more stuff... */ } MMRESULT waveOutWrite( handle, LPWAVEHDR hdr, ...) { /* The following assignment fails rarely, causing the problem: */ hdr-&gt;reserved-&gt;p1 = malloc( /* chunk of private data */ ); /* Probably more code to initiate playback */ } </code></pre> <p>Normally, the header is returned to the application by waveCompleteHeader(), a function internal to wdmaud.dll. waveCompleteHeader() tries to deallocate the pointer allocated by waveOutWrite() by calling GlobalHandle()/GlobalUnlock() and friends. Sometimes, GlobalHandle() bombs, as shown above.</p> <p>Now, the reason that GlobalHandle() bombs is not due to a heap corruption, as I suspected at first - it's because waveOutWrite() returned without setting the first pointer in the internal structure to a valid pointer. I suspect that it frees the memory pointed to by that pointer before returning, but I haven't disassembled it yet.</p> <p>This only appears to happen when the wave playback system is low on buffers, which is why I'm using a single header to reproduce this.</p> <p>At this point I have a pretty good case against this being a bug in my application - after all, my application is not even running. Has anyone seen this before?</p> <p>I'm seeing this on Windows XP SP2. The audio card is from SigmaTel, and the driver version is 5.10.0.4995.</p> <p>Notes:</p> <p>To prevent confusion in the future, I'd like to point out that the answer suggesting that the problem lies with the use of malloc()/free() to manage the buffers being played is simply wrong. You'll note that I changed the code above to reflect the suggestion, to prevent more people from making the same mistake - it doesn't make a difference. The buffer being freed by waveCompleteHeader() is not the one containing the PCM data, the responsibility to free the PCM buffer lies with the application, and there's no requirement that it be allocated in any specific way.</p> <p>Also, I make sure that none of the waveOut API calls I use fail.</p> <p>I'm currently assuming that this is either a bug in Windows, or in the audio driver. Dissenting opinions are always welcome.</p>
[ { "answer_id": 514317, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 2, "selected": false, "text": "hdr->reserved hdr->reserved fdwOpen = CALLBACK_FUNCTION" }, { "answer_id": 1303694, "author": "pps", "author_id": 96174, "author_profile": "https://Stackoverflow.com/users/96174", "pm_score": 0, "selected": false, "text": "hdr->reserved = (Undocumented*)calloc(sizeof(Undocumented));\n" }, { "answer_id": 36082265, "author": "Vadim Galkin", "author_id": 4098174, "author_profile": "https://Stackoverflow.com/users/4098174", "pm_score": 0, "selected": false, "text": "WAVEHDR header = { buffer, sizeof(buffer), 0, 0, 0, 0, 0, 0 };\nwaveOutPrepareHeader(hWaveOut, &header, sizeof(WAVEHDR));\nwaveOutWrite(hWaveOut, &header, sizeof(WAVEHDR));\n/*\n* wait a while for the block to play then start trying\n* to unprepare the header. this will fail until the block has\n* played.\n*/\nwhile (waveOutUnprepareHeader(hWaveOut,&header,sizeof(WAVEHDR)) == WAVERR_STILLPLAYING) \nSleep(100);\nwaveOutClose(hWaveOut);\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9047/" ]
195,697
<p>I have an XML file, which I open in F# like this:</p> <pre><code>let Bookmarks(xmlFile:string) = let xml = XDocument.Load(xmlFile) </code></pre> <p>Once I have the XDocument I need to navigate it using LINQ to XML and extract all specific tags. Part of my solution is:</p> <pre><code>let xname (tag:string) = XName.Get(tag) let tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href") attribute.Value let Bookmarks(xmlFile:string) = let xml = XDocument.Load(xmlFile) xml.Elements &lt;| xname "A" |&gt; Seq.map(tagUrl) </code></pre> <p>How can I extract the specific tags from the XML file?</p>
[ { "answer_id": 195859, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "open System.IO\nopen System.Xml\nopen System.Xml.Linq \n\nlet xmlStr = @\"<?xml version='1.0' encoding='UTF-8'?>\n<doc>\n <blah>Blah</blah>\n <a href='urn:foo' />\n <yadda>\n <blah>Blah</blah>\n <a href='urn:bar' />\n </yadda>\n</doc>\"\n\nlet xns = XNamespace.op_Implicit \"\"\nlet a = xns + \"a\"\nlet reader = new StringReader(xmlStr)\nlet xdoc = XDocument.Load(reader)\nlet aElements = [for x in xdoc.Root.Elements() do\n if x.Name = a then\n yield x]\nlet href = xns + \"href\"\naElements |> List.iter (fun e -> printfn \"%A\" (e.Attribute(href)))\n" }, { "answer_id": 195870, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 4, "selected": true, "text": "#light\nopen System\nopen System.Xml.Linq\n\nlet xname s = XName.Get(s)\nlet bookmarks (xmlFile : string) = \n let xd = XDocument.Load xmlFile\n xd.Descendants <| xname \"bookmark\"\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18619/" ]
195,709
<p>After switching back and forth between several scripting languages this week, I found myself thinking how similar they all are. Yet I'm always reaching for Google (or nowadays SO) to remember details like what the local equivalents of "instanceof" and "endswith" are, or the right syntax to declare an interface, or whatever.</p> <p>This reminded me of the (human) language <a href="http://en.wikipedia.org/wiki/Europanto" rel="nofollow noreferrer">Europonto</a>. Just pick some vaguely English syntax and some vaguely Romance/Germanic/Slavic vocabulary, and it's all good!</p> <p>So what would happen if we tried to do the same thing with a scripting language. In the mood for Python-style indented blocks today? Fine! Want to use a prototype object? Ok! Can only remember how to spell the PHP names of some library function? No problem!</p> <p>Anyway, that's the wild and crazy idea. Since we need a question that admits concrete answers, let's tighten it up like this:</p> <p>What would be the most significant conflicts in creating a scripting language that permitted all the native syntax and library functions of [Python, Ruby, PHP, Perl, shell, and JavaScript], such that you could freely intermix code blocks and function names between languages?</p> <p>And let's say that any particular construction should be consistent at the statement level. So we'll allow:</p> <pre><code>foreach( $foo as $bar ) { if $foo == 2: print "hi" } </code></pre> <p>but not, say,</p> <pre><code>foreach( $foo as $bar ) { if $foo == 2: print "hi" endif end </code></pre> <p>Conflicts can include: parser ambiguities; name collision; conflicting semantics for objects or functions or closures; etc. I'm guessing that scope will be a ginormous issue, but you tell me.</p> <p>I'll start this as "community wiki" from the get go, so if you think it's a fun question but want to make it more rigorous, feel free to edit.</p>
[ { "answer_id": 195846, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 1, "selected": false, "text": "print sys.argv sys.argv" }, { "answer_id": 850141, "author": "inkredibl", "author_id": 22129, "author_profile": "https://Stackoverflow.com/users/22129", "pm_score": 1, "selected": false, "text": "string.startsWith() strstr()" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
195,714
<p>I'm writing an editor for large <em>archive files</em> (see below) of 4GB+, in native&amp;managed C++.</p> <p>For accessing the files, I'm using <em>file mapping</em> (see below) like any sane person. This is absolutely great for reading data, but a problem arises in actually editing the archive. File mapping does not allow resizing a file while it's being accessed, so I don't know how I should proceed when the user wants to insert new data in the file (which would exceed the file's original size, when it was mapped.)</p> <p>Should I remap the whole thing every time? That's bound to be slow. However, I'd want to keep the editor real-time with exclusive file access, since that simplifies the programming a lot, and won't let the file get screwed by other applications while being modified. I wouldn't want to spend an eternity working on the editor; It's just a simple dev-tool for the actual project I'm working on.</p> <p>So I'd like to hear how you've handled similar cases, and what other archiving software and especially other games do to solve this?</p> <p>To clarify:</p> <ul> <li><p>This is not a text file, I'm writing a specific binary <em>archive file format</em>. By which I mean a big file that contains many others, in directories. Custom archive files are very common in game usage for a number of reasons. With my format, I'm aiming to a similar (but somewhat simpler) structure as with <a href="http://www.wunderboy.org/docs/gcfformat.php" rel="nofollow noreferrer">Valve Software's GCF format</a> - I would have used the GCF format as it is, but unfortunately no editor exists for the format, although there are many great implementations for reading them, like <a href="http://nemesis.thewavelength.net/index.php?p=35" rel="nofollow noreferrer">HLLib</a>.</p></li> <li><p>Accessing the file must be fast, as it is intended for storing game resources. So it's not a database. Database files would be contained inside it, along with GFX, SFX etc. files.</p></li> <li><p>"File mapping" as talked here is a specific technique on the Windows platform, which allows direct access to a large file through creating "views" to parts of it, see here: <a href="http://msdn.microsoft.com/en-us/library/aa366556(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa366556(VS.85).aspx</a> - This technique allows minimal latency and memory usage and is a no-brainer for accessing any large files. So this does <em>not</em> mean reading the whole 4GB file into memory, it's exactly the contrary.</p></li> </ul>
[ { "answer_id": 196248, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 2, "selected": true, "text": "// Open memory mapped file \nHANDLE FileHandle = ::CreateFileW(file_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\nsize_t Size = ::GetFileSize(FileHandle, 0);\nHANDLE MappingHandle = ::CreateFileMapping(FileHandle, NULL, PAGE_READWRITE, 0, Size, NULL);\nvoid* ViewHandle = ::MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, Size);\n\n...\n\n// increase size of file\nUnmapViewOfFile(ViewHandle);\nCloseHandle(MappingHandle);\n\nSize += 1024;\n\n\nLARGE_INTEGER offset;\noffset.QuadPart = Size;\n\nLARGE_INTEGER newpos;\nSetFilePointerEx(FileHandle, offset, &newpos, FILE_BEGIN);\nSetEndOfFile(FileHandle);\n\nMappingHandle = ::CreateFileMapping(FileHandle, NULL, PAGE_READWRITE, 0, Size, NULL);\nViewHandle = ::MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, Size);\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15477/" ]
195,717
<p>My father died recently and I've inherited his Mac. I'd love to put it to use in my own life, but I don't want to wipe its brains out just so I can reconfigure it to use in my network, etc. His old files are historically important to me&mdash;I trust you can understand my desire to keep them.</p> <p>I can log in as I had an account on the machine before he passed, but that's about it.</p>
[ { "answer_id": 195725, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 2, "selected": false, "text": "sudo passwd root\n" }, { "answer_id": 12132784, "author": "Michael Zaporozhets", "author_id": 1061967, "author_profile": "https://Stackoverflow.com/users/1061967", "pm_score": 1, "selected": false, "text": "command s mount -uw / rm /var/db/.AppleSetupDone .AppleSetupDone mount -uw /\ncd /private/var/db/netinfo\nmv local.nidb local.old\nrm ../.AppleSetupDone\nexit \n" }, { "answer_id": 21249628, "author": "a female faust", "author_id": 1413335, "author_profile": "https://Stackoverflow.com/users/1413335", "pm_score": 0, "selected": false, "text": " sudo ditto <his files> <directory where you want the copies>\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26976/" ]
195,740
<p>I'm writing a Rails application, but can't seem to find how to do relative time, i.e. if given a certain Time class, it can calculate "30 seconds ago" or "2 days ago" or if it's longer than a month "9/1/2008", etc.</p>
[ { "answer_id": 195743, "author": "TonyLa", "author_id": 1295, "author_profile": "https://Stackoverflow.com/users/1295", "pm_score": 4, "selected": false, "text": "Time.now - 2.days \n" }, { "answer_id": 195793, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 3, "selected": false, "text": "def relative_time(start_time)\n diff_seconds = Time.now - start_time\n case diff_seconds\n when 0 .. 59\n puts \"#{diff_seconds} seconds ago\"\n when 60 .. (3600-1)\n puts \"#{diff_seconds/60} minutes ago\"\n when 3600 .. (3600*24-1)\n puts \"#{diff_seconds/3600} hours ago\"\n when (3600*24) .. (3600*24*30) \n puts \"#{diff_seconds/(3600*24)} days ago\"\n else\n puts start_time.strftime(\"%m/%d/%Y\")\n end\nend\n" }, { "answer_id": 195841, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 4, "selected": false, "text": "30.seconds.ago\n2.days.ago\n" }, { "answer_id": 195883, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 9, "selected": false, "text": "time_ago_in_words distance_of_time_in_words <%= time_ago_in_words(timestamp) %>\n" }, { "answer_id": 195894, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 6, "selected": false, "text": "module PrettyDate\n def to_pretty\n a = (Time.now-self).to_i\n\n case a\n when 0 then 'just now'\n when 1 then 'a second ago'\n when 2..59 then a.to_s+' seconds ago' \n when 60..119 then 'a minute ago' #120 = 2 minutes\n when 120..3540 then (a/60).to_i.to_s+' minutes ago'\n when 3541..7100 then 'an hour ago' # 3600 = 1 hour\n when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago' \n when 82801..172000 then 'a day ago' # 86400 = 1 day\n when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago'\n when 518400..1036800 then 'a week ago'\n else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'\n end\n end\nend\n\nTime.send :include, PrettyDate\n" }, { "answer_id": 16182048, "author": "davogones", "author_id": 59631, "author_profile": "https://Stackoverflow.com/users/59631", "pm_score": 3, "selected": false, "text": "Time.now.yesterday\nTime.now.ago(2.days).end_of_day\nTime.now.next_month.beginning_of_month\n" }, { "answer_id": 18798641, "author": "seo", "author_id": 2446285, "author_profile": "https://Stackoverflow.com/users/2446285", "pm_score": 5, "selected": false, "text": "<%= time_ago_in_words(Date.today - 1) %>\n include ActionView::Helpers::DateHelper\ndef index\n @sexy_date = time_ago_in_words(Date.today - 1)\nend\n" }, { "answer_id": 21495459, "author": "Rahul garg", "author_id": 985051, "author_profile": "https://Stackoverflow.com/users/985051", "pm_score": 3, "selected": false, "text": "<%= time_ago_in_words(comment.created_at) %>\n <abbr class=\"timeago\" title=\"<%= comment.created_at.getutc.iso8601 %>\">\n <%= comment.created_at.to_s %>\n</abbr>\n $(\"abbr.timeago\").timeago();\n" }, { "answer_id": 48931665, "author": "Zack Xu", "author_id": 874283, "author_profile": "https://Stackoverflow.com/users/874283", "pm_score": 2, "selected": false, "text": "Time.zone.now\nTime.zone.today\nTime.zone.yesterday\n Time.zone.now Time.zone.now - 10.minute\nTime.zone.today.days_ago(5)\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
195,742
<p>I can run the server on my local machine and connect to it on the same machine, but when I try to connect to it from a different computer over the internet, there is not sign of activity on my server, nor a response from the server on the computer I'm testing it on. I've tried both XP and Vista, turn off firewalls, opened ports, ran as admin; nothing is working. :(</p> <p><strong>Here is my code that I'm using to accept an incoming connection:</strong><pre><code> int port = 3326; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, port)); listener.Start(); Console.WriteLine("Server established\nListening on Port: {0}\n", port); while (true) { socket = listener.AcceptSocket(); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, outime); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); socket.DontFragment = true; NewConnection pxy = new NewConnection(socket); Thread client = new Thread(new ThreadStart(pxy.Start)); client.IsBackground = true; client.Start(); } }</code></pre></p>
[ { "answer_id": 195749, "author": "hectorsq", "author_id": 14755, "author_profile": "https://Stackoverflow.com/users/14755", "pm_score": 4, "selected": true, "text": "3326" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22582/" ]
195,764
<p>Here's the XML file i'm working on:</p> <pre><code>&lt;list&gt; &lt;activity&gt;swimming&lt;/activity&gt; &lt;activity&gt;running&lt;/activity&gt; &lt;activity&gt;soccer&lt;/activity&gt; &lt;/list&gt; </code></pre> <p>The index.php, page that shows the list of activities with checkboxes, a button to delete the checked activities, and a field to add new activities:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;?php $xmldoc = new DOMDocument(); $xmldoc-&gt;load('sample.xml', LIBXML_NOBLANKS); $count = 0; $activities = $xmldoc-&gt;firstChild-&gt;firstChild; //prints the list of activities, with checkboxes on the left for each item //the $count variable is the id to each entry if($activities!=null){ echo '&lt;form name=\'erase\' action=\'delete.php\' method=\'post\'&gt;' . "\n"; while($activities!=null){ $count++; echo " &lt;input type=\"checkbox\" name=\"activity[]\" value=\"$count\"/&gt;"; echo ' '.$activities-&gt;textContent.'&lt;br/&gt;'."\n"; $activities = $activities-&gt;nextSibling; } echo ' &lt;input type=\'submit\' value=\'erase selected\'&gt;'; echo '&lt;/form&gt;'; } ?&gt; //section used for inserting new entries. this feature is working as expected. &lt;form name='input' action='insert.php' method='post'&gt; insert activity: &lt;input type='text name='activity'/&gt; &lt;input type='submit' value='send'/&gt; &lt;br/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>the delete.php, which is not working as expected:</p> <pre><code>&lt;?php $xmldoc = new DOMDocument(); $xmldoc-&gt;load('sample.xml', LIBXML_NOBLANKS); $atvID = $_POST['activity']; foreach($atvID as $id){ $delnode = $xmldoc-&gt;getElementsByTagName('activity'); $xmldoc-&gt;firstChild-&gt;removeChild($delnode-&gt;item($id)); } $xmldoc-&gt;save('sample.xml'); ?&gt; </code></pre> <p>I've tested the deletion routine without the loop, using an hard-coded arbitrary id, and it worked. I also tested the $atvID array, and it printed the selected id numbers correctly. When it is inside the loop, here's the error it outputs:</p> <blockquote> <p>Catchable fatal error: Argument 1 passed to DOMNode::removeChild() must be an instance of DOMNode, null given in /directorypath/delete.php on line 9</p> </blockquote> <p>What is wrong with my code?</p>
[ { "answer_id": 203430, "author": "John ODonnell", "author_id": 28072, "author_profile": "https://Stackoverflow.com/users/28072", "pm_score": 1, "selected": false, "text": "<list>\n <activity name=\"swimming\">swimming</activity>\n <activity name=\"running\">running</activity>\n <activity name=\"soccer\">soccer</activity>\n</list>\n $xpath = new DOMXPath($xmldoc);\n$xmldoc->firstChild->removeChild($xpath->query(\"/list/activity[@name='$id']\")->item(0));\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27090/" ]
195,768
<p>I'm in search of a JavaScript month selection tool. I'm already using jQuery on the website, so if it were a jQuery plugin, that would fit nicely. I'm open to other options, as well.</p> <p>Basically, I'm after a simplified version of the <a href="http://docs.jquery.com/UI/Datepicker" rel="noreferrer">jQuery UI Date Picker</a>. I don't care about the day of the month, just the month and year. Using the Date Picker control feels like overkill and a kludge. I know I could just use a pair of select boxes, but that feels cluttered, and then I also need a confirmation button.</p> <p>I'm envisioning a grid of either two rows of six columns, or three rows of four columns, for month selection, and current and future years across the top. (Maybe the ability to list a few years? I can't see anyone ever needing to go more than a year or two ahead, so if I could list the current and next two years, that would be swell.)</p> <p>It's really just a dumbed down version of the DatePicker. Does something like this exist?</p>
[ { "answer_id": 3348217, "author": "Cory", "author_id": 8207, "author_profile": "https://Stackoverflow.com/users/8207", "pm_score": 4, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js\"></script>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css\">\n<script type=\"text/javascript\">\n$(function() {\n $('.date-picker').datepicker( {\n changeMonth: true,\n changeYear: true,\n showButtonPanel: true,\n dateFormat: 'MM yy',\n onClose: function(dateText, inst) { \n var month = $(\"#ui-datepicker-div .ui-datepicker-month :selected\").val();\n var year = $(\"#ui-datepicker-div .ui-datepicker-year :selected\").val();\n $(this).datepicker('setDate', new Date(year, month, 1));\n }\n });\n});\n</script>\n<style>\n.ui-datepicker-calendar {\n display: none;\n }\n</style>\n</head>\n<body>\n <label for=\"startDate\">Date :</label>\n <input name=\"startDate\" id=\"startDate\" class=\"date-picker\" />\n</body>\n</html>\n" }, { "answer_id": 19389060, "author": "gustavohenke", "author_id": 2083599, "author_profile": "https://Stackoverflow.com/users/2083599", "pm_score": 5, "selected": true, "text": "$(\"input[type='month']\").MonthPicker();\n" }, { "answer_id": 32613585, "author": "Apolo", "author_id": 3484498, "author_profile": "https://Stackoverflow.com/users/3484498", "pm_score": 2, "selected": false, "text": "$(\"#myTextInput\").Monthpicker();\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751/" ]
195,794
<p>Assuming Visual C/C++ 6, I have a complex data structure of 22399 elements that looks like this:</p> <pre><code>{ { "(SAME", "AS", "U+4E18)", "HILLOCK", "OR", "MOUND"}, { "TO", "LICK;", {1, 1, 0}, "TASTE,", "A", "MAT,", "BAMBOO", "BARK"}, { "(J)", "NON-STANDARD", "FORM", "OF", "U+559C", ",", {1, 1, 0}, "LIKE,", "LOVE,", "ENJOY;", {1, 1, 4}, "JOYFUL", "THING"}, { "(AN", "ANCIENT", {1, 2, 2}, {1, 2, 3}, "U+4E94)", "FIVE"}, ... } </code></pre> <p>What's the best way to declare this? I've tried things like </p> <pre><code>char * abbrevs3[22399][] = { ... }; </code></pre> <p>and </p> <pre><code>char * abbrevs3[22399][][] = { ... }; </code></pre> <p>but the compile whinges something chronic. </p> <p><strong>EDIT</strong>: The data is a database of descriptions of certain Unihan characters. I've been exploring various ways of compacting the data. As it stands you have 22399 entries, each of which may contain a varying number of strings, or triplets of { abbrev marker, line where last seen, element of that line where last seen }. </p> <p>By the way Greg's talking, I may need to have each line contain the same number of elements, even if some of them are empty strings. Is that the case?</p> <p><strong>EDIT #2</strong>: And it occurs to me that some of the numeric values in the triplets are way outside the limits of char.</p>
[ { "answer_id": 195805, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "char * abbrevs3[][22399] = { ... };\n" }, { "answer_id": 195825, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "enum EntryType { string = 0, triple = 1 };\n\ntypedef struct {\n enum EntryType entry_type;\n union {\n char** string;\n int[3] *triple;\n }\n} Entry;\n\ntypedef struct {\n Entry *entries;\n} Abbreviation;\n\nAbbreviation *abbrevs3;\n\nabbrevs3 = parseAbbreviationData(\"path-to-abbreviations/abbrevs.xml\");\n" }, { "answer_id": 195860, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 1, "selected": false, "text": "const char * arr[][3] =\n {\n {\"bla\", \"bla\", \"bla\"},\n {\"bla\", \"bla\" }\n };\n typedef struct\n{\n const char * somestring;\n const char * someotherstring;\n const unsigned int triple[3];\n} Abbreviation;\n\nconst Abbreviation abb[] =\n {\n {\"First Thing\", \"Second String\", {1,2,3} },\n {\"Other Thing\", \"Some String\", {4,5,6} }\n };\n" }, { "answer_id": 197921, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 0, "selected": false, "text": "int" }, { "answer_id": 198411, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 3, "selected": true, "text": "{ \"(AN\", \"ANCIENT\", {1, 2, 2}, {1, 2, 3}, \"U+4E94)\", \"FIVE\"},\n { \"(AN\", \"ANCIENT\", \"FORM\", \"OF\", \"U+4E94)\", \"FIVE\"},\n const char * words[] = {\n \"hello\", \"world\", \"goodbye\", \"cruel\"\n };\n\nconst int strings[] = {\n { 0, 1 },\n { 2, 3, 1 }\n };\n" }, { "answer_id": 199700, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 1, "selected": false, "text": "\"VULGAR FRACTION ONE QUARTER\" \"A KIND OF PUNISHMENT IN HAN DYNASTY, NAME OF CHESSMEN IN CHINESE CHESS GAME(SIMPLIFIED FORM, A VARIANT U+7F75) TO CURSE; TO REVILE; TO ABUSE, TO SCOLD\"" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426/" ]
195,802
<p>I was wondering if there was any difference in the way the following code was compiled into assembly. I've heard that switch-case is more efficient than if else, but in this example I am not quite sure if that would be the case.</p> <pre><code>if(x==1){ ... }else if(x==2){ ... }else{ ... } </code></pre> <p>and</p> <pre><code>switch(x){ case 1: ... break; case 2: ... break; default: ... } </code></pre>
[ { "answer_id": 195810, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "switch if = == x if x volatile" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17162/" ]
195,809
<p>I am thinking of developing a web search engine using Erlang, Mnesia &amp; Yaws. Is it possible to make a powerful and the fastest web search engine using these software? What will it need to accomplish this and how what do I start with? </p>
[ { "answer_id": 213571, "author": "uwiger", "author_id": 6834, "author_profile": "https://Stackoverflow.com/users/6834", "pm_score": 1, "selected": false, "text": "rdbms_wsearch.erl\nrdbms_wsearch_idx.erl\nrdbms_wsearch_porter.erl\n" }, { "answer_id": 4004413, "author": "Muzaaya Joshua", "author_id": 431620, "author_profile": "https://Stackoverflow.com/users/431620", "pm_score": 5, "selected": true, "text": "inets httpc module ibrowse curl os:cmd/1 zip module mochiweb's html parser and XPATH Keywords description title Couch Base Server Riak Memcached schemaless DBMS Availability rather than Consistency" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24813/" ]
195,834
<p>When are <strong>custom Exception classes</strong> most-valuable?<br> Are there cases when they should or should not be used? What are the benefits?</p> <p><strong>Related questions:</strong></p> <ol> <li><strong><a href="https://stackoverflow.com/questions/6891/performance-considerations-for-throwing-exceptions">Performace Considerations for throwing Exceptions</a></strong></li> <li><strong><a href="https://stackoverflow.com/questions/21652/do-you-write-exceptions-for-specific-issues-or-general-exceptions">Do you write exceptions for specific issues or general exceptions?</a></strong></li> </ol>
[ { "answer_id": 196211, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "throw catch()" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19468/" ]
195,840
<p>What are the main differences between XHTML and HTML? Which one is better in your opinion, and why? Do most browsers support both?</p>
[ { "answer_id": 195850, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 0, "selected": false, "text": "<br>\n <br />\n" }, { "answer_id": 196187, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "text/html application/xhtml+xml" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24644/" ]
195,849
<p>Is there a way to programmatically find the location of the current user's Outlook .pst file(s) through an API call or registry entry?</p>
[ { "answer_id": 197358, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "RDOStores RDOSession.Stores Sub PstFiles()\n Dim f As MAPIFolder\n\n For Each f In Session.Folders\n Debug.Print f.StoreID\n Debug.Print GetPathFromStoreID(f.StoreID)\n Next f\nEnd Sub\n\nPublic Function GetPathFromStoreID(sStoreID As String) As String\n On Error Resume Next\n Dim i As Long\n Dim lPos As Long\n Dim sRes As String\n\n For i = 1 To Len(sStoreID) Step 2\n sRes = sRes & Chr(\"&h\" & Mid$(sStoreID, i, 2))\n Next\n\n sRes = Replace(sRes, Chr(0), vbNullString)\n lPos = InStr(sRes, \":\\\")\n\n If lPos Then\n GetPathFromStoreID = Right$(sRes, (Len(sRes)) - (lPos - 2))\n End If\nEnd Function\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27236/" ]
195,853
<p>What are the basic differences between a semaphore &amp; spin-lock?</p> <p>When would we use a semaphore over a spin-lock?</p>
[ { "answer_id": 17221568, "author": "Damon", "author_id": 572743, "author_profile": "https://Stackoverflow.com/users/572743", "pm_score": 8, "selected": true, "text": "sys_futex" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24813/" ]
195,872
<p>I need to have multiple forms in the same webpage, all of them POSTing to itself and then performing different actions depending on the type of form.</p> <p>What's the best way to achieve this?</p> <p>To be more specific, the page shows the details of an event, with a form to subscribe (a drop-down box) and another form for each of the subscribed persons that allows them to unsubscribe (it's just a button).</p>
[ { "answer_id": 195878, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 4, "selected": true, "text": "<input type=\"hidden\" name=\"formname\" value=\"firstForm\" /> <form action=\"mypage.php?formtype=firstForm\" ...> <input type=\"submit\" name=\"firstForm\" value=\"Submit\" />" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
195,886
<p>I've searched around a bit, but haven't found a satisfactory answer, so I'd like to hear your opinions on this.</p> <p>I have a couple of tools which I have to update and deploy to a few servers every now and then. The source is managed in a SVN repository.</p> <p>To save myself the bother of copying the binaries to the production servers by ftp or similar means (I have no means of building the projects on the servers), I'm thinking of creating an area in the repository to commit them as well. I could then simply retrieve the most current version of the executables from the svn server whenever I need them.</p> <p>Since I don't necessarily want to update/commit the binaries every time I work on the source, I would not create the folder for the binaries as a subfolder of my project. Committing the binaries would then (and should) be a separate, conscious act.</p> <pre><code>--- trunk --- project1 --- project2 --- built --- project1 --- project2 </code></pre> <p>As far as I can see, there should be no problems with this setup. What I'd really like is to then give both the source revision and the binaries a single tag, so as to be able to retrieve everything that belongs together at once.</p> <pre><code>--- tags/project1/release2/ includes files from --- trunk/project1/ revision 487 and --- built/project1/ revision 488 </code></pre> <p>Is what I'm after possible, and how would I achieve it? Should I instead be looking at some other way of solving this problem?</p>
[ { "answer_id": 195891, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 0, "selected": false, "text": "<tag id <code as usual" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2899/" ]
195,887
<p>I've seen a number of 'code metrics' related questions on SO lately, and have to wonder what the fascination is? Here are some recent examples:</p> <ul> <li><a href="https://stackoverflow.com/questions/187289/what-code-metrics-convince-you-that-provided-code-is-crappy">what code metrics convince you that provided code is crappy</a></li> <li><a href="https://stackoverflow.com/questions/184071/when-if-ever-is-number-of-lines-of-code-a-useful-metric">when if ever is number of lines of code a useful metric</a></li> <li><a href="https://stackoverflow.com/questions/195856/writing-quality-tests">writing quality tests</a></li> </ul> <p>In my mind, no metric can substitute for a code review, though:</p> <ul> <li>some metrics sometimes may indicate places that need to be reviewed, and</li> <li>radical changes in metrics over short time frames may indicate places that need to be reviewed</li> </ul> <p>But I cannot think of a single metric that by itself always indicates 'good' or 'bad' code - there are always exceptions and reasons for things that the measurements cannot see.</p> <p>Is there some magical insight to be gained from code metrics that I've overlooked? Are lazy programmers/managers looking for excuses not to read code? Are people presented with giant legacy code bases and looking for a place to start? What's going on?</p> <blockquote>Note: I have asked some of these questions on the specific threads both in answers and comments and got no replies, so I thought I should ask the community in general as perhaps I am missing something. It would be nice to run a metrics batch job and not actually have to read other people's code (or my own) ever again, I just don't think it is practical!</blockquote> <p>EDIT: I am familiar with most if not all of the metrics being discussed, I just don't see the point of them in isolation or as arbitrary standards of quality.</p>
[ { "answer_id": 3346033, "author": "RMatthews", "author_id": 75155, "author_profile": "https://Stackoverflow.com/users/75155", "pm_score": 4, "selected": false, "text": "CRAP(m) = comp(m)^2 * (1 – cov(m)/100)^3 + comp(m) Method’s Cyclomatic Complexity % of coverage required to be\n below CRAPpy threshold\n------------------------------ --------------------------------\n0 – 5 0%\n10 42%\n15 57%\n20 71%\n25 80%\n30 100%\n31+ No amount of testing will keep methods\n this complex out of CRAP territory.\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
195,919
<p>When uninstalling my application, I'd like to configure the <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">Wix</a> setup to remove all the files that were added <strong>after the original installation</strong>. It seems like the uninstaller removes only the directories and files that were originally installed from the MSI file and it leaves everything else that was added later in the application folder. In another words, I'd like to purge the directory when uninstalling. How do I do that?</p>
[ { "answer_id": 196149, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 7, "selected": true, "text": "<Directory Id=\"CommonAppDataFolder\" Name=\"CommonAppDataFolder\">\n <Directory Id=\"MyAppFolder\" Name=\"My\">\n <Component Id=\"MyAppFolder\" Guid=\"*\">\n <CreateFolder />\n <RemoveFile Id=\"PurgeAppFolder\" Name=\"*.*\" On=\"uninstall\" />\n </Component>\n </Directory>\n</Directory>\n" }, { "answer_id": 270396, "author": "Friend Of George", "author_id": 424, "author_profile": "https://Stackoverflow.com/users/424", "pm_score": 4, "selected": false, "text": "<Binary Id=\"InstallUtil\" src=\"InstallUtilLib.dll\" />\n\n<CustomAction Id=\"DIRCA_TARGETDIR\" Return=\"check\" Execute=\"firstSequence\" Property=\"TARGETDIR\" Value=\"[ProgramFilesFolder][Manufacturer]\\[ProductName]\" />\n<CustomAction Id=\"Uninstall\" BinaryKey=\"InstallUtil\" DllEntry=\"ManagedInstall\" Execute=\"deferred\" />\n<CustomAction Id=\"UninstallSetProp\" Property=\"Uninstall\" Value=\"/installtype=notransaction /action=uninstall /LogFile= /targetDir=&quot;[TARGETDIR]\\Bin&quot; &quot;[#InstallerCustomActionsDLL]&quot; &quot;[#InstallerCustomActionsDLLCONFIG]&quot;\" />\n\n<Directory Id=\"BinFolder\" Name=\"Bin\" >\n <Component Id=\"InstallerCustomActions\" Guid=\"*\">\n <File Id=\"InstallerCustomActionsDLL\" Name=\"SetupCA.dll\" LongName=\"InstallerCustomActions.dll\" src=\"InstallerCustomActions.dll\" Vital=\"yes\" KeyPath=\"yes\" DiskId=\"1\" Compressed=\"no\" />\n <File Id=\"InstallerCustomActionsDLLCONFIG\" Name=\"SetupCA.con\" LongName=\"InstallerCustomActions.dll.Config\" src=\"InstallerCustomActions.dll.Config\" Vital=\"yes\" DiskId=\"1\" />\n </Component>\n</Directory>\n\n<Feature Id=\"Complete\" Level=\"1\" ConfigurableDirectory=\"TARGETDIR\">\n <ComponentRef Id=\"InstallerCustomActions\" />\n</Feature>\n\n<InstallExecuteSequence>\n <Custom Action=\"UninstallSetProp\" After=\"MsiUnpublishAssemblies\">$InstallerCustomActions=2</Custom>\n <Custom Action=\"Uninstall\" After=\"UninstallSetProp\">$InstallerCustomActions=2</Custom>\n</InstallExecuteSequence>\n Protected Overrides Sub OnBeforeUninstall(ByVal savedState As System.Collections.IDictionary)\n MyBase.OnBeforeUninstall(savedState)\n\n Try\n Dim CommonAppData As String = Me.Context.Parameters(\"CommonAppData\")\n If CommonAppData.StartsWith(\"\\\") And Not CommonAppData.StartsWith(\"\\\\\") Then\n CommonAppData = \"\\\" + CommonAppData\n End If\n Dim targetDir As String = Me.Context.Parameters(\"targetDir\")\n If targetDir.StartsWith(\"\\\") And Not targetDir.StartsWith(\"\\\\\") Then\n targetDir = \"\\\" + targetDir\n End If\n\n DeleteFile(\"<filename.extension>\", targetDir) 'delete from bin directory\n DeleteDirectory(\"*.*\", \"<DirectoryName>\") 'delete any extra directories created by program\n Catch\n End Try\nEnd Sub\n\nPrivate Sub DeleteFile(ByVal searchPattern As String, ByVal deleteDir As String)\n Try\n For Each fileName As String In Directory.GetFiles(deleteDir, searchPattern)\n File.Delete(fileName)\n Next\n Catch\n End Try\nEnd Sub\n\nPrivate Sub DeleteDirectory(ByVal searchPattern As String, ByVal deleteDir As String)\n Try\n For Each dirName As String In Directory.GetDirectories(deleteDir, searchPattern)\n Directory.Delete(dirName)\n Next\n Catch\n End Try\nEnd Sub\n" }, { "answer_id": 2184066, "author": "tronda", "author_id": 6896, "author_profile": "https://Stackoverflow.com/users/6896", "pm_score": 3, "selected": false, "text": "<Binary Id=\"CommandPrompt\" SourceFile=\"C:\\Windows\\System32\\cmd.exe\" />\n <CustomAction Id=\"DeleteFolder\" BinaryKey=\"CommandPrompt\" \n ExeCommand='/c rmdir /S /Q \"[CommonAppDataFolder]MyAppFolder\\PurgeAppFolder\"' \n Execute=\"immediate\" Return=\"check\" />\n" }, { "answer_id": 10477561, "author": "Alexey Ivanov", "author_id": 572834, "author_profile": "https://Stackoverflow.com/users/572834", "pm_score": 5, "selected": false, "text": "RemoveFolderEx RemoveFile RemoveFile RemoveFolder" }, { "answer_id": 17513551, "author": "Pierre", "author_id": 282901, "author_profile": "https://Stackoverflow.com/users/282901", "pm_score": 4, "selected": false, "text": "<Product>\n <CustomAction Id=\"Cleanup_logfile\" Directory=\"INSTALLFOLDER\"\n ExeCommand=\"cmd /C &quot;del install.log&quot;\"\n Execute=\"deferred\" Return=\"ignore\" HideTarget=\"no\" Impersonate=\"no\" />\n\n <InstallExecuteSequence>\n <Custom Action=\"Cleanup_logfile\" Before=\"RemoveFiles\" >\n REMOVE=\"ALL\"\n </Custom>\n </InstallExecuteSequence>\n</Product>\n" }, { "answer_id": 33736356, "author": "Eli", "author_id": 2069294, "author_profile": "https://Stackoverflow.com/users/2069294", "pm_score": 3, "selected": false, "text": "<Fragment Id=\"FolderUninstall\">\n <?define RegDir=\"SYSTEM\\ControlSet001\\services\\[Manufacturer]:[ProductName]\"?>\n <?define RegValueName=\"InstallDir\"?>\n <Property Id=\"INSTALLFOLDER\">\n <RegistrySearch Root=\"HKLM\" Key=\"$(var.RegDir)\" Type=\"raw\" \n Id=\"APPLICATIONFOLDER_REGSEARCH\" Name=\"$(var.RegValueName)\" />\n </Property>\n\n <DirectoryRef Id='INSTALLFOLDER'>\n <Component Id=\"UninstallFolder\" Guid=\"*\">\n <CreateFolder Directory=\"INSTALLFOLDER\"/>\n <util:RemoveFolderEx Property=\"INSTALLFOLDER\" On=\"uninstall\"/>\n <RemoveFolder Id=\"INSTALLFOLDER\" On=\"uninstall\"/>\n <RegistryValue Root=\"HKLM\" Key=\"$(var.RegDir)\" Name=\"$(var.RegValueName)\" \n Type=\"string\" Value=\"[INSTALLFOLDER]\" KeyPath=\"yes\"/>\n </Component>\n </DirectoryRef>\n</Fragment>\n <Feature Id=\"Uninstall\">\n <ComponentRef Id=\"UninstallFolder\" Primary=\"yes\"/>\n</Feature>\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23609/" ]
195,951
<p>How can I change the class of an HTML element in response to an <code>onclick</code> or any other events using JavaScript?</p>
[ { "answer_id": 195961, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": -1, "selected": false, "text": "<input type=\"button\" onClick=\"javascript:test_byid();\" value=\"id='second'\" />\n\n<script>\nfunction test_byid()\n{\n $(\"#second\").toggleClass(\"highlight\");\n}\n</script>\n" }, { "answer_id": 195977, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": -1, "selected": false, "text": "function highlight(elm){\n elm.style.backgroundColor =\"#345\";\n elm.style.color = \"#fff\";\n}\n" }, { "answer_id": 196016, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 7, "selected": false, "text": "node.className document.getElementById('foo').className = 'bar';\n" }, { "answer_id": 196038, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 13, "selected": true, "text": "document.getElementById(\"MyElement\").classList.add('MyClass');\n\ndocument.getElementById(\"MyElement\").classList.remove('MyClass');\n\nif ( document.getElementById(\"MyElement\").classList.contains('MyClass') )\n\ndocument.getElementById(\"MyElement\").classList.toggle('MyClass');\n document.getElementById(\"Id\") this document.getElementById(\"MyElement\").className = \"MyClass\";\n document.getElementById(\"MyElement\").className += \" MyClass\";\n document.getElementById(\"MyElement\").className =\n document.getElementById(\"MyElement\").className.replace\n ( /(?:^|\\s)MyClass(?!\\S)/g , '' )\n/* Code wrapped for readability - above is all one statement */\n (?:^|\\s) # Match the start of the string or any single whitespace character\n\nMyClass # The literal text for the classname to remove\n\n(?!\\S) # Negative lookahead to verify the above is the whole classname\n # Ensures there is no non-space character following\n # (i.e. must be the end of the string or space)\n g if ( document.getElementById(\"MyElement\").className.match(/(?:^|\\s)MyClass(?!\\S)/) )\n onclick=\"this.className+=' MyClass'\" <script type=\"text/javascript\">\n function changeClass(){\n // Code examples from above\n }\n</script>\n...\n<button onclick=\"changeClass()\">My Button</button>\n <script type=\"text/javascript\">\n function changeClass(){\n // Code examples from above\n }\n\n window.onload = function(){\n document.getElementById(\"MyElement\").addEventListener( 'click', changeClass);\n }\n</script>\n...\n<button id=\"MyElement\">My Button</button>\n $ $('#MyElement').addClass('MyClass');\n\n$('#MyElement').removeClass('MyClass');\n\nif ( $('#MyElement').hasClass('MyClass') )\n $('#MyElement').toggleClass('MyClass');\n $('#MyElement').click(changeClass);\n $(':button:contains(My Button)').click(changeClass);\n" }, { "answer_id": 1870241, "author": "Eric Bailey", "author_id": 227530, "author_profile": "https://Stackoverflow.com/users/227530", "pm_score": 4, "selected": false, "text": "document.getElementById(\"MyElement\").className = document.getElementById(\"MyElement\").className.replace(/\\bMyClass\\b/','')\n document.getElementById(\"MyElement\").className = document.getElementById(\"MyElement\").className.replace('/\\bMyClass\\b/','');\n" }, { "answer_id": 6160260, "author": "Hiren Kansara", "author_id": 774111, "author_profile": "https://Stackoverflow.com/users/774111", "pm_score": 4, "selected": false, "text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If Not Page.IsPostBack Then\n lbSave.Attributes.Add(\"onmouseover\", \"this.className = 'LinkButtonStyle1'\")\n lbSave.Attributes.Add(\"onmouseout\", \"this.className = 'LinkButtonStyle'\")\n lbCancel.Attributes.Add(\"onmouseover\", \"this.className = 'LinkButtonStyle1'\")\n lbCancel.Attributes.Add(\"onmouseout\", \"this.className = 'LinkButtonStyle'\")\n End If\nEnd Sub\n" }, { "answer_id": 6160317, "author": "Andrew Orsich", "author_id": 508601, "author_profile": "https://Stackoverflow.com/users/508601", "pm_score": 7, "selected": false, "text": "function hasClass(ele, cls) {\n return ele.className.match(new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)'));\n}\n\nfunction addClass(ele, cls) {\n if (!hasClass(ele, cls))\n ele.className += \" \" + cls;\n}\n\nfunction removeClass(ele, cls) {\n if (hasClass(ele, cls)) {\n var reg = new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)');\n ele.className = ele.className.replace(reg, ' ');\n }\n}\n onclick <script type=\"text/javascript\">\n function changeClass(btn, cls) {\n if(!hasClass(btn, cls)) {\n addClass(btn, cls);\n }\n }\n</script>\n...\n<button onclick=\"changeClass(this, \"someClass\")\">My Button</button>\n" }, { "answer_id": 6960449, "author": "Tyilo", "author_id": 640584, "author_profile": "https://Stackoverflow.com/users/640584", "pm_score": 9, "selected": false, "text": "document.getElementById('id').classList.add('class');\ndocument.getElementById('id').classList.remove('class');\n document.getElementById('id').classList.toggle('class');\n" }, { "answer_id": 7487686, "author": "PseudoNinja", "author_id": 588005, "author_profile": "https://Stackoverflow.com/users/588005", "pm_score": 6, "selected": false, "text": "function hasClass(ele, cls) {\n return ele.className.match(new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)'));\n}\n\nfunction addClass(ele, cls) {\n if (!this.hasClass(ele, cls)) ele.className += \" \" + cls;\n}\n\nfunction removeClass(ele, cls) {\n if (hasClass(ele, cls)) {\n var reg = new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)');\n ele.className = ele.className.replace(reg, ' ');\n }\n}\n\nfunction replaceClass(ele, oldClass, newClass){\n if(hasClass(ele, oldClass)){\n removeClass(ele, oldClass);\n addClass(ele, newClass);\n }\n return;\n}\n\nfunction toggleClass(ele, cls1, cls2){\n if(hasClass(ele, cls1)){\n replaceClass(ele, cls1, cls2);\n }else if(hasClass(ele, cls2)){\n replaceClass(ele, cls2, cls1);\n }else{\n addClass(ele, cls1);\n }\n}\n" }, { "answer_id": 8281605, "author": "Ben Flynn", "author_id": 449161, "author_profile": "https://Stackoverflow.com/users/449161", "pm_score": 5, "selected": false, "text": "goog.dom.classes.add(element, var_args)\n\ngoog.dom.classes.addRemove(element, classesToRemove, classesToAdd)\n\ngoog.dom.classes.remove(element, var_args)\n var myElement = goog.dom.query(\"#MyElement\")[0];\n" }, { "answer_id": 8428872, "author": "Gopal Krishna Ranjan", "author_id": 1070666, "author_profile": "https://Stackoverflow.com/users/1070666", "pm_score": 5, "selected": false, "text": "function setCSS(eleID) {\n var currTabElem = document.getElementById(eleID);\n\n currTabElem.setAttribute(\"class\", \"some_class_name\");\n currTabElem.setAttribute(\"className\", \"some_class_name\");\n}\n" }, { "answer_id": 8748357, "author": "Travis J", "author_id": 1026459, "author_profile": "https://Stackoverflow.com/users/1026459", "pm_score": 6, "selected": false, "text": "<div class=\"firstClass\" onclick=\"this.className='secondClass'\">\n" }, { "answer_id": 10407953, "author": "Alex Robinson", "author_id": 972805, "author_profile": "https://Stackoverflow.com/users/972805", "pm_score": 4, "selected": false, "text": "var s = \"testing one four one two\";\nvar cls = \"one\";\nvar rg = new RegExp(\"(^|\\\\s+)\" + cls + \"(\\\\s+|$)\", 'ig');\nalert(\"[\" + s.replace(rg, ' ') + \"]\");\nvar cls = \"test\";\nvar rg = new RegExp(\"(^|\\\\s+)\" + cls + \"(\\\\s+|$)\", 'ig');\nalert(\"[\" + s.replace(rg, ' ') + \"]\");\nvar cls = \"testing\";\nvar rg = new RegExp(\"(^|\\\\s+)\" + cls + \"(\\\\s+|$)\", 'ig');\nalert(\"[\" + s.replace(rg, ' ') + \"]\");\nvar cls = \"tWo\";\nvar rg = new RegExp(\"(^|\\\\s+)\" + cls + \"(\\\\s+|$)\", 'ig');\nalert(\"[\" + s.replace(rg, ' ') + \"]\");\n" }, { "answer_id": 10458392, "author": "shingokko", "author_id": 557761, "author_profile": "https://Stackoverflow.com/users/557761", "pm_score": 4, "selected": false, "text": "jQuery(function($) {\n $(\"#some-element\").click(function() {\n $(this).toggleClass(\"clicked\");\n });\n});\n" }, { "answer_id": 12934226, "author": "alfred", "author_id": 345517, "author_profile": "https://Stackoverflow.com/users/345517", "pm_score": 4, "selected": false, "text": "function addHTMLClass(item, classname) {\n var obj = item\n if (typeof item==\"string\") {\n obj = document.getElementById(item)\n }\n obj.className += \" \" + classname\n}\n\nfunction removeHTMLClass(item, classname) {\n var obj = item\n if (typeof item==\"string\") {\n obj = document.getElementById(item)\n }\n var classes = \"\"+obj.className\n while (classes.indexOf(classname)>-1) {\n classes = classes.replace (classname, \"\")\n }\n obj.className = classes\n}\n <tr onmouseover='addHTMLClass(this,\"clsSelected\")'\nonmouseout='removeHTMLClass(this,\"clsSelected\")' >\n" }, { "answer_id": 15946168, "author": "moka", "author_id": 1312722, "author_profile": "https://Stackoverflow.com/users/1312722", "pm_score": 5, "selected": false, "text": "HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;\n\nHTMLElement.prototype.addClass = function(string) {\n if (!(string instanceof Array)) {\n string = string.split(' ');\n }\n for(var i = 0, len = string.length; i < len; ++i) {\n if (string[i] && !new RegExp('(\\\\s+|^)' + string[i] + '(\\\\s+|$)').test(this.className)) {\n this.className = this.className.trim() + ' ' + string[i];\n }\n }\n}\n\nHTMLElement.prototype.removeClass = function(string) {\n if (!(string instanceof Array)) {\n string = string.split(' ');\n }\n for(var i = 0, len = string.length; i < len; ++i) {\n this.className = this.className.replace(new RegExp('(\\\\s+|^)' + string[i] + '(\\\\s+|$)'), ' ').trim();\n }\n}\n\nHTMLElement.prototype.toggleClass = function(string) {\n if (string) {\n if (new RegExp('(\\\\s+|^)' + string + '(\\\\s+|$)').test(this.className)) {\n this.className = this.className.replace(new RegExp('(\\\\s+|^)' + string + '(\\\\s+|$)'), ' ').trim();\n } else {\n this.className = this.className.trim() + ' ' + string;\n }\n }\n}\n\nHTMLElement.prototype.hasClass = function(string) {\n return string && new RegExp('(\\\\s+|^)' + string + '(\\\\s+|$)').test(this.className);\n}\n document.getElementById('yourElementId').onclick = function() {\n this.toggleClass('active');\n}\n" }, { "answer_id": 21202309, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 3, "selected": false, "text": "indexOf function addClass(el, cn) {\n var c0 = (\" \" + el.className + \" \").replace(/\\s+/g, \" \"),\n c1 = (\" \" + cn + \" \").replace(/\\s+/g, \" \");\n if (c0.indexOf(c1) < 0) {\n el.className = (c0 + c1).replace(/\\s+/g, \" \").replace(/^ | $/g, \"\");\n }\n}\n\nfunction delClass(el, cn) {\n var c0 = (\" \" + el.className + \" \").replace(/\\s+/g, \" \"),\n c1 = (\" \" + cn + \" \").replace(/\\s+/g, \" \");\n if (c0.indexOf(c1) >= 0) {\n el.className = c0.replace(c1, \" \").replace(/\\s+/g, \" \").replace(/^ | $/g, \"\");\n }\n}\n" }, { "answer_id": 22890596, "author": "uttamcafedeweb", "author_id": 3078123, "author_profile": "https://Stackoverflow.com/users/3078123", "pm_score": -1, "selected": false, "text": "$(\".class1\").click(function(argument) {\n $(\".parentclass\").removeClass(\"classtoremove\");\n setTimeout(function (argument) {\n $(\".parentclass\").addClass(\"classtoadd\");\n }, 100);\n});\n" }, { "answer_id": 29158446, "author": "StackSlave", "author_id": 2438423, "author_profile": "https://Stackoverflow.com/users/2438423", "pm_score": 2, "selected": false, "text": "function inArray(val, ary){\n for(var i=0,l=ary.length; i<l; i++){\n if(ary[i] === val){\n return true;\n }\n }\n return false;\n}\nfunction removeClassName(classNameS, fromElement){\n var x = classNameS.split(/\\s/), s = fromElement.className.split(/\\s/), r = [];\n for(var i=0,l=s.length; i<l; i++){\n if(!iA(s[i], x))r.push(s[i]);\n }\n fromElement.className = r.join(' ');\n}\nfunction addClassName(classNameS, toElement){\n var s = toElement.className.split(/\\s/);\n s.push(c); toElement.className = s.join(' ');\n}\n" }, { "answer_id": 33384795, "author": "kofifus", "author_id": 460084, "author_profile": "https://Stackoverflow.com/users/460084", "pm_score": 4, "selected": false, "text": "// If newState is provided add/remove theClass accordingly, otherwise toggle theClass\nfunction toggleClass(elem, theClass, newState) {\n var matchRegExp = new RegExp('(?:^|\\\\s)' + theClass + '(?!\\\\S)', 'g');\n var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));\n\n elem.className=elem.className.replace(matchRegExp, ''); // clear all\n if (add) elem.className += ' ' + theClass;\n}\n" }, { "answer_id": 33528818, "author": "Eugene Tiurin", "author_id": 2676500, "author_profile": "https://Stackoverflow.com/users/2676500", "pm_score": 4, "selected": false, "text": "attributes function getClassNode(element) {\n for (var i = element.attributes.length; i--;)\n if (element.attributes[i].nodeName === 'class')\n return element.attributes[i];\n}\n\nfunction removeClass(classNode, className) {\n var index, classList = classNode.value.split(' ');\n if ((index = classList.indexOf(className)) > -1) {\n classList.splice(index, 1);\n classNode.value = classList.join(' ');\n }\n}\n\nfunction hasClass(classNode, className) {\n return classNode.value.indexOf(className) > -1;\n}\n\nfunction addClass(classNode, className) {\n if (!hasClass(classNode, className))\n classNode.value += ' ' + className;\n}\n\ndocument.getElementById('message').addEventListener('click', function() {\n var classNode = getClassNode(this);\n var className = hasClass(classNode, 'red') && 'blue' || 'red';\n\n removeClass(classNode, 'red');\n removeClass(classNode, 'blue');\n\n addClass(classNode, className);\n}) .red {\n color: red;\n}\n.red:before {\n content: 'I am red! ';\n}\n.red:after {\n content: ' again';\n}\n.blue {\n color: blue;\n}\n.blue:before {\n content: 'I am blue! '\n} <span id=\"message\" class=\"\">Click me</span>" }, { "answer_id": 43533114, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 2, "selected": false, "text": "myElement.classList=\"new-class\" classList.add, .remove var doc = document;\nvar divOne = doc.getElementById(\"one\");\nvar goButton = doc.getElementById(\"go\");\n\ngoButton.addEventListener(\"click\", function() {\n divOne.classList=\"blue\";\n}); div{\n min-height: 48px;\n min-width: 48px;\n}\n.bordered{\n border: 1px solid black;\n}\n.green{\n background: green;\n}\n.blue{\n background: blue;\n} <button id=\"go\">Change Class</button>\n\n<div id=\"one\" class=\"bordered green\">\n\n</div>" }, { "answer_id": 44243730, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 2, "selected": false, "text": "// Simple JavaScript utilities for class management in ES6\nvar classUtil = {\n\n addClass: (id, cl) => {\n document.getElementById(id).classList.add(cl);\n },\n\n removeClass: (id, cl) => {\n document.getElementById(id).classList.remove(cl);\n },\n\n hasClass: (id, cl) => {\n return document.getElementById(id).classList.contains(cl);\n },\n\n toggleClass: (id, cl) => {\n document.getElementById(id).classList.toggle(cl);\n }\n\n}\n classUtil.addClass('myId', 'myClass');\nclassUtil.removeClass('myId', 'myClass');\nclassUtil.hasClass('myId', 'myClass');\nclassUtil.toggleClass('myId', 'myClass');\n" }, { "answer_id": 52440576, "author": "Willem van der Veen", "author_id": 8059459, "author_profile": "https://Stackoverflow.com/users/8059459", "pm_score": 2, "selected": false, "text": "classList classList const el = document.getElementById(\"main\");\nconsole.log(el.classList); <div class=\"content wrapper animated\" id=\"main\"></div> const el = document.getElementById('container');\n\nfunction addClass () {\n el.classList.add('newclass');\n}\n\n\nfunction replaceClass () {\n el.classList.replace('foo', 'newFoo');\n}\n\n\nfunction removeClass () {\n el.classList.remove('bar');\n} button{\n margin: 20px;\n}\n\n.foo{\n color: red;\n}\n\n.newFoo {\n color: blue;\n}\n\n.bar{\n background-color: powderblue;\n}\n\n.newclass{\n border: 2px solid green;\n} <div class=\"foo bar\" id=\"container\">\n \"Sed ut perspiciatis unde omnis\n iste natus error sit voluptatem accusantium doloremque laudantium,\n totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et\n quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam\n voluptatem quia voluptas\n </div>\n\n<button onclick=\"addClass()\">AddClass</button>\n\n<button onclick=\"replaceClass()\">ReplaceClass</button>\n\n<button onclick=\"removeClass()\">removeClass</button>" }, { "answer_id": 54555429, "author": "Danish Khan", "author_id": 4619794, "author_profile": "https://Stackoverflow.com/users/4619794", "pm_score": 2, "selected": false, "text": "const tabs=document.querySelectorAll('.menu li');\n\nfor(let tab of tabs){\n\n tab.onclick = function(){\n\n let activetab = document.querySelectorAll('li.active');\n\n activetab[0].classList.remove('active')\n\n tab.classList.add('active');\n }\n\n} body {\n padding: 20px;\n font-family: sans-serif;\n}\n\nul {\n margin: 20px 0;\n list-style: none;\n}\n\nli {\n background: #dfdfdf;\n padding: 10px;\n margin: 6px 0;\n cursor: pointer;\n}\n\nli.active {\n background: #2794c7;\n font-weight: bold;\n color: #ffffff;\n} <i>Please click an item:</i>\n\n<ul class=\"menu\">\n <li class=\"active\"><span>Three</span></li>\n <li><span>Two</span></li>\n <li><span>One</span></li>\n</ul>" }, { "answer_id": 54824928, "author": "tfont", "author_id": 1804013, "author_profile": "https://Stackoverflow.com/users/1804013", "pm_score": 2, "selected": false, "text": "document.getElementById('id').className = 'class'\n document.getElementById('id').classList.add('class');\ndocument.getElementById('id').classList.remove('class');\n getElementById() getElementsByClassName() querySelector() querySelectorAll()" }, { "answer_id": 55674450, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 3, "selected": false, "text": "element.className='second'\n function change(box) { box.className='second' } .first { width: 70px; height: 70px; background: #ff0 }\n.second { width: 150px; height: 150px; background: #f00; transition: 1s } <div onclick=\"change(this)\" class=\"first\">Click me</div>" }, { "answer_id": 57615210, "author": "Brian Nezhad", "author_id": 2556515, "author_profile": "https://Stackoverflow.com/users/2556515", "pm_score": 3, "selected": false, "text": "classList style classList style classList style classList add remove toggle contain add remove margin-top // Get the Element\nconst el = document.querySelector('#element');\n\n// Add CSS property \nel.style.margintop = \"0px\"\nel.style.margintop = \"25px\" // This would add a 25px to the top of the element.\n <div class=\"class-a class-b\"> class-a class-b remove add classList class-b // Get the Element\nconst el = document.querySelector('#element');\n\n// Remove class-b style from the element\nel.classList.remove(\"class-b\")\n\n class-c // Get the Element\nconst el = document.querySelector('#element');\n\n// Add class-b style from the element\nel.classList.add(\"class-c\")\n\n" }, { "answer_id": 57791625, "author": "donatso", "author_id": 7733202, "author_profile": "https://Stackoverflow.com/users/7733202", "pm_score": 2, "selected": false, "text": "function classed(el, class_name, add_class) {\n const re = new RegExp(\"(?:^|\\\\s)\" + class_name + \"(?!\\\\S)\", \"g\");\n if (add_class && !el.className.match(re)) el.className += \" \" + class_name\n else if (!add_class) el.className = el.className.replace(re, '');\n}\n classed(document.getElementById(\"denis\"), \"active\", true)\n classed(document.getElementById(\"denis\"), \"active\", false)\n" }, { "answer_id": 60774130, "author": "Jai Prakash", "author_id": 12257880, "author_profile": "https://Stackoverflow.com/users/12257880", "pm_score": 2, "selected": false, "text": "<!DOCTYPE html>\n<html>\n<head>\n<title>How can I change the class of an HTML element in JavaScript?</title>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\n</head>\n<body>\n<h1 align=\"center\"><i class=\"fa fa-home\" id=\"icon\"></i></h1><br />\n\n<center><button id=\"change-class\">Change Class</button></center>\n\n<script>\nvar change_class = document.getElementById(\"change-class\");\nchange_class.onclick = function()\n{\n var icon=document.getElementById(\"icon\");\n icon.className = \"fa fa-gear\";\n}\n</script>\n</body>\n</html>\n" }, { "answer_id": 61582806, "author": "timbo", "author_id": 127660, "author_profile": "https://Stackoverflow.com/users/127660", "pm_score": 3, "selected": false, "text": "document.getElementById('id').classList.replace('span1', 'span2') classList" }, { "answer_id": 69060627, "author": "Satish Chandra Gupta", "author_id": 9445290, "author_profile": "https://Stackoverflow.com/users/9445290", "pm_score": 5, "selected": false, "text": "classList.add() function addClass() {\n let element = document.getElementById('id1');\n\n // adding class\n element.classList.add('beautify');\n}\n add() function addClass() {\n let element = document.getElementById('id1');\n\n // adding multiple class\n element.classList.add('class1', 'class2', 'class3');\n}\n className className function addClass() {\n let element = document.getElementById('id1');\n\n // adding multiple class\n element.className = 'beautify';\n}\n += function addClass() {\n let element = document.getElementById('id1');\n\n // adding single multiple class\n element.className += ' beautify';\n // adding multiple classes\n element.className += ' class1 class2 class3';\n}\n classList.remove() function removeClass() {\n let element = document.getElementById('id1');\n\n // removing class\n element.classList.remove('beautify');\n}\n function removeClass() {\n let element = document.getElementById('id1');\n\n // removing class\n element.classList.remove('class1', 'class2', 'class3');\n}\n className className function removeClass() {\n let element = document.getElementById('id1');\n\n // removing class\n element.className = '';\n}\n className className function removeClass() {\n let element = document.getElementById('id1');\n\n // removing class\n element.className = element.className.replace('class1', '');\n}\n classList.contains() true function checkClass() {\n let element = document.getElementById('id1');\n\n // checking class\n if(element.classList.contains('beautify') {\n alert('Yes! class exists');\n }\n}\n classList.toggle() function toggleClass() {\n let element = document.getElementById('id1');\n\n // toggle class\n element.classList.toggle('beautify');\n}\n" }, { "answer_id": 69131856, "author": "gomn", "author_id": 7347433, "author_profile": "https://Stackoverflow.com/users/7347433", "pm_score": 3, "selected": false, "text": "classList var elem = document.getElementById('some-id');\n\n// don't forget the extra space before the class name\nvar classList = elem.getAttribute('class') + ' other-class-name';\n\nelem.setAttribute('class', classList);\n" }, { "answer_id": 74653402, "author": "fatima hassan", "author_id": 8891459, "author_profile": "https://Stackoverflow.com/users/8891459", "pm_score": 0, "selected": false, "text": " document.getElementById(\"MyTest\").classList.add('TestClass');\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4998/" ]
195,975
<p>For example, how to avoid writing the 'func_name' twice?</p> <pre><code>#ifndef TEST_FUN # define TEST_FUN func_name # define TEST_FUN_NAME "func_name" #endif </code></pre> <p>I'd like to follow the <a href="http://en.wikipedia.org/wiki/Single_Point_of_Truth" rel="noreferrer">Single Point of Truth</a> rule.</p> <p>Version of C preprocessor:</p> <pre><code>$ cpp --version cpp (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14) </code></pre>
[ { "answer_id": 195980, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": -1, "selected": false, "text": "#define TEST_FUN_NAME #FUNC_NAME" }, { "answer_id": 195999, "author": "Jason Weathered", "author_id": 3736, "author_profile": "https://Stackoverflow.com/users/3736", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\n#define QUOTEME(x) #x\n\n#ifndef TEST_FUN\n# define TEST_FUN func_name\n# define TEST_FUN_NAME QUOTEME(TEST_FUN)\n#endif\n\nint main(void)\n{\n puts(TEST_FUN_NAME);\n return 0;\n}\n" }, { "answer_id": 196018, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 7, "selected": true, "text": "#define TEST_FUNC test_func\n#define TEST_FUNC_NAME #TEST_FUNC\n\n#include <stdio.h>\nint main(void)\n{\n puts(TEST_FUNC_NAME);\n return(0);\n}\n #define FUNCTION_NAME(name) #name\n#define TEST_FUNC_NAME FUNCTION_NAME(test_func)\n\n#include <stdio.h>\n\nint main(void)\n{\n puts(TEST_FUNC_NAME);\n return(0);\n}\n #define STR_VALUE(arg) #arg\n#define FUNCTION_NAME(name) STR_VALUE(name)\n\n#define TEST_FUNC test_func\n#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)\n\n#include <stdio.h>\n\nstatic void TEST_FUNC(void)\n{\n printf(\"In function %s\\n\", TEST_FUNC_NAME);\n}\n\nint main(void)\n{\n puts(TEST_FUNC_NAME);\n TEST_FUNC();\n return(0);\n}\n" }, { "answer_id": 196093, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "/** compile-time dispatch \n\n $ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub\n*/\n#include <stdio.h>\n\n#define QUOTE(name) #name\n#define STR(macro) QUOTE(macro)\n\n#ifndef TEST_FUN\n# define TEST_FUN some_func\n#endif\n\n#define TEST_FUN_NAME STR(TEST_FUN)\n\nvoid some_func(void)\n{\n printf(\"some_func() called\\n\");\n}\n\nvoid another_func(void)\n{\n printf(\"do something else\\n\");\n}\n\nint main(void)\n{\n TEST_FUN();\n printf(\"TEST_FUN_NAME=%s\\n\", TEST_FUN_NAME);\n return 0;\n}\n $ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub\ndo something else\nTEST_FUN_NAME=another_func\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
195,991
<p>For explanation imagine a simple address. Written in a HTML paragraph with line breaks it would like this:</p> <pre><code>Street: Example Street 1 City: Vienna Zip Code: 1010 Country: Austria </code></pre> <p>Most of the time that's completely okay, but sometimes I have to achieve the following output:</p> <pre><code>Street: Example Street 1 City: Vienna Zip Code: 1010 Country: Austria </code></pre> <p>My thoughts so far:</p> <ol> <li>Should be valid XHTML and work or degrade gracefully in all major browsers</li> <li>Using tags in a semantically correct way is strongly preferred</li> <li>Because of point two: I hope there's a better solution than tables</li> <li>The problem is not limited to addresses - would be useful in other situation too</li> </ol> <p>How do you achieve this output (using HTML and/or CSS)?</p>
[ { "answer_id": 196007, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": false, "text": "<th> <td> <caption> <dl> <th> <td> <th> <dl> <address>" }, { "answer_id": 196030, "author": "Eevee", "author_id": 17875, "author_profile": "https://Stackoverflow.com/users/17875", "pm_score": 4, "selected": true, "text": "dt :after" }, { "answer_id": 196067, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": -1, "selected": false, "text": "<div class=DetailsRow>\n <div class=DetailsLabel>Street</div>\n <div class=DetailsContent>123 Main Street</div>\n</div>\n<div class=DetailsRow>\n <div class=DetailsLabel>City</div>\n <div class=DetailsContent>Vienna</div>\n</div>\n ...etc\n div.DetailsRow\n{\nclear:both;\n}\n\ndiv.DetailsLabel\n{\nfloat:left;\nwidth:100px;\ncolor:gray;\n}\n\ndiv.DetailsContent\n{\nfloat:left;\nwidth:400px;\n}\n" }, { "answer_id": 196133, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "dl dt dd <dl>\n <dt>Street</dt>\n <dd>Example Street 1</dd>\n <dt>City</dt>\n <dd>Vienna</dd>\n <dt>Zip Code</dt>\n <dd>1010</dd>\n <dt>Country</dt>\n <dd>Austria</dd>\n</dl>\n dt {\n width: 150px;\n float: left;\n clear: left\n}\ndd {\n float: left;\n}\n dd dt inline-block dt float left-margin 150px dd" }, { "answer_id": 198704, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 0, "selected": false, "text": "<p class=\"details\">\n <span class=\"label\">Street:</span>\n Some Street or other.\n <br />\n\n <span class=\"label\">City:</span>\n A City.\n <br />\n</p>\n p.details {\n padding-left: 200px;\n}\n\np.details span.label {\n float: left;\n clear: left;\n width: 200px;\n margin-left: -200px;\n}\n <label> <form>" }, { "answer_id": 3335348, "author": "panzi", "author_id": 277767, "author_profile": "https://Stackoverflow.com/users/277767", "pm_score": -1, "selected": false, "text": "<html>\n<head>\n<title>abusing divs</title>\n<style type=\"text/css\">\ndiv.details {\n display: table;\n}\ndiv.details > div {\n display: table-row;\n}\ndiv.details > div > div {\n display: table-cell;\n padding-left: 0.25em;\n padding-right: 0.25em;\n}\n</style>\n</head>\n<body>\n<div class=\"details\">\n <div>\n <div>Street</div>\n <div>123 Main Street</div>\n </div>\n <div>\n <div>City</div>\n <div>Vienna</div>\n </div>\n <div>\n <div>This is a very very loooong label</div>\n <div>...</div>\n </div>\n</div>\n</body>\n</html>\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/195991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20467/" ]
196,017
<p>I'd like to generate unique random numbers between 0 and 1000 that never repeat (i.e. 6 doesn't show up twice), but that doesn't resort to something like an O(N) search of previous values to do it. Is this possible?</p>
[ { "answer_id": 196065, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 9, "selected": true, "text": "+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|\n+--+--+--+--+--+--+--+--+--+--+--+\n ^\n max \n max = 10, r = 3\n +--------------------+\n v v\n+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 1| 2|10| 4| 5| 6| 7| 8| 9| 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n\nmax = 9, r = 7\n +-----+\n v v\n+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 1| 2|10| 4| 5| 6| 9| 8| 7: 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n\nmax = 8, r = 1\n +--------------------+\n v v\n+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 8| 2|10| 4| 5| 6| 9| 1: 7| 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n\nmax = 7, r = 5\n +-----+\n v v\n+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 8| 2|10| 4| 9| 6| 5: 1| 7| 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n\n...\n +--+--+--+--+--+--+--+--+--+--+--+\n| 4|10| 8| 6| 2| 0| 9| 5| 1| 7| 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n" }, { "answer_id": 196164, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 5, "selected": false, "text": "m" }, { "answer_id": 3094476, "author": "sellibitze", "author_id": 172531, "author_profile": "https://Stackoverflow.com/users/172531", "pm_score": 3, "selected": false, "text": "unsigned randperm(string key, unsigned bits, unsigned index) {\n unsigned half1 = bits / 2;\n unsigned half2 = (bits+1) / 2;\n unsigned mask1 = (1 << half1) - 1;\n unsigned mask2 = (1 << half2) - 1;\n for (int round=0; round<5; ++round) {\n unsigned temp = (index >> half1);\n temp = (temp << 4) + round;\n index ^= hash( key + \"/\" + int2str(temp) ) & mask1;\n index = ((index & mask2) << half1) | ((index >> half2) & mask1);\n }\n return index;\n}\n hash randperm index" }, { "answer_id": 3568781, "author": "firedrawndagger", "author_id": 306528, "author_profile": "https://Stackoverflow.com/users/306528", "pm_score": 2, "selected": false, "text": "// Initialize variables\nRandom RandomClass = new Random();\nint RandArrayNum;\nint MaxNumber = 10;\nint LastNumInArray;\nint PickedNumInArray;\nint[] OrderedArray = new int[MaxNumber]; // Ordered Array - set\nint[] ShuffledArray = new int[MaxNumber]; // Shuffled Array - not set\n\n// Populate the Ordered Array\nfor (int i = 0; i < MaxNumber; i++) \n{\n OrderedArray[i] = i;\n listBox1.Items.Add(OrderedArray[i]);\n}\n\n// Execute the Shuffle \nfor (int i = MaxNumber - 1; i > 0; i--)\n{\n RandArrayNum = RandomClass.Next(i + 1); // Save random #\n ShuffledArray[i] = OrderedArray[RandArrayNum]; // Populting the array in reverse\n LastNumInArray = OrderedArray[i]; // Save Last Number in Test array\n PickedNumInArray = OrderedArray[RandArrayNum]; // Save Picked Random #\n OrderedArray[i] = PickedNumInArray; // The number is now moved to the back end\n OrderedArray[RandArrayNum] = LastNumInArray; // The picked number is moved into position\n}\n\nfor (int i = 0; i < MaxNumber; i++) \n{\n listBox2.Items.Add(ShuffledArray[i]);\n}\n" }, { "answer_id": 8931218, "author": "salva", "author_id": 124951, "author_profile": "https://Stackoverflow.com/users/124951", "pm_score": 2, "selected": false, "text": "#!/usr/bin/perl\n\n($top, $n) = @ARGV; # generate $n integer numbers in [0, $top)\n\n$last = -1;\nfor $i (0 .. $n-1) {\n $range = $top - $n + $i - $last;\n $r = 1 - rand(1.0)**(1 / ($n - $i));\n $last += int($r * $range + 1);\n print \"$last ($r)\\n\";\n}\n" }, { "answer_id": 10726753, "author": "Erez Robinson", "author_id": 1413476, "author_profile": "https://Stackoverflow.com/users/1413476", "pm_score": 2, "selected": false, "text": "public static int[] randN(int n, int min, int max)\n{\n if (max <= min)\n throw new ArgumentException(\"Max need to be greater than Min\");\n if (max - min < n)\n throw new ArgumentException(\"Range needs to be longer than N\");\n\n var r = new Random();\n\n HashSet<int> set = new HashSet<int>();\n\n while (set.Count < n)\n {\n var i = r.Next(max - min) + min;\n if (!set.Contains(i))\n set.Add(i);\n }\n\n return set.ToArray();\n}\n" }, { "answer_id": 16097246, "author": "Craig McQueen", "author_id": 60075, "author_profile": "https://Stackoverflow.com/users/60075", "pm_score": 5, "selected": false, "text": "000 733\n001 374\n002 882\n003 684\n004 593\n005 578\n006 233\n007 811\n008 072\n009 337\n010 119\n011 103\n012 797\n013 257\n014 932\n015 433\n... ...\n" }, { "answer_id": 28653834, "author": "Myron Denson", "author_id": 4589963, "author_profile": "https://Stackoverflow.com/users/4589963", "pm_score": 2, "selected": false, "text": " IDENTIFICATION DIVISION.\n PROGRAM-ID. RANDGEN as \"ConsoleApplication2.RANDGEN\".\n AUTHOR. Myron D Denson.\n DATE-COMPILED.\n * ************************************************************** \n * SUBROUTINE TO GENERATE RANDOM NUMBERS THAT ARE GREATER THAN\n * ZERO AND LESS OR EQUAL TO THE RANDOM NUMBERS NEEDED WITH NO\n * DUPLICATIONS. (CALL \"RANDGEN\" USING RANDGEN-AREA.)\n * \n * CALLING PROGRAM MUST HAVE A COMPARABLE LINKAGE SECTION\n * AND SET 3 VARIABLES PRIOR TO THE FIRST CALL IN RANDGEN-AREA \n *\n * FORMULA CYCLES THROUGH EVERY NUMBER OF 2X2 ONLY ONCE. \n * RANDOM-NUMBERS FROM 1 TO RANDOM-NUMBERS-NEEDED ARE CREATED \n * AND PASSED BACK TO YOU.\n *\n * RULES TO USE RANDGEN:\n *\n * RANDOM-NUMBERS-NEEDED > ZERO \n * \n * COUNT-OF-ACCESSES MUST = ZERO FIRST TIME CALLED.\n * \n * RANDOM-NUMBER = ZERO, WILL BUILD A SEED FOR YOU\n * WHEN COUNT-OF-ACCESSES IS ALSO = 0 \n * \n * RANDOM-NUMBER NOT = ZERO, WILL BE NEXT SEED FOR RANDGEN\n * (RANDOM-NUMBER MUST BE <= RANDOM-NUMBERS-NEEDED) \n * \n * YOU CAN PASS RANDGEN YOUR OWN RANDOM-NUMBER SEED\n * THE FIRST TIME YOU USE RANDGEN.\n * \n * BY PLACING A NUMBER IN RANDOM-NUMBER FIELD\n * THAT FOLLOWES THESE SIMPLE RULES:\n * IF COUNT-OF-ACCESSES = ZERO AND \n * RANDOM-NUMBER > ZERO AND \n * RANDOM-NUMBER <= RANDOM-NUMBERS-NEEDED\n * \n * YOU CAN LET RANDGEN BUILD A SEED FOR YOU\n * \n * THAT FOLLOWES THESE SIMPLE RULES:\n * IF COUNT-OF-ACCESSES = ZERO AND \n * RANDOM-NUMBER = ZERO AND \n * RANDOM-NUMBER-NEEDED > ZERO \n * \n * TO INSURING A DIFFERENT PATTERN OF RANDOM NUMBERS\n * A LOW-RANGE AND HIGH-RANGE IS USED TO BUILD\n * RANDOM NUMBERS.\n * COMPUTE LOW-RANGE =\n * ((SECONDS * HOURS * MINUTES * MS) / 3). \n * A HIGH-RANGE = RANDOM-NUMBERS-NEEDED + LOW-RANGE\n * AFTER RANDOM-NUMBER-BUILT IS CREATED \n * AND IS BETWEEN LOW AND HIGH RANGE\n * RANDUM-NUMBER = RANDOM-NUMBER-BUILT - LOW-RANGE\n * \n * ************************************************************** \n ENVIRONMENT DIVISION.\n INPUT-OUTPUT SECTION.\n FILE-CONTROL.\n DATA DIVISION.\n FILE SECTION.\n WORKING-STORAGE SECTION.\n 01 WORK-AREA.\n 05 X2-POWER PIC 9 VALUE 2. \n 05 2X2 PIC 9(12) VALUE 2 COMP-3.\n 05 RANDOM-NUMBER-BUILT PIC 9(12) COMP.\n 05 FIRST-PART PIC 9(12) COMP.\n 05 WORKING-NUMBER PIC 9(12) COMP.\n 05 LOW-RANGE PIC 9(12) VALUE ZERO.\n 05 HIGH-RANGE PIC 9(12) VALUE ZERO.\n 05 YOU-PROVIDE-SEED PIC X VALUE SPACE.\n 05 RUN-AGAIN PIC X VALUE SPACE.\n 05 PAUSE-FOR-A-SECOND PIC X VALUE SPACE. \n 01 SEED-TIME.\n 05 HOURS PIC 99.\n 05 MINUTES PIC 99.\n 05 SECONDS PIC 99.\n 05 MS PIC 99. \n *\n * LINKAGE SECTION.\n * Not used during testing \n 01 RANDGEN-AREA.\n 05 COUNT-OF-ACCESSES PIC 9(12) VALUE ZERO.\n 05 RANDOM-NUMBERS-NEEDED PIC 9(12) VALUE ZERO.\n 05 RANDOM-NUMBER PIC 9(12) VALUE ZERO.\n 05 RANDOM-MSG PIC X(60) VALUE SPACE.\n * \n * PROCEDURE DIVISION USING RANDGEN-AREA.\n * Not used during testing \n * \n PROCEDURE DIVISION.\n 100-RANDGEN-EDIT-HOUSEKEEPING.\n MOVE SPACE TO RANDOM-MSG. \n IF RANDOM-NUMBERS-NEEDED = ZERO\n DISPLAY 'RANDOM-NUMBERS-NEEDED ' NO ADVANCING\n ACCEPT RANDOM-NUMBERS-NEEDED.\n IF RANDOM-NUMBERS-NEEDED NOT NUMERIC \n MOVE 'RANDOM-NUMBERS-NEEDED NOT NUMERIC' TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n IF RANDOM-NUMBERS-NEEDED = ZERO\n MOVE 'RANDOM-NUMBERS-NEEDED = ZERO' TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n IF COUNT-OF-ACCESSES NOT NUMERIC\n MOVE 'COUNT-OF-ACCESSES NOT NUMERIC' TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n IF COUNT-OF-ACCESSES GREATER THAN RANDOM-NUMBERS-NEEDED\n MOVE 'COUNT-OF-ACCESSES > THAT RANDOM-NUMBERS-NEEDED'\n TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n IF YOU-PROVIDE-SEED = SPACE AND RANDOM-NUMBER = ZERO\n DISPLAY 'DO YOU WANT TO PROVIDE SEED Y OR N: '\n NO ADVANCING\n ACCEPT YOU-PROVIDE-SEED. \n IF RANDOM-NUMBER = ZERO AND\n (YOU-PROVIDE-SEED = 'Y' OR 'y')\n DISPLAY 'ENTER SEED ' NO ADVANCING\n ACCEPT RANDOM-NUMBER. \n IF RANDOM-NUMBER NOT NUMERIC\n MOVE 'RANDOM-NUMBER NOT NUMERIC' TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n 200-RANDGEN-DATA-HOUSEKEEPING. \n MOVE FUNCTION CURRENT-DATE (9:8) TO SEED-TIME.\n IF COUNT-OF-ACCESSES = ZERO\n COMPUTE LOW-RANGE =\n ((SECONDS * HOURS * MINUTES * MS) / 3).\n COMPUTE RANDOM-NUMBER-BUILT = RANDOM-NUMBER + LOW-RANGE. \n COMPUTE HIGH-RANGE = RANDOM-NUMBERS-NEEDED + LOW-RANGE.\n MOVE X2-POWER TO 2X2. \n 300-SET-2X2-DIVISOR.\n IF 2X2 < (HIGH-RANGE + 1) \n COMPUTE 2X2 = 2X2 * X2-POWER\n GO TO 300-SET-2X2-DIVISOR. \n * ********************************************************* \n * IF FIRST TIME THROUGH AND YOU WANT TO BUILD A SEED. *\n * ********************************************************* \n IF COUNT-OF-ACCESSES = ZERO AND RANDOM-NUMBER = ZERO\n COMPUTE RANDOM-NUMBER-BUILT =\n ((SECONDS * HOURS * MINUTES * MS) + HIGH-RANGE).\n IF COUNT-OF-ACCESSES = ZERO \n DISPLAY 'SEED TIME ' SEED-TIME \n ' RANDOM-NUMBER-BUILT ' RANDOM-NUMBER-BUILT \n ' LOW-RANGE ' LOW-RANGE. \n * ********************************************* \n * END OF BUILDING A SEED IF YOU WANTED TO * \n * ********************************************* \n * ***************************************************\n * THIS PROCESS IS WHERE THE RANDOM-NUMBER IS BUILT * \n * *************************************************** \n 400-RANDGEN-FORMULA.\n COMPUTE FIRST-PART = (5 * RANDOM-NUMBER-BUILT) + 7.\n DIVIDE FIRST-PART BY 2X2 GIVING WORKING-NUMBER \n REMAINDER RANDOM-NUMBER-BUILT. \n IF RANDOM-NUMBER-BUILT > LOW-RANGE AND\n RANDOM-NUMBER-BUILT < (HIGH-RANGE + 1)\n GO TO 600-RANDGEN-CLEANUP.\n GO TO 400-RANDGEN-FORMULA.\n * ********************************************* \n * GOOD RANDOM NUMBER HAS BEEN BUILT * \n * *********************************************\n 600-RANDGEN-CLEANUP.\n ADD 1 TO COUNT-OF-ACCESSES.\n COMPUTE RANDOM-NUMBER = \n RANDOM-NUMBER-BUILT - LOW-RANGE. \n * *******************************************************\n * THE NEXT 3 LINE OF CODE ARE FOR TESTING ON CONSOLE * \n * *******************************************************\n DISPLAY RANDOM-NUMBER.\n IF COUNT-OF-ACCESSES < RANDOM-NUMBERS-NEEDED\n GO TO 100-RANDGEN-EDIT-HOUSEKEEPING. \n 900-EXIT-RANDGEN.\n IF RANDOM-MSG NOT = SPACE\n DISPLAY 'RANDOM-MSG: ' RANDOM-MSG.\n MOVE ZERO TO COUNT-OF-ACCESSES RANDOM-NUMBERS-NEEDED RANDOM-NUMBER. \n MOVE SPACE TO YOU-PROVIDE-SEED RUN-AGAIN.\n DISPLAY 'RUN AGAIN Y OR N '\n NO ADVANCING.\n ACCEPT RUN-AGAIN.\n IF (RUN-AGAIN = 'Y' OR 'y')\n GO TO 100-RANDGEN-EDIT-HOUSEKEEPING.\n ACCEPT PAUSE-FOR-A-SECOND.\n GOBACK.\n" }, { "answer_id": 30587391, "author": "sh1", "author_id": 2417578, "author_profile": "https://Stackoverflow.com/users/2417578", "pm_score": 1, "selected": false, "text": "int nrrand(void) {\n static int s = 1;\n static int start = -1;\n do {\n s = (s * 1103515245 + 12345) & 1023;\n } while (s >= 1001);\n if (start < 0) start = s;\n else if (s == start) abort();\n\n return s;\n}\n int nrrand(void) {\n static int h[1001];\n static int n = -1;\n\n if (n < 0) {\n int s = 1;\n for (int i = 0; i < 1001; i++) {\n do {\n s = (s * 1103515245 + 12345) & 1023;\n } while (s >= 1001);\n /* If we used `i` rather than `s` then our early results would be poorly distributed. */\n h[i] = s;\n }\n n = 0;\n }\n\n int i = rand(500);\n if (i != 0) {\n i = (n + i) % 1001;\n int t = h[i];\n h[i] = h[n];\n h[n] = t;\n }\n i = h[n];\n n = (n + 1) % 1001;\n\n return i;\n}\n" }, { "answer_id": 36900316, "author": "Khaled.K", "author_id": 2128327, "author_profile": "https://Stackoverflow.com/users/2128327", "pm_score": 2, "selected": false, "text": "O(n) 2n n cursor = 0\n\nselector = A\nother = B\n\nshuffle(A)\n temp = selector[cursor]\n\nswap(other[cursor], other[random])\n\nif cursor == N\nthen swap(selector, other); cursor = 0\nelse cursor = cursor + 1\n\nreturn temp\n" }, { "answer_id": 41195350, "author": "Max Abramovich", "author_id": 6855859, "author_profile": "https://Stackoverflow.com/users/6855859", "pm_score": 3, "selected": false, "text": "a = 1002 c = 757 m = 1001 X = (1002 * X + 757) mod 1001\n" }, { "answer_id": 42541661, "author": "paparazzo", "author_id": 607314, "author_profile": "https://Stackoverflow.com/users/607314", "pm_score": 0, "selected": false, "text": "for i from n−1 downto 1 do\n j ← random integer such that 0 ≤ j ≤ i\n exchange a[j] and a[i]\n public static List<int> FisherYates(int n)\n{\n List<int> list = new List<int>(Enumerable.Range(0, n));\n Random rand = new Random();\n int swap;\n int temp;\n for (int i = n - 1; i > 0; i--)\n {\n swap = rand.Next(i + 1); //.net rand is not inclusive\n if(swap != i) // it can stay in place - if you force a move it is not a uniform shuffle\n {\n temp = list[i];\n list[i] = list[swap];\n list[swap] = temp;\n }\n }\n return list;\n}\n" }, { "answer_id": 58666154, "author": "Grog Klingon", "author_id": 7821991, "author_profile": "https://Stackoverflow.com/users/7821991", "pm_score": -1, "selected": false, "text": "for(i=0;i<10; ++i) {\n arr[i].index = i;\n arr[i].ran = rand();\n}\n #include <stdio.h>\n#include <stdlib.h>\n\nstruct RanStr { int index; int ran;};\nstruct RanStr arr[10];\n\nint sort_function(const void *a, const void *b);\n\nint main(int argc, char *argv[])\n{\n int cnt, i;\n\n //seed(125);\n\n for(i=0;i<10; ++i)\n {\n arr[i].ran = rand();\n arr[i].index = i;\n printf(\"arr[%d] Initial Order=%2d, random=%d\\n\", i, arr[i].index, arr[i].ran);\n }\n\n qsort( (void *)arr, 10, sizeof(arr[0]), sort_function);\n printf(\"\\n===================\\n\");\n for(i=0;i<10; ++i)\n {\n printf(\"arr[%d] Random Order=%2d, random=%d\\n\", i, arr[i].index, arr[i].ran);\n }\n\n return 0;\n}\n\nint sort_function(const void *a, const void *b)\n{\n struct RanStr *a1, *b1;\n\n a1=(struct RanStr *) a;\n b1=(struct RanStr *) b;\n\n return( a1->ran - b1->ran );\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3886/" ]
196,020
<p>I need to create a 'slider' for a client's site. The slider should allow people to select how many items they want of x item, and show what the price will be based on that. The weird(ish) part is that the ratio of the price increase will go down as the amount of items goes up:</p> <ul> <li>1 item: $100</li> <li>2 items: +90 = $190</li> <li>3 items: + 80 = $270</li> <li>4 items: + 70 = $340</li> <li>5 items: + 60 = $400</li> <li>6 items: + 50 = $450</li> <li>7 items: + 50 = $500</li> </ul> <p>And all increases from then on are +50. This probably seems like an overly simplistic question, but does anyone know how I could go about doing this? I have almost no experience with JavaScript :( </p>
[ { "answer_id": 196034, "author": "Dimitry", "author_id": 27073, "author_profile": "https://Stackoverflow.com/users/27073", "pm_score": 3, "selected": false, "text": "// First example of http://demos.mootools.net/Slider\n\n<div class=\"slider\" id=\"myslider\">\n <div class=\"knob\" style=\"position: relative;\"/>\n </div>\n var el = $('myslider'); // The slider graphic\nnew Slider(el, el.getElement('.knob'), {\n steps: 7, // There are 7 choices\n range: [1, 7], // Minimum value is 1, maximum is 7\n onChange: function(value){\n // Calculation of the value goes here\n }\n});\n" }, { "answer_id": 196040, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 0, "selected": false, "text": "else-if 100-(i*10) 50" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12765/" ]
196,027
<p>Something that has always bugged me is how unpredictable the <code>setTimeout()</code> method in Javascript is.</p> <p>In my experience, the timer is horribly inaccurate in a lot of situations. By inaccurate, I mean the actual delay time seems to vary by 250-500ms more or less. Although this isn't a huge amount of time, when using it to hide/show UI elements the time can be visibly noticeable.</p> <p>Are there any tricks that can be done to ensure that <code>setTimeout()</code> performs accurately (without resorting to an external API) or is this a lost cause?</p>
[ { "answer_id": 196138, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 7, "selected": true, "text": "setTimeout() setTimeout() setTimeout() (new Date()).milliseconds setTimeout()" }, { "answer_id": 3652173, "author": "Noel Walters", "author_id": 53030, "author_profile": "https://Stackoverflow.com/users/53030", "pm_score": 2, "selected": false, "text": "calculate_remaining_time\nif remaining_time > 20ms // maybe as much as 50\n re-queue the handler for 10ms time\nelse\n{\n while( remaining_time > 0 ) calculate_remaining_time;\n do_your_thing();\n re-queue the handler for 100ms before the next required time\n}\n" }, { "answer_id": 7269112, "author": "manast", "author_id": 815441, "author_profile": "https://Stackoverflow.com/users/815441", "pm_score": 3, "selected": false, "text": "function interval(duration, fn){\n var _this = this\n this.baseline = undefined\n \n this.run = function(){\n if(_this.baseline === undefined){\n _this.baseline = new Date().getTime()\n }\n fn()\n var end = new Date().getTime()\n _this.baseline += duration\n \n var nextTick = duration - (end - _this.baseline)\n if(nextTick<0){\n nextTick = 0\n }\n \n _this.timer = setTimeout(function(){\n _this.run(end)\n }, nextTick)\n }\n\n this.stop = function(){\n clearTimeout(_this.timer)\n }\n}\n" }, { "answer_id": 9576841, "author": "user1213320", "author_id": 1213320, "author_profile": "https://Stackoverflow.com/users/1213320", "pm_score": 5, "selected": false, "text": "var start = new Date().getTime(), \n time = 0, \n elapsed = '0.0'; \nfunction instance() \n{ \n time += 100; \n elapsed = Math.floor(time / 100) / 10; \n if(Math.round(elapsed) == elapsed) { elapsed += '.0'; } \n document.title = elapsed; \n var diff = (new Date().getTime() - start) - time; \n window.setTimeout(instance, (100 - diff)); \n} \nwindow.setTimeout(instance, 100); \n" }, { "answer_id": 15285075, "author": "Dean", "author_id": 276457, "author_profile": "https://Stackoverflow.com/users/276457", "pm_score": 2, "selected": false, "text": "var TOTAL_SEC = 6;\nvar FRAMES_PER_SEC = 60;\nvar percent = 0;\nvar startTime = new Date().getTime();\n\nsetTimeout(updateProgress, 1000 / FRAMES_PER_SEC);\n\nfunction updateProgress() {\n var currentTime = new Date().getTime();\n\n // 1000 to convert to milliseconds, and 100 to convert to percentage\n percent = (currentTime - startTime) / (TOTAL_SEC * 1000) * 100;\n\n $(\"#progressbar\").progressbar({ value: percent });\n\n if (percent >= 100) {\n window.location = \"newLocation.html\";\n } else {\n setTimeout(updateProgress, 1000 / FRAMES_PER_SEC);\n } \n}\n" }, { "answer_id": 16103377, "author": "Chris GW Green", "author_id": 1818728, "author_profile": "https://Stackoverflow.com/users/1818728", "pm_score": 4, "selected": false, "text": "requestAnimationFrame window.performance = window.performance || {};\n performance.now = (function() {\n return performance.now ||\n performance.mozNow ||\n performance.msNow ||\n performance.oNow ||\n performance.webkitNow ||\n function() {\n //Doh! Crap browser!\n return new Date().getTime(); \n };\n })();\n" }, { "answer_id": 21117513, "author": "NicJ", "author_id": 43815, "author_profile": "https://Stackoverflow.com/users/43815", "pm_score": 2, "selected": false, "text": "setTimeout() setImmediate() setImmediate() setTimeout() setTimeout(..., 16) setTimeout(..., 4) setTimeout(..., 0) setTimeout() setImmediate() setImmediate() setImmediate() setTimeout() setTimeout() window.performance.now() Date.now()" }, { "answer_id": 27299152, "author": "Code Whisperer", "author_id": 2299820, "author_profile": "https://Stackoverflow.com/users/2299820", "pm_score": 1, "selected": false, "text": "var Timer = function(){\n var framebuffer = 0,\n var msSinceInitialized = 0,\n var timer = this;\n\n var timeAtLastInterval = new Date().getTime();\n\n setInterval(function(){\n var frametime = new Date().getTime();\n var timeElapsed = frametime - timeAtLastInterval;\n msSinceInitialized += timeElapsed;\n timeAtLastInterval = frametime;\n },1);\n\n this.setInterval = function(callback,timeout,arguments) {\n var timeStarted = msSinceInitialized;\n var interval = setInterval(function(){\n var totaltimepassed = msSinceInitialized - timeStarted;\n if (totaltimepassed >= timeout) {\n callback(arguments);\n timeStarted = msSinceInitialized;\n }\n },1);\n\n return interval;\n }\n}\n\nvar timer = new Timer();\ntimer.setInterval(function(){console.log(\"This timer will not drift.\"),1000}" }, { "answer_id": 46484357, "author": "agm1984", "author_id": 6141025, "author_profile": "https://Stackoverflow.com/users/6141025", "pm_score": 0, "selected": false, "text": "const round = (places, number) => +(Math.round(number + `e+${places}`) + `e-${places}`)\n places that + symbol Number() const start = performance.now()\n\n// I wonder how long this comment takes to parse\n\nconst end = performance.now()\n\nconst result = (end - start) + ' ms'\n\nconst adjusted = round(2, result) // see above rounding function\n // Start timer\nconst startTimer = () => process.hrtime()\n\n// End timer\nconst endTimer = (time) => {\n const diff = process.hrtime(time)\n const NS_PER_SEC = 1e9\n const result = (diff[0] * NS_PER_SEC + diff[1])\n const elapsed = Math.round((result * 0.0000010))\n return elapsed\n}\n\n// This end timer converts the number from nanoseconds into milliseconds;\n// you can find the nanosecond version if you need some seriously high-resolution timers.\n\nconst start = startTimer()\n\n// I wonder how long this comment takes to parse\n\nconst end = endTimer(start)\n\nconsole.log(end + ' ms')\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
196,029
<p>I have a PHP script that initialises an image gallery. It loops through all images, checks if they are thumbnailed and watermarks them.</p> <p>My shared hosting account only lets me have 30 seconds of execution per script, as set in the php.ini settings. I can't change that.</p> <p>What can I do to get round this? Currently I refresh the page after every 5 images, this prevents the script timing out, but the browser recognises that the script won't complete and gives an error. That's ok, but it's not really user friendly.</p> <p>Any suggestions?</p>
[ { "answer_id": 196050, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 2, "selected": false, "text": "<meta http-equiv=\"refresh\" content=\"2;url=script.php?start=5\">\n" }, { "answer_id": 196057, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "set_time_limit" }, { "answer_id": 196231, "author": "Willem", "author_id": 15447, "author_profile": "https://Stackoverflow.com/users/15447", "pm_score": 2, "selected": false, "text": "fpassthru() <img src=\"/image.php?DSC001.JPG\">\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ]
196,032
<p>What Visual Studio settings and .emacs macros improve the likelihood that code written on Windows (in visual studio) will still look good in Emacs (and vice versa)? I've recently taken to turning off tabs in emacs (so tabs are rendered via spaces) and this at least makes the code look the same (tho people who like certain tab sizes are out of luck). Is there a better way?</p>
[ { "answer_id": 196245, "author": "ejgottl", "author_id": 9808, "author_profile": "https://Stackoverflow.com/users/9808", "pm_score": 1, "selected": false, "text": "'(c-default-style (quote ((c-mode . \"bsd\") (c++-mode . \"bsd\") (java-mode . \"jav\na\") (other . \"gnu\"))))\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3886/" ]
196,037
<p>How can I access a public static member of a Java class from ColdFusion?</p>
[ { "answer_id": 196107, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 5, "selected": true, "text": "<cfset systemObject = createObject(\"java\", \"java.lang.System\") />\n<cfoutput>#systemObject.currentTimeMillis()#</cfoutput> \n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
196,048
<p>I have a system which generates a large number of XML documents every day (of the order of 1 million) and I would like to be able to store and index these so that I can, for example, search for all documents with a certain field set to a given value.</p> <p>I understand that there are fundamentally two types of XML database, those that provide XML support on top of a conventional relational database and those that are "native" XML database. Given that I am open to using either, what would you recommend?</p>
[ { "answer_id": 13856159, "author": "thewhitetulip", "author_id": 1160051, "author_profile": "https://Stackoverflow.com/users/1160051", "pm_score": 1, "selected": false, "text": "create table person(name varchar(20), data xml);\n\ninsert into person values('bane', XMLPARSE(DOCUMENT '\n<person>\n<first-name>Tom</first-name>\n<last-name>Hardy</last-name>\n<mobile>89898989</mobile>\n\n</person>\n' STRIP WHITESPACE))\n\n\nsome simple xQueries\n\nSELECT *\nFROM googolplex.person\nWHERE xmlexists('$s[person/first-name=\"bane\"]' PASSING person AS \"s\");\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3305/" ]
196,053
<p>I am in the process of developing a web application that consists visually of a header above a body containing four columns of variable-height content. The design gods have decreed it to be fixed height, mainly because each of the columns can potentially get very long, and so (being designers) they are wanting iframes with independent scrollbars.</p> <p>Four (potential) scrollbars are bad enough, but if the overall page height is fixed higher than the browser window then it'll end up with five! The 'normal' solution in a case like this of course is to fix the overall page height at something like 700 pixels to give it the 'best chance' of fitting vertically, but I don't want to do that for various reasons which I'd hope would be obvious.</p> <p>So my question is: What would be the best way to have a body container that fills the available (vertical space) with each of the columns doing the same thing? Is it even practical/possible? Bonus question: Can I reliably use the CSS overflow property for the columns or do I need nasty iframes? I have lots of CSS experience, but next to none with using percentage dimensions (especially when combined with pixel dimensions as I'll need for the header). Also, this must be standards-compliant and backwards-compatible to IE6.</p> <p>TIA.</p> <p>EDIT: I'm not looking for a CSS layout solution per se, my problem is how to accommodate the need for each column to be the maximum height possible within the body container and scrollable, without fixing the height of the body in pixels - unless I absolutely need to.</p>
[ { "answer_id": 196078, "author": "Dimitry", "author_id": 27073, "author_profile": "https://Stackoverflow.com/users/27073", "pm_score": 0, "selected": false, "text": "<div id=\"head\"></div>\n<div id=\"body\">\n <div id=\"col1\"></div>\n <div id=\"col2\"></div>\n <div id=\"col3\"></div>\n <div id=\"col4\"></div>\n</div>\n #body { position: absolute; top: 60px /* height of the header */; bottom: 0px; width: 100%; }\n#body div { position: absolute; top:0; bottom:0 ;width: 25% }\n window.onResize = function () {\n // Calculate the height of the body, substract the height of the head and apply to all columns\n}\n" }, { "answer_id": 201389, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 0, "selected": false, "text": "DIV height:100% padding:60px height width: 12em - 2px;\nborder: 1px solid #FED; /* Total width including border is 12em exactly */\n width: 25% - 1em;\nmargin: 1.25em 1em;\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14979/" ]
196,087
<p>I listen to the podcast java posse, on this there is often discussion about components (note components are not (clearly) objects). They lament the fact that Java does not have components, and contrast with .NET that does. Components apparently makes developing applications (not just GUI apps) easier.</p> <p>I can figure from the discussion certain qualities that a component has, its something to-do with decoupling (substituting one component for another is just a matter of plumbing). It has something to-do with properties, it definitely has something to-do with events and delegates. </p> <p>So to the questions:</p> <p>./ can anyone explain to me what a component is. (and why java beans are not components).</p> <p>./ can anyone explain how they help development.</p> <p>./ can anyone explain why java does not have them if they are so useful.</p>
[ { "answer_id": 22465686, "author": "Miguel Gamboa", "author_id": 1140754, "author_profile": "https://Stackoverflow.com/users/1140754", "pm_score": 2, "selected": false, "text": ".class .class .class .dll .exe" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6715/" ]
196,088
<p>Assume I have a function template like this:</p> <pre><code>template&lt;class T&gt; inline void doStuff(T* arr) { // stuff that needs to use sizeof(T) } </code></pre> <p>Then in another <code>.h</code> filee I have a template class <code>Foo</code> that has:</p> <pre><code>public: operator T*() const; </code></pre> <p>Now, I realize that those are different Ts. But If I have a variable <code>Foo&lt;Bar&gt; f</code> on the stack, the only way to coerce it to <em>any</em> kind of pointer would be to invoke <code>operator T*()</code>. Yet, if call <code>doStuff(f)</code>, GCC complains that <code>doStuff</code> can't take <code>Foo&lt;Bar&gt;</code> instead of automatically using operator <code>T*()</code> to coerce to <code>Bar*</code> and then specializing the function template with <code>Bar</code> as <code>T</code>.</p> <p>Is there anything I can do to make this work with two templates? Or does either the argument of the template function have to be a real pointer type or the template class with the coercion operator be passed to a non-template function?</p>
[ { "answer_id": 196103, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": -1, "selected": false, "text": "\ntemplate \ninline\nvoid \ndoStuff(T& arrRef)\n{\n doStuff(&arrRef);\n}\n" }, { "answer_id": 196151, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": true, "text": "template<typename T> inline void doStuff(const Foo<T>& arr) {\n doStuff(static_cast<T*>(arr));\n}\n #include <boost/type_traits/is_convertible.hpp>\n#include <boost/utility/enable_if.hpp>\ntemplate<template <typename> class T, typename U> inline typename boost::enable_if<typename boost::is_convertible<T<U>, U*>::type>::type doStuff(const T<U>& arr) {\n doStuff(static_cast<U*>(arr));\n}\n" }, { "answer_id": 196153, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "doStuff<Bar>(f);\n" }, { "answer_id": 196440, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 0, "selected": false, "text": "doStuff(static_cast<Bar*>(f));\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18721/" ]
196,094
<p>I know I can get the public static members of a class by doing something like:</p> <p><code>obj.getClass().getFields()</code></p> <p>but this doesn't get me the enums. I'd like to be able to get them from the Class object returned by the getClass method. Any ideas?</p>
[ { "answer_id": 196117, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "Class.getDeclaredClasses() Class.isEnum() Class.getEnumConstants()" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
196,097
<p>On a site of mine in which a textarea is used for submission, I have code that can appear something along the lines of the following:</p> <pre><code>&lt;textarea&gt;&lt;p&gt;text&lt;/p&gt;&lt;/textarea&gt; </code></pre> <p>When validating (XHTML 1.0 Transitional), this error arises,</p> <pre><code>line 88 column 50 - Error: document type does not allow element "p" here </code></pre> <p>If this is not a valid method, then what is expected? I could do a workaround with an onload JavaScript event, but that seems needless. Regardless this doesn't affect the output, but I'd rather my site validate.</p>
[ { "answer_id": 196105, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "<p> <textarea> <textarea>&lt;p&gt;text&lt;/p&gt;</textarea>\n" }, { "answer_id": 196108, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 0, "selected": false, "text": "&lt;p&gt; &lt;/p&gt;" }, { "answer_id": 196134, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "eg: replace < > with &lt; &gt;\n\n<textarea cols=\"\" rows=\"\">&lt;p&gt;text&lt;/p&gt;</textarea>\n" }, { "answer_id": 196141, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 1, "selected": false, "text": "textarea" }, { "answer_id": 196193, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<textarea><![CDATA[\n <p>Blah</p>\n]]></textarea>\n" }, { "answer_id": 367941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function clean_data($value) {\n if (get_magic_quotes_gpc()) { $value = stripslashes($value); }\n $value = addslashes(htmlentities(trim($value)));\n $value = str_replace(\"\\'\", \"&#39;\", $value);\n $value = str_replace(\"'\", \"&#39;\", $value);\n $value = str_replace(\":\", \"&#58;\", $value);\n return $value;\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23666/" ]
196,109
<p>Does anybody know of a good media framework for Flex?<br/> I'd like to be able to create apps that can play not only those formats that the Flex framework provides support for, but other formats as well (like wav, wma, ogg and other...).</p> <p><strong>EDIT 13.10.2008.:</strong> It was recently pointed out to me in the answers section that I should perhaps rephrase the question, so here goes: What I'm really looking for is a way to play various media formats in a Flex/Air app. Onekidney posted a nice answer about Ogg/Vorbis. Does anybody know of a way to play other media formats? Never mind about the portability to different platforms now. Portability would be nice, but if I can't get it, I can live without it :-).<br/> Thanks for the answers!</p>
[ { "answer_id": 196105, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "<p> <textarea> <textarea>&lt;p&gt;text&lt;/p&gt;</textarea>\n" }, { "answer_id": 196108, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 0, "selected": false, "text": "&lt;p&gt; &lt;/p&gt;" }, { "answer_id": 196134, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "eg: replace < > with &lt; &gt;\n\n<textarea cols=\"\" rows=\"\">&lt;p&gt;text&lt;/p&gt;</textarea>\n" }, { "answer_id": 196141, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 1, "selected": false, "text": "textarea" }, { "answer_id": 196193, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<textarea><![CDATA[\n <p>Blah</p>\n]]></textarea>\n" }, { "answer_id": 367941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function clean_data($value) {\n if (get_magic_quotes_gpc()) { $value = stripslashes($value); }\n $value = addslashes(htmlentities(trim($value)));\n $value = str_replace(\"\\'\", \"&#39;\", $value);\n $value = str_replace(\"'\", \"&#39;\", $value);\n $value = str_replace(\":\", \"&#58;\", $value);\n return $value;\n}\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19911/" ]
196,114
<p>I chmod'ed the directory to 777, same with the directory contents. Still, I get a "permission denied" error. Does PHP throw this error if apache is not the group/owner, regardless of the file permissions? Here's the call that's failing:</p> <pre><code>rename('/correct/path/to/dir/1', '/correct/path/to/dir/2'); </code></pre>
[ { "answer_id": 196118, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "print_r(posix_getpwuid(getmyuid()));\nprint_r(pathinfo($YOUR_PATH));\n" }, { "answer_id": 196167, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "-rwxrwxrwx user user temp/\n-rwxr-xr-x apache apache temp2/\n-rw-r--r-- user user script.php\n // this operation fails as PHP (running as apache) does not own \"temp\",\n// despite having write permissions \nrename('temp', 'temp.bak');\n\n// this operation is successful as PHP owns \"temp2\"\nrename('temp2, 'temp.bak'); \n" }, { "answer_id": 60288441, "author": "Alfredo Morales", "author_id": 12893415, "author_profile": "https://Stackoverflow.com/users/12893415", "pm_score": 0, "selected": false, "text": "chown -R www-data:www-data /directory/path/to/apply/chown\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
196,136
<p>I'm working on designing the kernel (which I'm going to actually call the "core" just to be different, but its basically the same) for an OS I'm working on. The specifics of the OS itself are irrelevant if I can't get multi-tasking, memory management, and other basic things up and running, so I need to work on that first. I've some questinos about designing a malloc routine.</p> <p>I figure that malloc() is either going to be a part of the kernel itself (I'm leaning towards this) or a part of the program, but I'm going to have to write my own implementation of the C standard library either way, so I get to write a malloc. My question is actually rather simple in this regard, how does C (or C++) manage its heap?</p> <p>What I've always been taught in theorey classes is that the heap is an ever expanding piece of memory, starting at a specified address, and in a lot of senses behaving like a stack. In this way, I know that variables declared in global scope are at the beginning, and more variables are "pushed" onto the heap as they are declared in their respective scopes, and variables that go out of scope are simply left in memory space, but that space is marked as free so the heap can expand more if it needs to.</p> <p>What I need to know is, how on earth does C actually handle a dynamically expanding heap in this manner? Does a compiled C program make its own calls to a malloc routine and handle its own heap, or do I need to provide it with an automatically expanding space? Also, how does the C program know where the heap begins?</p> <p>Oh, and I know that the same concepts apply to other languages, but I would like any examples to be in C/C++ because I'm most comfortable with that language. I also would like to not worry about other things such as the stack, as I think I'm able to handle things like this on my own.</p> <p>So I suppose my real question is, other than malloc/free (which handles getting and freeing pages for itself, etc) does a program need the OS to provide anything else?</p> <p>Thanks!</p> <p><em>EDIT</em> I'm more interested in how C uses malloc in relation with the heap than in the actual workings of the malloc routine itself. If it helps, I'm doing this on x86, but C is cross compiler so it shouldn't matter. ^_^</p> <p>EDIT FURTHER: I understand that I may be getting terms confused. I was taught that the "heap" was where the program stored things like global/local variables. I'm used to dealing with a "stack" in assembly programming, and I just realized that I probably mean that instead. A little research on my part shows that "heap" is more commonly used to refer to the total memory that a program has allocated for itself, or, the total number (and order) of pages of memory the OS has provided.</p> <p>So, with that in mind, how do I deal with an ever expanding <em>stack</em>? (it does appear that my C theory class was mildly... flawed.)</p>
[ { "answer_id": 196146, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "malloc mmap sbrk malloc" }, { "answer_id": 196191, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": true, "text": "malloc malloc free lib/malloc.c sys_page_alloc sys_page_unmap" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
196,171
<p>Is it possible to use a CHECK constraint to prevent any date that falls on a Sunday? I don't want to use a trigger.</p>
[ { "answer_id": 196190, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": 1, "selected": false, "text": "TO_CHAR(sysdate, 'D'); \n" }, { "answer_id": 196196, "author": "Plasmer", "author_id": 397314, "author_profile": "https://Stackoverflow.com/users/397314", "pm_score": 4, "selected": true, "text": "create table date_test (entry_date date);\n\nalter table date_test add constraint day_is_not_sunday\n check ( to_char(entry_date,'DAY','NLS_DATE_LANGUAGE = ENGLISH') not like 'SUNDAY%'); \n insert into date_test values(to_date('2008-10-12','YYYY-MM-DD')); --Sunday\ninsert into date_test values(to_date('2008-10-11','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-10','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-09','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-08','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-07','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-06','YYYY-MM-DD'));\n ORA-02290: check constraint (SYS.DAY_IS_NOT_SUNDAY) violated" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3401/" ]
196,173
<p>Modern UI's are starting to give their UI elments nice inertia when moving. Tabs slide in, page transitions, even some listboxes and scroll elments have nice inertia to them (the iphone for example). What is the best algorythm for this? It is more than just gravity as they speed up, and then slow down as they fall into place. I have tried various formulae's for speeding up to a maximum (terminal) velocity and then slowing down but nothing I have tried "feels" right. It always feels a little bit off. Is there a standard for this, or is it just a matter of playing with various numbers until it looks/feels right?</p>
[ { "answer_id": 196209, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "smoothstep(t) = 3*t*t - 2*t*t*t [0 <= t <= 1]\n smoothstep_eo(t) = 2*smoothstep((t+1)/2) - 1\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
196,177
<p>I have code like this:</p> <pre><code>var newMsg = new Msg { Var1 = var1, Var2 = var2 }; using (AppDataContext appDataContext = new AppDataContext(ConnectionString)) { appDataContext.CClass.InsertOnSubmit(newMsg); appDataContext.SubmitChanges(); } </code></pre> <p>After reading <a href="https://stackoverflow.com/questions/157924/does-linqs-executecommand-provide-protection-from-sql-injection-attacks">this post</a> I believe that the same logic applies.</p> <p>Does anyone think that this is subject to SQL Injection Attack?</p>
[ { "answer_id": 196304, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": false, "text": "INSERT INTO [MSG] [Var1] = @p1, [Var2] = @p2\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
196,179
<p>I'm having a problem understanding the shift/reduce confict for a grammar that I know has no ambiguity. The case is one of the if else type but it's not the 'dangling else' problem since I have mandatory END clauses delimiting code blocks.</p> <p>Here is the grammar for gppg (Its a Bison like compiler compiler ... and that was not an echo):</p> <pre><code>%output=program.cs %start program %token FOR %token END %token THINGS %token WHILE %token SET %token IF %token ELSEIF %token ELSE %% program : statements ; statements : /*empty */ | statements stmt ; stmt : flow | THINGS ; flow : '#' IF '(' ')' statements else ; else : '#' END | '#' ELSE statements '#' END | elseifs ; elseifs : elseifs '#' ELSEIF statements else | '#' ELSEIF statements else ; </code></pre> <p>Here is the conflict output:</p> <pre><code>// Parser Conflict Information for grammar file "program.y" Shift/Reduce conflict on symbol "'#'", parser will shift Reduce 10: else -&gt; elseifs Shift "'#'": State-22 -&gt; State-23 Items for From-state State 22 10 else: elseifs . -lookahead: '#', THINGS, EOF 11 elseifs: elseifs . '#' ELSEIF statements else Items for Next-state State 23 11 elseifs: elseifs '#' . ELSEIF statements else // End conflict information for parser </code></pre> <p>I already switched arround everything, and I do know how to resolve it, but that solution involves giving up the left recursion on 'elseif' for a right recursion.</p> <p>Ive been through all the scarse documentation I have found on the internet regarding this issue (I post some links at the end) and still have not found an elegant solution. I know about ANTLR and I don't want to consider it right now. Please limit your solution to Yacc/Bison parsers.</p> <p>I would appreciate elegant solutions, I managed to do It by eleminating the /* empty */ rules and duplication everything that needed an empty list but in the larger grammar Im working on It just ends up like 'sparghetti grammar syndrome'.</p> <p>Here are some links:</p> <p><a href="http://nitsan.org/~maratb/cs164/bison.html" rel="noreferrer">http://nitsan.org/~maratb/cs164/bison.html</a></p> <p><a href="http://compilers.iecc.com/comparch/article/98-01-079" rel="noreferrer">http://compilers.iecc.com/comparch/article/98-01-079</a></p> <p><a href="http://plas.fit.qut.edu.au/gppg/" rel="noreferrer">GPPG, the parser I'm using</a></p> <p><a href="http://www.gnu.org/software/bison/manual/index.html" rel="noreferrer">Bison manual</a></p>
[ { "answer_id": 196201, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "elseifs : elseifs '#' ELSEIF statements else\n | '#' ELSEIF statements else\n ;\n else : '#' END\n | '#' ELSE statements '#' END\n | elseifs\n ;\n elseifs : '#' ELSEIF statements else\n ;\n" }, { "answer_id": 196229, "author": "Caerbanog", "author_id": 23190, "author_profile": "https://Stackoverflow.com/users/23190", "pm_score": 0, "selected": false, "text": "flow : '#' IF '(' ')' statements elsebody \n ;\n\nelsebody : else \n | elseifs else\n ;\n\nelse : '#' ELSE statements '#' END\n | '#' END\n ;\n\nelseifs : /* empty */\n | elseifs '#' ELSEIF statements\n ;\n // Parser Conflict Information for grammar file \"program.y\"\n\nShift/Reduce conflict on symbol \"'#'\", parser will shift\n Reduce 12: elseifs -> /* empty */\n Shift \"'#'\": State-10 -> State-13\n Items for From-state State 10\n 7 flow: '#' IF '(' ')' statements . elsebody \n 4 statements: statements . stmt \n Items for Next-state State 13\n 10 else: '#' . ELSE statements '#' END \n 11 else: '#' . END \n 7 flow: '#' . IF '(' ')' statements elsebody \n\nShift/Reduce conflict on symbol \"'#'\", parser will shift\n Reduce 13: elseifs -> elseifs, '#', ELSEIF, statements\n Shift \"'#'\": State-24 -> State-6\n Items for From-state State 24\n 13 elseifs: elseifs '#' ELSEIF statements .\n -lookahead: '#'\n 4 statements: statements . stmt \n Items for Next-state State 6\n 7 flow: '#' . IF '(' ')' statements elsebody \n\n// End conflict information for parser\n" }, { "answer_id": 196301, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "elsebody : else\n | elseifs else\n ;\n elseifs : /* Nothing */\n | elseifs ...something... \n ;\n flow : '#' IF '(' ')' statements opt_elseifs opt_else end\n ;\n\nopt_elseifs : /* Nothing */\n | opt_elseifs '#' ELSIF '(' ')' statements \n ;\n\nopt_else : /* Nothing */\n | '#' ELSE statements\n ;\n\nend : '#' END\n ;\n" }, { "answer_id": 196306, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "elsebody : elseifs else\n | elseifs\n ;\n\nelseifs : /* empty */\n | elseifs '#' ELSEIF statements\n ;\n\nelse : '#' ELSE statements '#' END\n ;\n" }, { "answer_id": 196692, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "%token NUMBER IF ELSE\n%token ELIF END\n%token THEN\n%start program\n\n%%\n\nprogram\n : stmtlist\n ;\n\nstmtlist\n : /* Nothing */\n | stmtlist stmt\n ;\n\nstmt\n : ifstmt\n ;\n\nifstmt\n : ifcond endif\n | ifcond else begin\n | ifcond eliflist begin\n ;\n\nifcond\n : ifstart cond then stmtlist\n ;\n\nifstart\n : IF\n ;\n\ncond\n : '(' expr ')'\n ;\n\nthen\n : /* Nothing */\n | THEN\n ;\n\nendif\n : END IF begin\n ;\n\nelse\n : ELSE stmtlist END IF\n ;\n\neliflist\n : elifblock\n | elifcond eliflist begin /* RIGHT RECURSION */\n ;\n\nelifblock\n : elifcond else begin\n | elifcond endif\n ;\n\nelifcond\n : elif cond then stmtlist end\n ;\n\nelif\n : ELIF\n ;\n\nbegin\n : /* Nothing */\n ;\n\nend\n : /* Nothing */\n ;\n\nexpr\n : NUMBER\n ;\n\n%%\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23190/" ]
196,216
<p>I am new to strut/web programming and I thought I could learn a lot by reading a sample app. On google, I searched and found a sample app at <a href="http://www.roseindia.net/struts/struts2/struts2tutorial.zip" rel="nofollow noreferrer">http://www.roseindia.net/struts/struts2/struts2tutorial.zip</a> , the tutorial is really nice and it gives a sample login page.</p> <p>However, I couldn't run this sample app. I tried posting on the roseindia.net site and got no help neither.</p> <p>There is no error logged during the start of the server, but when I try and open one of the helloworld's link the following is outputted</p> <p>I am getting this error</p> <blockquote> <p>SEVERE: Could not find action or result There is no Action mapped for action name HelloWorld. - [unknown location]</p> </blockquote> <p>The folder structure of this thing on my eclipse is</p> <pre><code>/WebContent/WEB-INF/java/net/roseindia/Struts2HelloWorld.java /WebContent/pages/HelloWorld.jsp /WebContent/WEB-INF/struts.xml </code></pre> <p>while in strut.xml the sample had..<br> </p> <pre><code> &lt;action name="HelloWorld" class="net.roseindia.Struts2HelloWorld"&gt; &lt;result&gt;/pages/HelloWorld.jsp&lt;/result&gt; &lt;/action&gt; </code></pre> <p>I am suspecting something in the strut.xml is wrong? I am using eclipse J2EE and tomcat6, I have already tried posting on roseindia's site and got no help.</p>
[ { "answer_id": 4298347, "author": "Hans Beemsterboer", "author_id": 522561, "author_profile": "https://Stackoverflow.com/users/522561", "pm_score": 0, "selected": false, "text": "WebContent/WEB-INF/classes\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17085/" ]
196,221
<p>Is it possible to assign a custom ID to a HTTP session through Servlet API?</p> <p>I know that session handling from any application server, Tomcat for example, it's enough good to generate unique IDs. But I have custom unique session IDs based on information per user and time, so it won't be repeated.</p> <p>And I looked at every documentation about session handling but nowhere I find what I need.</p> <p>It's a requirement for a project, so if it's not possible, I need to know the reasons (or it's only not available through API?).</p>
[ { "answer_id": 196343, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 1, "selected": false, "text": "/** \n * The String key of the user id attribute.\n */\npublic static final String USER_ID_KEY = \"userIdKey\";\n\n// Set the user attribute (createUniqueUserId's parameters and return type are up to you)\nhttpSession.setAttribute(USER_ID_KEY, createUniqueUserId());\n\n// Retrieve the user attribute later\nhttpSession.getAttribute(USER_ID_KEY);\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11583/" ]
196,224
<p>I have a component which writes/generates javascript from a server side renderer. This component can be used in multiple times in a same page. However, once the page is loaded I have to collect all the variables or JSO written by this multiple components in the page. How can I do this so that I will have a collection of all the variables or JSO? For e.g. If this component (lets say ) is used twice in the page then it emits two javascript block on client/browser - var arr1 = new Array['First', 'Second'] and var arr2 = new Array['Third', 'Fourth']. </p> <p>In order to make a final rendering I have to combine these two arrays.</p>
[ { "answer_id": 196271, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 2, "selected": true, "text": "Component_appendArray(['First', 'Second']);\n...\nComponent_appendArray(['Third', 'Fourth']);\n Component_appendArray() var globalArray = [];\nfunction Component_appendArray(array)\n{\n globalArray = globalArray.concat(array);\n}\n globalArray ['First', 'Second', 'Third', 'Fourth']\n" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3627/" ]
196,244
<p>Can anyone point to some code that deals with the security of files access via a path specified (in part) by an environment variable, specifically for Unix and its variants, but Windows solutions are also of interest?</p> <p><em>This is a big long question - I'm not sure how well it fits the SO paradigm.</em></p> <p>Consider this scenario:</p> <p><strong>Background:</strong></p> <ul> <li>Software package PQR can be installed in a location chosen by users.</li> <li>The environment variable $PQRHOME is used to identify the install directory.</li> <li>By default, all programs and files under $PQRHOME belong to a special group, pqrgrp.</li> <li>Similarly, all programs and files under $PQRHOME either belong to a special user, pqrusr, or to user root (and those are SUID root programs).</li> <li>A few programs are SUID pqrusr; a few more programs are SGID pqrgrp.</li> <li>Most directories are owned by pqrusr and belong to pqrgrp; some can belong to other groups, and the members of those groups acquire extra privileges with the software.</li> <li>Many of the privileged executables must be run by people who are not members of pqrgrp; the programs have to validate that the user is permitted to run it by arcane rules that do not directly concern this question.</li> <li>After startup, some of the privileged programs have to retain their elevated privileges because they are long-running daemons that may act on behalf of many users over their lifetime.</li> <li>The programs are not authorized to change directory to $PQRHOME for a variety of arcane reasons.</li> </ul> <p><strong>Current checking:</strong></p> <ul> <li>The programs currently check that $PQRHOME and key directories under it are 'safe' (owned by pqrusr, belong to pqrgrp, do not have public write access).</li> <li>Thereafter, programs access files under $PQRHOME via the full value of environment variable.</li> <li>In particular, the G11N and L10N is achieved by accessing files in 'safe' directories, and reading format strings for printf() etc out of the files in those directories, using the full pathname derived from $PQRHOME plus a known sub-structure (for example, $PQRHOME/g11n/en_us/messages.l10n).</li> </ul> <p>Assume that the 'as installed' value of $PQRHOME is /opt/pqr.</p> <p><strong>Known attack:</strong></p> <ul> <li>Attacker sets PQRHOME=/home/attacker/pqr.</li> <li>This is actually a symlink to /opt/pqr, so when one of the PQR programs, call it pqr-victim, checks the directory, it has correct permissions.</li> <li>Immediately after the security checking is completed successfully, the attacker changes the symlink so that it points to /home/attacker/bogus-pqr, which is clearly under the attacker's control.</li> <li>Dire things happen when the pqr-victim now accesses a file under the supposedly safe directory.</li> </ul> <p><strong>Given that PQR currently behaves as described, and is a large package (multiple millions of lines of code, developed over more than a decade to a variety of coding standards, which were frequently ignored, anyway), what techniques would you use to remediate the problem?</strong></p> <p><em>Known options include:</em></p> <ol> <li>Change all formatting calls to use function that checks actual arguments against the format strings, with an extra argument indicating the actual types passed to the function. (This is tricky, and potentially error prone because of the sheer number of format operations to be changed - but if the checking function is itself sound, works well.)</li> <li>Establish the direct path to PQRHOME and validate it for security (details below), refusing to start if it is not secure, and thereafter using the direct path and not the value of $PQRHOME (when they differ). (This requires all file operations that use $PQRHOME to use not the value from getenv() but the mapped path. For example, this would require the software to establish that /home/attacker/pqr is a symlink to /opt/pqr, that the path to /opt/pqr is secure, and thereafter, whenever a file is referenced as $PQRHOME/some/thing, the name used would be /opt/pqr/some/thing and not /home/attacker/pqr/some/thing. This is a large code base - not trivial to fix.)</li> <li>Ensure that all directories on $PQRHOME, even tracking through symlinks, are secure (details below, again), and the software refuses to start if anything is insecure.</li> <li>Hard-code the path to the software install location. (This won't work PQR; it makes testing hell, if nothing else. For users, it means they can have but one version installed, and upgrades etc require parallel running. This does not work for PQR.)</li> </ol> <p><em>Proposed criteria for secure paths:</em></p> <ul> <li>For each directory, the owner must be trusted. (<em>Rationale: the owner can change permissions at any time, so the owner must be trusted not to make changes at random that break the security of the software.</em>)</li> <li>For each directory, the group must either not have write privileges (so members of the group cannot modify the directory contents) or the group must be trusted. (<em>Rationale: if the group members can modify the directory, then they can break the security of the software, so either they must be unable to change it, or they must be trusted not to changed it.</em>)</li> <li>For each directory, 'others' must have no write privilege on the directory.</li> <li>By default, the users root, bin, sys, and pqrusr can be trusted (where bin and sys exist).</li> <li>By default, the group with GID=0 (variously known as root, wheel or system), bin, sys, and pqrgrp can be trusted. Additionally, the group that owns the root directory (which is called admin on MacOS X) can be trusted.</li> </ul> <p>The POSIX function <code>realpath()</code> provides a mapping service that will map /home/attacker/pqr to /opt/pqr; it does not do the security checking, but that need only be done on the resolved path.</p> <p><strong>So, with all that as background, is there any known software which goes through vaguely related gyrations to ensure its security? Is this being overly paranoid? (If so, why - and are you really sure?)</strong></p> <p><em>Edited:</em></p> <p>Thanks for the various comments.</p> <p>@S.Lott: The attack (outlined in the question) means that at least one setuid root program can be made to use a format string of the (unprivileged) user's choosing, and can at least crash the program and therefore most probably can acquire a root shell. It requires local shell access, fortunately; it is not a remote attack. It requires a non-negligible amount of knowledge to get there, but I consider it unwise to assume that the expertise is not 'out there'.</p> <p>So, what I'm describing is a 'format string vulnerability' and the known attack path involves faking the program out so that although it thinks it is accessing secure message files, it actually goes and uses the message files (which contain format strings) that are under the control of the user, not under the control of the software.</p>
[ { "answer_id": 196280, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": "$PQRHOME socketpair" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15168/" ]
196,253
<p>I'm using LINQ to SQL in a data access object library. The library is used in both web (web application/web service) and non-web (windows service) contexts. Initially, I stored the <code>DataContext</code> on the current <code>HttpContext</code> since it permitted me to manage a fairly small unit of work (one web request) and avoided global objects in a web app. Obviously, this doesn't work in a Windows Service.</p> <p>Rick Strahl has a nice article on managing the <code>DataContext</code>'s lifetime: <a href="http://www.west-wind.com/weblog/posts/246222.aspx" rel="nofollow noreferrer">http://www.west-wind.com/weblog/posts/246222.aspx</a>. Unfortunately, I can't make up my mind on the best approach. A global <code>DataContext</code> doesn't work for reasons he mentions, a per-Thread <code>DataContext</code> seems complicated and potentially more trouble than it's worth, and a per-object instance seems fussy - you lose some elegance when you attach the <code>DataContext</code> used to create a <code>DAO</code> to that <code>DAO</code> so it can <code>update</code> or <code>delete</code> later - not to mention, there's something unpleasantly chicken-and-eggish about the relationship.</p> <p>Does anyone have personal experience that suggests one approach is better than another? Or better yet, does anyone have a fourth or fifth approach I'm not seeing? Where is the best place to store and manage your <code>DataContext</code>?</p>
[ { "answer_id": 196264, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 5, "selected": false, "text": "DataContext IDisposable DataContext using DataContext" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7625/" ]
196,294
<p>I'm trying to learn about catamorphisms and I've read <a href="http://en.wikipedia.org/wiki/Catamorphism" rel="noreferrer">the Wikipedia article</a> and the first couple posts in <a href="http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!256.entry" rel="noreferrer">the series of the topic for F#</a> on the <em>Inside F#</em> blog. </p> <p>I understand that it's a generalization of folds (i.e., mapping a structure of many values to one value, including a list of values to another list). And I gather that the fold-list and fold-tree is a canonical example.</p> <p>Can this be shown to be done in C#, using LINQ's <code>Aggregate</code> operator or some other higher-order method?</p>
[ { "answer_id": 196309, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": false, "text": "IEnumerable<A> => B Max() Min() Aggregate()" }, { "answer_id": 196451, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 6, "selected": true, "text": "Aggregate() IEnumerables Aggregate() IEnumerables FoldTree Trees using System;\nusing System.Collections.Generic;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Shapes;\n\nclass Tree<T> // use null for Leaf\n{\n public T Data { get; private set; }\n public Tree<T> Left { get; private set; }\n public Tree<T> Right { get; private set; }\n public Tree(T data, Tree<T> left, Tree<T> rright)\n {\n this.Data = data;\n this.Left = left;\n this.Right = right;\n }\n\n public static Tree<T> Node<T>(T data, Tree<T> left, Tree<T> right)\n {\n return new Tree<T>(data, left, right);\n }\n}\n class Tree\n{\n public static Tree<int> Tree7 =\n Node(4, Node(2, Node(1, null, null), Node(3, null, null)),\n Node(6, Node(5, null, null), Node(7, null, null)));\n\n public static R XFoldTree<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> tree)\n {\n return Loop(nodeF, leafV, tree, x => x);\n }\n\n public static R Loop<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> t, Func<R, R> cont)\n {\n if (t == null)\n return cont(leafV(t));\n else\n return Loop(nodeF, leafV, t.Left, lacc =>\n Loop(nodeF, leafV, t.Right, racc =>\n cont(nodeF(t.Data, lacc, racc, t))));\n }\n\n public static R FoldTree<A, R>(Func<A, R, R, R> nodeF, R leafV, Tree<A> tree)\n {\n return XFoldTree((x, l, r, _) => nodeF(x, l, r), _ => leafV, tree);\n }\n\n public static Func<Tree<A>, Tree<A>> XNode<A>(A x, Tree<A> l, Tree<A> r)\n {\n return (Tree<A> t) => x.Equals(t.Data) && l == t.Left && r == t.Right ? t : Node(x, l, r);\n }\n\n // DiffTree: Tree<'a> * Tree<'a> -> Tree<'a * bool> \n // return second tree with extra bool \n // the bool signifies whether the Node \"ReferenceEquals\" the first tree \n public static Tree<KeyValuePair<A, bool>> DiffTree<A>(Tree<A> tree, Tree<A> tree2)\n {\n return XFoldTree((A x, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> l, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> r, Tree<A> t) => (Tree<A> t2) =>\n Node(new KeyValuePair<A, bool>(t2.Data, object.ReferenceEquals(t, t2)),\n l(t2.Left), r(t2.Right)),\n x => y => null, tree)(tree2);\n }\n}\n class Example\n{\n // original version recreates entire tree, yuck \n public static Tree<int> Change5to0(Tree<int> tree)\n {\n return Tree.FoldTree((int x, Tree<int> l, Tree<int> r) => Tree.Node(x == 5 ? 0 : x, l, r), null, tree);\n }\n\n // here it is with XFold - same as original, only with Xs \n public static Tree<int> XChange5to0(Tree<int> tree)\n {\n return Tree.XFoldTree((int x, Tree<int> l, Tree<int> r, Tree<int> orig) =>\n Tree.XNode(x == 5 ? 0 : x, l, r)(orig), _ => null, tree);\n }\n}\n class MyWPFWindow : Window \n{\n void Draw(Canvas canvas, Tree<KeyValuePair<int, bool>> tree)\n {\n // assumes canvas is normalized to 1.0 x 1.0 \n Tree.FoldTree((KeyValuePair<int, bool> kvp, Func<Transform, Transform> l, Func<Transform, Transform> r) => trans =>\n {\n // current node in top half, centered left-to-right \n var tb = new TextBox();\n tb.Width = 100.0; \n tb.Height = 100.0;\n tb.FontSize = 70.0;\n // the tree is a \"diff tree\" where the bool represents \n // \"ReferenceEquals\" differences, so color diffs Red \n tb.Foreground = (kvp.Value ? Brushes.Black : Brushes.Red);\n tb.HorizontalContentAlignment = HorizontalAlignment.Center;\n tb.VerticalContentAlignment = VerticalAlignment.Center;\n tb.RenderTransform = AddT(trans, TranslateT(0.25, 0.0, ScaleT(0.005, 0.005, new TransformGroup())));\n tb.Text = kvp.Key.ToString();\n canvas.Children.Add(tb);\n // left child in bottom-left quadrant \n l(AddT(trans, TranslateT(0.0, 0.5, ScaleT(0.5, 0.5, new TransformGroup()))));\n // right child in bottom-right quadrant \n r(AddT(trans, TranslateT(0.5, 0.5, ScaleT(0.5, 0.5, new TransformGroup()))));\n return null;\n }, _ => null, tree)(new TransformGroup());\n }\n\n public MyWPFWindow(Tree<KeyValuePair<int, bool>> tree)\n {\n var canvas = new Canvas();\n canvas.Width=1.0;\n canvas.Height=1.0;\n canvas.Background = Brushes.Blue;\n canvas.LayoutTransform=new ScaleTransform(200.0, 200.0);\n Draw(canvas, tree);\n this.Content = canvas;\n this.Title = \"MyWPFWindow\";\n this.SizeToContent = SizeToContent.WidthAndHeight;\n }\n TransformGroup AddT(Transform t, TransformGroup tg) { tg.Children.Add(t); return tg; }\n TransformGroup ScaleT(double x, double y, TransformGroup tg) { tg.Children.Add(new ScaleTransform(x,y)); return tg; }\n TransformGroup TranslateT(double x, double y, TransformGroup tg) { tg.Children.Add(new TranslateTransform(x,y)); return tg; }\n\n [STAThread]\n static void Main(string[] args)\n {\n var app = new Application();\n //app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7,Example.Change5to0(Tree.Tree7))));\n app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7, Example.XChange5to0(Tree.Tree7))));\n }\n} \n" }, { "answer_id": 11583895, "author": "Tuomas Hietanen", "author_id": 17791, "author_profile": "https://Stackoverflow.com/users/17791", "pm_score": 2, "selected": false, "text": "public class Node<TData, TLeft, TRight>\n{\n public TLeft Left { get; private set; }\n public TRight Right { get; private set; }\n public TData Data { get; private set; }\n public Node(TData x, TLeft l, TRight r){ Data = x; Left = l; Right = r; }\n}\n public class Tree<T> : Node</* data: */ T, /* left: */ Tree<T>, /* right: */ Tree<T>>\n{\n // Normal node:\n public Tree(T data, Tree<T> left, Tree<T> right): base(data, left, right){}\n // No children:\n public Tree(T data) : base(data, null, null) { }\n}\n public static class TreeExtensions\n{\n private static R Loop<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> t, Func<R, R> cont)\n {\n if (t == null) return cont(leafV(t));\n return Loop(nodeF, leafV, t.Left, lacc =>\n Loop(nodeF, leafV, t.Right, racc =>\n cont(nodeF(t.Data, lacc, racc, t))));\n } \n public static R XAggregateTree<A, R>(this Tree<A> tree, Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV)\n {\n return Loop(nodeF, leafV, tree, x => x);\n }\n\n public static R Aggregate<A, R>(this Tree<A> tree, Func<A, R, R, R> nodeF, R leafV)\n {\n return tree.XAggregateTree((x, l, r, _) => nodeF(x, l, r), _ => leafV);\n }\n}\n [TestMethod] // or Console Application:\nstatic void Main(string[] args)\n{\n // This is our tree:\n // 4 \n // 2 6 \n // 1 3 5 7 \n var tree7 = new Tree<int>(4, new Tree<int>(2, new Tree<int>(1), new Tree<int>(3)),\n new Tree<int>(6, new Tree<int>(5), new Tree<int>(7)));\n\n var sumTree = tree7.Aggregate((x, l, r) => x + l + r, 0);\n Console.WriteLine(sumTree); // 28\n Console.ReadLine();\n\n var inOrder = tree7.Aggregate((x, l, r) =>\n {\n var tmp = new List<int>(l) {x};\n tmp.AddRange(r);\n return tmp;\n }, new List<int>());\n inOrder.ForEach(Console.WriteLine); // 1 2 3 4 5 6 7\n Console.ReadLine();\n\n var heightTree = tree7.Aggregate((_, l, r) => 1 + (l>r?l:r), 0);\n Console.WriteLine(heightTree); // 3\n Console.ReadLine();\n}\n" }, { "answer_id": 21103146, "author": "Polymer", "author_id": 730606, "author_profile": "https://Stackoverflow.com/users/730606", "pm_score": 3, "selected": false, "text": "node class Node {\n public Node Left;\n public Node Right;\n public int value;\n public Node(int v = 0, Node left = null, Node right = null) {\n value = v;\n Left = left;\n Right = right;\n }\n}\n var Tree = \n new Node(4,\n new Node(2, \n new Node(1),\n new Node(3)\n ),\n new Node(6,\n new Node(5),\n new Node(7)\n )\n );\n Node public static R fold<R>(\n Func<int, R, R, R> combine,\n R leaf_value,\n Node tree) {\n\n if (tree == null) return leaf_value;\n\n return \n combine(\n tree.value, \n fold(combine, leaf_value, tree.Left),\n fold(combine, leaf_value, tree.Right)\n );\n}\n public static int Sum_Tree(Node tree){\n if (tree == null) return 0;\n var accumulated = tree.value;\n accumulated += Sum_Tree(tree.Left);\n accumulated += Sum_Tree(tree.Right);\n return accumulated; \n}\n public static int sum_tree_fold(Node tree) {\n return Node.fold(\n (x, l, r) => x + l + r,\n 0,\n tree\n );\n}\n Console.WriteLine(Node.Sum_Tree(Tree)); public static List<int> In_Order_fold(Node tree) {\n return Node.fold(\n (x, l, r) => {\n var tree_list = new List<int>();\n tree_list.Add(x);\n tree_list.InsertRange(0, l);\n tree_list.AddRange(r);\n return tree_list;\n },\n new List<int>(),\n tree\n );\n}\npublic static int Height_fold(Node tree) {\n return Node.fold(\n (x, l, r) => 1 + Math.Max(l, r),\n 0,\n tree\n );\n}\n In_Order_fold In_Order_fold" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
196,302
<p>Since I keep showing up late for answering questions tagged php where i actually know the answer i figured i'd try asking a question myself.</p> <p>I've been working on so many complete rewrites of a custom template engine in php for so long and so many times that i thought i'd ask for opinions.</p> <p>In short, this is the most important part i have implemented so far:</p> <ol> <li>Any http request is routed to handler.php</li> <li>based on the requested URL a controller is instantiated and a method on that controller is called.</li> <li>The controller method must return an <code>IView</code> compatible class instance ( <code>IView</code> defines a <code>Render()</code> method) <ol> <li>The template engine does some xpath for every namespace that ends in 'serverside' <code>sprintf('//%s:*[@runat="server"]', $namespaceprefix )</code></li> <li>For every found tag, it looks up the php class identified by <code>$tag.localName</code> and instantiates one and attaches it to the original template.</li> <li>Once attached, the original template node is fed to the 'ServerTag' so it can initialize properly</li> <li>the fully complete IView compatible instance is assigned to a temporary variable in the controller method. </li> </ol></li> <li>The controller asks pushes data from a Model class to the view which does some nifty xpath DOM replacement.</li> <li>The controller returns the completely filled view to <code>main()</code>the handler, which renders it.</li> </ol> <p>I am basing my template on xml. a simple template currently looks like:</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:red="http://www.theredhead.nl/serverside"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;Title will be filed by the View depending on the Controller&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/" /&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- the entire body may be reset by the view using it, using XPath and DOM functions --&gt; &lt;!-- Usually the PageHeader and PageFooter would be put back after clearing the body --&gt; &lt;div id="PageHeader"&gt; &lt;img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo" /&gt; &lt;/div&gt; &lt;h1&gt;www.theredhead.nl :: Test Template&lt;/h1&gt; &lt;p&gt; Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee. &lt;/p&gt; &lt;div id="PageFooter"&gt; Built by &lt;br /&gt; &lt;red:UserProfileLink runat="server" Username="kris" /&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>At current, this outputs (including the broken indentation):</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:red="http://www.theredhead.nl/serverside"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/&gt; &lt;title&gt;Welcome to my site&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/"/&gt; &lt;link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Custom/"/&gt; &lt;link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Profile/"/&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- the entire body may be reset by the view using it, using XPath and DOM functions --&gt; &lt;!-- Usually the PageHeader and PageFooter would be put back after clearing the body --&gt; &lt;div id="PageHeader"&gt; &lt;img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo"/&gt; &lt;/div&gt; &lt;h1&gt;www.theredhead.nl :: ModelViewController&lt;/h1&gt; &lt;p&gt; Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee. &lt;/p&gt; &lt;div id="PageFooter"&gt; Built by &lt;br/&gt; &lt;div&gt;&lt;div xmlns:profile="http://www.theredhead.nl/profile" class="ProfileBadge" style="font-size : .8em;"&gt; &lt;a style="text-decoration : none; border: none;" href="/Profile/View/kris"&gt; &lt;img style="float : left;" src="http://www.gravatar.com/avatar/5beeab66d6fe021cbd4daa041330cc86?d=identicon&amp;amp;s=32&amp;amp;r=pg" alt="Gravatar"/&gt; &amp;#xA0;Kris &lt;/a&gt; &lt;br/&gt; &lt;small&gt; &amp;#xA0;Rep:&amp;#xA0;1 &lt;/small&gt; &lt;/div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <ul> <li>I've only touched on the tip of the iceberg here and yes, I will be stripping unused xmlns attributes from the output once I'm happy with the functionality</li> <li>there are currently just over 200 classes in my mvc and core frameworks</li> <li>I am aware there are existing solutions that can do similar things, but I want to build my own.</li> </ul> <p>So the big question is: <strong>Do you have any input on must-have functionality?</strong></p> <p>P.S. if anyone is interested in the complete source-code, please leave a comment, I will be providing it on my site when I reach reasonable developer usability levels.</p>
[ { "answer_id": 197119, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 3, "selected": false, "text": "<?php=$variable;?>" }, { "answer_id": 206935, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 1, "selected": false, "text": "<asp:DataGrid> <?php ... ?>" } ]
2008/10/12
[ "https://Stackoverflow.com/questions/196302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18565/" ]
196,326
<p>.NET newbie here... I'd like to make a button in a Windows form that displays a progress or "cooldown" effect. That is, when the button is pressed, it becomes disabled. As some event or timer is progressing, the button shows the progress graphically. When the progress is finished, the graphic completes and the button becomes enabled. Similar effects can be seen in many games.</p> <p>I'd considered using a combination of the built in Button class, and the GDI+ DrawPath function, but the complexity scales poorly, and I get the nagging feeling that there must be an easier way.</p> <p>Any ideas? Thanks.</p>
[ { "answer_id": 196335, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 1, "selected": true, "text": "button += new buttonPaintEvent(buttonPaintEventHandlerMethod);\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3696/" ]
196,329
<p>I'm working on a project in C and it requires memalign(). Really, posix_memalign() would do as well, but darwin/OSX lacks both of them.</p> <p>What is a good solution to shoehorn-in memalign? I don't understand the licensing for posix-C code if I were to rip off memalign.c and put it in my project- I don't want any viral-type licensing LGPL-ing my whole project.</p>
[ { "answer_id": 196361, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "void *aligned_malloc( size_t size, int align )\n{\n void *mem = malloc( size + (align-1) + sizeof(void*) );\n\n char *amem = ((char*)mem) + sizeof(void*);\n amem += align - ((uintptr)amem & (align - 1));\n\n ((void**)amem)[-1] = mem;\n return amem;\n}\n\nvoid aligned_free( void *mem )\n{\n free( ((void**)mem)[-1] );\n}\n" }, { "answer_id": 196394, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "amem += align - ((uintptr)amem & (align - 1));\n" }, { "answer_id": 14575277, "author": "meh", "author_id": 2020294, "author_profile": "https://Stackoverflow.com/users/2020294", "pm_score": 0, "selected": false, "text": "#if defined(_MSC_VER)\n return (TypePtr )_aligned_malloc (theBytesCount, theAlign);\n#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)\n return (TypePtr ) _mm_malloc (theBytesCount, theAlign);\n#elif defined(__BORLANDC__)\n return (TypePtr ) malloc (theBytesCount);\n#else\n void* aPtr;\n if (posix_memalign (&aPtr, theAlign, theBytesCount))\n {\n aPtr = NULL;\n }\n return (TypePtr )aPtr;\n#endif\n __BORLANDC__ __GNUC__ #elif (defined(__BORLANDC__) || defined(__APPLE__)) //now above `__GNUC__`\n" }, { "answer_id": 22876707, "author": "fearless_fool", "author_id": 558639, "author_profile": "https://Stackoverflow.com/users/558639", "pm_score": 4, "selected": false, "text": "posix_memalign() posix_memalign() #include <stdlib.h>\n\nchar *buffer;\nint pagesize;\n\npagesize = sysconf(_SC_PAGE_SIZE);\nif (pagesize == -1) handle_error(\"sysconf\");\n\nif (posix_memalign((void **)&buffer, pagesize, 4 * pagesize) != 0) {\n handle_error(\"posix_memalign\");\n}\n memalign() posix_memalign() **buffer" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17925/" ]
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord" rel="noreferrer"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
[ { "answer_id": 196391, "author": "Vincent Marchetti", "author_id": 8935, "author_profile": "https://Stackoverflow.com/users/8935", "pm_score": 8, "selected": false, "text": "try:\n mystring.decode('ascii')\nexcept UnicodeDecodeError:\n print \"it was not a ascii-encoded unicode string\"\nelse:\n print \"It may have been an ascii-encoded unicode string\"\n" }, { "answer_id": 196392, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 9, "selected": true, "text": "def is_ascii(s):\n return all(ord(c) < 128 for c in s)\n" }, { "answer_id": 198205, "author": "miya", "author_id": 293, "author_profile": "https://Stackoverflow.com/users/293", "pm_score": 3, "selected": false, "text": "import string\n\ndef isAscii(s):\n for c in s:\n if c not in string.ascii_letters:\n return False\n return True\n" }, { "answer_id": 200267, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 4, "selected": false, "text": "ord(u'é') >>> [ord(x) for x in u'é']\n chr() unichr() >>> unichr(233)\nu'\\xe9'\n u'e\\u0301' u'\\u00e9' len(u'e\\u0301') == 2 len(u'\\u00e9') == 1 unicodedata.normalize" }, { "answer_id": 200311, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 2, "selected": false, "text": "str decode" }, { "answer_id": 3296808, "author": "mvknowles", "author_id": 397587, "author_profile": "https://Stackoverflow.com/users/397587", "pm_score": -1, "selected": false, "text": ">> print 'test string'.__class__.__name__\nstr\n>>> print u'test string'.__class__.__name__\nunicode\n>>> \n def is_ascii(input):\n if input.__class__.__name__ == \"str\":\n return True\n return False\n" }, { "answer_id": 6988354, "author": "Alvin", "author_id": 141686, "author_profile": "https://Stackoverflow.com/users/141686", "pm_score": 4, "selected": false, "text": "import chardet\n\nencoding = chardet.detect(string)\nif encoding['encoding'] == 'ascii':\n print 'string is in ascii'\n string_ascii = string.decode(encoding['encoding']).encode('ascii')\n" }, { "answer_id": 12064457, "author": "Max P Magee", "author_id": 727541, "author_profile": "https://Stackoverflow.com/users/727541", "pm_score": 3, "selected": false, "text": "escaped_string = unicode(original_string.encode('ascii','xmlcharrefreplace'))\n # -*- coding: utf-8 -*-\n >>> specials='àéç'\n>>> specials.decode('latin-1').encode('ascii','xmlcharrefreplace')\n'&#224;&#233;&#231;'\n" }, { "answer_id": 17516466, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "try-except TypeErrors >>> ord(\"¶\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: ord() expected a character, but string of length 2 found\n def is_ascii(s):\n try:\n return all(ord(c) < 128 for c in s)\n except TypeError:\n return False\n" }, { "answer_id": 18403812, "author": "far", "author_id": 2044053, "author_profile": "https://Stackoverflow.com/users/2044053", "pm_score": 7, "selected": false, "text": "def isascii(s):\n \"\"\"Check if the characters in string s are in ASCII, U+0-U+7F.\"\"\"\n return len(s) == len(s.encode())\n >>> isascii(\"♥O◘♦♥O◘♦\")\nFalse\n>>> isascii(\"Python\")\nTrue\n" }, { "answer_id": 30392263, "author": "Sergey Nevmerzhitsky", "author_id": 3155344, "author_profile": "https://Stackoverflow.com/users/3155344", "pm_score": 2, "selected": false, "text": "from curses import ascii\n\ndef isascii(s):\n return all(ascii.isascii(c) for c in s)\n" }, { "answer_id": 32357552, "author": "drs", "author_id": 1484957, "author_profile": "https://Stackoverflow.com/users/1484957", "pm_score": 5, "selected": false, "text": "str.decode str.encode try:\n mystring.encode('ascii')\nexcept UnicodeEncodeError:\n pass # string is not ascii\nelse:\n pass # string is ascii\n UnicodeDecodeError UnicodeEncodeError" }, { "answer_id": 32869248, "author": "Roger Dahl", "author_id": 442006, "author_profile": "https://Stackoverflow.com/users/442006", "pm_score": 0, "selected": false, "text": "import re\n\ndef is_ascii(s):\n return bool(re.match(r'[\\x00-\\x7F]+$', s))\n + *" }, { "answer_id": 40309367, "author": "hobs", "author_id": 623735, "author_profile": "https://Stackoverflow.com/users/623735", "pm_score": 1, "selected": false, "text": "find_all match >>> import re\n>>> re.search('[^\\x00-\\x7F]', 'Did you catch that \\x00?') is not None\nFalse\n>>> re.search('[^\\x00-\\x7F]', 'Did you catch that \\xFF?') is not None\nTrue\n" }, { "answer_id": 51141941, "author": "Taku", "author_id": 6622817, "author_profile": "https://Stackoverflow.com/users/6622817", "pm_score": 7, "selected": false, "text": "str bytes bytearray .isascii() print(\"is this ascii?\".isascii())\n# True\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3504/" ]
196,357
<p>In bash shell with emacs key-binding, you can use key combination like M-f, M-b to move one word forward or backward on the shell prompt respectively. Usually, the meta key is mapped to Alt key on Windows and Linux. However, in iTerm, I could not find a way to map this meta key to either Option or Command key on my MacBook Pro.</p> <p>It seems that in OS X, the meta key is by default mapped to ESC key. So you can use ESC-f, ESC-b on iTerm. However, ESC key is apparently not practical to use. In addition, iTerm does have option that allow you to modifier mapping for the meta key (Bookmarks > Profiles > Keyboard Profiles > Global > Option Key as...), this setting does not seem to work at all.</p> <p>Therefore, if anyone know what is the solution to this problem, please let me know. </p> <p>I have upgraded to the latest release, 0.9.6.1012, and this behavior is still persist.</p> <p><strong>Edit:</strong> Some clarification to my question. The key-binding I'm talking about is for bash shell, not in emacs. It just happens that, by default, bash shell also use the same key-binding as emacs.</p>
[ { "answer_id": 197092, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": true, "text": "Profiles Keys General Left Option key: Esc+" }, { "answer_id": 4369714, "author": "ches", "author_id": 455009, "author_profile": "https://Stackoverflow.com/users/455009", "pm_score": 2, "selected": false, "text": "man ascii Opt-Backspace Ctrl-w" }, { "answer_id": 60079965, "author": "Nick D", "author_id": 7837941, "author_profile": "https://Stackoverflow.com/users/7837941", "pm_score": 4, "selected": false, "text": "Profiles Keys Left option Key acts as: +Esc" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27274/" ]
196,382
<p>I see that the SML/NJ includes a queue structure. I can't figure out how to use it. How do I use the additional libraries provided by SML/NJ?</p>
[ { "answer_id": 1070416, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": true, "text": "Queue open Queue." }, { "answer_id": 18422301, "author": "N A", "author_id": 1415760, "author_profile": "https://Stackoverflow.com/users/1415760", "pm_score": 1, "selected": false, "text": "val que = Queue.mkqueue(): int Queue.queue\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013/" ]