qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
255,008
<p>What are the ways by which we can reduce the size of the HTML Response sent by an asp.net application?</p> <p>I am using Controls which are not owned by me and it produces output with white spaces. I am interested in Minifying the entire HTML output of the page just like how google does (View source www.google.com) to improve the timing.</p> <p>Is there any Utility classes available for ASP.NET which can do this stuff for me?</p>
[ { "answer_id": 28692638, "author": "Veverke", "author_id": 1219280, "author_profile": "https://Stackoverflow.com/users/1219280", "pm_score": 2, "selected": false, "text": "@{\n ... \n ...\n // anything\n ...\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30594/" ]
255,019
<p>Is there any way to do the equivalent of the following in a JSP without using scriptlet?</p> <pre><code>&lt;% response.setContentType("text/plain"); %&gt; </code></pre> <p>I can't simply use</p> <p>because I need to set the content-type in 2 places (each in a different branch of a ) and the JSP compiler will only allow one such directive.</p> <p>Also, I can't write two separate JSPs and forward to one or the other in a servlet because the JSP is triggered by the container when an authentication failure occurs.</p> <p>Cheers, Don</p>
[ { "answer_id": 255023, "author": "AlexJReid", "author_id": 32320, "author_profile": "https://Stackoverflow.com/users/32320", "pm_score": 2, "selected": false, "text": "<%@ page language=\"java\" contentType=\"text/plain\" %>\n" }, { "answer_id": 255105, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 2, "selected": false, "text": "<%@tag description=\"put the tag description here\" pageEncoding=\"UTF-8\"%>\n<%@ attribute name=\"mimeType\" required=\"true\"%>\n<%\n response.setContentType(jspContext.findAttribute(\"mimeType\"));\n%>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
255,035
<p>How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.</p>
[ { "answer_id": 255053, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 7, "selected": true, "text": "import time, datetime\n\nd = datetime.datetime.now()\nprint time.mktime(d.timetuple())\n" }, { "answer_id": 5872022, "author": "fixermark", "author_id": 57720, "author_profile": "https://Stackoverflow.com/users/57720", "pm_score": 5, "selected": false, "text": "calendar.timegm" }, { "answer_id": 14369386, "author": "gnu_lorien", "author_id": 1609543, "author_profile": "https://Stackoverflow.com/users/1609543", "pm_score": 2, "selected": false, "text": "import time, datetime\n\nposix_now = time.time()\n\nd = datetime.datetime.fromtimestamp(posix_now)\nno_microseconds_time = time.mktime(d.timetuple())\nhas_microseconds_time = time.mktime(d.timetuple()) + d.microsecond * 0.000001\n\nprint posix_now\nprint no_microseconds_time\nprint has_microseconds_time\n" }, { "answer_id": 47007272, "author": "Clément", "author_id": 695591, "author_profile": "https://Stackoverflow.com/users/695591", "pm_score": 4, "selected": false, "text": "datetime" }, { "answer_id": 58055713, "author": "vishal", "author_id": 8588108, "author_profile": "https://Stackoverflow.com/users/8588108", "pm_score": 0, "selected": false, "text": "this_time = datetime.datetime.utcnow() # datetime.datetime type\nepoch_time = this_time.timestamp() # posix time or epoch time\nthis_time = datetime.datetime.fromtimestamp(epoch_time)\n" }, { "answer_id": 64886073, "author": "Marc", "author_id": 2128265, "author_profile": "https://Stackoverflow.com/users/2128265", "pm_score": 0, "selected": false, "text": "from datetime import datetime, timezone\naware_date = datetime.now(tz=timezone.utc)\nposix_timestamp = aware_date.timestamp()\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
255,041
<p>Is there some way I can define <code>String[int]</code> to avoid using <code>String.CharAt(int)</code>?</p>
[ { "answer_id": 255046, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 5, "selected": true, "text": "operator*" }, { "answer_id": 255051, "author": "Lee Kowalkowski", "author_id": 30945, "author_profile": "https://Stackoverflow.com/users/30945", "pm_score": 4, "selected": false, "text": "var newArray = oldString.split(''); \n" }, { "answer_id": 255064, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "\"TEST\"[1]; // = E\n" }, { "answer_id": 255796, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 0, "selected": false, "text": "String.prototype.toChars = function() {\n for (var i=0; i<this.length; i++) {\n this[i+\"\"] = this.charAt(i);\n }\n};\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4435/" ]
255,056
<p>I have a standard .NET windows service written in C#.</p> <p>Can it install itself without using InstallUtil? Should I use the service installer class? How should I use it?</p> <p>I want to be able to call the following:</p> <pre><code>MyService.exe -install </code></pre> <p>And it will have the same effect as calling:</p> <pre><code>InstallUtil MyService.exe </code></pre>
[ { "answer_id": 255062, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "[RunInstaller(true)]\npublic sealed class MyServiceInstallerProcess : ServiceProcessInstaller\n{\n public MyServiceInstallerProcess()\n {\n this.Account = ServiceAccount.NetworkService;\n }\n}\n\n[RunInstaller(true)]\npublic sealed class MyServiceInstaller : ServiceInstaller\n{\n public MyServiceInstaller()\n {\n this.Description = \"Service Description\";\n this.DisplayName = \"Service Name\";\n this.ServiceName = \"ServiceName\";\n this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;\n }\n}\n\nstatic void Install(bool undo, string[] args)\n{\n try\n {\n Console.WriteLine(undo ? \"uninstalling\" : \"installing\");\n using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))\n {\n IDictionary state = new Hashtable();\n inst.UseNewContext = true;\n try\n {\n if (undo)\n {\n inst.Uninstall(state);\n }\n else\n {\n inst.Install(state);\n inst.Commit(state);\n }\n }\n catch\n {\n try\n {\n inst.Rollback(state);\n }\n catch { }\n throw;\n }\n }\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine(ex.Message);\n }\n}\n" }, { "answer_id": 255097, "author": "Brad Bruce", "author_id": 5008, "author_profile": "https://Stackoverflow.com/users/5008", "pm_score": 3, "selected": false, "text": " IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();\n Inst.Install(\"MySvc\", \"My Sample Service\", \"Service that executes something\",\n _InstanceID,\n// System.ServiceProcess.ServiceAccount.LocalService, // this is more secure, but only available in XP and above and WS-2003 and above\n System.ServiceProcess.ServiceAccount.LocalSystem, // this is required for WS-2000\n System.ServiceProcess.ServiceStartMode.Automatic);\n if (controller == null)\n {\n controller = new System.ServiceProcess.ServiceController(String.Format(\"MySvc_{0}\", _InstanceID), \".\");\n }\n if (controller.Status == System.ServiceProcess.ServiceControllerStatus.Running)\n {\n Start_Stop.Text = \"Stop Service\";\n Start_Stop_Debugging.Enabled = false;\n }\n else\n {\n Start_Stop.Text = \"Start Service\";\n Start_Stop_Debugging.Enabled = true;\n }\n" }, { "answer_id": 1015502, "author": "adrianbanks", "author_id": 116923, "author_profile": "https://Stackoverflow.com/users/116923", "pm_score": 5, "selected": false, "text": "string[] args;\nManagedInstallerClass.InstallHelper(args);\n" }, { "answer_id": 1812537, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 4, "selected": false, "text": "OpenSCManager" }, { "answer_id": 30650205, "author": "Kraang Prime", "author_id": 3504007, "author_profile": "https://Stackoverflow.com/users/3504007", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nusing System.ServiceProcess;\nusing System.Runtime.InteropServices;\n\nnamespace SystemControl {\n class Services {\n\n#region \"Environment Variables\"\n public static string GetEnvironment(string name, bool ExpandVariables=true) {\n if ( ExpandVariables ) {\n return System.Environment.GetEnvironmentVariable( name );\n } else {\n return (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey( @\"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\\\" ).GetValue( name, \"\", Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames );\n }\n }\n\n public static void SetEnvironment( string name, string value ) {\n System.Environment.SetEnvironmentVariable(name, value);\n }\n#endregion\n\n#region \"ServiceCalls Native\"\n public static ServiceController[] List { get { return ServiceController.GetServices(); } }\n\n public static void Start( string serviceName, int timeoutMilliseconds ) {\n ServiceController service=new ServiceController( serviceName );\n try {\n TimeSpan timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds );\n\n service.Start();\n service.WaitForStatus( ServiceControllerStatus.Running, timeout );\n } catch {\n // ...\n }\n }\n\n public static void Stop( string serviceName, int timeoutMilliseconds ) {\n ServiceController service=new ServiceController( serviceName );\n try {\n TimeSpan timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds );\n\n service.Stop();\n service.WaitForStatus( ServiceControllerStatus.Stopped, timeout );\n } catch {\n // ...\n }\n }\n\n public static void Restart( string serviceName, int timeoutMilliseconds ) {\n ServiceController service=new ServiceController( serviceName );\n try {\n int millisec1=Environment.TickCount;\n TimeSpan timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds );\n\n service.Stop();\n service.WaitForStatus( ServiceControllerStatus.Stopped, timeout );\n\n // count the rest of the timeout\n int millisec2=Environment.TickCount;\n timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds-( millisec2-millisec1 ) );\n\n service.Start();\n service.WaitForStatus( ServiceControllerStatus.Running, timeout );\n } catch {\n // ...\n }\n }\n\n public static bool IsInstalled( string serviceName ) {\n // get list of Windows services\n ServiceController[] services=ServiceController.GetServices();\n\n // try to find service name\n foreach ( ServiceController service in services ) {\n if ( service.ServiceName==serviceName )\n return true;\n }\n return false;\n }\n#endregion\n\n#region \"ServiceCalls API\"\n private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;\n private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;\n\n [Flags]\n public enum ServiceManagerRights {\n Connect = 0x0001,\n CreateService = 0x0002,\n EnumerateService = 0x0004,\n Lock = 0x0008,\n QueryLockStatus = 0x0010,\n ModifyBootConfig = 0x0020,\n StandardRightsRequired = 0xF0000,\n AllAccess = (StandardRightsRequired | Connect | CreateService |\n EnumerateService | Lock | QueryLockStatus | ModifyBootConfig)\n }\n\n [Flags]\n public enum ServiceRights {\n QueryConfig = 0x1,\n ChangeConfig = 0x2,\n QueryStatus = 0x4,\n EnumerateDependants = 0x8,\n Start = 0x10,\n Stop = 0x20,\n PauseContinue = 0x40,\n Interrogate = 0x80,\n UserDefinedControl = 0x100,\n Delete = 0x00010000,\n StandardRightsRequired = 0xF0000,\n AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig |\n QueryStatus | EnumerateDependants | Start | Stop | PauseContinue |\n Interrogate | UserDefinedControl)\n }\n\n public enum ServiceBootFlag {\n Start = 0x00000000,\n SystemStart = 0x00000001,\n AutoStart = 0x00000002,\n DemandStart = 0x00000003,\n Disabled = 0x00000004\n }\n\n public enum ServiceState {\n Unknown = -1, // The state cannot be (has not been) retrieved.\n NotFound = 0, // The service is not known on the host server.\n Stop = 1, // The service is NET stopped.\n Run = 2, // The service is NET started.\n Stopping = 3,\n Starting = 4,\n }\n\n public enum ServiceControl {\n Stop = 0x00000001,\n Pause = 0x00000002,\n Continue = 0x00000003,\n Interrogate = 0x00000004,\n Shutdown = 0x00000005,\n ParamChange = 0x00000006,\n NetBindAdd = 0x00000007,\n NetBindRemove = 0x00000008,\n NetBindEnable = 0x00000009,\n NetBindDisable = 0x0000000A\n }\n\n public enum ServiceError {\n Ignore = 0x00000000,\n Normal = 0x00000001,\n Severe = 0x00000002,\n Critical = 0x00000003\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private class SERVICE_STATUS {\n public int dwServiceType = 0;\n public ServiceState dwCurrentState = 0;\n public int dwControlsAccepted = 0;\n public int dwWin32ExitCode = 0;\n public int dwServiceSpecificExitCode = 0;\n public int dwCheckPoint = 0;\n public int dwWaitHint = 0;\n }\n\n [DllImport(\"advapi32.dll\", EntryPoint = \"OpenSCManagerA\")]\n private static extern IntPtr OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerRights dwDesiredAccess);\n [DllImport(\"advapi32.dll\", EntryPoint = \"OpenServiceA\", CharSet = CharSet.Ansi)]\n private static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess);\n [DllImport(\"advapi32.dll\", EntryPoint = \"CreateServiceA\")]\n private static extern IntPtr CreateService(IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword);\n [DllImport(\"advapi32.dll\")]\n private static extern int CloseServiceHandle(IntPtr hSCObject);\n [DllImport(\"advapi32.dll\")]\n private static extern int QueryServiceStatus(IntPtr hService, SERVICE_STATUS lpServiceStatus);\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int DeleteService(IntPtr hService);\n [DllImport(\"advapi32.dll\")]\n private static extern int ControlService(IntPtr hService, ServiceControl dwControl, SERVICE_STATUS lpServiceStatus);\n [DllImport(\"advapi32.dll\", EntryPoint = \"StartServiceA\")]\n private static extern int StartService(IntPtr hService, int dwNumServiceArgs, int lpServiceArgVectors);\n\n /// <summary>\n /// Takes a service name and tries to stop and then uninstall the windows serviceError\n /// </summary>\n /// <param name=\"ServiceName\">The windows service name to uninstall</param>\n public static void Uninstall(string ServiceName)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr service = OpenService(scman, ServiceName, ServiceRights.StandardRightsRequired | ServiceRights.Stop | ServiceRights.QueryStatus);\n if (service == IntPtr.Zero)\n {\n throw new ApplicationException(\"Service not installed.\");\n }\n try\n {\n StopService(service);\n int ret = DeleteService(service);\n if (ret == 0)\n {\n int error = Marshal.GetLastWin32Error();\n throw new ApplicationException(\"Could not delete service \" + error);\n }\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Accepts a service name and returns true if the service with that service name exists\n /// </summary>\n /// <param name=\"ServiceName\">The service name that we will check for existence</param>\n /// <returns>True if that service exists false otherwise</returns>\n public static bool ServiceIsInstalled(string ServiceName)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr service = OpenService(scman, ServiceName,\n ServiceRights.QueryStatus);\n if (service == IntPtr.Zero) return false;\n CloseServiceHandle(service);\n return true;\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Takes a service name, a service display name and the path to the service executable and installs / starts the windows service.\n /// </summary>\n /// <param name=\"ServiceName\">The service name that this service will have</param>\n /// <param name=\"DisplayName\">The display name that this service will have</param>\n /// <param name=\"FileName\">The path to the executable of the service</param>\n public static void InstallAndStart(string ServiceName, string DisplayName,\n string FileName)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect |\n ServiceManagerRights.CreateService);\n try\n {\n IntPtr service = OpenService(scman, ServiceName,\n ServiceRights.QueryStatus | ServiceRights.Start);\n if (service == IntPtr.Zero)\n {\n service = CreateService(scman, ServiceName, DisplayName,\n ServiceRights.QueryStatus | ServiceRights.Start, SERVICE_WIN32_OWN_PROCESS,\n ServiceBootFlag.AutoStart, ServiceError.Normal, FileName, null, IntPtr.Zero,\n null, null, null);\n }\n if (service == IntPtr.Zero)\n {\n throw new ApplicationException(\"Failed to install service.\");\n }\n try\n {\n StartService(service);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Takes a service name and starts it\n /// </summary>\n /// <param name=\"Name\">The service name</param>\n public static void StartService(string Name)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr hService = OpenService(scman, Name, ServiceRights.QueryStatus |\n ServiceRights.Start);\n if (hService == IntPtr.Zero)\n {\n throw new ApplicationException(\"Could not open service.\");\n }\n try\n {\n StartService(hService);\n }\n finally\n {\n CloseServiceHandle(hService);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Stops the provided windows service\n /// </summary>\n /// <param name=\"Name\">The service name that will be stopped</param>\n public static void StopService(string Name)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr hService = OpenService(scman, Name, ServiceRights.QueryStatus |\n ServiceRights.Stop);\n if (hService == IntPtr.Zero)\n {\n throw new ApplicationException(\"Could not open service.\");\n }\n try\n {\n StopService(hService);\n }\n finally\n {\n CloseServiceHandle(hService);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Stars the provided windows service\n /// </summary>\n /// <param name=\"hService\">The handle to the windows service</param>\n private static void StartService(IntPtr hService)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n StartService(hService, 0, 0);\n WaitForServiceStatus(hService, ServiceState.Starting, ServiceState.Run);\n }\n\n /// <summary>\n /// Stops the provided windows service\n /// </summary>\n /// <param name=\"hService\">The handle to the windows service</param>\n private static void StopService(IntPtr hService)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n ControlService(hService, ServiceControl.Stop, status);\n WaitForServiceStatus(hService, ServiceState.Stopping, ServiceState.Stop);\n }\n\n /// <summary>\n /// Takes a service name and returns the <code>ServiceState</code> of the corresponding service\n /// </summary>\n /// <param name=\"ServiceName\">The service name that we will check for his <code>ServiceState</code></param>\n /// <returns>The ServiceState of the service we wanted to check</returns>\n public static ServiceState GetServiceStatus(string ServiceName)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr hService = OpenService(scman, ServiceName,\n ServiceRights.QueryStatus);\n if (hService == IntPtr.Zero)\n {\n return ServiceState.NotFound;\n }\n try\n {\n return GetServiceStatus(hService);\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Gets the service state by using the handle of the provided windows service\n /// </summary>\n /// <param name=\"hService\">The handle to the service</param>\n /// <returns>The <code>ServiceState</code> of the service</returns>\n private static ServiceState GetServiceStatus(IntPtr hService)\n {\n SERVICE_STATUS ssStatus = new SERVICE_STATUS();\n if (QueryServiceStatus(hService, ssStatus) == 0)\n {\n throw new ApplicationException(\"Failed to query service status.\");\n }\n return ssStatus.dwCurrentState;\n }\n\n /// <summary>\n /// Returns true when the service status has been changes from wait status to desired status\n /// ,this method waits around 10 seconds for this operation.\n /// </summary>\n /// <param name=\"hService\">The handle to the service</param>\n /// <param name=\"WaitStatus\">The current state of the service</param>\n /// <param name=\"DesiredStatus\">The desired state of the service</param>\n /// <returns>bool if the service has successfully changed states within the allowed timeline</returns>\n private static bool WaitForServiceStatus(IntPtr hService, ServiceState\n WaitStatus, ServiceState DesiredStatus)\n {\n SERVICE_STATUS ssStatus = new SERVICE_STATUS();\n int dwOldCheckPoint;\n int dwStartTickCount;\n\n QueryServiceStatus(hService, ssStatus);\n if (ssStatus.dwCurrentState == DesiredStatus) return true;\n dwStartTickCount = Environment.TickCount;\n dwOldCheckPoint = ssStatus.dwCheckPoint;\n\n while (ssStatus.dwCurrentState == WaitStatus)\n {\n // Do not wait longer than the wait hint. A good interval is\n // one tenth the wait hint, but no less than 1 second and no\n // more than 10 seconds.\n\n int dwWaitTime = ssStatus.dwWaitHint / 10;\n\n if (dwWaitTime < 1000) dwWaitTime = 1000;\n else if (dwWaitTime > 10000) dwWaitTime = 10000;\n\n System.Threading.Thread.Sleep(dwWaitTime);\n\n // Check the status again.\n\n if (QueryServiceStatus(hService, ssStatus) == 0) break;\n\n if (ssStatus.dwCheckPoint > dwOldCheckPoint)\n {\n // The service is making progress.\n dwStartTickCount = Environment.TickCount;\n dwOldCheckPoint = ssStatus.dwCheckPoint;\n }\n else\n {\n if (Environment.TickCount - dwStartTickCount > ssStatus.dwWaitHint)\n {\n // No progress made within the wait hint\n break;\n }\n }\n }\n return (ssStatus.dwCurrentState == DesiredStatus);\n }\n\n /// <summary>\n /// Opens the service manager\n /// </summary>\n /// <param name=\"Rights\">The service manager rights</param>\n /// <returns>the handle to the service manager</returns>\n private static IntPtr OpenSCManager(ServiceManagerRights Rights)\n {\n IntPtr scman = OpenSCManager(null, null, Rights);\n if (scman == IntPtr.Zero)\n {\n throw new ApplicationException(\"Could not connect to service control manager.\");\n }\n return scman;\n }\n\n#endregion\n\n }\n}\n" }, { "answer_id": 45245815, "author": "Mansoor", "author_id": 4240382, "author_profile": "https://Stackoverflow.com/users/4240382", "pm_score": -1, "selected": false, "text": "Process QProc = new Process();\nQProc.StartInfo.FileName = \"cmd\";\nQProc.StartInfo.Arguments =\"/c InstallUtil \"+ \"\\\"\"+ filefullPath +\"\\\"\";\nQProc.StartInfo.WorkingDirectory = Environment.GetEnvironmentVariable(\"windir\") + @\"\\Microsoft.NET\\Framework\\v2.0.50727\\\";\nQProc.StartInfo.UseShellExecute = false;\n// QProc.StartInfo.CreateNoWindow = true;\nQProc.StartInfo.RedirectStandardOutput = true;\nQProc.Start();\n// QProc.WaitForExit();\nQProc.Close();\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20257/" ]
255,063
<p>Would there a more elegant way of writing the following syntax? </p> <pre><code> Thread t0 = new Thread(new ParameterizedThreadStart(doWork)); t0.Start('someVal'); t0.Join(); Thread t1 = new Thread(new ParameterizedThreadStart(doWork)); t1.Start('someDiffVal'); t1.Join(); </code></pre> <p>Presuming we want to pass 20 different values, what would the best way of setting this up be? Looping through and joining at the end?</p> <p>If a new thread isn't instantiated (like below), it errors that the thread can't be restarted. For example:</p> <pre><code> Thread t1 = new Thread(new ParameterizedThreadStart(doWork)); t1.Start('someVal'); t1.Start('someDiffVal'); </code></pre>
[ { "answer_id": 255072, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "List<Thread> threads = new List<Thread>();\n\nforeach (string item in items)\n{\n string copy = item; // Important due to variable capture\n ThreadStart ts = () => DoWork(copy); // Strongly typed :)\n Thread t = new Thread(ts);\n t.Start();\n threads.Add(t);\n}\n\nforeach (Thread t in threads)\n{\n t.Join();\n}\n" }, { "answer_id": 255084, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "Parallel.ForEach" }, { "answer_id": 255111, "author": "mmr", "author_id": 21981, "author_profile": "https://Stackoverflow.com/users/21981", "pm_score": 0, "selected": false, "text": "class GonnaDoSomeThreading {\n private Object mBlockLock = new Object();\n private MyParameterBlock mBlock;\n public MyParameterBlock Block {\n get { \n MyParameterBlock tmp;\n lock (mBlockLock){\n tmp = new MyParameterBlock(mBlock); //or some other cloning\n }\n return tmp; //use a tmp in order to make sure that modifications done\n //do not modify the block directly, but that modifications must\n //be 'committed' through the set function\n }\n set { lock (mBlockLock){ mBlock = value; } } \n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30649/" ]
255,071
<p>I've been tasked with implementing a Date/Time selector for several areas of our web project, and instructed to use a control that another developer created as part of it. The control I'm working on is supposed to allow the user to choose a date from a calendar, choose a format for the display of that date (from several pre-defined formats, or with a simple text override) and optionally a time string (which is really just freeform text).</p> <p>The control I was instructed to use is documented here: <a href="http://www.west-wind.com/WebLog/posts/213015.aspx" rel="nofollow noreferrer">http://www.west-wind.com/WebLog/posts/213015.aspx</a>, and uses the DatePicker from jQuery.</p> <p>After I implemented my control and tested it, I began integrating it into the pages which needed Date and/or time inputs. In my testing of those implementations, I discovered a bug: when I include multiple copies of my control on a page, only the first one gets the jQuery calendar. The others are not tied to it.</p> <p>I have tried some of the methods suggested in a seemingly-related question (titled 'duplicating jquery datepicker'), such as calling the '.datepicker()' function on the west-wind control (which renders a textbox) via the $("css-selector").datepicker() syntax, and ASP.NET is guaranteeing unique IDs for all the text boxes.</p> <p>So, in summation, it looks like this:</p> <pre><code>&lt;page&gt; &lt;mycontrol&gt; &lt;west-windjQuerycontrol /&gt; &lt;/mycontrol&gt; &lt;mycontrol&gt; &lt;west-windjQuerycontrol /&gt; &lt;/mycontrol&gt; &lt;/page&gt; </code></pre> <p>Now, the strange part: When there are multiple copies of the west-wind control on the page, without the other user control containing them, they work correctly. Other than the jQuery control, my control has nothing unusual about it: simply labels, textboxes, panels, and dropdowns. Something about bundling the West-Wind jQuery control into a user control seems to be breaking it.</p> <p>Any advice? I've been banging my head against this for a while, hampered by my poor javascript skills and limited exposure to jQuery.</p> <p>As pointed out below, it's hard to say without the HTML. I've included it below.</p> <pre><code>&lt;form name="form1" method="post" action="ControlTest.aspx" id="form1"&gt; &lt;div&gt; &lt;input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /&gt; &lt;input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /&gt; &lt;input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" /&gt; &lt;input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTU4NjEzMDEwOQ9kFgICAw9kFgQCAw9kFgRmD2QWAgIDD2QWAgIDDxBkZBYBZmQCAg9kFgICAw9kFgICAQ8QZGQWAWZkAgUPZBYEZg9kFgICAw9kFgICAw8QZGQWAWZkAgIPZBYCAgMPZBYCAgEPEGRkFgFmZGRDjfLpdb+XxaVaQYP2XkPil2Galw==" /&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; //&lt;![CDATA[ var theForm = document.forms['form1']; if (!theForm) { theForm = document.form1; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]&gt; &lt;/script&gt; &lt;script src="/SSO/DE/WebResource.axd?d=jMPpL-KK8_mPj_ssZzGblw2&amp;amp;t=633481894229838141" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="/SSO/DE/ScriptResource.axd?d=8KwRIGaNAD3hi2Loz3YV-uxgrdZpGe8nnwH5E3gxLW_lQpnYjRbyIYThTnHtD9rt0&amp;amp;t=633613004148118290" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="/SSO/DE/ScriptResource.axd?d=8KwRIGaNAD3hi2Loz3YV-uxgrdZpGe8nnwH5E3gxLW-K0Kuw-pGK1O3mE_r1y3sjKmhHtQjSXeMtYSim0bjyGA2&amp;amp;t=633613004148118290" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="/SSO/DE/ScriptResource.axd?d=Id5yAacLMZHF7TWlkgrrid30ZStmsXuLHcF6WQ404YLySP4Itj4qxv2wi9ffbsWQA86oLdnZPWkwDnu4NKxfG1Ue7qdGG1SbOfb4ooHVs7M1&amp;amp;t=633481957084709567" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; //&lt;![CDATA[ if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.'); //]]&gt; &lt;/script&gt; &lt;script src="/SSO/DE/ScriptResource.axd?d=Id5yAacLMZHF7TWlkgrrid30ZStmsXuLHcF6WQ404YLySP4Itj4qxv2wi9ffbsWQhT3MFELBAa2rFJZXnSlYAZIN7RT1npcBxJRsWGjJWIwTF0Es1m0vOd-xYnFqWJKz0&amp;amp;t=633481957084709567" type="text/javascript"&gt;&lt;/script&gt; &lt;div style="margin:25px 10px;width:100%;"&gt; &lt;script type="text/javascript"&gt; //&lt;![CDATA[ Sys.WebForms.PageRequestManager._initialize('stupidThing', document.getElementById('form1')); Sys.WebForms.PageRequestManager.getInstance()._updateControls([], [], [], 90); //]]&gt; &lt;/script&gt; &lt;div id="datePicker_Div0" class="AdminRowOdd DERow"&gt; &lt;div id="datePicker_Div1" class="DELabel"&gt; &lt;span id="datePicker_DateLabel"&gt;Date&lt;/span&gt; &lt;/div&gt; &lt;div id="datePicker_Div2" class="DEInput datePicker"&gt; &lt;input name="datePicker$DateSelector" type="text" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateSelector\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="datePicker_DateSelector" style="width:80px;" /&gt; &lt;select name="datePicker$languageSelector" onchange="javascript:setTimeout('__doPostBack(\'datePicker$languageSelector\',\'\')', 0)" id="datePicker_languageSelector"&gt; &lt;option selected="selected" value="en-US"&gt;en-US&lt;/option&gt; &lt;option value="fr-CA"&gt;fr-CA&lt;/option&gt; &lt;option value="fr-FR"&gt;fr-FR&lt;/option&gt; &lt;option value="es-ES"&gt;es-ES&lt;/option&gt; &lt;option value="es-MX"&gt;es-MX&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="datePicker_Div3" class="AdminRowEven DERow"&gt; &lt;div id="datePicker_Div4" class="DELabel"&gt; &lt;span id="datePicker_FormatChoiceLabel"&gt;Choose your display format: &lt;/span&gt; &lt;/div&gt; &lt;div id="datePicker_Div5" class="DEInput"&gt; &lt;select name="datePicker$DateFormatSelector" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateFormatSelector\',\'\')', 0)" id="datePicker_DateFormatSelector"&gt; &lt;option selected="selected" value="Choose a date first"&gt;Choose a date first&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="datePicker_Div6" class="AdminRowOdd DERow"&gt; &lt;div id="datePicker_Div7" class="DELabel"&gt; &lt;span id="datePicker_FormatOverrideLabel"&gt;Or enter your own text&lt;/span&gt; &lt;/div&gt; &lt;div id="datePicker_Div8" class="DEInput"&gt; &lt;input name="datePicker$DateFormatOverride" type="text" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateFormatOverride\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="datePicker_DateFormatOverride" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;br /&gt; &lt;div id="date1_Div0" class="AdminRowOdd DERow"&gt; &lt;div id="date1_Div1" class="DELabel"&gt; &lt;span id="date1_DateLabel"&gt;Date&lt;/span&gt; &lt;/div&gt; &lt;div id="date1_Div2" class="DEInput datePicker"&gt; &lt;input name="date1$DateSelector" type="text" onchange="javascript:setTimeout('__doPostBack(\'date1$DateSelector\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="date1_DateSelector" style="width:80px;" /&gt; &lt;select name="date1$languageSelector" onchange="javascript:setTimeout('__doPostBack(\'date1$languageSelector\',\'\')', 0)" id="date1_languageSelector"&gt; &lt;option selected="selected" value="en-US"&gt;en-US&lt;/option&gt; &lt;option value="fr-CA"&gt;fr-CA&lt;/option&gt; &lt;option value="fr-FR"&gt;fr-FR&lt;/option&gt; &lt;option value="es-ES"&gt;es-ES&lt;/option&gt; &lt;option value="es-MX"&gt;es-MX&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="date1_Div3" class="AdminRowEven DERow"&gt; &lt;div id="date1_Div4" class="DELabel"&gt; &lt;span id="date1_FormatChoiceLabel"&gt;Choose your display format:&lt;/span&gt; &lt;/div&gt; &lt;div id="date1_Div5" class="DEInput"&gt; &lt;select name="date1$DateFormatSelector" onchange="javascript:setTimeout('__doPostBack(\'date1$DateFormatSelector\',\'\')', 0)" id="date1_DateFormatSelector"&gt; &lt;option selected="selected" value="Choose a date first"&gt;Choose a date first&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="date1_Div6" class="AdminRowOdd DERow"&gt; &lt;div id="date1_Div7" class="DELabel"&gt; &lt;span id="date1_FormatOverrideLabel"&gt;Or enter your own text&lt;/span&gt; &lt;/div&gt; &lt;div id="date1_Div8" class="DEInput"&gt; &lt;input name="date1$DateFormatOverride" type="text" onchange="javascript:setTimeout('__doPostBack(\'date1$DateFormatOverride\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="date1_DateFormatOverride" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWFQLr6MeTCwKb1Zr0AwKVt6utCQKIwaTjAQKdwYzzBwLiwsDhDQKIwdCLBAKHwbCtCgLRr42cCQKi9vj4DgK2lM6kBQLLrsUtAsaboRMC2+2u3QgCzu2GzQ4Cse7K3wQC2+3atQ0C1O26kwMCpdTivwwC1o2X2wsCoubqnQk8I1BK30Q/iVw/rExUww2Cs4bicw==" /&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; //&lt;![CDATA[ jQuery(document).ready( function() { var cal = jQuery('#datePicker_DateSelector').datepicker({yearRange: '-1500:+100',dateFormat: 'm/d/yy'}); } ); Sys.Application.initialize(); //]]&gt; &lt;/script&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 255072, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "List<Thread> threads = new List<Thread>();\n\nforeach (string item in items)\n{\n string copy = item; // Important due to variable capture\n ThreadStart ts = () => DoWork(copy); // Strongly typed :)\n Thread t = new Thread(ts);\n t.Start();\n threads.Add(t);\n}\n\nforeach (Thread t in threads)\n{\n t.Join();\n}\n" }, { "answer_id": 255084, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "Parallel.ForEach" }, { "answer_id": 255111, "author": "mmr", "author_id": 21981, "author_profile": "https://Stackoverflow.com/users/21981", "pm_score": 0, "selected": false, "text": "class GonnaDoSomeThreading {\n private Object mBlockLock = new Object();\n private MyParameterBlock mBlock;\n public MyParameterBlock Block {\n get { \n MyParameterBlock tmp;\n lock (mBlockLock){\n tmp = new MyParameterBlock(mBlock); //or some other cloning\n }\n return tmp; //use a tmp in order to make sure that modifications done\n //do not modify the block directly, but that modifications must\n //be 'committed' through the set function\n }\n set { lock (mBlockLock){ mBlock = value; } } \n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23902/" ]
255,077
<p>I have just installed VMWare Server 2.0 on a fresh Fedora Core 8 install. The ports for the web access console of VMWare are 8222 and 8333 (like the defaults).</p> <p>When I try a remote http access to myserver:8222 it fails. But when I run</p> <pre><code>/sbin/service iptables stop </code></pre> <p>access becomes possibles (although not very satisfactory). Thus, I have updated the conf file as follow</p> <pre><code>cat /etc/sysconfig/iptables # Firewall configuration written by system-config-firewall # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] :RH-Firewall-1-INPUT - [0:0] -A INPUT -j RH-Firewall-1-INPUT -A RH-Firewall-1-INPUT -i lo -j ACCEPT -A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT -A RH-Firewall-1-INPUT -p 50 -j ACCEPT -A RH-Firewall-1-INPUT -p 51 -j ACCEPT -A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT -A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT -A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT -A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited # Custom authorization for VMWare administration -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8222 -j ACCEPT -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8333 -j ACCEPT COMMIT </code></pre> <p>yet, even after reloading the iptables settings it's still not working. Do anyone knows what I am doing wrong?</p>
[ { "answer_id": 255331, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": true, "text": "-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT\n# Custom authorization for VMWare administration\n-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8222 -j LOG --log-prefix=\"8222 \"\n-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8222 -j ACCEPT\n-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8333 -j LOG --log-prefix=\"8333 \"\n-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8333 -j ACCEPT\n-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited\n-A FORWARD -j REJECT --reject-with icmp-host-prohibited\nCOMMIT\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18858/" ]
255,078
<p>What's the difference between a string and a symbol in Ruby and when should I use one over the other?</p>
[ { "answer_id": 255099, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 8, "selected": true, "text": "irb(main):007:0> :test.object_id\n=> 83618\nirb(main):008:0> :test.object_id\n=> 83618\nirb(main):009:0> :test.object_id\n=> 83618\n" }, { "answer_id": 255909, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 3, "selected": false, "text": "String" }, { "answer_id": 23358644, "author": "Feuda", "author_id": 642616, "author_profile": "https://Stackoverflow.com/users/642616", "pm_score": 4, "selected": false, "text": "split" }, { "answer_id": 38193530, "author": "Leo Le", "author_id": 2001053, "author_profile": "https://Stackoverflow.com/users/2001053", "pm_score": 2, "selected": false, "text": "puts \"abc\".object_id # 70322858612020\nputs \"abc\".object_id # 70322846847380\nputs \"abc\".object_id # 70322846815460\n" }, { "answer_id": 39518834, "author": "Nitin9791", "author_id": 2873883, "author_profile": "https://Stackoverflow.com/users/2873883", "pm_score": 3, "selected": false, "text": "foo = \"bar\"\n" }, { "answer_id": 54203941, "author": "Chimed Palden", "author_id": 4110918, "author_profile": "https://Stackoverflow.com/users/4110918", "pm_score": 2, "selected": false, "text": "params.map(&:to_sym)" }, { "answer_id": 68827126, "author": "Abhishek Tanwar", "author_id": 15002139, "author_profile": "https://Stackoverflow.com/users/15002139", "pm_score": 0, "selected": false, "text": "x = \"hello\"\np x => \"hello\"\np :x => :x\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
255,081
<p>I have a situation where another developer is including source files from a project that I maintain in a project that he maintains. The nature of the files is such that each source file registers a "command" in an interpretive environment so all you have to do is link in a new source file to register a new "command". We can't put these files in a static library because, unless the project makes explicit reference to the symbols in the file, the linker will optimise the file away. </p> <p>It seems like a potential solution is to have a file external to both projects that "includes" a list of source file names in both projects. The problem is that I have no idea whether or how this could be done. Suggestions, anyone?</p>
[ { "answer_id": 255090, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 0, "selected": false, "text": "#include" }, { "answer_id": 255159, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": true, "text": "#pragma comment(linker, \"/include:__mySymbol\")\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19674/" ]
255,098
<p>I am experimenting with calling delegate functions from a delegate array. I've been able to create the array of delegates, but how do I call the delegate?</p> <pre><code>public delegate void pd(); public static class MyClass { static void p1() { //... } static void p2 () { //... } //... static pd[] delegates = new pd[] { new pd( MyClass.p1 ), new pd( MyClass.p2) /* ... */ }; } public class MainClass { static void Main() { // Call pd[0] // Call pd[1] } } </code></pre> <p><strong>EDIT:</strong> The reason for the array is that I need to call the delegate functions by an index as needed. They are not run in response to an event. I see a critical (stupid) error in my code as I had tried to execute the delegate function using the pd[] type rather than the name of the array (delegates).</p>
[ { "answer_id": 255107, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 3, "selected": false, "text": "public class MainClass\n{\n static void Main()\n {\n pd[0]();\n pd[1]();\n }\n}\n" }, { "answer_id": 255113, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "static pd delegateInstance = new pd(MyClass.p1) + new pd(MyClass.p2) ...;\n\n...\npd();\n" }, { "answer_id": 255252, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 3, "selected": false, "text": "public delegate void MessageArrivedHandler(MessageBase msg);\npublic class MyClass\n{\n public event MessageArrivedHandler MessageArrivedClientHandler; \n\n public void CallEachDelegate(MessageBase msg)\n {\n if (MessageArrivedClientHandler == null)\n return;\n Delegate[] clientList = MessageArrivedClientHandler.GetInvocationList();\n foreach (Delegate d in clientList)\n {\n if (d is MessageArrivedHandler)\n (d as MessageArrivedHandler)(msg);\n }\n }\n}\n" }, { "answer_id": 13284760, "author": "Garric", "author_id": 1808515, "author_profile": "https://Stackoverflow.com/users/1808515", "pm_score": 2, "selected": false, "text": "public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n pd[0]();\n pd[1]();\n }\n\n public delegate void delegates();\n\n static delegates[] pd = new delegates[] \n { \n new delegates(MyClass.p1), \n new delegates(MyClass.p2) \n };\n\n public static class MyClass\n {\n public static void p1()\n {\n MessageBox.Show(\"1\");\n }\n\n public static void p2()\n {\n MessageBox.Show(\"2\");\n }\n }\n}\n" }, { "answer_id": 13285006, "author": "Garric", "author_id": 1808515, "author_profile": "https://Stackoverflow.com/users/1808515", "pm_score": 0, "selected": false, "text": "public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n pd[0](1);\n pd[1](2);\n }\n\n public delegate void delegates(int par);\n static delegates[] pd = new delegates[] \n { \n new delegates(MyClass.p1), \n new delegates(MyClass.p2) \n };\n public static class MyClass\n {\n\n public static void p1(int par)\n {\n MessageBox.Show(par.ToString());\n }\n\n public static void p2(int par)\n {\n MessageBox.Show(par.ToString());\n }\n\n\n }\n\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7899/" ]
255,104
<p>I'm working on a WinForms app and I have a user control in it. The buttons in the user control raise events up to the form to be handled by other code. One of the buttons starts some processses that will cause problems if they run simultaneously. I have logic in the code to manage the state so typically a user can't run the process if it's already running. However, if the user double-clicks the button it will start the process twice so quickly that it's tough for me to prevent it.</p> <p>I'm wondering, what's the best way to handle this?</p> <p>I started out by disabling the button in the click event but the second click comes in before the first click causes the button to be disabled. Setting other flags in the code didn't catch it either.</p> <p>I'm considering adding some sort of sync lock on the code that raises the event but I'm wondering if any of you have a better idea. </p> <p>Since this project is mostly complete I'm looking for answers that don't involve a radical rewrite of the app (like implementing the composite application block), however, feel free to post those ideas too since I can use them in my next projects.</p>
[ { "answer_id": 255138, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": 4, "selected": true, "text": "private bool runningExclusiveProcess = false;\n\npublic void onClickHandler(object sender, EventArgs e)\n{\n if (!runningExclusiveProcess)\n {\n runningExclusiveProcess = true;\n myButton.Enabled = false;\n\n // Do super secret stuff here\n\n // If your task is synchronous, then undo your flag here:\n runningExclusiveProcess = false;\n myButton.Enabled = true;\n }\n}\n\n// Otherwise, if your task is asynchronous with a callback, then undo your flag here:\npublic void taskCompletedCallback()\n{\n runningExclusiveProcess = false;\n myButton.Enabled = true;\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10221/" ]
255,114
<p>Let's make this very easy. What I want:</p> <pre><code>@array = qw/one two one/; my @duplicates = duplicate(@array); print "@duplicates"; # This should now print 'one'. </code></pre> <p>How to print duplicate values of a array/hash?</p>
[ { "answer_id": 255177, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": true, "text": "sub duplicate {\n my @args = @_;\n my %items;\n for my $element(@args) {\n $items{$element}++;\n }\n return grep {$items{$_} > 1} keys %items;\n}\n" }, { "answer_id": 255188, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 2, "selected": false, "text": "\nsub duplicate {\n my %value_hash;\n foreach my $val (@_) {\n $value_hash{$val} +=1;\n }\n my @arr;\n while (my ($val, $num) = each(%value_hash)) {\n if ($num > 1) {\n push(@arr, $val)\n }\n }\n return @arr;\n}\n" }, { "answer_id": 255191, "author": "Amanibhavam", "author_id": 33238, "author_profile": "https://Stackoverflow.com/users/33238", "pm_score": 2, "selected": false, "text": "# assumes inputs can be hash keys\n@a = (1, 2, 3, 3, 4, 4, 5);\n\n# keep count for each unique input\n%h = ();\nmap { $h{$_}++ } @a;\n\n# duplicate inputs have count > 1\n@dupes = grep { $h{$_} > 1 } keys %h;\n\n# should print 3, 4\nprint join(\", \", sort @dupes), \"\\n\";\n" }, { "answer_id": 256221, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": -1, "selected": false, "text": "sub duplicate {\n my %count;\n grep $count{$_}++, @_;\n}\n\n@array = qw/one two one/;\nmy @duplicates = duplicate(@array);\nprint \"@duplicates\"; # This should now print 'one'.\n\n# or if returning *exactly* 1 occurrence of each duplicated item is important\nsub duplicate {\n my %count;\n grep ++$count{$_} == 2, @_;\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33232/" ]
255,133
<p>I'm a long-time ActionScript 2 user, now getting started with ActionScript 3. The one thing I'm missing is an easy way to duplicate the functionality of AS2's MovieClip.onReleaseOutside. It is almost always necessary to implement this event, otherwise you get funny bugs like flash thinks your mouse is down when really it's up. </p> <p>According to the <a href="http://livedocs.adobe.com/flex/2/langref/migration.html" rel="nofollow noreferrer">AS2 to AS3 Migration Guide</a>, I'm supposed to use <code>flash.display.InteractiveObject.setCapture()</code> for this, however it does not exist as far as I can tell. I guess this document is out of date or incorrect. I've found a few posts on the web about how to duplicate this functionality, but they either have their own problems:</p> <ul> <li><a href="http://www.arpitonline.com/blog/?p=33" rel="nofollow noreferrer">This one</a> triggers onReleaseOutside even if there was no corresponding onPress event. </li> <li><a href="http://www.kirupa.com/forum/showpost.php?p=1948182&amp;postcount=204" rel="nofollow noreferrer">This one</a> seems very inefficient, you'll add and remove an event listener every time the mouse is clicked anywhere inside your app.</li> </ul> <p>There has to be an easier way, don't tell me Adobe forgot about this when rewriting Actionscript?</p> <p>Example AS2 code:</p> <pre><code>// Assume myMC is a simple square or something on the stage myMC.onPress = function() { this._rotation = 45; } myMC.onRelease = myMC.onReleaseOutside = function() { this._rotation = 0; } </code></pre> <p>Without the onReleaseOutside handler, if you pressed down on the squre, dragged your mouse outside of it, and released the mouse, then the square would not un-rotate, and appear to be stuck.</p>
[ { "answer_id": 256007, "author": "Ronnie Liew", "author_id": 1987, "author_profile": "https://Stackoverflow.com/users/1987", "pm_score": 2, "selected": false, "text": "flash.events.Event.MOUSE_LEAVE\n" }, { "answer_id": 257441, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 4, "selected": true, "text": "button.addEventListener( MouseEvent.MOUSE_DOWN, mouseDownHandler );\nbutton.addEventListener( MouseEvent.MOUSE_UP, buttonMouseUpHandler ); // *\n\nfunction mouseDownHandler( event : MouseEvent ) : void {\n trace( \"onPress\" );\n // this will catch the event anywhere\n event.target.stage.addEventListener( MouseEvent.MOUSE_UP, mouseUpHandler );\n}\n\nfunction buttonMouseUpHandler( event : MouseEvent ) : void {\n trace( \"onRelease\" );\n // don't bubble up, which would trigger the mouse up on the stage\n event.stopImmediatePropagation( );\n}\n\nfunction mouseUpHandler( event : MouseEvent ) : void {\n trace( \"onReleaseOutside\" );\n event.target.removeEventListener( MouseEvent.MOUSE_UP, mouseUpHandler );\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
[ { "answer_id": 255154, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 9, "selected": true, "text": "import sys\n\nsys.stdout.write('h')\nsys.stdout.flush()\n\nsys.stdout.write('m')\nsys.stdout.flush()\n" }, { "answer_id": 255172, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 8, "selected": false, "text": "print('h', end='')\n" }, { "answer_id": 255199, "author": "Dan", "author_id": 444, "author_profile": "https://Stackoverflow.com/users/444", "pm_score": 5, "selected": false, "text": "lst = ['h', 'm']\nprint \"\".join(lst)\n" }, { "answer_id": 255306, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 4, "selected": false, "text": "Python 2.5.2 (r252:60911, Sep 27 2008, 07:03:14)\n[GCC 4.3.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> print \"hello\",; print \"there\"\nhello there\n>>> print \"hello\",; sys.stdout.softspace=False; print \"there\"\nhellothere\n" }, { "answer_id": 255336, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "import sys\nprint \"hello\",\nsys.stdout.softspace=0\nprint \"world\",\nprint \"!\"\n" }, { "answer_id": 410850, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "+" }, { "answer_id": 1036396, "author": "John Machin", "author_id": 84270, "author_profile": "https://Stackoverflow.com/users/84270", "pm_score": 3, "selected": false, "text": "from __past__ import printf\n" }, { "answer_id": 20677875, "author": "Abd", "author_id": 3118564, "author_profile": "https://Stackoverflow.com/users/3118564", "pm_score": 4, "selected": false, "text": " print 'h',\n print '\\bm'\n" }, { "answer_id": 23247362, "author": "Benjamin", "author_id": 1027842, "author_profile": "https://Stackoverflow.com/users/1027842", "pm_score": 2, "selected": false, "text": ">>> print 'h','m','h'\nh m h\n>>> from __future__ import print_function\n>>> print('h',end='')\nh>>> print('h',end='');print('m',end='');print('h',end='')\nhmh>>>\n>>> print('h','m','h',sep='');\nhmh\n>>>\n" }, { "answer_id": 24686404, "author": "Michael Murphy", "author_id": 1991735, "author_profile": "https://Stackoverflow.com/users/1991735", "pm_score": 1, "selected": false, "text": "print(\"{0}{1}{2}\".format(a, b, c))\n" }, { "answer_id": 26343928, "author": "joker", "author_id": 1051589, "author_profile": "https://Stackoverflow.com/users/1051589", "pm_score": 3, "selected": false, "text": "sys.stdout.write(someString)" }, { "answer_id": 27295541, "author": "Aaron McDaid", "author_id": 146041, "author_profile": "https://Stackoverflow.com/users/146041", "pm_score": 0, "selected": false, "text": "sys.stdout.write" }, { "answer_id": 29714273, "author": "Mrinal", "author_id": 4290713, "author_profile": "https://Stackoverflow.com/users/4290713", "pm_score": -1, "selected": false, "text": "import sys\na=raw_input()\nfor i in range(0,len(a)):\n sys.stdout.write(a[i])\n" }, { "answer_id": 42319647, "author": "ahmed khattab", "author_id": 6309432, "author_profile": "https://Stackoverflow.com/users/6309432", "pm_score": 0, "selected": false, "text": "print('''first line \\\nsecond line''')\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4343/" ]
255,153
<p>how do i determine what a mysql db's charset is set to? in the cli?</p>
[ { "answer_id": 255163, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": true, "text": "SHOW CREATE DATABASE db-name\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18285/" ]
255,170
<p>I am making a site that publishes articles in issues each month. It is straightforward, and I think using a Markdown editor (like the <a href="http://code.google.com/p/wmd/" rel="noreferrer">WMD</a> one here in Stack&nbsp;Overflow) would be perfect.</p> <p>However, <strong>they do need the ability to have images right-aligned in a given paragraph</strong>.</p> <p>I can't see a way to do that with the current system - is it possible?</p>
[ { "answer_id": 255182, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 9, "selected": true, "text": "<img style=\"float: right;\" src=\"whatever.jpg\">\n\nContinue markdown text...\n" }, { "answer_id": 1228126, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<div style=\"float:left;margin:0 10px 10px 0\" markdown=\"1\">\n ![book](/images/book01.jpg)\n</div>\n" }, { "answer_id": 4178054, "author": "ma11hew28", "author_id": 242933, "author_profile": "https://Stackoverflow.com/users/242933", "pm_score": 3, "selected": false, "text": "p#given img { float: right }" }, { "answer_id": 5054055, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "![Flowers](/flowers.jpeg)\n" }, { "answer_id": 8484967, "author": "yoyo", "author_id": 1095122, "author_profile": "https://Stackoverflow.com/users/1095122", "pm_score": -1, "selected": false, "text": "<center>![Alt test](http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png)</center>\n" }, { "answer_id": 14508301, "author": "learnvst", "author_id": 276193, "author_profile": "https://Stackoverflow.com/users/276193", "pm_score": 5, "selected": false, "text": "|" }, { "answer_id": 16278366, "author": "gerwitz", "author_id": 5610, "author_profile": "https://Stackoverflow.com/users/5610", "pm_score": 6, "selected": false, "text": "![Flowers](/flowers.jpeg){.callout}\n" }, { "answer_id": 16372869, "author": "abbood", "author_id": 766570, "author_profile": "https://Stackoverflow.com/users/766570", "pm_score": 2, "selected": false, "text": "'<div> // Put image here </div>`\n" }, { "answer_id": 19040921, "author": "jameh", "author_id": 1402511, "author_profile": "https://Stackoverflow.com/users/1402511", "pm_score": 3, "selected": false, "text": "![A picture of a cat](cat.png){: style=\"float:right\"}\n" }, { "answer_id": 37607513, "author": "icarito", "author_id": 1112124, "author_profile": "https://Stackoverflow.com/users/1112124", "pm_score": 3, "selected": false, "text": "| - | - |\n|---|---|\n| I am text to the left | ![Flowers](/flowers.jpeg) |\n| ![Flowers](/flowers.jpeg) | I am text to the right |\n" }, { "answer_id": 39614958, "author": "OzzyCzech", "author_id": 355316, "author_profile": "https://Stackoverflow.com/users/355316", "pm_score": 7, "selected": false, "text": "![image alt >](/image-right.jpg)\n![image alt <](/image-left.jpg)\n![image alt ><](/center-image.jpg)\n" }, { "answer_id": 43691462, "author": "tremor", "author_id": 2839538, "author_profile": "https://Stackoverflow.com/users/2839538", "pm_score": 6, "selected": false, "text": "![my image](/img/myImage.jpg#left)\n![my image](/img/myImage.jpg#right)\n![my image](/img/myImage.jpg#center)\n" }, { "answer_id": 48699229, "author": "Zuha Karim", "author_id": 7589751, "author_profile": "https://Stackoverflow.com/users/7589751", "pm_score": 1, "selected": false, "text": "<div style=\"text-align: right\"><img src=\"/default/image/sms.png\" width=\"100\" /></div>\n" }, { "answer_id": 61921006, "author": "Andersonfrfilho", "author_id": 8157632, "author_profile": "https://Stackoverflow.com/users/8157632", "pm_score": -1, "selected": false, "text": "<p align=\"center\">\n <img src=\"/LogoOfficial.png\" width=\"300\" >\n</p>\n" }, { "answer_id": 69747905, "author": "rahul-ahuja", "author_id": 12818901, "author_profile": "https://Stackoverflow.com/users/12818901", "pm_score": -1, "selected": false, "text": "<div class=\"warning\" style='background-color:#EDF2F7; color:#1A2067; border-left: solid #718096 4px; border-radius: 4px;'>\n<p style='padding:0.7em; margin-left:0.7em; display: inline-block;'>\n<img src=\"typora_images/image-20211028083121348.png\" style=\"zoom:70%; float:right; padding:0.7em\"/>\n<b>isomorphism</b> &rarr; In mathematics, an isomorphism is a structure-preserving mapping between two structures of the same type that can be reversed by an inverse mapping.<br>\n</p>\n</div>\n" }, { "answer_id": 71658868, "author": "dopexxx", "author_id": 6383205, "author_profile": "https://Stackoverflow.com/users/6383205", "pm_score": -1, "selected": false, "text": "align=\"right\"" }, { "answer_id": 71981760, "author": "Chetan B B", "author_id": 17783052, "author_profile": "https://Stackoverflow.com/users/17783052", "pm_score": 0, "selected": false, "text": " <img align=\"right\" width=\"100\" height=\"100\" src=\"https://images.unsplash.com/photo-1650620109005-099c2de720f8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxM3x8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60\">" }, { "answer_id": 73398133, "author": "N. Joppi", "author_id": 8832723, "author_profile": "https://Stackoverflow.com/users/8832723", "pm_score": 0, "selected": false, "text": "<div style=\"display:flex; align-items: center;\">\n <div style=\"flex:1\">\n <img src=\"https://www.researchgate.net/profile/Jinsong-Chong/publication/233165295/figure/fig5/AS:667635838640135@1536188196882/Initial-contour-Figure-9-Detection-result-in-low-resolution-image-in-low-resolution-image.ppm\"/>\n </div>\n <div style=\"flex:1;padding-left:10px;\">\n <img src=\"https://www.researchgate.net/profile/Miguel-Vega-4/publication/228966464/figure/fig1/AS:669376512544781@1536603205341/a-Observed-low-resolution-multispectral-image-b-Panchromatic-image-c.ppm\" />\n </div>\n</div>" }, { "answer_id": 73721756, "author": "Bill Hoag", "author_id": 40422, "author_profile": "https://Stackoverflow.com/users/40422", "pm_score": 0, "selected": false, "text": "img" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9913/" ]
255,189
<p>If I have a type defined as a <strong>set of</strong> an enumerated type, it's easy to create an empty set with [], but how do I create a <em>full</em> set?</p> <p>EDIT: Yeah, the obvious solution is to use a for loop. That's also a really bad solution if there's another way. Does anyone know of a way that'll work in constant time?</p>
[ { "answer_id": 255321, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 3, "selected": false, "text": "FillChar(VarSet, SizeOf(VarSet), $FF);\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
255,194
<p>I'm working on a Grails project using Hibernate (GORM). I have the following Domain Models:</p> <pre><code>ClientContact { static hasMany = [owners: Person] static belongsTo = [Person] } Person { static hasMany = [clientContacts: ClientContact] } </code></pre> <p>When I try to retrieve all the <code>ClientContacts</code> with a specific owner (<code>Person</code>), I'm running into some funny issues. I'm using the following query criteria:</p> <pre><code>def query = { owners { eq("id", Long.parseLong(params.ownerId)) } } def criteria = ClientContact.createCriteria() def results = criteria.list(params, query) </code></pre> <p>The problem is when I iterate through each of my <code>ClientContacts</code> in the results, they only have <strong>the one owner</strong> - when in fact, most have many other owners. What gives? I know hibernate/GORM uses lazy fetching, but I thought it would fetch all of the other owners on a <code>ClientContact</code> when I tried to access them.</p> <p>Any thoughts? I would like to continue using the <em>list()</em> function since it provides some nice paging features.</p>
[ { "answer_id": 255295, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 0, "selected": false, "text": "eqId()" }, { "answer_id": 311865, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 0, "selected": false, "text": " def query = {\n owners {\n eqId(Long.parseLong(params.ownerId))\n }\n }\n def criteria = ClientContact.createCriteria()\n def results = criteria.list(params, query)\n" }, { "answer_id": 9035504, "author": "Pawel Gwozdz", "author_id": 1173774, "author_profile": "https://Stackoverflow.com/users/1173774", "pm_score": 3, "selected": true, "text": "def query = {\n owners {\n eq(\"id\", Long.parseLong(params.ownerId))\n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21832/" ]
255,202
<p>When I type <code>git diff</code>, I want to view the output with my visual diff tool of choice (SourceGear "diffmerge" on Windows). How do I configure git to do this?</p>
[ { "answer_id": 255212, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 10, "selected": true, "text": "path old-file old-hex old-mode new-file new-hex new-mode\n" }, { "answer_id": 392899, "author": "Milan Gardian", "author_id": 23843, "author_profile": "https://Stackoverflow.com/users/23843", "pm_score": 3, "selected": false, "text": "gitdiff" }, { "answer_id": 573579, "author": "Steve Hanov", "author_id": 15947, "author_profile": "https://Stackoverflow.com/users/15947", "pm_score": 4, "selected": false, "text": "@echo off\nREM This is gitdiff.bat\n\"C:\\Program Files\\WinMerge\\WinMergeU.exe\" %2 %5\n" }, { "answer_id": 732555, "author": "Brad Robinson", "author_id": 77002, "author_profile": "https://Stackoverflow.com/users/77002", "pm_score": 3, "selected": false, "text": "gitvdiff --install \n" }, { "answer_id": 901386, "author": "Jakub Narębski", "author_id": 46058, "author_profile": "https://Stackoverflow.com/users/46058", "pm_score": 5, "selected": false, "text": "difftool.<tool>.cmd" }, { "answer_id": 949242, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": false, "text": "'[--tool=tool] [--commit=ref] [--start=ref --end=ref] [--no-prompt] [file to merge]'" }, { "answer_id": 1339962, "author": "Seba Illingworth", "author_id": 93451, "author_profile": "https://Stackoverflow.com/users/93451", "pm_score": 6, "selected": false, "text": "[diff]\n tool = any-name\n[difftool \"any-name\"]\n cmd = \"\\\"C:/path/to/my/ext/diff.exe\\\" \\\"$LOCAL\\\" \\\"$REMOTE\\\"\"\n" }, { "answer_id": 1607200, "author": "Fire Crow", "author_id": 80479, "author_profile": "https://Stackoverflow.com/users/80479", "pm_score": 3, "selected": false, "text": "[diff]\n external = git_diff_wrapper\n[pager]\n diff =\n" }, { "answer_id": 2267755, "author": "Bilal and Olga", "author_id": 253511, "author_profile": "https://Stackoverflow.com/users/253511", "pm_score": 1, "selected": false, "text": "sudo apt-get install kompare\n" }, { "answer_id": 2442822, "author": "Charles Merriam", "author_id": 1320510, "author_profile": "https://Stackoverflow.com/users/1320510", "pm_score": 7, "selected": false, "text": "$ meld my_project_using_git\n" }, { "answer_id": 2547322, "author": "idbrii", "author_id": 79125, "author_profile": "https://Stackoverflow.com/users/79125", "pm_score": 3, "selected": false, "text": "$ git config difftool.bc3.cmd \"git-diff-bcomp-wrapper.sh \\$LOCAL \\$REMOTE\"\n$ cat git-diff-bcomp-wrapper.sh\n#!/bin/sh\n\"c:/Program Files (x86)/Beyond Compare 3/BComp.exe\" `cygpath -w $1` `cygpath -w $2`\n" }, { "answer_id": 3837231, "author": "Jiqing Tang", "author_id": 463611, "author_profile": "https://Stackoverflow.com/users/463611", "pm_score": 0, "selected": false, "text": "xd" }, { "answer_id": 4116806, "author": "David Marble", "author_id": 216735, "author_profile": "https://Stackoverflow.com/users/216735", "pm_score": 4, "selected": false, "text": "git config --global diff.tool winmerge\ngit config --global difftool.winmerge.cmd \"winmerge.sh \\\"$LOCAL\\\" \\\"$REMOTE\\\" \\\"$BASE\\\"\"\ngit config --global difftool.prompt false\n" }, { "answer_id": 4881489, "author": "Kem Mason", "author_id": 398582, "author_profile": "https://Stackoverflow.com/users/398582", "pm_score": 5, "selected": false, "text": "git difftool -t\n" }, { "answer_id": 7298214, "author": "LuxuryMode", "author_id": 479180, "author_profile": "https://Stackoverflow.com/users/479180", "pm_score": 3, "selected": false, "text": "git difftool -t opendiff\n" }, { "answer_id": 9120254, "author": "Sharas", "author_id": 1107786, "author_profile": "https://Stackoverflow.com/users/1107786", "pm_score": 3, "selected": false, "text": " [diff]\n tool = kdiff3\n\n [difftool]\n prompt = false\n\n [difftool \"kdiff3\"]\n path = C:/Program Files (x86)/KDiff3/kdiff3.exe\n cmd = \"$LOCAL\" \"$REMOTE\"\n" }, { "answer_id": 17587613, "author": "abo-abo", "author_id": 1350992, "author_profile": "https://Stackoverflow.com/users/1350992", "pm_score": 1, "selected": false, "text": "~/.gitconfig" }, { "answer_id": 20389035, "author": "Theodore Sternberg", "author_id": 3068121, "author_profile": "https://Stackoverflow.com/users/3068121", "pm_score": 2, "selected": false, "text": "$ cat tkgitdiff\n#!/bin/sh\n\n#\n# tkdiff for git.\n# Gives you the diff between HEAD and the current state of your file.\n#\n\nnewfile=$1\ngit diff HEAD -- $newfile > /tmp/patch.dat\ncp $newfile /tmp\nsavedPWD=$PWD\ncd /tmp\npatch -R $newfile < patch.dat\ncd $savedPWD\ntkdiff /tmp/$newfile $newfile\n" }, { "answer_id": 20422642, "author": "suhailvs", "author_id": 2351696, "author_profile": "https://Stackoverflow.com/users/2351696", "pm_score": 2, "selected": false, "text": "git difftool" }, { "answer_id": 21416192, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 0, "selected": false, "text": "git diff" }, { "answer_id": 26732990, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "git difftool --tool-help\ngit config --global diff.tool <chosen tool>\ngit config --global --add difftool.prompt false\n" }, { "answer_id": 32663282, "author": "G. I. Joe", "author_id": 2986881, "author_profile": "https://Stackoverflow.com/users/2986881", "pm_score": 3, "selected": false, "text": " # apt-get install meld\n" }, { "answer_id": 37109430, "author": "Shreyas", "author_id": 3098229, "author_profile": "https://Stackoverflow.com/users/3098229", "pm_score": 2, "selected": false, "text": "git difftool -t diffuse\n" }, { "answer_id": 44663812, "author": "David Rawson", "author_id": 5241933, "author_profile": "https://Stackoverflow.com/users/5241933", "pm_score": 3, "selected": false, "text": "diff" }, { "answer_id": 53837839, "author": "dolphus333", "author_id": 1429266, "author_profile": "https://Stackoverflow.com/users/1429266", "pm_score": 2, "selected": false, "text": "git difftool --tool=tkdiff <path to the file to be diffed>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3891/" ]
255,214
<p>I keep seeing references to the visitor pattern in blogs but I've got to admit, I just don't get it. I read the <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="noreferrer">wikipedia article for the pattern</a> and I understand its mechanics but I'm still confused as to when I'd use it.</p> <p>As someone who just recently really <strong>got</strong> the decorator pattern and is now seeing uses for it absolutely everywhere I'd like to be able to really understand intuitively this seemingly handy pattern as well.</p>
[ { "answer_id": 255300, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 8, "selected": false, "text": "class Animal { };\nclass Dog: public Animal { };\nclass Cat: public Animal { };\n" }, { "answer_id": 255437, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": false, "text": "class TreeNode( object ):\n def __init__( self, name, *children ):\n self.name= name\n self.children= children\n def visit( self, someVisitor ):\n someVisitor.arrivedAt( self )\n someVisitor.down()\n for c in self.children:\n c.visit( someVisitor )\n someVisitor.up()\n" }, { "answer_id": 15308066, "author": "kaosad", "author_id": 1711215, "author_profile": "https://Stackoverflow.com/users/1711215", "pm_score": 3, "selected": false, "text": "Visitor Pattern" }, { "answer_id": 20205309, "author": "Carl", "author_id": 13760, "author_profile": "https://Stackoverflow.com/users/13760", "pm_score": 1, "selected": false, "text": "class SpaceShip {};\nclass ApolloSpacecraft : public SpaceShip {};\nclass ExplodingAsteroid : public Asteroid {\npublic:\n virtual void CollideWith(SpaceShip&) {\n cout << \"ExplodingAsteroid hit a SpaceShip\" << endl;\n }\n virtual void CollideWith(ApolloSpacecraft&) {\n cout << \"ExplodingAsteroid hit an ApolloSpacecraft\" << endl;\n }\n}\n" }, { "answer_id": 24595957, "author": "Seyed Morteza Mousavi", "author_id": 953975, "author_profile": "https://Stackoverflow.com/users/953975", "pm_score": 3, "selected": false, "text": "Pill" }, { "answer_id": 30078229, "author": "Fuhrmanator", "author_id": 1168342, "author_profile": "https://Stackoverflow.com/users/1168342", "pm_score": 3, "selected": false, "text": "FileNode" }, { "answer_id": 35406737, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 2, "selected": false, "text": "import java.util.HashMap;\n\ninterface Visitable{\n void accept(Visitor visitor);\n}\n\ninterface Visitor{\n void logGameStatistics(Chess chess);\n void logGameStatistics(Checkers checkers);\n void logGameStatistics(Ludo ludo); \n}\nclass GameVisitor implements Visitor{\n public void logGameStatistics(Chess chess){\n System.out.println(\"Logging Chess statistics: Game Completion duration, number of moves etc..\"); \n }\n public void logGameStatistics(Checkers checkers){\n System.out.println(\"Logging Checkers statistics: Game Completion duration, remaining coins of loser\"); \n }\n public void logGameStatistics(Ludo ludo){\n System.out.println(\"Logging Ludo statistics: Game Completion duration, remaining coins of loser\"); \n }\n}\n\nabstract class Game{\n // Add game related attributes and methods here\n public Game(){\n\n }\n public void getNextMove(){};\n public void makeNextMove(){}\n public abstract String getName();\n}\nclass Chess extends Game implements Visitable{\n public String getName(){\n return Chess.class.getName();\n }\n public void accept(Visitor visitor){\n visitor.logGameStatistics(this);\n }\n}\nclass Checkers extends Game implements Visitable{\n public String getName(){\n return Checkers.class.getName();\n }\n public void accept(Visitor visitor){\n visitor.logGameStatistics(this);\n }\n}\nclass Ludo extends Game implements Visitable{\n public String getName(){\n return Ludo.class.getName();\n }\n public void accept(Visitor visitor){\n visitor.logGameStatistics(this);\n }\n}\n\npublic class VisitorPattern{\n public static void main(String args[]){\n Visitor visitor = new GameVisitor();\n Visitable games[] = { new Chess(),new Checkers(), new Ludo()};\n for (Visitable v : games){\n v.accept(visitor);\n }\n }\n}\n" }, { "answer_id": 36273106, "author": "Tomás Escamez", "author_id": 1582225, "author_profile": "https://Stackoverflow.com/users/1582225", "pm_score": 2, "selected": false, "text": "public interface IAnimal\n{\n void DoSound();\n}\n\npublic class Dog : IAnimal\n{\n public void DoSound()\n {\n Console.WriteLine(\"Woof\");\n }\n}\n\npublic class Cat : IAnimal\n{\n public void DoSound(IOperation o)\n {\n Console.WriteLine(\"Meaw\");\n }\n}\n" }, { "answer_id": 38341948, "author": "Kapoor", "author_id": 5252960, "author_profile": "https://Stackoverflow.com/users/5252960", "pm_score": 4, "selected": false, "text": " void SwitchOnBlueTooth(IMobileDevice mobileDevice, IBlueToothRadio blueToothRadio)\n" }, { "answer_id": 47968789, "author": "davidxxx", "author_id": 270371, "author_profile": "https://Stackoverflow.com/users/270371", "pm_score": 4, "selected": false, "text": "if (myObj instanceof Foo) {}" }, { "answer_id": 50575946, "author": "Hearen", "author_id": 2361308, "author_profile": "https://Stackoverflow.com/users/2361308", "pm_score": 0, "selected": false, "text": "import static java.lang.System.out;\npublic class Visitor_2 {\n public static void main(String...args) {\n Hearen hearen = new Hearen();\n FoodImpl food = new FoodImpl();\n hearen.showTheHobby(food);\n Katherine katherine = new Katherine();\n katherine.presentHobby(food);\n }\n}\n\ninterface Hobby {\n void insert(Hearen hearen);\n void embed(Katherine katherine);\n}\n\n\nclass Hearen {\n String name = \"Hearen\";\n void showTheHobby(Hobby hobby) {\n hobby.insert(this);\n }\n}\n\nclass Katherine {\n String name = \"Katherine\";\n void presentHobby(Hobby hobby) {\n hobby.embed(this);\n }\n}\n\nclass FoodImpl implements Hobby {\n public void insert(Hearen hearen) {\n out.println(hearen.name + \" start to eat bread\");\n }\n public void embed(Katherine katherine) {\n out.println(katherine.name + \" start to eat mango\");\n }\n}\n" }, { "answer_id": 51015854, "author": "j2emanue", "author_id": 835883, "author_profile": "https://Stackoverflow.com/users/835883", "pm_score": 0, "selected": false, "text": "//psuedo code\n if(payPal) \n do paypal checkout \n if(stripe)\n do strip stuff checkout\n if(payoneer)\n do payoneer checkout\n" }, { "answer_id": 53315503, "author": "Access Denied", "author_id": 1099716, "author_profile": "https://Stackoverflow.com/users/1099716", "pm_score": 2, "selected": false, "text": "public class Employee\n{\n}\n\npublic class SalariedEmployee : Employee\n{\n}\n\npublic class HourlyEmployee : Employee\n{\n}\n\npublic class QtdHoursAndPayReport\n{\n public void PrintReport()\n {\n var employees = new List<Employee>\n {\n new SalariedEmployee(),\n new HourlyEmployee()\n };\n foreach (Employee e in employees)\n {\n if (e is HourlyEmployee he)\n PrintReportLine(he);\n if (e is SalariedEmployee se)\n PrintReportLine(se);\n }\n }\n\n public void PrintReportLine(HourlyEmployee he)\n {\n System.Diagnostics.Debug.WriteLine(\"hours\");\n }\n public void PrintReportLine(SalariedEmployee se)\n {\n System.Diagnostics.Debug.WriteLine(\"fix\");\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n new QtdHoursAndPayReport().PrintReport();\n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
255,216
<p>So far, I've only been passing javascript strings to my web methods, which get parsed, usually as Guids. but now i have a method that accepts an IList... on the client, i build this array of objects and then attempt to pass it like: </p> <pre><code>$.ajax({ type: 'POST', url: 'personalization.aspx/SetPersonalization', data: "{'backerEntries':" + backerEntries + "}", contentType: 'application/json; charset=utf-8', dataType: 'json', success: postcardManager.SetPersonalizationComplete }); </code></pre> <p>The post: </p> <pre><code>{'backerEntries':[object Object],[object Object],[object Object]} </code></pre> <p>The error response: </p> <pre><code>Invalid JSON primitive: object. </code></pre> <p>For some reason, jquery doesn't seem to convert my array into a json string? Any ideas why? I tried putting [] around the backerEntries, and {}, as well as {[]} just in sheer desperation. Am I missing something obvious here? </p>
[ { "answer_id": 255261, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 2, "selected": false, "text": "data:{backerEntries: backerEntries }\n" }, { "answer_id": 255269, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "data: \"{'backerEntries':\" + backerEntries.toString() + \"}\",\n" }, { "answer_id": 255754, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 2, "selected": false, "text": "var backerEntriesJson = Sys.Serialization.JavaScriptSerializer.serialize(backerEntries);\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
255,278
<p>What would be the best way to determine if an object equals number zero (0) or string.empty in C#?</p> <p><b>EDIT:</b> The object can equal any built-in System.Value type or reference type.</p> <p>Source Code:</p> <pre><code>public void MyMethod(object input1, object input2) { bool result = false; object compare = new object(); if(input != null &amp;&amp; input2 != null) { if(input1 is IComparable &amp;&amp; input2 is IComparable) { //do check for zero or string.empty //if input1 equals to zero or string.empty result = object.Equals(input2); //if input1 not equals to zero or string.empty result = object.Equals(input1) &amp;&amp; object.Equals(input2); //yes not valid, but this is what I want to accomplish } } } </code></pre>
[ { "answer_id": 255292, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": false, "text": "string x = \"Some String\"\nif( string.IsNullOrEmpty(string input) ) { ... }\n" }, { "answer_id": 255339, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": " static bool IsZeroOrEmpty(object o1)\n {\n if (o1 == null)\n return false;\n if (o1.GetType().IsValueType)\n { \n return (o1 as System.ValueType).Equals(0);\n }\n else\n {\n if (o1.GetType() == typeof(String))\n {\n return o1.Equals(String.Empty);\n }\n\n return o1.Equals(0);\n }\n }\n" }, { "answer_id": 255384, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "obj => obj is int && (int)obj == 0 || obj is string && (string)obj == string.Empty\n" }, { "answer_id": 255399, "author": "Cybis", "author_id": 32998, "author_profile": "https://Stackoverflow.com/users/32998", "pm_score": 2, "selected": false, "text": "public static bool IsZeroOrEmptyString(object obj)\n{\n if (obj == null)\n return false;\n else if (obj.Equals(0) || obj.Equals(\"\"))\n return true;\n else\n return false;\n}\n" }, { "answer_id": 266173, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 3, "selected": true, "text": "static bool IsZeroOrEmpty(object o1)\n{\n bool Passed = false;\n object ZeroValue = 0;\n\n if(o1 != null)\n {\n if(o1.GetType().IsValueType)\n {\n Passed = (o1 as System.ValueType).Equals(Convert.ChangeType(ZeroValue, o1.GetType()))\n }\n else\n {\n if (o1.GetType() == typeof(String))\n {\n Passed = o1.Equals(String.Empty);\n }\n }\n }\n\n return Passed;\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/255278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
255,302
<p>Hoping some of you TinyXML++ people can help me out. Really, since you recomended to me before I think you owe me ;)</p> <p>I have the following code:</p> <pre><code> //ticpp::Iterator&lt; ticpp::Element &gt; child( "SetPiece" ); ticpp::Iterator&lt; ticpp::Node &gt; child("SetPiece"); GLuint lc_SPieces = 0; for(child = child.begin( this ); child != child.end(); child++ ) { lc_SPieces++; } </code></pre> <p>If I use the top declaration for child I get the error:</p> <blockquote> <p>Unhandled exception at 0x7c812aeb in Drawing.exe: Microsoft C++ exception: __non_rtti_object @ 0x0012f7b4.</p> </blockquote> <p>And I get it in dbgheap.c at this line:</p> <pre><code>pvBlk = _heap_alloc_dbg(nSize, nBlockUse, szFileName, nLine); </code></pre> <p>What's weird is it works with Node, and I know that there are elements in there(I checked using the TinyXML iteration methods).</p> <p>Has anyone run into this before?</p>
[ { "answer_id": 285834, "author": "paavo256", "author_id": 34911, "author_profile": "https://Stackoverflow.com/users/34911", "pm_score": 1, "selected": false, "text": "__non_rtti_object" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23829/" ]
255,312
<p>Say i have this PHP code:</p> <pre><code>$FooBar = "a string"; </code></pre> <p>i then need a function like this:</p> <pre><code>print_var_name($FooBar); </code></pre> <p>which prints:</p> <pre><code>FooBar </code></pre> <p>Any Ideas how to achieve this? Is this even possible in PHP?</p>
[ { "answer_id": 255335, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 7, "selected": true, "text": "function print_var_name($var) {\n foreach($GLOBALS as $var_name => $value) {\n if ($value === $var) {\n return $var_name;\n }\n }\n\n return false;\n}\n" }, { "answer_id": 255498, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 1, "selected": false, "text": "$variable" }, { "answer_id": 404562, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "$var_name = \"FooBar\";\n$$var_name = \"a string\";\n" }, { "answer_id": 404637, "author": "Nick Presta", "author_id": 40906, "author_profile": "https://Stackoverflow.com/users/40906", "pm_score": 6, "selected": false, "text": "<?php\n\nfunction varName( $v ) {\n $trace = debug_backtrace();\n $vLine = file( __FILE__ );\n $fLine = $vLine[ $trace[0]['line'] - 1 ];\n preg_match( \"#\\\\$(\\w+)#\", $fLine, $match );\n print_r( $match );\n}\n\n$foo = \"knight\";\n$bar = array( 1, 2, 3 );\n$baz = 12345;\n\nvarName( $foo );\nvarName( $bar );\nvarName( $baz );\n\n?>\n\n// Returns\nArray\n(\n [0] => $foo\n [1] => foo\n)\nArray\n(\n [0] => $bar\n [1] => bar\n)\nArray\n(\n [0] => $baz\n [1] => baz\n)\n" }, { "answer_id": 1232338, "author": "Xyz", "author_id": 150926, "author_profile": "https://Stackoverflow.com/users/150926", "pm_score": 1, "selected": false, "text": "$colour = 'blue';\ncacheVariable($colour);\n" }, { "answer_id": 2414745, "author": "Sebastián Grignoli", "author_id": 290221, "author_profile": "https://Stackoverflow.com/users/290221", "pm_score": 4, "selected": false, "text": "function inspect($label, $value = \"__undefin_e_d__\")\n{\n if($value == \"__undefin_e_d__\") {\n\n /* The first argument is not the label but the \n variable to inspect itself, so we need a label.\n Let's try to find out it's name by peeking at \n the source code. \n */\n\n /* The reason for using an exotic string like \n \"__undefin_e_d__\" instead of NULL here is that \n inspected variables can also be NULL and I want \n to inspect them anyway.\n */\n\n $value = $label;\n\n $bt = debug_backtrace();\n $src = file($bt[0][\"file\"]);\n $line = $src[ $bt[0]['line'] - 1 ];\n\n // let's match the function call and the last closing bracket\n preg_match( \"#inspect\\((.+)\\)#\", $line, $match );\n\n /* let's count brackets to see how many of them actually belongs \n to the var name\n Eg: die(inspect($this->getUser()->hasCredential(\"delete\")));\n We want: $this->getUser()->hasCredential(\"delete\")\n */\n $max = strlen($match[1]);\n $varname = \"\";\n $c = 0;\n for($i = 0; $i < $max; $i++){\n if( $match[1]{$i} == \"(\" ) $c++;\n elseif( $match[1]{$i} == \")\" ) $c--;\n if($c < 0) break;\n $varname .= $match[1]{$i};\n }\n $label = $varname;\n }\n\n // $label now holds the name of the passed variable ($ included)\n // Eg: inspect($hello) \n // => $label = \"$hello\"\n // or the whole expression evaluated\n // Eg: inspect($this->getUser()->hasCredential(\"delete\"))\n // => $label = \"$this->getUser()->hasCredential(\\\"delete\\\")\"\n\n // now the actual function call to the inspector method, \n // passing the var name as the label:\n\n // return dInspect::dump($label, $val);\n // UPDATE: I commented this line because people got confused about \n // the dInspect class, wich has nothing to do with the issue here.\n\n echo(\"The label is: \".$label);\n echo(\"The value is: \".$value);\n\n}\n" }, { "answer_id": 3046038, "author": "Will Fastie", "author_id": 330377, "author_profile": "https://Stackoverflow.com/users/330377", "pm_score": 1, "selected": false, "text": " debug_echo(array('$query'=>$query, '$nrUsers'=>$nrUsers, '$hdr'=>$hdr));\n" }, { "answer_id": 4034225, "author": "Workman", "author_id": 488909, "author_profile": "https://Stackoverflow.com/users/488909", "pm_score": 4, "selected": false, "text": "function variable_name( &$var, $scope=false, $prefix='UNIQUE', $suffix='VARIABLE' ){\n if($scope) {\n $vals = $scope;\n } else {\n $vals = $GLOBALS;\n }\n $old = $var;\n $var = $new = $prefix.rand().$suffix;\n $vname = FALSE;\n foreach($vals as $key => $val) {\n if($val === $new) $vname = $key;\n }\n $var = $old;\n return $vname;\n}\n" }, { "answer_id": 6403889, "author": "AnOldMan", "author_id": 805562, "author_profile": "https://Stackoverflow.com/users/805562", "pm_score": 0, "selected": false, "text": "/**\n * Prints out $obj for debug\n *\n * @param any_type $obj\n * @param (string) $title\n */\nfunction print_all( $obj, $title = false )\n{\n print \"\\n<div style=\\\"font-family:Arial;\\\">\\n\";\n if( $title ) print \"<div style=\\\"background-color:red; color:white; font-size:16px; font-weight:bold; margin:0; padding:10px; text-align:center;\\\">$title</div>\\n\";\n print \"<pre style=\\\"background-color:yellow; border:2px solid red; color:black; margin:0; padding:10px;\\\">\\n\\n\";\n var_export( $obj );\n print \"\\n\\n</pre>\\n</div>\\n\";\n}\n\nprint_all( $aUser, '$aUser' );\n" }, { "answer_id": 7049999, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<?php\nfunction vname(&$var, $scope=0)\n{\n $old = $var;\n if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key; \n}\n?>\n" }, { "answer_id": 9614338, "author": "dakiquang", "author_id": 931877, "author_profile": "https://Stackoverflow.com/users/931877", "pm_score": 1, "selected": false, "text": "Jeremy Ruten" }, { "answer_id": 9730533, "author": "K. Brunner", "author_id": 1272978, "author_profile": "https://Stackoverflow.com/users/1272978", "pm_score": 3, "selected": false, "text": "function getReference(&$var)\n{\n if(is_object($var))\n $var->___uniqid = uniqid();\n else\n $var = serialize($var);\n $name = getReference_traverse($var,$GLOBALS);\n if(is_object($var))\n unset($var->___uniqid);\n else\n $var = unserialize($var);\n return \"\\${$name}\"; \n}\n\nfunction getReference_traverse(&$var,$arr)\n{\n if($name = array_search($var,$arr,true))\n return \"{$name}\";\n foreach($arr as $key=>$value)\n if(is_object($value))\n if($name = getReference_traverse($var,get_object_vars($value)))\n return \"{$key}->{$name}\";\n}\n" }, { "answer_id": 10435829, "author": "Ajaxmint", "author_id": 1373122, "author_profile": "https://Stackoverflow.com/users/1373122", "pm_score": -1, "selected": false, "text": " $variableName = \"ajaxmint\";\n\n echo getVarName('$variableName');\n\n function getVarName($name) {\n return str_replace('$','',$name);\n }\n" }, { "answer_id": 10959842, "author": "user1446000", "author_id": 1446000, "author_profile": "https://Stackoverflow.com/users/1446000", "pm_score": -1, "selected": false, "text": "function get_user_var_defined () \n{\n return array_slice($GLOBALS,8,count($GLOBALS)-8); \n}\n\nfunction get_var_name ($var) \n{\n $vuser = get_user_var_defined(); \n foreach($vuser as $key=>$value) \n {\n if($var===$value) return $key ; \n }\n}\n" }, { "answer_id": 13391688, "author": "Kieron Axten", "author_id": 1825667, "author_profile": "https://Stackoverflow.com/users/1825667", "pm_score": 0, "selected": false, "text": "function VarTest($my_var,$my_var_name){\n echo '$'.$my_var_name.': '.$my_var.'<br />';\n}\n\n$fruit='apple';\nVarTest($fruit,'fruit');\n" }, { "answer_id": 14062672, "author": "user1933288", "author_id": 1933288, "author_profile": "https://Stackoverflow.com/users/1933288", "pm_score": 2, "selected": false, "text": "function compact_assoc(&$v1='__undefined__', &$v2='__undefined__',&$v3='__undefined__',&$v4='__undefined__',&$v5='__undefined__',&$v6='__undefined__',&$v7='__undefined__',&$v8='__undefined__',&$v9='__undefined__',&$v10='__undefined__',&$v11='__undefined__',&$v12='__undefined__',&$v13='__undefined__',&$v14='__undefined__',&$v15='__undefined__',&$v16='__undefined__',&$v17='__undefined__',&$v18='__undefined__',&$v19='__undefined__'\n) {\n $defined_vars=get_defined_vars();\n\n $result=Array();\n $reverse_key=Array();\n $original_value=Array();\n foreach( $defined_vars as $source_key => $source_value){\n if($source_value==='__undefined__') break;\n $original_value[$source_key]=$$source_key;\n $new_test_value=\"PREFIX\".rand().\"SUFIX\";\n $reverse_key[$new_test_value]=$source_key;\n $$source_key=$new_test_value;\n\n }\n foreach($GLOBALS as $key => &$value){\n if( is_string($value) && isset($reverse_key[$value]) ) {\n $result[$key]=&$value;\n }\n }\n foreach( $original_value as $source_key => $original_value){\n $$source_key=$original_value;\n }\n return $result;\n}\n\n\n$a = 'A';\n$b = 'B';\n$c = '999';\n$myArray=Array ('id'=>'id123','name'=>'Foo');\nprint_r(compact_assoc($a,$b,$c,$myArray) );\n\n//print\nArray\n(\n [a] => A\n [b] => B\n [c] => 999\n [myArray] => Array\n (\n [id] => id123\n [name] => Foo\n )\n\n)\n" }, { "answer_id": 15936154, "author": "IMSoP", "author_id": 157957, "author_profile": "https://Stackoverflow.com/users/157957", "pm_score": 5, "selected": false, "text": "$foo = $bar" }, { "answer_id": 21973770, "author": "user3344253", "author_id": 3344253, "author_profile": "https://Stackoverflow.com/users/3344253", "pm_score": -1, "selected": false, "text": "public function getVarName($var) { \n $tmp = array($var => '');\n $keys = array_keys($tmp);\n return trim($keys[0]);\n}\n" }, { "answer_id": 26045008, "author": "Budove", "author_id": 1628741, "author_profile": "https://Stackoverflow.com/users/1628741", "pm_score": 1, "selected": false, "text": "$FooBar = \"a string\";\n\n$newArray = compact('FooBar');\n" }, { "answer_id": 29436177, "author": "Janaka R Rajapaksha", "author_id": 2020193, "author_profile": "https://Stackoverflow.com/users/2020193", "pm_score": 1, "selected": false, "text": "$vars = array('FooBar' => 'a string');\n" }, { "answer_id": 36921487, "author": "adilbo", "author_id": 5201919, "author_profile": "https://Stackoverflow.com/users/5201919", "pm_score": 5, "selected": false, "text": "function print_var_name(){\n // read backtrace\n $bt = debug_backtrace();\n // read file\n $file = file($bt[0]['file']);\n // select exact print_var_name($varname) line\n $src = $file[$bt[0]['line']-1];\n // search pattern\n $pat = '#(.*)'.__FUNCTION__.' *?\\( *?(.*) *?\\)(.*)#i';\n // extract $varname from match no 2\n $var = preg_replace($pat, '$2', $src);\n // print to browser\n echo '<pre>' . trim($var) . ' = ' . print_r(current(func_get_args()), true) . '</pre>';\n}\n" }, { "answer_id": 60701076, "author": "Stuperfied", "author_id": 5411736, "author_profile": "https://Stackoverflow.com/users/5411736", "pm_score": 0, "selected": false, "text": "$data = array('$FooBar'); \n\n$vars = []; \n$vars = preg_replace('/^\\\\$/', '', $data); \n\n$varname = key(compact($vars)); \necho $varname;\n" }, { "answer_id": 61442261, "author": "Rain", "author_id": 5999372, "author_profile": "https://Stackoverflow.com/users/5999372", "pm_score": 1, "selected": false, "text": "function getVar(&$var) {\n $tmp = $var; // store the variable value\n $var = '_$_%&33xc$%^*7_r4'; // give the variable a new unique value\n $name = array_search($var, $GLOBALS); // search $GLOBALS for that unique value and return the key(variable)\n $var = $tmp; // restore the variable old value\n return $name;\n}\n" }, { "answer_id": 65645016, "author": "thomas", "author_id": 12903396, "author_profile": "https://Stackoverflow.com/users/12903396", "pm_score": 1, "selected": false, "text": "get_defined_vars()" }, { "answer_id": 69171251, "author": "Juan Carlos Constantine", "author_id": 3083631, "author_profile": "https://Stackoverflow.com/users/3083631", "pm_score": 0, "selected": false, "text": "function varsToArrayAssoc(...$arguments){\n \n $bt = debug_backtrace();\n $file = file($bt[0]['file']);\n $src = $file[$bt[0]['line']-1];\n $pat = '#(.*)'.__FUNCTION__.' *?\\( *?(.*) *?\\)(.*)#i';\n $vars =explode(',',substr_replace(trim(preg_replace($pat, '$2', $src)) ,\"\", -1));\n $result=[];\n foreach(func_get_args() as $key=>$v){\n $index=trim(explode('$',$vars[$key])[1]);\n $result[$index]=$v;\n }\n return $result;\n}\n\n$a=12;\n$b=13;\n$c=123;\n$d='aa';\n\nvar_dump(varsToArrayAssoc($a,$b,$c,$d));\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
255,317
<p>I have an asp.net page with a button. This button generates and inserts a user control into the page, so many controls could exist on one page. I need to validate that a certain dynamically generated control inside the generated control exists. </p> <p>So..Page has 0 to N Control1’s. Each Control 1 can have 0 to N Control2’s. When SaveButton is clicked on Page, I need to make sure there are at least 1 Control2’s inside every Control1. </p> <p>I’m currently between two options:</p> <p>• Dynamically insert CustomValidators for each control that is generated, each of which would validate one Control1.</p> <p>• Do the validation manually (with jQuery), calling a validation function from SaveButton.OnClientClick.</p> <p>Both are sloppy in their own way – which is why I’m sharing this with you all. Am I missing the easy solution?</p> <p>Thanks in advance.. (btw – anything up to and including .NET 3.5 SP1 is fair game)</p>
[ { "answer_id": 256251, "author": "SecretDeveloper", "author_id": 2720, "author_profile": "https://Stackoverflow.com/users/2720", "pm_score": 4, "selected": true, "text": "public interface IValidatableControl\n{\n bool IsValidControl(); \n}\n" }, { "answer_id": 309401, "author": "Kelly Adams", "author_id": 12734, "author_profile": "https://Stackoverflow.com/users/12734", "pm_score": 1, "selected": false, "text": "[ValidationProperty(\"Control2Ref\")]\npublic partial class Control1 : UserControl\n{\n public string Control2Ref\n {\n get { return FindControl(\"Control2\"); }\n }\n // rest of control 1 class\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33253/" ]
255,337
<p>I want to read and write from serial using events/interrupts. Currently, I have it in a while loop and it continuously reads and writes through the serial. I want it to only read when something comes from the serial port. How do I implement this in C++?</p> <p>This is my current code:</p> <pre> while(true) { //read if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){ //error occurred. Report to user. } //write if(!WriteFile(hSerial, szBuff, n, &dwBytesRead, NULL)){ //error occurred. Report to user. } //print what you are reading printf("%s\n", szBuff); } </pre>
[ { "answer_id": 256251, "author": "SecretDeveloper", "author_id": 2720, "author_profile": "https://Stackoverflow.com/users/2720", "pm_score": 4, "selected": true, "text": "public interface IValidatableControl\n{\n bool IsValidControl(); \n}\n" }, { "answer_id": 309401, "author": "Kelly Adams", "author_id": 12734, "author_profile": "https://Stackoverflow.com/users/12734", "pm_score": 1, "selected": false, "text": "[ValidationProperty(\"Control2Ref\")]\npublic partial class Control1 : UserControl\n{\n public string Control2Ref\n {\n get { return FindControl(\"Control2\"); }\n }\n // rest of control 1 class\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
255,341
<p>It's easy to get the value of a key from a .NET generic Dictionary:</p> <pre><code>Dictionary&lt;int, string&gt; greek = new Dictionary&lt;int, string&gt;(); greek.Add(1, "Alpha"); greek.Add(2, "Beta"); string secondGreek = greek[2]; // Beta </code></pre> <p>But trying to get the keys given a value is not as straightforward because there could be multiple keys:</p> <pre><code>int[] betaKeys = greek.WhatDoIPutHere("Beta"); // expecting single 2 </code></pre>
[ { "answer_id": 255348, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 2, "selected": false, "text": "var key = (from k in yourDictionary where string.Compare(k.Value, \"yourValue\", true) == 0 select k.Key).FirstOrDefault();\n" }, { "answer_id": 255352, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 5, "selected": false, "text": "var greek = new Dictionary<int, string> { { 1, \"Alpha\" }, { 2, \"Alpha\" } };\n" }, { "answer_id": 255354, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": false, "text": "int betaKey; \nforeach (KeyValuePair<int, string> pair in lookup)\n{\n if (pair.Value == value)\n {\n betaKey = pair.Key; // Found\n break;\n }\n}\nbetaKey = -1; // Not found\n" }, { "answer_id": 255364, "author": "Cybis", "author_id": 32998, "author_profile": "https://Stackoverflow.com/users/32998", "pm_score": 1, "selected": false, "text": "\n public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >\n {\n private Dictionary < TValue, TKey > _keys;\n\n public TValue this[TKey key]\n {\n get\n {\n return base[key];\n }\n set \n { \n base[key] = value;\n _keys[value] = key;\n }\n }\n\n public MyDict()\n {\n _keys = new Dictionary < TValue, TKey >();\n }\n\n public TKey GetKeyFromValue(TValue value)\n {\n return _keys[value];\n }\n }\n" }, { "answer_id": 255630, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "using System;\nusing System.Collections.Generic;\n\nclass BiDictionary<TFirst, TSecond>\n{\n IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();\n IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();\n\n public void Add(TFirst first, TSecond second)\n {\n if (firstToSecond.ContainsKey(first) ||\n secondToFirst.ContainsKey(second))\n {\n throw new ArgumentException(\"Duplicate first or second\");\n }\n firstToSecond.Add(first, second);\n secondToFirst.Add(second, first);\n }\n\n public bool TryGetByFirst(TFirst first, out TSecond second)\n {\n return firstToSecond.TryGetValue(first, out second);\n }\n\n public bool TryGetBySecond(TSecond second, out TFirst first)\n {\n return secondToFirst.TryGetValue(second, out first);\n }\n}\n\nclass Test\n{\n static void Main()\n {\n BiDictionary<int, string> greek = new BiDictionary<int, string>();\n greek.Add(1, \"Alpha\");\n greek.Add(2, \"Beta\");\n int x;\n greek.TryGetBySecond(\"Beta\", out x);\n Console.WriteLine(x);\n }\n}\n" }, { "answer_id": 255638, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nclass BiDictionary<TFirst, TSecond>\n{\n IDictionary<TFirst, IList<TSecond>> firstToSecond = new Dictionary<TFirst, IList<TSecond>>();\n IDictionary<TSecond, IList<TFirst>> secondToFirst = new Dictionary<TSecond, IList<TFirst>>();\n\n private static IList<TFirst> EmptyFirstList = new TFirst[0];\n private static IList<TSecond> EmptySecondList = new TSecond[0];\n\n public void Add(TFirst first, TSecond second)\n {\n IList<TFirst> firsts;\n IList<TSecond> seconds;\n if (!firstToSecond.TryGetValue(first, out seconds))\n {\n seconds = new List<TSecond>();\n firstToSecond[first] = seconds;\n }\n if (!secondToFirst.TryGetValue(second, out firsts))\n {\n firsts = new List<TFirst>();\n secondToFirst[second] = firsts;\n }\n seconds.Add(second);\n firsts.Add(first);\n }\n\n // Note potential ambiguity using indexers (e.g. mapping from int to int)\n // Hence the methods as well...\n public IList<TSecond> this[TFirst first]\n {\n get { return GetByFirst(first); }\n }\n\n public IList<TFirst> this[TSecond second]\n {\n get { return GetBySecond(second); }\n }\n\n public IList<TSecond> GetByFirst(TFirst first)\n {\n IList<TSecond> list;\n if (!firstToSecond.TryGetValue(first, out list))\n {\n return EmptySecondList;\n }\n return new List<TSecond>(list); // Create a copy for sanity\n }\n\n public IList<TFirst> GetBySecond(TSecond second)\n {\n IList<TFirst> list;\n if (!secondToFirst.TryGetValue(second, out list))\n {\n return EmptyFirstList;\n }\n return new List<TFirst>(list); // Create a copy for sanity\n }\n}\n\nclass Test\n{\n static void Main()\n {\n BiDictionary<int, string> greek = new BiDictionary<int, string>();\n greek.Add(1, \"Alpha\");\n greek.Add(2, \"Beta\");\n greek.Add(5, \"Beta\");\n ShowEntries(greek, \"Alpha\");\n ShowEntries(greek, \"Beta\");\n ShowEntries(greek, \"Gamma\");\n }\n\n static void ShowEntries(BiDictionary<int, string> dict, string key)\n {\n IList<int> values = dict[key];\n StringBuilder builder = new StringBuilder();\n foreach (int value in values)\n {\n if (builder.Length != 0)\n {\n builder.Append(\", \");\n }\n builder.Append(value);\n }\n Console.WriteLine(\"{0}: [{1}]\", key, builder);\n }\n}\n" }, { "answer_id": 255643, "author": "dbkk", "author_id": 838, "author_profile": "https://Stackoverflow.com/users/838", "pm_score": 2, "selected": false, "text": "public List<TKey> GetKeysFromValue<TKey, TVal>(Dictionary<TKey, TVal> dict, TVal val)\n{\n List<TKey> ks = new List<TKey>();\n foreach(TKey k in dict.Keys)\n {\n if (dict[k] == val) { ks.Add(k); }\n }\n return ks;\n}\n" }, { "answer_id": 11853278, "author": "Loay", "author_id": 1161506, "author_profile": "https://Stackoverflow.com/users/1161506", "pm_score": 1, "selected": false, "text": "Dictionary<string, string> dic = new Dictionary<string, string>();\ndic[\"A\"] = \"Ahmed\";\ndic[\"B\"] = \"Boys\";\n\nforeach (string mk in dic.Keys)\n{\n if(dic[mk] == \"Ahmed\")\n {\n Console.WriteLine(\"The key that contains \\\"Ahmed\\\" is \" + mk);\n }\n}\n" }, { "answer_id": 22230811, "author": "DavidRR", "author_id": 1497596, "author_profile": "https://Stackoverflow.com/users/1497596", "pm_score": 1, "selected": false, "text": "Dictionary<K, V>" }, { "answer_id": 26724048, "author": "Michail Michailidis", "author_id": 986160, "author_profile": "https://Stackoverflow.com/users/986160", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Collections;\n\nnamespace MyApp.Dictionaries\n{\n\n class BiDictionary<TFirst, TSecond> : IEnumerable\n {\n IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();\n IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();\n\n public void Add(TFirst first, TSecond second)\n {\n firstToSecond.Add(first, second);\n secondToFirst.Add(second, first);\n }\n\n public TSecond this[TFirst first]\n {\n get { return GetByFirst(first); }\n }\n\n public TFirst this[TSecond second]\n {\n get { return GetBySecond(second); }\n }\n\n public TSecond GetByFirst(TFirst first)\n {\n return firstToSecond[first];\n }\n\n public TFirst GetBySecond(TSecond second)\n {\n return secondToFirst[second];\n }\n\n public IEnumerator GetEnumerator()\n {\n return GetFirstEnumerator();\n }\n\n public IEnumerator GetFirstEnumerator()\n {\n return firstToSecond.GetEnumerator();\n }\n\n public IEnumerator GetSecondEnumerator()\n {\n return secondToFirst.GetEnumerator();\n }\n }\n}\n" }, { "answer_id": 40020615, "author": "DW.com", "author_id": 6406263, "author_profile": "https://Stackoverflow.com/users/6406263", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Common\n{\n /// <summary>Represents a bidirectional collection of keys and values.</summary>\n /// <typeparam name=\"TFirst\">The type of the keys in the dictionary</typeparam>\n /// <typeparam name=\"TSecond\">The type of the values in the dictionary</typeparam>\n [System.Runtime.InteropServices.ComVisible(false)]\n [System.Diagnostics.DebuggerDisplay(\"Count = {Count}\")]\n //[System.Diagnostics.DebuggerTypeProxy(typeof(System.Collections.Generic.Mscorlib_DictionaryDebugView<,>))]\n //[System.Reflection.DefaultMember(\"Item\")]\n public class BiDictionary<TFirst, TSecond> : Dictionary<TFirst, TSecond>\n {\n IDictionary<TSecond, TFirst> _ValueKey = new Dictionary<TSecond, TFirst>();\n /// <summary> PropertyAccessor for Iterator over KeyValue-Relation </summary>\n public IDictionary<TFirst, TSecond> KeyValue => this;\n /// <summary> PropertyAccessor for Iterator over ValueKey-Relation </summary>\n public IDictionary<TSecond, TFirst> ValueKey => _ValueKey;\n\n #region Implemented members\n\n /// <Summary>Gets or sets the value associated with the specified key.</Summary>\n /// <param name=\"key\">The key of the value to get or set.</param>\n /// <Returns>The value associated with the specified key. If the specified key is not found,\n /// a get operation throws a <see cref=\"KeyNotFoundException\"/>, and\n /// a set operation creates a new element with the specified key.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"key\"/> is null.</exception>\n /// <exception cref=\"T:System.Collections.Generic.KeyNotFoundException\">\n /// The property is retrieved and <paramref name=\"key\"/> does not exist in the collection.</exception>\n /// <exception cref=\"T:System.ArgumentException\"> An element with the same key already\n /// exists in the <see cref=\"ValueKey\"/> <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</exception>\n public new TSecond this[TFirst key]\n {\n get { return base[key]; }\n set { _ValueKey.Remove(base[key]); base[key] = value; _ValueKey.Add(value, key); }\n }\n\n /// <Summary>Gets or sets the key associated with the specified value.</Summary>\n /// <param name=\"val\">The value of the key to get or set.</param>\n /// <Returns>The key associated with the specified value. If the specified value is not found,\n /// a get operation throws a <see cref=\"KeyNotFoundException\"/>, and\n /// a set operation creates a new element with the specified value.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"val\"/> is null.</exception>\n /// <exception cref=\"T:System.Collections.Generic.KeyNotFoundException\">\n /// The property is retrieved and <paramref name=\"val\"/> does not exist in the collection.</exception>\n /// <exception cref=\"T:System.ArgumentException\"> An element with the same value already\n /// exists in the <see cref=\"KeyValue\"/> <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</exception>\n public TFirst this[TSecond val]\n {\n get { return _ValueKey[val]; }\n set { base.Remove(_ValueKey[val]); _ValueKey[val] = value; base.Add(value, val); }\n }\n\n /// <Summary>Adds the specified key and value to the dictionary.</Summary>\n /// <param name=\"key\">The key of the element to add.</param>\n /// <param name=\"value\">The value of the element to add.</param>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"key\"/> or <paramref name=\"value\"/> is null.</exception>\n /// <exception cref=\"T:System.ArgumentException\">An element with the same key or value already exists in the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</exception>\n public new void Add(TFirst key, TSecond value) {\n base.Add(key, value);\n _ValueKey.Add(value, key);\n }\n\n /// <Summary>Removes all keys and values from the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Summary>\n public new void Clear() { base.Clear(); _ValueKey.Clear(); }\n\n /// <Summary>Determines whether the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/> contains the specified\n /// KeyValuePair.</Summary>\n /// <param name=\"item\">The KeyValuePair to locate in the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</param>\n /// <Returns>true if the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/> contains an element with\n /// the specified key which links to the specified value; otherwise, false.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"item\"/> is null.</exception>\n public bool Contains(KeyValuePair<TFirst, TSecond> item) => base.ContainsKey(item.Key) & _ValueKey.ContainsKey(item.Value);\n\n /// <Summary>Removes the specified KeyValuePair from the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Summary>\n /// <param name=\"item\">The KeyValuePair to remove.</param>\n /// <Returns>true if the KeyValuePair is successfully found and removed; otherwise, false. This\n /// method returns false if <paramref name=\"item\"/> is not found in the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"item\"/> is null.</exception>\n public bool Remove(KeyValuePair<TFirst, TSecond> item) => base.Remove(item.Key) & _ValueKey.Remove(item.Value);\n\n /// <Summary>Removes the value with the specified key from the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Summary>\n /// <param name=\"key\">The key of the element to remove.</param>\n /// <Returns>true if the element is successfully found and removed; otherwise, false. This\n /// method returns false if <paramref name=\"key\"/> is not found in the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"key\"/> is null.</exception>\n public new bool Remove(TFirst key) => _ValueKey.Remove(base[key]) & base.Remove(key);\n\n /// <Summary>Gets the key associated with the specified value.</Summary>\n /// <param name=\"value\">The value of the key to get.</param>\n /// <param name=\"key\">When this method returns, contains the key associated with the specified value,\n /// if the value is found; otherwise, the default value for the type of the key parameter.\n /// This parameter is passed uninitialized.</param>\n /// <Returns>true if <see cref=\"ValueKey\"/> contains an element with the specified value; \n /// otherwise, false.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"value\"/> is null.</exception>\n public bool TryGetValue(TSecond value, out TFirst key) => _ValueKey.TryGetValue(value, out key);\n #endregion\n }\n}\n" }, { "answer_id": 50731776, "author": "beppe9000", "author_id": 3389585, "author_profile": "https://Stackoverflow.com/users/3389585", "pm_score": 0, "selected": false, "text": " public Dictionary<TValue, TKey> Invert(Dictionary<TKey, TValue> dict) {\n Dictionary<TValue, TKey> ret = new Dictionary<TValue, TKey>();\n foreach (var kvp in dict) {ret[kvp.value] = kvp.key;} return ret; }\n" }, { "answer_id": 63500438, "author": "Jessica", "author_id": 5151441, "author_profile": "https://Stackoverflow.com/users/5151441", "pm_score": 1, "selected": false, "text": "IEnumerable<KeyValuePair<int, string>>" }, { "answer_id": 73478394, "author": "iiKuzmychov", "author_id": 10846531, "author_profile": "https://Stackoverflow.com/users/10846531", "pm_score": 0, "selected": false, "text": "O(1)" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22437/" ]
255,370
<p>I am developing Eclipse plugins, and I need to be able to automate the building and execution of the test suite for each plugin. (Using Junit)</p> <p>Test are working within Eclipse, and I can break the plugins into the actual plugin and a fragment plugin for unit testing as described <a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.test/testframework.html?view=co" rel="nofollow noreferrer">here</a>, <a href="http://rcpquickstart.com/2007/08/06/running-automated-tests-with-pde-build/" rel="nofollow noreferrer">here</a> and in a couple places <a href="http://eclipsenuggets.blogspot.com/2007/09/6-great-links-for-eclipse-build.html" rel="nofollow noreferrer">here</a>.</p> <p>However, each of the approaches above results in the same issue: The java ant task/commandline command that issues the build or should trigger the test, generates no observable side effects, and returns the value "13". I've tried everything I can find, and I've learned a fair bit about how Eclipse starts up (eg: since v3.3 you can no longer use startup.jar -- it doesn't exist -- but you should use <a href="http://blog.ciscavate.org/2008/11/treat-your-mailing-lists-like-reference-documents-please.html" rel="nofollow noreferrer">org.eclipse.equinox.launcher</a>). Unfortunately, while that is apparently necessary information, it is far from sufficient.</p> <p>I am working with Eclipse 3.4, Junit 4.3.1 (the org.junit4 bundle, but I would much rather use JUnit 4.4. See <a href="https://stackoverflow.com/questions/251791">here</a>.)</p> <p>So, my question is: How exactly do you automate the build and testing of Eclipse plugins? </p> <p><em>Edit:</em> To clarify, I <em>want</em> to use something like ant + cruise control, but I can't even get the unit tests to run <em>at all</em> outside of Eclipse. I say "something like" because there are other technologies that accomplish the same thing, and I am not so picky as to discard a solution that works just because it's using say, Maven or Buckminster, if those technologies make this substantially easier.</p> <p><em>Edit2:</em> The 'Java Result 13' mentioned above seems to be caused by the inability to find the coretestrunner. From the log:</p> <pre><code>java.lang.RuntimeException: Application "org.eclipse.test.coretestapplication" could not be found in the registry. The applications available are: org.eclipse.equinox.app.error, com.rcpquickstart.helloworld.application. at org.eclipse.equinox.internal.app.EclipseAppContainer.startDefaultApp(EclipseAppContainer.java:242) at org.eclipse.equinox.internal.app.MainApplicationLauncher.run(MainApplicationLauncher.java:29) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504) at org.eclipse.equinox.launcher.Main.run(Main.java:1236) at org.eclipse.equinox.launcher.Main.main(Main.java:1212) at org.eclipse.core.launcher.Main.main(Main.java:30) !ENTRY org.eclipse.osgi 2 0 2008-11-04 21:02:10.514 !MESSAGE The following is a complete list of bundles which are not resolved, see the prior log entry for the root cause if it exists: !SUBENTRY 1 org.eclipse.osgi 2 0 2008-11-04 21:02:10.515 !MESSAGE Bundle update@plugins/org.eclipse.test_3.2.0/ [34] was not resolved. !SUBENTRY 2 org.eclipse.test 2 0 2008-11-04 21:02:10.516 !MESSAGE Missing required bundle org.apache.ant_0.0.0. !SUBENTRY 2 org.eclipse.test 2 0 2008-11-04 21:02:10.516 !MESSAGE Missing required bundle org.eclipse.ui.ide.application_0.0.0. !SUBENTRY 1 org.eclipse.osgi 2 0 2008-11-04 21:02:10.518 !MESSAGE Bundle update@plugins/org.eclipse.ant.optional.junit_3.2.100.jar [60] was not resolved. !SUBENTRY 2 org.eclipse.ant.optional.junit 2 0 2008-11-04 21:02:10.519 !MESSAGE Missing host org.apache.ant_[1.6.5,2.0.0). !SUBENTRY 2 org.eclipse.ant.optional.junit 2 0 2008-11-04 21:02:10.519 !MESSAGE Missing required bundle org.eclipse.core.runtime.compatibility_0.0.0. </code></pre>
[ { "answer_id": 288064, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 4, "selected": false, "text": "uitestapplication" }, { "answer_id": 963808, "author": "liangzan", "author_id": 11927, "author_profile": "https://Stackoverflow.com/users/11927", "pm_score": 2, "selected": false, "text": "<features>\n <feature id=\"mock_feature\" version=\"1.0.0\"/>\n <feature id=\"mock_feature_test\" version=\"1.0.0\"/>\n <feature id=\"org.eclipse.rcp\" version=\"3.2.0.v20060609m-SVDNgVrNoh-MeGG\"/>\n <feature id=\"org.eclipse.test\" version=\"3.2.0.v20060220------0842282442\"/>\n </features>\n" }, { "answer_id": 27933127, "author": "Gunjan Aggarwal", "author_id": 2888308, "author_profile": "https://Stackoverflow.com/users/2888308", "pm_score": 2, "selected": false, "text": "java -Xms40m -Xmx1024m -XX:MaxPermSize=512m -Dorg.eclipse.swt.browser.DefaultType=mozilla -Declipse.pde.launch=true -classpath C:\\eclipse\\eclipse-standard-luna-M2-win32-x86_64\\eclipse\\plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar org.eclipse.equinox.launcher.Main -port 22 -testLoaderClass org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader -loaderpluginname org.eclipse.jdt.junit4.runtime -classNames testpackage.testClass -application org.eclipse.pde.junit.runtime.uitestapplication -data C:\\temp\\log.temp -dev bin -consoleLog -testpluginname PluginName\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446/" ]
255,393
<p>I'm trying to make a page in php that takes rows from a database, displays them, and then give the viewer a chance to upvote or downvote a specific entry. Here is a snippet:</p> <pre><code>echo("&lt;form action=\"vote.php\" method=\"post\"&gt; \n"); echo("&lt;INPUT type=\"hidden\" name=\"idnum\" value=\"".$row[0]."\"&gt;"); echo("&lt;INPUT type=\"submit\" name=\"up\" value=\"Upvote.\"&gt; \n"); echo("&lt;INPUT type=\"submit\" name=\"down\" value=\"Downvote\"&gt; "); echo("&lt;form/&gt;\n"); </code></pre> <p>The problem is when I hit a submit button, the value for idnum that gets sent is based on the one farthest down it seems. So my questions is, when a submit button is pressed, are the values for all inputs on a page sent?</p>
[ { "answer_id": 255396, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "</form>" }, { "answer_id": 255397, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "</form>" }, { "answer_id": 255398, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": true, "text": "<form/>" }, { "answer_id": 255432, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<form action=\"vote.php\" method=\"post\">\n <input type=\"hidden\" name=\"idnum\" value=\"<?php echo $row[0]; ?>\">\n <input type=\"submit\" name=\"up\" value=\"Upvote.\">\n <input type=\"submit\" name=\"down\" value=\"Downvote\">\n</form>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25680/" ]
255,400
<p>This is a very complicated question concerning how to serialize data via a web service call, when the data is not-strongly typed. I'll try to lay it out as best possible.</p> <p><strong>Sample Storage Object:</strong></p> <pre><code>[Serializable] public class StorageObject { public string Name { get; set; } public string Birthday { get; set; } public List&lt;NameValuePairs&gt; OtherInfo { get; set; } } [Serializable] public class NameValuePairs { public string Name { get; set; } public string Value { get; set; } } </code></pre> <p><strong>Sample Use:</strong></p> <pre><code>[WebMethod] public List&lt;StorageObject&gt; GetStorageObjects() { List&lt;StorageObject&gt; o = new List&lt;StorageObject&gt;() { new StorageObject() { Name = "Matthew", Birthday = "Jan 1st, 2008", OtherInfo = new List&lt;NameValuePairs&gt;() { new NameValuePairs() { Name = "Hobbies", Value = "Programming" }, new NameValuePairs() { Name = "Website", Value = "Stackoverflow.com" } } }, new StorageObject() { Name = "Joe", Birthday = "Jan 10th, 2008", OtherInfo = new List&lt;NameValuePairs&gt;() { new NameValuePairs() { Name = "Hobbies", Value = "Programming" }, new NameValuePairs() { Name = "Website", Value = "Stackoverflow.com" } } } }; return o; } </code></pre> <p><strong>Return Value from Web Service:</strong></p> <pre><code>&lt;StorageObject&gt; &lt;Name&gt;Matthew&lt;/Name&gt; &lt;Birthday&gt;Jan 1st, 2008&lt;/Birthday&gt; &lt;OtherInfo&gt; &lt;NameValuePairs&gt; &lt;Name&gt;Hobbies&lt;/Name&gt; &lt;Value&gt;Programming&lt;/Value&gt; &lt;/NameValuePairs&gt; &lt;NameValuePairs&gt; &lt;Name&gt;Website&lt;/Name&gt; &lt;Value&gt;Stackoverflow.com&lt;/Value&gt; &lt;/NameValuePairs&gt; &lt;/OtherInfo&gt; &lt;/StorageObject&gt; </code></pre> <p><strong>What I want:</strong></p> <pre><code>&lt;OtherInfo&gt; &lt;Hobbies&gt;Programming&lt;/Hobbies&gt; &lt;Website&gt;Stackoverflow.com&lt;/Website&gt; &lt;/OtherInfo&gt; </code></pre> <p><strong>The Reason &amp; Other Stuff:</strong></p> <p>First, I'm sorry for the length of the post, but I wanted to give reproducible code as well. </p> <p>I want it in this format, because I'm consuming the web services from PHP. I want to easily go:</p> <p>// THIS IS IMPORANT</p> <pre><code>In PHP =&gt; "$Result["StorageObject"]["OtherInfo"]["Hobbies"]". </code></pre> <p>If it's in the other format, then there would be no way for me to accomplish that, at all. Additionally, in C# if I am consuming the service, I would also like to be able to do the following:</p> <p>// THIS IS IMPORANT</p> <pre><code>In C# =&gt; var m = ServiceResult[0].OtherInfo["Hobbies"]; </code></pre> <p>Unfortunately, I'm not sure how to accomplish this. I was able to get it this way, by building a custom Dictionary that implemented IXmlSerializer (see <a href="https://stackoverflow.com/questions/67959/c-xml-serialization-gotchas">StackOverflow: IXmlSerializer Dictionary</a>), however, it blew the WSDL schema out of the water. It's also much too complicated, and produced horrible results in my WinFormsTester application!</p> <p>Is there any way to accomplish this ? What type of objects do I need to create ? Is there any way to do this /other than by making a strongly typed collection/ ? Obviously, if I make it strongly typed like this:</p> <pre><code>public class OtherInfo { public string Hobbies { get; set; } public string FavoriteWebsite { get; set; } } </code></pre> <p>Then it would work perfectly, I would have no WSDL issues, I would be able to easily access it from PHP, and C# (.OtherInfo.Hobbies). </p> <p>However, I would completely lose the point of NVP's, in that I would have to know in advance what the list is, and it would be unchangeable.. say, from a Database.</p> <p>Thanks everyone!! I hope we're able to come up with some sort of solution to this. Here's are the requirements again:</p> <ol> <li>WSDL schema should not break</li> <li>Name value pairs (NVP's) should be serialized into attribute format</li> <li>Should be easy to access NVP's in PHP by name ["Hobbies"]</li> <li>Should be easy to access in C# (and be compatible with it's Proxy generator)</li> <li>Be easily serializable</li> <li>Not require me to strongly type the data</li> </ol> <p>Now, I am /completely/ open to input on a better/different way to do this. I'm storing some relatively "static" information (like Name), and a bunch of pieces of data. If there's a better way, I'd love to hear it.</p>
[ { "answer_id": 255411, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": -1, "selected": false, "text": "Dictionary<string,List<string>> OtherInfo" }, { "answer_id": 255424, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 4, "selected": true, "text": "public class StorageObject {\n public string Name { get; set; }\n public string Birthday { get; set; }\n public List<string> OtherInfo { get; set; } \n}\n" }, { "answer_id": 255455, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "OtherInfo" }, { "answer_id": 255469, "author": "Matthew M.", "author_id": 27472, "author_profile": "https://Stackoverflow.com/users/27472", "pm_score": 2, "selected": false, "text": "public class StorageObject {\n public string Name { get; set; }\n public string Birthday { get; set; }\n [XmlAnyElement(\"Info\")] // this prevents double-nodes in the XML\n public XElement OtherInfo { get; set; }\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27472/" ]
255,414
<p>I'm trying to write a small script to change the current directory to my project directory:</p> <pre><code>#!/bin/bash cd /home/tree/projects/java </code></pre> <p>I saved this file as proj, added execute permission with <code>chmod</code>, and copied it to <code>/usr/bin</code>. When I call it by: <code>proj</code>, it does nothing. What am I doing wrong?</p>
[ { "answer_id": 255415, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 10, "selected": true, "text": "cd" }, { "answer_id": 255416, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 9, "selected": false, "text": ". proj\n" }, { "answer_id": 255417, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 4, "selected": false, "text": "/bin/bash" }, { "answer_id": 255418, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "cd my-project" }, { "answer_id": 255439, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 4, "selected": false, "text": "#!/bin/bash\ncd /your/project/directory\n# start another shell and replacing the current\nexec /bin/bash\n" }, { "answer_id": 255526, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": false, "text": "CDPATH=:$HOME/projects\n" }, { "answer_id": 259349, "author": "J. A. Faucett", "author_id": 18503, "author_profile": "https://Stackoverflow.com/users/18503", "pm_score": 3, "selected": false, "text": "alias proj=\"cd \\`/usr/bin/proj !*\\`\"\n" }, { "answer_id": 2236614, "author": "Tzachi.e", "author_id": 270251, "author_profile": "https://Stackoverflow.com/users/270251", "pm_score": 7, "selected": false, "text": "cd" }, { "answer_id": 5627915, "author": "chris", "author_id": 702998, "author_profile": "https://Stackoverflow.com/users/702998", "pm_score": 2, "selected": false, "text": "#!/bin/sh\n\ncd /home/\"$1\"\n" }, { "answer_id": 7020787, "author": "DigitalRoss", "author_id": 140740, "author_profile": "https://Stackoverflow.com/users/140740", "pm_score": 8, "selected": false, "text": "cd" }, { "answer_id": 9207009, "author": "rjmoggach", "author_id": 586932, "author_profile": "https://Stackoverflow.com/users/586932", "pm_score": 3, "selected": false, "text": "alias project=\". project\"\n" }, { "answer_id": 12423064, "author": "workdreamer", "author_id": 855668, "author_profile": "https://Stackoverflow.com/users/855668", "pm_score": 4, "selected": false, "text": " function switchp\n {\n cd /home/tree/projects/$1\n }\n" }, { "answer_id": 13112324, "author": "kaelhop", "author_id": 1781341, "author_profile": "https://Stackoverflow.com/users/1781341", "pm_score": 5, "selected": false, "text": ". <your file name>" }, { "answer_id": 13844527, "author": "Lane Roathe", "author_id": 812716, "author_profile": "https://Stackoverflow.com/users/812716", "pm_score": 0, "selected": false, "text": "function proj\n cd /home/tree/projects/java\nend\nfuncsave proj\n" }, { "answer_id": 15849531, "author": "Max", "author_id": 2251927, "author_profile": "https://Stackoverflow.com/users/2251927", "pm_score": -1, "selected": false, "text": "cd somedir; \\\npwd\n" }, { "answer_id": 18306584, "author": "mihai.ciorobea", "author_id": 2071602, "author_profile": "https://Stackoverflow.com/users/2071602", "pm_score": 3, "selected": false, "text": "move_me() {\n cd ~/path/to/dest\n}\n" }, { "answer_id": 19135116, "author": "godzilla", "author_id": 1054503, "author_profile": "https://Stackoverflow.com/users/1054503", "pm_score": -1, "selected": false, "text": "alias p='. p'\n" }, { "answer_id": 21498174, "author": "thomasd", "author_id": 468828, "author_profile": "https://Stackoverflow.com/users/468828", "pm_score": 2, "selected": false, "text": "function cdbm() {\n cd whereever_you_want_to_go\n echo \"Arguments to the functions were $1, $2, ...\"\n}\n" }, { "answer_id": 21676651, "author": "Sagar", "author_id": 1483186, "author_profile": "https://Stackoverflow.com/users/1483186", "pm_score": 6, "selected": false, "text": "." }, { "answer_id": 36768357, "author": "Serge Stroobandt", "author_id": 2192488, "author_profile": "https://Stackoverflow.com/users/2192488", "pm_score": 5, "selected": false, "text": "exec bash" }, { "answer_id": 38771044, "author": "Krish", "author_id": 2018627, "author_profile": "https://Stackoverflow.com/users/2018627", "pm_score": 2, "selected": false, "text": ".bash_profile" }, { "answer_id": 39406080, "author": "Gauthier", "author_id": 108802, "author_profile": "https://Stackoverflow.com/users/108802", "pm_score": 0, "selected": false, "text": "shopt -s cdable_vars\n" }, { "answer_id": 42720845, "author": "warhansen", "author_id": 5497373, "author_profile": "https://Stackoverflow.com/users/5497373", "pm_score": 4, "selected": false, "text": "cd /home/xxx/yyy && command_you_want\n" }, { "answer_id": 49748187, "author": "intika", "author_id": 4877948, "author_profile": "https://Stackoverflow.com/users/4877948", "pm_score": 1, "selected": false, "text": "sh" }, { "answer_id": 50145087, "author": "jithu83", "author_id": 2950979, "author_profile": "https://Stackoverflow.com/users/2950979", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n\n# saved as mov_dir.sh\ncd ~/mt/v3/rt_linux-rt-tools/\nbash\n" }, { "answer_id": 51986175, "author": "18446744073709551615", "author_id": 755804, "author_profile": "https://Stackoverflow.com/users/755804", "pm_score": 0, "selected": false, "text": "tailcd" }, { "answer_id": 60427463, "author": "Yuri Nudelman", "author_id": 5528355, "author_profile": "https://Stackoverflow.com/users/5528355", "pm_score": 0, "selected": false, "text": "export PWD=the/path/you/want\n" }, { "answer_id": 63926954, "author": "ZakS", "author_id": 8270512, "author_profile": "https://Stackoverflow.com/users/8270512", "pm_score": 0, "selected": false, "text": "a alias_name 'set a = `pwd`; set b = `echo $a | replace \"Trees\" \"Tests\"` ; cd $b'\n" }, { "answer_id": 64529986, "author": "Asclepius", "author_id": 832230, "author_profile": "https://Stackoverflow.com/users/832230", "pm_score": 0, "selected": false, "text": "getent" }, { "answer_id": 71812788, "author": "zyfyy", "author_id": 1857269, "author_profile": "https://Stackoverflow.com/users/1857269", "pm_score": 0, "selected": false, "text": "source" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33203/" ]
255,419
<p>Trying to write a PowerShell cmdlet that will mute the sound at start, unless already muted, and un-mute it at the end (only if it wasn't muted to begin with). Couldn't find any PoweShell or WMI object I could use. I was toying with using Win32 functions like <a href="http://msdn.microsoft.com/en-us/library/ms706237(VS.85).aspx" rel="noreferrer">auxGetVolume</a> or <a href="http://msdn.microsoft.com/en-us/library/ms706237(VS.85).aspx" rel="noreferrer">auxSetVolume</a>, but couldn't quite get it to work (how to read the values from an IntPtr?).</p> <p>I'm using V2 CTP2. Any ideas folks?</p> <p>Thanks!</p>
[ { "answer_id": 1670848, "author": "user202195", "author_id": 202195, "author_profile": "https://Stackoverflow.com/users/202195", "pm_score": 2, "selected": false, "text": "C:\\utils\\nircmd.exe mutesysvolume 0 # 1 to to unmute, 2 to toggle\n" }, { "answer_id": 12397737, "author": "Diogo", "author_id": 516290, "author_profile": "https://Stackoverflow.com/users/516290", "pm_score": 5, "selected": false, "text": "$obj = new-object -com wscript.shell \n$obj.SendKeys([char]173)\n" }, { "answer_id": 14616608, "author": "Michael", "author_id": 978370, "author_profile": "https://Stackoverflow.com/users/978370", "pm_score": 2, "selected": false, "text": "Set WshShell = CreateObject(\"WScript.Shell\")\nFor i = 0 To 50\n WshShell.SendKeys(chr(174))\n WScript.Sleep 100\nNext\n" }, { "answer_id": 19348221, "author": "Alex Jasmin", "author_id": 162407, "author_profile": "https://Stackoverflow.com/users/162407", "pm_score": 5, "selected": false, "text": "[Audio]::Volume" }, { "answer_id": 25015720, "author": "logicaldiagram", "author_id": 1050536, "author_profile": "https://Stackoverflow.com/users/1050536", "pm_score": 1, "selected": false, "text": "Set-DefaultAudioDeviceMute\n" }, { "answer_id": 35494000, "author": "ypeels", "author_id": 5948347, "author_profile": "https://Stackoverflow.com/users/5948347", "pm_score": 3, "selected": false, "text": "CreateObject(\"WScript.Shell\").SendKeys(chr(173))\n" }, { "answer_id": 39921792, "author": "Anchmerama", "author_id": 5301718, "author_profile": "https://Stackoverflow.com/users/5301718", "pm_score": 4, "selected": false, "text": "Add-Type -Language CsharpVersion3 -TypeDefinition @'\nusing System.Runtime.InteropServices;\n\n[Guid(\"5CDF2C82-841E-4546-9722-0CF74078229A\"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\ninterface IAudioEndpointVolume {\n // f(), g(), ... are unused COM method slots. Define these if you care\n int f(); int g(); int h(); int i();\n int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext);\n int j();\n int GetMasterVolumeLevelScalar(out float pfLevel);\n int k(); int l(); int m(); int n();\n int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext);\n int GetMute(out bool pbMute);\n}\n[Guid(\"D666063F-1587-4E43-81F1-B948E807363F\"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\ninterface IMMDevice {\n int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);\n}\n[Guid(\"A95664D2-9614-4F35-A746-DE8DB63617E6\"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\ninterface IMMDeviceEnumerator {\n int f(); // Unused\n int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);\n}\n[ComImport, Guid(\"BCDE0395-E52F-467C-8E3D-C4579291692E\")] class MMDeviceEnumeratorComObject { }\n\npublic class Audio {\n static IAudioEndpointVolume Vol() {\n var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;\n IMMDevice dev = null;\n Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(/*eRender*/ 0, /*eMultimedia*/ 1, out dev));\n IAudioEndpointVolume epv = null;\n var epvid = typeof(IAudioEndpointVolume).GUID;\n Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));\n return epv;\n }\n public static float Volume {\n get {float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v;}\n set {Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty));}\n }\n public static bool Mute {\n get { bool mute; Marshal.ThrowExceptionForHR(Vol().GetMute(out mute)); return mute; }\n set { Marshal.ThrowExceptionForHR(Vol().SetMute(value, System.Guid.Empty)); }\n }\n}\n'@\n" }, { "answer_id": 63156262, "author": "user18432", "author_id": 12632967, "author_profile": "https://Stackoverflow.com/users/12632967", "pm_score": 0, "selected": false, "text": "-Language CsharpVersion3\n" }, { "answer_id": 65427910, "author": "Dakota", "author_id": 14879200, "author_profile": "https://Stackoverflow.com/users/14879200", "pm_score": 1, "selected": false, "text": "Import-Module .\\AudioDeviceCmdlets\n$audio_device_list = Get-AudioDevice -list\n$recording_devices = $audio_device_list | ? {$_.Type -eq \"Recording\"}\n$recording_devices \n$recording_device_index = $recording_devices.Index | Out-String -stream\nforeach ($i in $recording_device_index) {\n $inti = [int]$i\n Set-AudioDevice $inti | out-null -erroraction SilentlyContinue\n Set-AudioDevice -RecordingMute 1 -erroraction SilentlyContinue\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19856/" ]
255,422
<p>I would like to create an HTML table with row colors changing based on position and content. But instead of alternating every row, I'd like to be able to group rows together, so that I can have some XML like this:</p> <pre><code>&lt;itemlist&gt; &lt;item group="0"&gt;Conent...blah blah&lt;/item&gt; &lt;item group="0"&gt;Content...who cares&lt;/item&gt; &lt;item group="1"&gt;Content&lt;/item&gt; &lt;item group="2"&gt;Content&lt;/item&gt; &lt;item group="2"&gt;Content&lt;/item&gt; &lt;/itemlist&gt; </code></pre> <p>And all of the items with group=0 are one color, and items with group=1 are another, and group=2 are either toggled back to the first color, or are their own color.</p> <p>All I can seem to find out there is ways to alternate every row, but I can't seem to "get it" when it comes to actually using the node data to help me make the decision.</p>
[ { "answer_id": 255467, "author": "jmcdowell", "author_id": 2421, "author_profile": "https://Stackoverflow.com/users/2421", "pm_score": 3, "selected": true, "text": "<xsl:template match=\"/\">\n <ul>\n <xsl:apply-templates select=\"itemlist/item\"/>\n </ul>\n</xsl:template>\n\n<xsl:template match=\"item\">\n <li>\n <xsl:attribute name=\"class\">\n <xsl:choose>\n <xsl:when test=\"@group = 0\">\n red\n </xsl:when>\n <xsl:when test=\"@group = 1\">\n green\n </xsl:when>\n <xsl:when test=\"@group = 2\">\n blue\n </xsl:when>\n <xsl:otherwise>\n black\n </xsl:otherwise>\n </xsl:choose>\n </xsl:attribute>\n <xsl:value-of select=\".\"/>\n </li>\n</xsl:template>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33263/" ]
255,423
<p>I seem to remember being able to print out (or locate) the specific switches that each -O&lt;num> option turns on. Can you remind?</p> <p>Thanks!</p>
[ { "answer_id": 255434, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "$ man gcc\n" }, { "answer_id": 255440, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 3, "selected": true, "text": "--help" }, { "answer_id": 255530, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "info gcc" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30636/" ]
255,429
<p>I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work?</p> <pre><code>&gt;&gt;&gt; {}.pop('test') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'pop(): dictionary is empty' &gt;&gt;&gt; {}.pop('test',None) &gt;&gt;&gt; {}.pop('test',3) 3 &gt;&gt;&gt; {}.pop('test',NotImplemented) NotImplemented </code></pre> <p>How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?</p> <p>Thanks</p>
[ { "answer_id": 255433, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "def isdefarg(*args):\n if len(args) > 0:\n print len(args), \"arguments\"\n else:\n print \"no arguments\"\n\nisdefarg()\nisdefarg(None)\nisdefarg(5, 7)\n" }, { "answer_id": 255438, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 5, "selected": true, "text": "dict.pop()" }, { "answer_id": 255446, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 1, "selected": false, "text": "def f(one, two=2):\n print \"I wonder if\", two, \"has been passed or not...\"\n\nf(1, 2)\n" }, { "answer_id": 255472, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "def fun(arg=Ellipsis):\n if arg is Ellipsis:\n print \"No arg provided\"\n else:\n print \"arg provided:\", repr(arg)\n" }, { "answer_id": 255580, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 4, "selected": false, "text": "arg=None" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24730/" ]
255,436
<p>Does anyone have any suggestions (or a regular expression) for parsing the HTTP Accept header?</p> <p>I am trying to do some content-type negotiation in ASP.NET MVC. There doesn't seem to be a built in way (which is fine, because there are a lot of schools of thought here), but the parsing is not entirely trivial and I would rather not re-invent the wheel if someone has already done it well and is willing to share.</p>
[ { "answer_id": 255541, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "/([^()<>@,;:\\\\\"\\/[\\]?={} \\t]+)\\/([^()<>@,;:\\\\\"\\/[\\]?={} \\t]+)/\n" }, { "answer_id": 49011308, "author": "Mark Bell", "author_id": 43140, "author_profile": "https://Stackoverflow.com/users/43140", "pm_score": 3, "selected": false, "text": "System.Net.Http.Headers" }, { "answer_id": 52813345, "author": "goofballLogic", "author_id": 275501, "author_profile": "https://Stackoverflow.com/users/275501", "pm_score": 1, "selected": false, "text": "public class MyController : Controller\n{\n\n [HttpGet]\n [Route(\"/test\")]\n public ActionResult Index() {\n\n // does this request accept HTML?\n var acceptsHTML = IsAcceptable(\"text/html\");\n var model = FetchViewModel();\n return acceptsHTML ? (ActionResult) View(model) : Ok(model);\n\n }\n\n private bool IsAcceptable(string mediaType) =>\n Request.Headers[\"Accept\"].Any(headerValue =>\n !string.IsNullOrWhiteSpace(headerValue) &&\n headerValue.Split(\",\").Any(segment => MediaTypeHeaderValue.Parse(segment).MediaType == mediaType));\n\n private object FetchViewModel() {\n\n return new { Description = \"To be completed\" };\n\n }\n\n} \n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11173/" ]
255,445
<p>Does anyone have a library or JavaScript snippet to validate the check digit of credit cards before the user hits Submit?</p>
[ { "answer_id": 23222562, "author": "alexey", "author_id": 92238, "author_profile": "https://Stackoverflow.com/users/92238", "pm_score": 3, "selected": false, "text": "function validateCardNumber(number) {\n var regex = new RegExp(\"^[0-9]{16}$\");\n if (!regex.test(number))\n return false;\n\n return luhnCheck(number);\n}\n\nfunction luhnCheck(val) {\n var sum = 0;\n for (var i = 0; i < val.length; i++) {\n var intVal = parseInt(val.substr(i, 1));\n if (i % 2 == 0) {\n intVal *= 2;\n if (intVal > 9) {\n intVal = 1 + (intVal % 10);\n }\n }\n sum += intVal;\n }\n return (sum % 10) == 0;\n}\n" }, { "answer_id": 28148056, "author": "Lewis", "author_id": 3247703, "author_profile": "https://Stackoverflow.com/users/3247703", "pm_score": 1, "selected": false, "text": "algorithm" }, { "answer_id": 30868032, "author": "leodido", "author_id": 794211, "author_profile": "https://Stackoverflow.com/users/794211", "pm_score": 2, "selected": false, "text": "function luhn(array) {\n return function (number) {\n let len = number ? number.length : 0,\n bit = 1,\n sum = 0;\n\n while (len--) {\n sum += !(bit ^= 1) ? parseInt(number[len], 10) : array[number[len]];\n }\n return sum % 10 === 0 && sum > 0;\n };\n}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9]);\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27193/" ]
255,470
<p>As the title describes, what are the different doctypes available and what do they mean? I notice that the layout looks a little different in IE7 when I switch from </p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" &gt; </code></pre> <p>to</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; </code></pre> <p>Are there any others and what are the effects or ramifications?</p> <p>Thanks!</p>
[ { "answer_id": 255474, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 7, "selected": true, "text": "html" }, { "answer_id": 255747, "author": "cic", "author_id": 4771, "author_profile": "https://Stackoverflow.com/users/4771", "pm_score": 3, "selected": false, "text": "document.compatMode" }, { "answer_id": 256674, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 2, "selected": false, "text": "<!DOCTYPE Chris>" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2849/" ]
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/" rel="noreferrer">Karrigell</a> for the web framework if I go browser-based.</p> <hr> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
[ { "answer_id": 255514, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "<?php if($_POST[\"email\"] ==\"\"){echo(\"Are you sure you want to continue?); ?>" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
255,509
<p>I've heard that projects developed using TDD are easier to refactor because the practice yields a comprehensive set of unit tests, which will (hopefully) fail if any change has broken the code. All of the examples I've seen of this, however, deal with refactoring implementation - changing an algorithm with a more efficient one, for example. </p> <p>I find that refactoring architecture is a lot more common in the early stages where the design is still being worked out. Interfaces change, new classes are added &amp; deleted, even the behavior of a function could change slightly (I thought I needed it to do this, but it actually needs to do that), etc... But if each test case is tightly coupled to these unstable classes, wouldn't you have to be constantly rewriting your test cases each time you change a design? </p> <p>Under what situations in TDD is it okay to alter and delete test cases? How can you be sure that altering the test cases don't break them? Plus it seems that having to synchronize a comprehensive test suite with constantly changing code would be a pain. I understand that the unit test suite could help tremendously during maintenance, once the software is built, stable, and functioning, but that's late in the game wheras TDD is supposed to help early on as well.</p> <p>Lastly, would a good book on TDD and/or refactoring address these sort of issues? If so, which would you recommend?</p>
[ { "answer_id": 255546, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 1, "selected": false, "text": "if definition of correctness changes\n change tests/specs\nend\n\nif definition of correctness does not change\n # no need to change tests/specs\n # though you still can for other reasons if you want/need\nend\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32998/" ]
255,511
<p>What's the difference between \n and \r (I know it has something to do with OS), and what's the best way to echo a line break that will work cross platform?</p> <p><strong>EDIT:</strong> In response to Jarod, I'll be using ths to echo a line break in a .txt log file, though I'm sure I'll be using it in the future for things such as echoing HTML makup onto a page.</p>
[ { "answer_id": 255512, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 7, "selected": true, "text": "\\n" }, { "answer_id": 255531, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 7, "selected": false, "text": "PHP_EOL" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27025/" ]
255,516
<p>I used the method</p> <pre><code>$("#dvTheatres a").hover(function (){ $(this).css("text-decoration", "underline"); },function(){ $(this).css("text-decoration", "none"); } ); </code></pre> <p>Is there a more elegant method?(single line)</p>
[ { "answer_id": 255519, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": false, "text": "#dvTheatres a {\n text-decoration: none;\n}\n\n#dvTheatres a:hover {\n text-decoration: underline;\n}\n" }, { "answer_id": 255539, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "function toggleUnderline() { $(this).toggleClass('underline') };\n$(\"#dvTheatres a\").hover(toggleUnderline, toggleUnderline);\n" }, { "answer_id": 255561, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "#myDiv .myClass a {\n color: red;\n}\n#myDiv a {\n color: blue;\n}\n" }, { "answer_id": 48724078, "author": "Rick", "author_id": 1827424, "author_profile": "https://Stackoverflow.com/users/1827424", "pm_score": 0, "selected": false, "text": "$('.my-awesome div a').hover().css('text-decoration', 'none');\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
255,517
<p>I would like to construct a query that displays all the results in a table, but is offset by 5 from the start of the table. As far as I can tell, MySQL's <code>LIMIT</code> requires a limit as well as an offset. Is there any way to do this?</p>
[ { "answer_id": 271648, "author": "Czimi", "author_id": 3906, "author_profile": "https://Stackoverflow.com/users/3906", "pm_score": 5, "selected": false, "text": "SELECT * FROM somewhere LIMIT 18446744073709551610 OFFSET 5\n" }, { "answer_id": 271650, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 8, "selected": true, "text": "SELECT * FROM tbl LIMIT 95, 18446744073709551615;\n" }, { "answer_id": 271673, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 3, "selected": false, "text": "SET @a := 0; \nselect @a:=@a + 1 AS counter, table.* FROM table \nHAVING counter > 4\n" }, { "answer_id": 10105941, "author": "fed", "author_id": 403099, "author_profile": "https://Stackoverflow.com/users/403099", "pm_score": -1, "selected": false, "text": "LIMIT x,y" }, { "answer_id": 21438563, "author": "Baron Von Sparklefarts", "author_id": 3250001, "author_profile": "https://Stackoverflow.com/users/3250001", "pm_score": -1, "selected": false, "text": "SELECT COUNT(*) FROM table_name;\n" }, { "answer_id": 21690378, "author": "user3131125", "author_id": 3131125, "author_profile": "https://Stackoverflow.com/users/3131125", "pm_score": -1, "selected": false, "text": "WHERE .... AND id > <YOUROFFSET>\n" }, { "answer_id": 37754209, "author": "sissi_luaty", "author_id": 2097703, "author_profile": "https://Stackoverflow.com/users/2097703", "pm_score": 0, "selected": false, "text": "START TRANSACTION;\nSET @my_offset = 5;\nSET @rows = (SELECT COUNT(*) FROM my_table);\nPREPARE statement FROM 'SELECT * FROM my_table LIMIT ? OFFSET ?';\nEXECUTE statement USING @rows, @my_offset;\nCOMMIT;\n" }, { "answer_id": 58806110, "author": "Bruno.S", "author_id": 9041942, "author_profile": "https://Stackoverflow.com/users/9041942", "pm_score": 3, "selected": false, "text": " LIMIT 95, ~0\n" }, { "answer_id": 67593830, "author": "fishstick", "author_id": 6648533, "author_profile": "https://Stackoverflow.com/users/6648533", "pm_score": 0, "selected": false, "text": "ROW_NUMBER()" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23335/" ]
255,527
<p>Is there a practical algorithm that gives "multiplication chains"</p> <p>To clarify, the goal is to produce a multiplication change of an <b>arbitrary and exact </b> length<br> Multiplication chains of length 1 are trivial.</p> <p>A "multiplication chain" would be defined as 2 numbers, {start} and {multiplier}, used in code:</p> <pre><code> Given a pointer to array of size [{count}] // count is a parameter a = start; do { a = a * multiplier; // Really: a = (a * multiplier) MOD (power of 2 *(pointer++) = a; } while (a != {constant} ) // Postcondition: all {count} entries are filled. </code></pre> <p>I'd like to find a routine that takes three parameters<br> 1. Power of 2<br> 2. Stopping {constant}<br> 3. {count} - Number of times the loop will iterate </p> <p>The routine would return {start} and {multiplier}. </p> <p>Ideally, a {Constant} value of 0 should be valid.</p> <p>Trivial example:</p> <pre><code>power of 2 = 256 stopping constant = 7 number of times for the loop = 1 returns {7,1} </code></pre> <p>Nontrivial example: </p> <pre><code>power of 2 = 256 stopping constant = 1 number of times for the loop = 49 returns {25, 19} </code></pre> <p>The maximum {count} for a given power of 2 can be fairly small.<br> For example, 2^4 (16) seems to be limited to a count of 4 </p>
[ { "answer_id": 255537, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "start = constant;\nmultiplier = 1;\n" }, { "answer_id": 255558, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 3, "selected": false, "text": "s * m^N = C (mod 2^D)" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24404/" ]
255,534
<p>I got an HTML with the <code>&lt;body onload="window.print()"&gt;</code>. </p> <p>The question I'm trying to ask is:</p> <ul> <li>Is there any way to remove the strings that the web browsers add to the printed page?</li> <li>Such as: <ul> <li>Web site from where the page was printed</li> <li>Page count</li> <li>Title of the web page</li> <li>Date of printing </li> </ul></li> </ul>
[ { "answer_id": 52952161, "author": "SCaffrey", "author_id": 4597306, "author_profile": "https://Stackoverflow.com/users/4597306", "pm_score": 2, "selected": false, "text": "@page {\n margin: 0;\n}\n@media print {\n footer {\n display: none;\n position: fixed;\n bottom: 0;\n }\n header {\n display: none;\n position: fixed;\n top: 0;\n }\n}\n" }, { "answer_id": 57826240, "author": "suraj kumar", "author_id": 9012930, "author_profile": "https://Stackoverflow.com/users/9012930", "pm_score": 1, "selected": false, "text": "@page {\n margin-top: 0cm;\n margin-bottom : 0cm;\n} \n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
255,551
<p>I'm using autotools to build a shared object. </p> <p>Using <code>pkglib_LTLIBRARIES</code> in my Makefile.am causes a <code>libtest.la</code> AND <code>libtest.so</code> to be built.</p> <p>I <em>only</em> want it to build/install <code>libtest.so</code>.</p> <p>Is this possible?</p>
[ { "answer_id": 1385147, "author": "William Pursell", "author_id": 140750, "author_profile": "https://Stackoverflow.com/users/140750", "pm_score": 2, "selected": false, "text": "--disable-static" }, { "answer_id": 47289012, "author": "Vadim Kotov", "author_id": 1000551, "author_profile": "https://Stackoverflow.com/users/1000551", "pm_score": 0, "selected": false, "text": "configure.ac" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
255,553
<p>I've heard that it's possible with extension methods, but I can't quite figure it out myself. I'd like to see a specific example if possible.</p> <p>Thanks!</p>
[ { "answer_id": 255621, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "public class Mixin : ISomeInterface\n{\n private SomeImplementation impl implements ISomeInterface;\n\n public void OneMethod()\n {\n // Specialise just this method\n }\n}\n" }, { "answer_id": 7753579, "author": "3dGrabber", "author_id": 141397, "author_profile": "https://Stackoverflow.com/users/141397", "pm_score": 4, "selected": false, "text": "public interface IColor\n{\n byte Red {get;}\n byte Green {get;}\n byte Blue {get;}\n}\n\npublic static class ColorExtensions\n{\n public static byte Luminance(this IColor c)\n {\n return (byte)(c.Red*0.3 + c.Green*0.59+ c.Blue*0.11);\n }\n}\n" }, { "answer_id": 11799305, "author": "staafl", "author_id": 1527706, "author_profile": "https://Stackoverflow.com/users/1527706", "pm_score": 2, "selected": false, "text": "// Mixin class: mixin infrastructure and mixin component definitions\npublic static class Mixin\n{ \n // =====================================\n // ComponentFoo: Sample mixin component\n // =====================================\n\n // ComponentFooState: ComponentFoo contents\n class ComponentFooState\n {\n public ComponentFooState() {\n // initialize as you like\n this.Name = \"default name\";\n }\n\n public string Name { get; set; }\n }\n\n // ComponentFoo methods\n\n // if you like, replace T with some interface \n // implemented by your target class(es)\n\n public static void \n SetName<T>(this T obj, string name) {\n var state = GetState(component_foo_states, obj);\n\n // do something with \"obj\" and \"state\"\n // for example: \n\n state.Name = name + \" the \" + obj.GetType();\n\n\n }\n public static string\n GetName<T>(this T obj) {\n var state = GetState(component_foo_states, obj);\n\n return state.Name; \n }\n\n // =====================================\n // boilerplate\n // =====================================\n\n // instances of ComponentFoo's state container class,\n // indexed by target object\n static readonly Dictionary<object, ComponentFooState>\n component_foo_states = new Dictionary<object, ComponentFooState>();\n\n // get a target class object's associated state\n // note lazy instantiation\n static TState\n GetState<TState>(Dictionary<object, TState> dict, object obj) \n where TState : new() {\n TState ret;\n if(!dict.TryGet(obj, out ret))\n dict[obj] = ret = new TState();\n\n return ret;\n }\n\n}\n" }, { "answer_id": 28652400, "author": "mll5", "author_id": 2699865, "author_profile": "https://Stackoverflow.com/users/2699865", "pm_score": 2, "selected": false, "text": "class Z : T, I\n{\n I impl;\n\n public Z(I impl)\n {\n this.impl = impl;\n }\n\n // Implement all methods of I by proxying them through this.impl\n // as follows: \n //\n // I.Foo()\n // {\n // return this.impl.Foo();\n // }\n}\n" }, { "answer_id": 30503470, "author": "regisbsb", "author_id": 434919, "author_profile": "https://Stackoverflow.com/users/434919", "pm_score": 1, "selected": false, "text": "public static class ModelBaseMixins\n{\n public interface IHasStuff{ }\n\n public static void AddStuff<TObjectBase>(this TObjectBase objectBase, Stuff stuff) where TObjectBase: ObjectBase, IHasStuff\n {\n var stuffStore = objectBase.Get<IList<Stuff>>(\"stuffStore\");\n stuffStore.Add(stuff);\n }\n}\n" }, { "answer_id": 36253410, "author": "GregRos", "author_id": 1333004, "author_profile": "https://Stackoverflow.com/users/1333004", "pm_score": 1, "selected": false, "text": "public interface Mixin {}\n" }, { "answer_id": 52643008, "author": "BartoszKP", "author_id": 2642204, "author_profile": "https://Stackoverflow.com/users/2642204", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Runtime.CompilerServices; //needed for ConditionalWeakTable\npublic interface MAgeProvider // use 'M' prefix to indicate mixin interface\n{\n // nothing needed in here, it's just a 'marker' interface\n}\npublic static class AgeProvider // implements the mixin using extensions methods\n{\n static ConditionalWeakTable<MAgeProvider, Fields> table;\n static AgeProvider()\n {\n table = new ConditionalWeakTable<MAgeProvider, Fields>();\n }\n private sealed class Fields // mixin's fields held in private nested class\n {\n internal DateTime BirthDate = DateTime.UtcNow;\n }\n public static int GetAge(this MAgeProvider map)\n {\n DateTime dtNow = DateTime.UtcNow;\n DateTime dtBorn = table.GetOrCreateValue(map).BirthDate;\n int age = ((dtNow.Year - dtBorn.Year) * 372\n + (dtNow.Month - dtBorn.Month) * 31\n + (dtNow.Day - dtBorn.Day)) / 372;\n return age;\n }\n public static void SetBirthDate(this MAgeProvider map, DateTime birthDate)\n {\n table.GetOrCreateValue(map).BirthDate = birthDate;\n }\n}\n\npublic abstract class Animal\n{\n // contents unimportant\n}\npublic class Human : Animal, MAgeProvider\n{\n public string Name;\n public Human(string name)\n {\n Name = name;\n }\n // nothing needed in here to implement MAgeProvider\n}\nstatic class Test\n{\n static void Main()\n {\n Human h = new Human(\"Jim\");\n h.SetBirthDate(new DateTime(1980, 1, 1));\n Console.WriteLine(\"Name {0}, Age = {1}\", h.Name, h.GetAge());\n Human h2 = new Human(\"Fred\");\n h2.SetBirthDate(new DateTime(1960, 6, 1));\n Console.WriteLine(\"Name {0}, Age = {1}\", h2.Name, h2.GetAge());\n Console.ReadKey();\n }\n}\n" }, { "answer_id": 71689898, "author": "Dmitri Nesteruk", "author_id": 9476, "author_profile": "https://Stackoverflow.com/users/9476", "pm_score": 0, "selected": false, "text": "IEnumerable" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
255,569
<p>Which sql data type should we use for number bases primary key:</p> <ol> <li>int</li> <li>bigint</li> <li>numeric</li> <li>float</li> </ol>
[ { "answer_id": 255572, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 7, "selected": true, "text": "int" }, { "answer_id": 489589, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 0, "selected": false, "text": "unsigned int" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
255,571
<p>I am having some trouble manipulating images using CodeIgniter 1.7. With the following code, the image is uploaded correctly. Alas, instead of a new image being made, and then modified; the existing image is modified. Any help?</p> <pre><code>//Upload image first $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png|bmp'; $this-&gt;load-&gt;library('upload', $config); $this-&gt;upload-&gt;do_upload(); //Now fix the image $picloc = $this-&gt;upload-&gt;data(); $picloc = $picloc['file_name']; $thumbnail = "thumb_".$picloc; $imagemanip['image_library'] = 'gd2'; $imagemanip['source_image'] = './uploads/'.$picloc; $imagemanip['new_img'] = './uploads/'.$thumbnail; $imagemanip['maintain_ratio'] = TRUE; $imagemanip['width'] = 250; $imagemanip['height'] = 250; $this-&gt;load-&gt;library('image_lib', $imagemanip); $this-&gt;image_lib-&gt;resize(); </code></pre>
[ { "answer_id": 255628, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "$imagemanip['new_img'] = './uploads/'.$thumbnail;\n" }, { "answer_id": 29937507, "author": "Abdulla Nilam", "author_id": 4595675, "author_profile": "https://Stackoverflow.com/users/4595675", "pm_score": 0, "selected": false, "text": "//Upload image first\n$config['upload_path'] = './uploads/';\n$config['allowed_types'] = 'gif|jpg|png|bmp';\n\n$this->load->library('upload', $config); \n$this->upload->do_upload();\n\n//Now fix the image\n$picloc = $this->upload->data();\n$picloc = $picloc['file_name'];\n\n$thumbnail = \"thumb_\".$picloc;\n\n$imagemanip['image_library'] = 'gd2';\n$imagemanip['source_image'] = './uploads/'.$picloc;\n$imagemanip['new_image'] = './uploads/'.$thumbnail;// this will get change in new code.\n$imagemanip['maintain_ratio'] = TRUE;\n$imagemanip['width'] = 250;\n$imagemanip['height'] = 250;\n\n$this->load->library('image_lib', $imagemanip);\n\n$this->image_lib->resize();\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
255,612
<p>I have a class that contains a dynamically allocated array, say</p> <pre><code>class A { int* myArray; A() { myArray = 0; } A(int size) { myArray = new int[size]; } ~A() { // Note that as per MikeB's helpful style critique, no need to check against 0. delete [] myArray; } } </code></pre> <p>But now I want to create a dynamically allocated array of these classes. Here's my current code:</p> <pre><code>A* arrayOfAs = new A[5]; for (int i = 0; i &lt; 5; ++i) { arrayOfAs[i] = A(3); } </code></pre> <p>But this blows up terribly. Because the new <code>A</code> object created (with the <code>A(3)</code> call) gets destructed when the <code>for</code> loop iteration finishes, and this means that the internal <code>myArray</code> of that <code>A</code> instance gets <code>delete []</code>-ed.</p> <p>So I think my syntax must be terribly wrong? I guess there are a few fixes that seem like overkill, which I'm hoping to avoid:</p> <ul> <li>Creating a copy constructor for <code>A</code>.</li> <li>Using <code>vector&lt;int&gt;</code> and <code>vector&lt;A&gt;</code> so I don't have to worry about all this.</li> <li>Instead of having <code>arrayOfAs</code> be an array of <code>A</code> objects, have it be an array of <code>A*</code> pointers.</li> </ul> <p>I would think this is just some beginners thing where there's a syntax that actually works when attempting to dynamically allocate an array of things that have internal dynamic allocation.</p> <p>(Also, style critiques appreciated, since it's been a while since I did C++.)</p> <p><strong>Update for future viewers</strong>: All of the answers below are really helpful. Martin's is accepted because of the example code and the useful "rule of 4," but I really suggest reading them all. Some are good, succinct statements of what's wrong, and some point out correctly how and why <code>vector</code>s are a good way to go.</p>
[ { "answer_id": 255649, "author": "IMil", "author_id": 11185, "author_profile": "https://Stackoverflow.com/users/11185", "pm_score": 4, "selected": false, "text": "typedef std::vector<int> A;\ntypedef std::vector<A> AS;\n" }, { "answer_id": 255681, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 2, "selected": false, "text": "arrayOfAs[i] = A(3);\n" }, { "answer_id": 255730, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "int[]" }, { "answer_id": 255744, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 8, "selected": true, "text": "class A\n{ \n std::vector<int> mArray;\n public:\n A(){}\n A(size_t s) :mArray(s) {}\n};\n" }, { "answer_id": 255859, "author": "baash05", "author_id": 31325, "author_profile": "https://Stackoverflow.com/users/31325", "pm_score": 2, "selected": false, "text": "A* arrayOfAs = new A[5];\nfor (int i = 0; i < 5; ++i)\n{\n arrayOfAs[i].SetSize(3);\n}\n" }, { "answer_id": 36799794, "author": "Saman Barghi", "author_id": 620409, "author_profile": "https://Stackoverflow.com/users/620409", "pm_score": 2, "selected": false, "text": "new" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3191/" ]
255,624
<p>While using Vim (at home and at work), I often find myself doing similar things repeatedly. For example, I may turn a bunch of CSV text into a series of SQL inserts. I've been using Vim for years, but only recently have I tried to seriously think about how I could improve my productivity while using it.</p> <p>My question is.. Is there a good way (or right way) to store commonly used commands or command sequences? And how is the best way to execute them? It would be nice to be able to use the same script on a live session and also over the command line against some file.</p> <p>I'm hoping that I can store them in a .vim file so that I can hand them to coworkers (who are not as proficient with vim) for them to use.</p>
[ { "answer_id": 255650, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 2, "selected": false, "text": ".vimrc" }, { "answer_id": 256494, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 2, "selected": false, "text": "q" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866/" ]
255,642
<p>I have a database table named call with columns call_time, location, emergency_type and there are three types of emergency: paramedics, police and firefighters. In the windows form I created CheckBoxes 'paramedics', 'police', 'firefighters' and I want to retrieve all table columns which meet user's selection.</p> <p>I created a function:</p> <pre><code>public static DataTable GetHistory(DateTime from, DateTime to, bool paramedics, bool police, bool firefighters) { string select = "SELECT call_time, location, emergency_type where call_time between @from AND @to AND"; if(paramedics) { select += " emergency_type = 'paramedics' "; } if(paramedics &amp;&amp; police) { select +=" emergency_type = 'paramedics' OR emergency_type = 'police'; } ... } </code></pre> <p>This code however seems very dirty because if there were 30 kinds of emergency there would be 30! combinations and I would get old before writing all if statements.</p> <p>I would appreciate if you shared your practice for retrieving data that meet the selected search conditions if there are many options you can chosse.</p> <p>Thanks!</p>
[ { "answer_id": 255657, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 0, "selected": false, "text": "string select = \"SELECT call_time, location, emergency_type where call_time between @from AND @to AND (1=0\";\n\nif(paramedics) { select += \" OR emergency_type = 'paramedics' \"; }\nif(police) { select += \" OR emergency_type = 'police'\"; }\nif(xyz) { select += \" OR emergency_type = 'xyz'\"; }\n\nselect += \")\";\n" }, { "answer_id": 255660, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 4, "selected": true, "text": "public static DataTable GetHistory(DateTime from, DateTime to, List<string> types)\n{\n ..\n}\n" }, { "answer_id": 255777, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "where ... and emergency_type in (?)\n" }, { "answer_id": 255803, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 0, "selected": false, "text": "SELECT call_time, \n location, \n emergency_type \nwhere call_time between @from AND @to \n AND CONTAINS( Emegency_Type, @EmergencyList )\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
255,644
<p>Today somebody told me that interface implementation in C# is just "Can-Do" relationship, not "Is-A" relationship. This conflicts with my long-time believing in LSP(Liskov Substitution Principle). I always think that all inheritance should means "Is-A" relationship. </p> <p>So, If interface implementation is just a "Can-Do" relationship. What if there is a interface "IHuman" and "IEngineer", and one class "Programmer" inherits from "IHuman" &amp; "IEngineer"? Surely, a "Programmer" Is A "IHuman" and A "IEngineer". </p> <p>If it is just "Can-Do" relationship, does it mean we cannot expect the "Programmer" instance behavior may be different between when treated as a IHuman and treated as IEngineer?</p>
[ { "answer_id": 422110, "author": "Jon Davis", "author_id": 11398, "author_profile": "https://Stackoverflow.com/users/11398", "pm_score": 2, "selected": false, "text": "Foo myFoo = new Foo(); \nreturn myFoo is IBar;\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
255,669
<p>How do I enable assembly bind failure logging (Fusion) in .NET?</p>
[ { "answer_id": 255670, "author": "user32736", "author_id": 32736, "author_profile": "https://Stackoverflow.com/users/32736", "pm_score": 7, "selected": false, "text": "Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Fusion]\n\"EnableLog\"=dword:00000001\n" }, { "answer_id": 3256753, "author": "Mike Goatly", "author_id": 266104, "author_profile": "https://Stackoverflow.com/users/266104", "pm_score": 8, "selected": false, "text": "c:\\FusionLogs" }, { "answer_id": 29374658, "author": "magicandre1981", "author_id": 1466046, "author_profile": "https://Stackoverflow.com/users/1466046", "pm_score": 4, "selected": false, "text": "Microsoft-Windows-DotNETRuntimePrivate" }, { "answer_id": 33013110, "author": "Tereza Tomcova", "author_id": 99237, "author_profile": "https://Stackoverflow.com/users/99237", "pm_score": 7, "selected": false, "text": "Set-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name ForceLog -Value 1 -Type DWord\nSet-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name LogFailures -Value 1 -Type DWord\nSet-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name LogResourceBinds -Value 1 -Type DWord\nSet-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name LogPath -Value 'C:\\FusionLog\\' -Type String\nmkdir C:\\FusionLog -Force\n" }, { "answer_id": 56044491, "author": "Igor Meszaros", "author_id": 946889, "author_profile": "https://Stackoverflow.com/users/946889", "pm_score": 3, "selected": false, "text": "reg add \"HKLM\\Software\\Microsoft\\Fusion\" /v EnableLog /t REG_DWORD /d 1 /f\nreg add \"HKLM\\Software\\Microsoft\\Fusion\" /v ForceLog /t REG_DWORD /d 1 /f\nreg add \"HKLM\\Software\\Microsoft\\Fusion\" /v LogFailures /t REG_DWORD /d 1 /f\nreg add \"HKLM\\Software\\Microsoft\\Fusion\" /v LogResourceBinds /t REG_DWORD /d 1 /f\nreg add \"HKLM\\Software\\Microsoft\\Fusion\" /v LogPath /t REG_SZ /d C:\\FusionLog\\\n\nif not exist \"C:\\FusionLog\\\" mkdir C:\\FusionLog\n" }, { "answer_id": 56067961, "author": "Waescher", "author_id": 704281, "author_profile": "https://Stackoverflow.com/users/704281", "pm_score": 5, "selected": false, "text": "choco install fusionplusplus" }, { "answer_id": 74081168, "author": "Igor Levicki", "author_id": 1778190, "author_profile": "https://Stackoverflow.com/users/1778190", "pm_score": 0, "selected": false, "text": "HTM" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32736/" ]
255,700
<p>In my website, users have the possibility to store links.</p> <p>During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.</p> <p>Example:</p> <p>User is typing as URL:</p> <pre><code>http://www.sta </code></pre> <p>Suggestions which would be displayed:</p> <pre><code>http://www.staples.com http://www.starbucks.com http://www.stackoverflow.com </code></pre> <p>How can I achieve this while not reinventing the wheel? :)</p>
[ { "answer_id": 256099, "author": "lacker", "author_id": 2652, "author_profile": "https://Stackoverflow.com/users/2652", "pm_score": 2, "selected": false, "text": "www.yoursite.com/suggest?typed=www.sta\n" }, { "answer_id": 656223, "author": "Justin R.", "author_id": 4593, "author_profile": "https://Stackoverflow.com/users/4593", "pm_score": 0, "selected": false, "text": "LINQ" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26763/" ]
255,714
<p>So I've got a Ruby method like this:</p> <pre><code>def something(variable, &amp;block) .... end </code></pre> <p>And I want to call it like this:</p> <pre><code>something 'hello' { do_it } </code></pre> <p>Except that isn't working for me, I'm getting a syntax error. If I do this instead, it works:</p> <pre><code>something 'hello' do do_it end </code></pre> <p>Except there I'm kind of missing the nice look of it being on one line.</p> <p>I can see why this is happening, as it could look like it's a hash being passed as a second variable, but without a comma in between the variables...but I assume that there must be a way to deal with this that I'm missing. Is there?</p>
[ { "answer_id": 255732, "author": "seanbehan", "author_id": 155970, "author_profile": "https://Stackoverflow.com/users/155970", "pm_score": 2, "selected": false, "text": "#to uppercase string\ndef something(my_input)\n yield my_input.upcase\nend\n\n# => \"HELLO WORLD\"\nsomething(\"hello world\") { |i| puts i}\n" }, { "answer_id": 255791, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 7, "selected": true, "text": "something('hello') { do_it }\n" }, { "answer_id": 256607, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 0, "selected": false, "text": ">> def something(arg1 , &block)\n>> yield block\n>> end\n=> nil\n>> def do_it\n>> puts \"Doing it!\"\n>> end\n=> nil\n>> something('hello') { do_it }\n\"Doing it!\"\n=> nil\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14873/" ]
255,741
<p>I'm a complete Ada newbie, though I've used Pascal for 2-3 years during HS.</p> <p>IIRC, it is possible to call Pascal compiled functions from C/C++. Is it possible to call procedures &amp; functions written in Ada from C++?</p>
[ { "answer_id": 41819129, "author": "Glen", "author_id": 7386272, "author_profile": "https://Stackoverflow.com/users/7386272", "pm_score": 3, "selected": false, "text": " package Ada_Pkg is\n procedure DoSomething (Number : in Integer);\n pragma Export (C, DoSomething, \"doSomething\");\n end Ada_Pkg;\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ]
255,771
<p>I need a modal dialog to gather some user input. I then need the same data to be consumed by the application MainFrame.</p> <p>Usually my Modal Dialog would have a pointer to some DataType able to store what I need, and I'd be passing this object by reference from the MainFrame in order to be able to recover data once the modal dialog is closed by the user. </p> <p>Is this the best way of passing around data?</p> <p>It doesn't feel right!</p>
[ { "answer_id": 255790, "author": "Samuel", "author_id": 32465, "author_profile": "https://Stackoverflow.com/users/32465", "pm_score": 3, "selected": true, "text": "public string UserName\n{\n get { return userNameTextBox.Text; }\n}\n" }, { "answer_id": 255952, "author": "Aidan Ryan", "author_id": 1042, "author_profile": "https://Stackoverflow.com/users/1042", "pm_score": 1, "selected": false, "text": "myGetter.SetTransferObject(dataStructInstance)\nmyGetter.GoGetTheData()\n// do stuff with dataStructInstance now that myGetter set it up.\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311500/" ]
255,785
<p>Does a tool exist for dynamically altering running javascript in a browser? For example, to change the values of javascript variables during runtime.</p>
[ { "answer_id": 255793, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": -1, "selected": false, "text": "<script type=\"text/javascript\" language=\"javascript\">\n example = function() {alert('first');}\n example();\n eval(\"example = function() {alert('second');}\");\n example();\n</script>\n" }, { "answer_id": 255812, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": false, "text": "debugger;\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
255,797
<p>In what areas of programming would I use state machines ? Why ? How could I implement one ?</p> <p><strong>EDIT:</strong> please provide a practical example , if it's not too much to ask .</p>
[ { "answer_id": 255826, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 2, "selected": false, "text": "http://web.dyfis.net/bzr/isg_state_machine_framework/" }, { "answer_id": 255886, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 4, "selected": false, "text": "int a[10] = {some unsorted integers};\n\nnot_sorted_state:;\n z = -1;\n while (z < (sizeof(a) / sizeof(a[0]) - 1)\n {\n z = z + 1\n if (a[z] > a[z + 1])\n {\n // ASSERT The array is not in order\n swap(a[z], a[z + 1]; // make the array more sorted\n goto not_sorted_state; // change state to sort the array\n }\n }\n // ASSERT the array is in order\n" }, { "answer_id": 256011, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 8, "selected": true, "text": "enum states { // Define the states in the state machine.\n NO_PIZZA, // Exit state machine.\n COUNT_PEOPLE, // Ask user for # of people.\n COUNT_SLICES, // Ask user for # slices.\n SERVE_PIZZA, // Validate and serve.\n EAT_PIZZA // Task is complete.\n} STATE;\n\nSTATE state = COUNT_PEOPLE;\nint nPeople, nSlices, nSlicesPerPerson;\n\n// Serve slices of pizza to people, so that each person gets\n/// the same number of slices. \nwhile (state != NO_PIZZA) {\n switch (state) {\n case COUNT_PEOPLE: \n if (promptForPeople(&nPeople)) // If input is valid..\n state = COUNT_SLICES; // .. go to next state..\n break; // .. else remain in this state.\n case COUNT_SLICES: \n if (promptForSlices(&nSlices))\n state = SERVE_PIZZA;\n break;\n case SERVE_PIZZA:\n if (nSlices % nPeople != 0) // Can't divide the pizza evenly.\n { \n getMorePizzaOrFriends(); // Do something about it.\n state = COUNT_PEOPLE; // Start over.\n }\n else\n {\n nSlicesPerPerson = nSlices/nPeople;\n state = EAT_PIZZA;\n }\n break;\n case EAT_PIZZA:\n // etc...\n state = NO_PIZZA; // Exit the state machine.\n break;\n } // switch\n} // while\n" }, { "answer_id": 256030, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "very_long_text = \"Bereshit bara Elohim et hashamayim ve'et ha'arets.\" …\nword = \"Elohim\"\nposition = find_in_string(very_long_text, word)\n" }, { "answer_id": 256174, "author": "old_timer", "author_id": 16007, "author_profile": "https://Stackoverflow.com/users/16007", "pm_score": 2, "selected": false, "text": " #include <stdio.h>\n #include <stdlib.h>\n #include <string.h>\n\nunsigned char testdata[] =\n{\n 0xFA,0x07,0x12,0x34,0x56,0x78,0xEB, \n 0x12,0x34,0x56, \n 0xFA,0x07,0x12,0x34,0x56,0x78,0xAA, \n 0xFA,0x00,0x12,0x34,0x56,0x78,0xEB, \n 0xFA,0x08,0x12,0x34,0x56,0x78,0x00,0xEA \n};\n\nunsigned int testoff=0;\n\n//packet structure \n// [0] packet header 0xFA \n// [1] bytes in packet (n) \n// [2] payload \n// ... payload \n// [n-1] checksum \n// \n\nunsigned int state;\n\nunsigned int packlen; \nunsigned int packoff; \nunsigned char packet[256]; \nunsigned int checksum; \n\nint process_packet( unsigned char *data, unsigned int len ) \n{ \n unsigned int ra; \n\n printf(\"good packet:\");\n for(ra=0;ra<len;ra++) printf(\"%02X\",data[ra]);\n printf(\"\\n\");\n} \nint getbyte ( unsigned char *d ) \n{ \n //check peripheral for a new byte \n //or serialize a packet or file \n\n if(testoff<sizeof(testdata))\n {\n *d=testdata[testoff++];\n return(1);\n }\n else\n {\n printf(\"no more test data\\n\");\n exit(0);\n }\n return(0);\n}\n\nint main ( void ) \n{ \n unsigned char b;\n\n state=0; //idle\n\n while(1)\n {\n if(getbyte(&b))\n {\n switch(state)\n {\n case 0: //idle\n if(b!=0xFA)\n {\n printf(\"Invalid sync pattern 0x%02X\\n\",b);\n break;\n }\n packoff=0;\n checksum=b;\n packet[packoff++]=b;\n\n state++;\n break;\n case 1: //packet length\n checksum+=b;\n packet[packoff++]=b;\n\n packlen=b;\n if(packlen<3)\n {\n printf(\"Invalid packet length %u\\n\",packlen);\n state=0;\n break;\n }\n\n state++;\n break;\n case 2: //payload\n checksum+=b;\n packet[packoff++]=b;\n\n if(packoff>=packlen)\n {\n state=0;\n checksum=checksum&0xFF;\n if(checksum)\n {\n printf(\"Checksum error 0x%02X\\n\",checksum);\n }\n else\n {\n process_packet(packet,packlen);\n }\n }\n break;\n }\n }\n\n //do other stuff, handle other devices/interfaces\n\n }\n}\n" }, { "answer_id": 300396, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "Show form 1\nprocess form 1\nshow form 2\nprocess form 2\n" }, { "answer_id": 300497, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 0, "selected": false, "text": "/* implement dd*[.d*] */\nif (isdigit(*p)){\n while(isdigit(*p)) p++;\n if (*p=='.'){\n p++;\n while(isdigit(*p)) p++;\n }\n /* got it! */\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
255,800
<p>I'm making a program which the user build directories (not in windows, in my app) and in these folders there are subfolders and so on; every folder must contain either folders or documents. What is the best data structure to use? Notice that the user may select a subfolder and search for documents in it and in its subfolders. And I don't want to limit the folders or the subfolders levels.</p>
[ { "answer_id": 255841, "author": "Jason", "author_id": 16794, "author_profile": "https://Stackoverflow.com/users/16794", "pm_score": 5, "selected": true, "text": "Root\n Folder1\n Folder2\n Folder3\n Folder4\n Folder5\n Folder6\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29276/" ]
255,815
<p>I have the following line:</p> <pre><code>"14:48 say;0ed673079715c343281355c2a1fde843;2;laka;hello ;)" </code></pre> <p>I parse this by using a simple regexp:</p> <pre><code>if($line =~ /(\d+:\d+)\ssay;(.*);(.*);(.*);(.*)/) { my($ts, $hash, $pid, $handle, $quote) = ($1, $2, $3, $4, $5); } </code></pre> <p>But the ; at the end messes things up and I don't know why. Shouldn't the greedy operator handle "everything"?</p>
[ { "answer_id": 255827, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "(.*)" }, { "answer_id": 255832, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "(\\d+:\\d+)\\ssay;([^;]*);([^;]*);([^;]*);(.*)\n" }, { "answer_id": 255839, "author": "Barry Brown", "author_id": 17312, "author_profile": "https://Stackoverflow.com/users/17312", "pm_score": 5, "selected": true, "text": "(\\d+:\\d+)\\ssay;(.*?);(.*?);(.*?);(.*)\n" }, { "answer_id": 255844, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "$line =~ /(\\d+:\\d+)\\ssay;(.*?);(.*?);(.*?);(.*)/\n" }, { "answer_id": 255882, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 3, "selected": false, "text": "$x=\"14:48 say;0ed673079715c343281355c2a1fde843;2;laka;hello ;)\";\n\nif (($ts,$rest) = $x =~ /(\\d+:\\d+)\\s+(.*)/)\n{\n my($command,$hash,$pid,$handle,$quote) = split /;/, $rest, 5;\n print join \",\", map { \"[$_]\" } $ts,$command,$hash,$pid,$handle,$quote\n}\n" }, { "answer_id": 256362, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 2, "selected": false, "text": "(\\d+:\\d+)\\ssay;([a-f0-9]+);(\\d+);(\\w+);([^;\\r\\n]+)\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33232/" ]
255,830
<p>I'm looking for someone to explain how to drag and drop in javascript, I want a horizontal line with some customizable images in it.</p> <p>I've had a look at the online tutorials for these but find them very hard to use.</p>
[ { "answer_id": 255884, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "print(\"<!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\">\n<head>\n\n\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n<title>Page</title>\n<--\n<style type=\"text/css\">\n<!--\n.DragContainer, .OverDragContainer {\n float: left;\n margin: 3px;\n width: 100px;\n border: #669999 2px solid;\n padding: 5px;\n}\n\n.DragBox, .OverDragBox, .DragDragBox, .miniDragBox {\n border: #000 1px solid;\n padding: 2px;\n font-size: 10px;\n margin-bottom: 5px;\n width: 94px;\n cursor: pointer;\n font-family: verdana, tahoma, arial;\n background-color: #eee;\n}\n\n.OverDragContainer {\n background-color: #eee;\n}\n\n.OverDragBox, .DragDragBox {\n background-color: #ffff99;\n}\n\n.DragDragBox {\n filter: alpha(opacity=50);\n background-color: #ff99cc;\n}\n\nlegend {\n font-weight: bold;\n font-size: 12px;\n color: #666699;\n font-family: verdana, tahoma, arial;\n}\n\nfieldset {\n padding: 3px;\n}\n\n.History {\n font-size: 10px;\n overflow: auto;\n width: 100%;\n font-family: verdana, tahoma, arial;\n height: 82px;\n}\n\n#DragContainer8 {\n border: #669999 1px solid;\n padding: 5px 0 0 5px\n width: 110px;\n height: 40px;\n}\n\n.miniDragBox {\n float: left;\n margin: 0 5px 5px 0;\n width: 20px;\n height: 20px;\n}\n-->\n</style>\n<--script type=\"text/javascript\">\n\n// iMouseDown represents the current mouse button state: up or down\n/*\nlMouseState represents the previous mouse button state so that we can\ncheck for button clicks and button releases:\n\nif(iMouseDown && !lMouseState) // button just clicked!\nif(!iMouseDown && lMouseState) // button just released!\n*/\nvar mouseOffset = null;\nvar iMouseDown = false;\nvar lMouseState = false;\nvar dragObject = null;\n\n// Demo 0 variables\nvar DragDrops = [];\nvar curTarget = null;\nvar lastTarget = null;\nvar dragHelper = null;\nvar tempDiv = null;\nvar rootParent = null;\nvar rootSibling = null;\n\nNumber.prototype.NaN0=function(){return isNaN(this)?0:this;}\n\nfunction CreateDragContainer(){\n /*\n Create a new \"Container Instance\" so that items from one \"Set\" can not\n be dragged into items from another \"Set\"\n */\n var cDrag = DragDrops.length;\n DragDrops[cDrag] = [];\n\n /*\n Each item passed to this function should be a \"container\". Store each\n of these items in our current container\n */\n for(var i=0; i<arguments.length; i++){\n var cObj = arguments[i];\n DragDrops[cDrag].push(cObj);\n cObj.setAttribute('DropObj', cDrag);\n\n /*\n Every top level item in these containers should be draggable. Do this\n by setting the DragObj attribute on each item and then later checking\n this attribute in the mouseMove function\n */\n for(var j=0; j<cObj.childNodes.length; j++){\n\n // Firefox puts in lots of #text nodes...skip these\n if(cObj.childNodes[j].nodeName=='#text') continue;\n\n cObj.childNodes[j].setAttribute('DragObj', cDrag);\n }\n }\n}\n\nfunction getMouseOffset(target, ev){\n ev = ev || window.event;\n\n var docPos = getPosition(target);\n var mousePos = mouseCoords(ev);\n return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};\n}\n\nfunction getPosition(e){\n var left = 0;\n var top = 0;\n\n while (e.offsetParent){\n left += e.offsetLeft;\n top += e.offsetTop;\n e = e.offsetParent;\n }\n\n left += e.offsetLeft;\n top += e.offsetTop;\n\n return {x:left, y:top};\n}\n\n\n\nfunction makeDraggable(item){\n if(!item) return;\n item.onmousedown = function(ev){\n dragObject = this;\n mouseOffset = getMouseOffset(this, ev);\n return false;\n }\n}\n\nfunction makeClickable(object){\n object.onmousedown = function(){\n dragObject = this;\n }\n}\n\nfunction mouseCoords(ev){\n if(ev.pageX || ev.pageY){\n return {x:ev.pageX, y:ev.pageY};\n }\n return {\n x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,\n y:ev.clientY + document.body.scrollTop - document.body.clientTop\n };\n}\n\n\nfunction mouseMove(ev){\n ev = ev || window.event;\n\n /*\n We are setting target to whatever item the mouse is currently on\n\n Firefox uses event.target here, MSIE uses event.srcElement\n */\n var target = ev.target || ev.srcElement;\n var mousePos = mouseCoords(ev);\n\n // mouseOut event - fires if the item the mouse is on has changed\n if(lastTarget && (target!==lastTarget)){\n // reset the classname for the target element\n var origClass = lastTarget.getAttribute('origClass');\n if(origClass) lastTarget.className = origClass;\n }\n\n /*\n dragObj is the grouping our item is in (set from the createDragContainer function).\n if the item is not in a grouping we ignore it since it can't be dragged with this\n script.\n */\n var dragObj = target.getAttribute('DragObj');\n\n // if the mouse was moved over an element that is draggable\n if(dragObj!=null){\n\n // mouseOver event - Change the item's class if necessary\n if(target!=lastTarget){\n var oClass = target.getAttribute('overClass');\n if(oClass){\n target.setAttribute('origClass', target.className);\n target.className = oClass;\n }\n }\n\n // if the user is just starting to drag the element\n if(iMouseDown && !lMouseState){\n // mouseDown target\n curTarget = target;\n\n // Record the mouse x and y offset for the element\n rootParent = curTarget.parentNode;\n rootSibling = curTarget.nextSibling;\n\n mouseOffset = getMouseOffset(target, ev);\n\n // We remove anything that is in our dragHelper DIV so we can put a new item in it.\n for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);\n\n // Make a copy of the current item and put it in our drag helper.\n dragHelper.appendChild(curTarget.cloneNode(true));\n dragHelper.style.display = 'block';\n\n // set the class on our helper DIV if necessary\n var dragClass = curTarget.getAttribute('dragClass');\n if(dragClass){\n dragHelper.firstChild.className = dragClass;\n }\n\n // disable dragging from our helper DIV (it's already being dragged)\n dragHelper.firstChild.removeAttribute('DragObj');\n\n /*\n Record the current position of all drag/drop targets related\n to the element. We do this here so that we do not have to do\n it on the general mouse move event which fires when the mouse\n moves even 1 pixel. If we don't do this here the script\n would run much slower.\n */\n var dragConts = DragDrops[dragObj];\n\n /*\n first record the width/height of our drag item. Then hide it since\n it is going to (potentially) be moved out of its parent.\n */\n curTarget.setAttribute('startWidth', parseInt(curTarget.offsetWidth));\n curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));\n curTarget.style.display = 'none';\n\n // loop through each possible drop container\n for(var i=0; i<dragConts.length; i++){\n with(dragConts[i]){\n var pos = getPosition(dragConts[i]);\n\n /*\n save the width, height and position of each container.\n\n Even though we are saving the width and height of each\n container back to the container this is much faster because\n we are saving the number and do not have to run through\n any calculations again. Also, offsetHeight and offsetWidth\n are both fairly slow. You would never normally notice any\n performance hit from these two functions but our code is\n going to be running hundreds of times each second so every\n little bit helps!\n\n Note that the biggest performance gain here, by far, comes\n from not having to run through the getPosition function\n hundreds of times.\n */\n setAttribute('startWidth', parseInt(offsetWidth));\n setAttribute('startHeight', parseInt(offsetHeight));\n setAttribute('startLeft', pos.x);\n setAttribute('startTop', pos.y);\n }\n\n // loop through each child element of each container\n for(var j=0; j<dragConts[i].childNodes.length; j++){\n with(dragConts[i].childNodes[j]){\n if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;\n\n var pos = getPosition(dragConts[i].childNodes[j]);\n\n // save the width, height and position of each element\n setAttribute('startWidth', parseInt(offsetWidth));\n setAttribute('startHeight', parseInt(offsetHeight));\n setAttribute('startLeft', pos.x);\n setAttribute('startTop', pos.y);\n }\n }\n }\n }\n }\n\n // If we get in here we are dragging something\n if(curTarget){\n // move our helper div to wherever the mouse is (adjusted by mouseOffset)\n dragHelper.style.top = mousePos.y - mouseOffset.y;\n dragHelper.style.left = mousePos.x - mouseOffset.x;\n\n var dragConts = DragDrops[curTarget.getAttribute('DragObj')];\n var activeCont = null;\n\n var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);\n var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2);\n\n // check each drop container to see if our target object is \"inside\" the container\n for(var i=0; i<dragConts.length; i++){\n with(dragConts[i]){\n if(((getAttribute('startLeft')) < xPos) &&\n ((getAttribute('startTop')) < yPos) &&\n ((getAttribute('startLeft') + getAttribute('startWidth')) > xPos) &&\n ((getAttribute('startTop') + getAttribute('startHeight')) > yPos)){\n\n /*\n our target is inside of our container so save the container into\n the activeCont variable and then exit the loop since we no longer\n need to check the rest of the containers\n */\n activeCont = dragConts[i];\n\n // exit the for loop\n break;\n }\n }\n }\n\n // Our target object is in one of our containers. Check to see where our div belongs\n if(activeCont){\n // beforeNode will hold the first node AFTER where our div belongs\n var beforeNode = null;\n\n // loop through each child node (skipping text nodes).\n for(var i=activeCont.childNodes.length-1; i>=0; i--){\n with(activeCont.childNodes[i]){\n if(nodeName=='#text') continue;\n\n // if the current item is \"After\" the item being dragged\n if(\n curTarget != activeCont.childNodes[i] &&\n ((getAttribute('startLeft') + getAttribute('startWidth')) > xPos) &&\n ((getAttribute('startTop') + getAttribute('startHeight')) > yPos)){\n beforeNode = activeCont.childNodes[i];\n }\n }\n }\n\n // the item being dragged belongs before another item\n if(beforeNode){\n if(beforeNode!=curTarget.nextSibling){\n activeCont.insertBefore(curTarget, beforeNode);\n }\n\n // the item being dragged belongs at the end of the current container\n } else {\n if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){\n activeCont.appendChild(curTarget);\n }\n }\n\n // make our drag item visible\n if(curTarget.style.display!=''){\n curTarget.style.display = '';\n }\n } else {\n\n // our drag item is not in a container, so hide it.\n if(curTarget.style.display!='none'){\n curTarget.style.display = 'none';\n }\n }\n }\n\n // track the current mouse state so we can compare against it next time\n lMouseState = iMouseDown;\n\n // mouseMove target\n lastTarget = target;\n\n // track the current mouse state so we can compare against it next time\n lMouseState = iMouseDown;\n\n // this helps prevent items on the page from being highlighted while dragging\n return false;\n}\n\nfunction mouseUp(ev){\n if(curTarget){\n // hide our helper object - it is no longer needed\n dragHelper.style.display = 'none';\n\n // if the drag item is invisible put it back where it was before moving it\n if(curTarget.style.display == 'none'){\n if(rootSibling){\n rootParent.insertBefore(curTarget, rootSibling);\n } else {\n rootParent.appendChild(curTarget);\n }\n }\n\n // make sure the drag item is visible\n curTarget.style.display = '';\n }\n curTarget = null;\n iMouseDown = false;\n}\n\nfunction mouseDown(){\n iMouseDown = true;\n if(lastTarget){\n return false;\n }\n}\n\ndocument.onmousemove = mouseMove;\ndocument.onmousedown = mouseDown;\ndocument.onmouseup = mouseUp;\n\nwindow.onload = function(){\n // Create our helper object that will show the item while dragging\n dragHelper = document.createElement('DIV');\n dragHelper.style.cssText = 'position:absolute;display:none;';\n\n CreateDragContainer(\n document.getElementById('DragContainer1'),\n document.getElementById('DragContainer2'),\n document.getElementById('DragContainer3')\n );\n\n document.body.appendChild(dragHelper);\n}\n</script><!--the mouse over and dragging class are defined on each item-->\n\n</head>\n<body>\n\n<br/>\n<div class=\"DragContainer\" id=\"DragContainer1\">\n <div class=\"DragBox\" id=\"Item1\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #1</div>\n <div class=\"DragBox\" id=\"Item2\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #2</div>\n <div class=\"DragBox\" id=\"Item3\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #3</div>\n <div class=\"DragBox\" id=\"Item4\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #4</div>\n</div>\n<div class=\"DragContainer\" id=\"DragContainer2\">\n <div class=\"DragBox\" id=\"Item5\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #5</div>\n <div class=\"DragBox\" id=\"Item6\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #6</div>\n <div class=\"DragBox\" id=\"Item7\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #7</div>\n <div class=\"DragBox\" id=\"Item8\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #8</div>\n</div>\n<div class=\"DragContainer\" id=\"DragContainer3\">\n <div class=\"DragBox\" id=\"Item9\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #9</div>\n <div class=\"DragBox\" id=\"Item10\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #10</div>\n <div class=\"DragBox\" id=\"Item11\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #11</div>\n <div class=\"DragBox\" id=\"Item12\" overClass=\"OverDragBox\" dragClass=\"DragDragBox\">Item #12</div>\n</div>\n<br/>\n\n</body>\n</html>\n\");\n" }, { "answer_id": 5286798, "author": "RuDy", "author_id": 657110, "author_profile": "https://Stackoverflow.com/users/657110", "pm_score": 2, "selected": false, "text": "dragHelper.style.top = mousePos.y - mouseOffset.y;\ndragHelper.style.left = mousePos.x - mouseOffset.x;\n" }, { "answer_id": 5289871, "author": "Trevor Rudolph", "author_id": 652487, "author_profile": "https://Stackoverflow.com/users/652487", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\" src=\"http://www.dynamicdrive.com/dynamicindex11/domdrag/dom-drag.js\"></script>\n<script type=\"text/javascript\">\nDrag.init(document.getElementById(\"exampleid\")); //sets the id to look for to make object draggable\n</script>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
255,846
<p>I'm having a lot of issues with NSDate objects being prematurely deallocated. I suspect that the issues may be related to the way that I deal with the objects returned from NSDate convenience methods. I <em>think</em> that my showDate property declaration in the JKShow class should be "retain", but changing it to assign or copy seems to have no effect on the issue.</p> <pre><code>JKShow *show; NSDate *date; NSMutableArray *list = [[NSMutableArray alloc] init]; // Show 1 show = [[JKShow alloc] init]; //... date = [gregorian dateFromComponents:dateComponents]; show.showDate = date; [list addObject:[show autorelease]]; // Show 2 show = [[JKShow alloc] init]; //... date = [gregorian dateFromComponents:dateComponents]; show.showDate = date; [list addObject:[show autorelease]]; </code></pre> <p><em>UPDATE</em></p> <p>The issue was not in the code copied here. In my <code>JKShow init</code> method I was not retaining the date returned from the <code>NSDate</code> convenience method. Thanks for your help, everyone.</p>
[ { "answer_id": 255931, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 0, "selected": false, "text": "list" }, { "answer_id": 255983, "author": "kubi", "author_id": 28422, "author_profile": "https://Stackoverflow.com/users/28422", "pm_score": 1, "selected": true, "text": "NSDate" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28422/" ]
255,852
<p>I've been writing a lot recently about Parallel computing and programming and I do notice that there are a lot of patterns that come up when it comes to parallel computing. Noting that Microsoft already has released a library along with the Microsoft Visual C++ 2010 Community Technical Preview (named Parallel Patterns Library) I'm wondering what are the common parallel programming patterns you have been using and encountering that may be worth remembering? Do you have any idioms you follow and patterns that you seem to keep popping up as you write parallel programs with C++?</p>
[ { "answer_id": 46700626, "author": "Beached", "author_id": 202861, "author_profile": "https://Stackoverflow.com/users/202861", "pm_score": 1, "selected": false, "text": "auto fut = async([]( ){..some work...} ).then( [](result_of_prev ){...more work} ).then... ;\nfut.wait( );\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11274/" ]
255,857
<p>I am trying to insert an image (jpg) in to a word document and the Selection.InlineShapes.AddPicture does not seem to be supported by win32old or I am doing something wrong. Has anyone had any luck inserting images. </p>
[ { "answer_id": 258389, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 1, "selected": false, "text": "require 'win32ole'\n\nbegin\n word = WIN32OLE::new('Word.Application') # create winole Object\n doc = word.Documents.Add\n word.Selection.InlineShapes.AddPicture \"C:\\\\pictures\\\\some_picture.jpg\", false, true\n word.ChangeFileOpenDirectory \"C:\\\\docs\\\\\"\n doc.SaveAs \"doc_with_pic.doc\"\n word.Quit\nrescue Exception => e\n puts e\n word.Quit\nensure\n word.Quit unless word.nil?\nend\n" }, { "answer_id": 1326313, "author": "RubyDubee", "author_id": 157324, "author_profile": "https://Stackoverflow.com/users/157324", "pm_score": 2, "selected": false, "text": " require 'win32ole'\n\n word = WIN32OLE.connect('Word.Application')\n doc = word.ActiveDocument\n\n image = 'C:\\MyImage.jpg'\n range = doc.Sentences(2)\n\n params = { 'FileName' => image, 'LinkToFile' => false, \n 'SaveWithDocument' => true, 'Range' => range }\n\n pic = doc.InlineShapes.AddPicture( params )\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
255,862
<p>Netbeans is great but there's no way to wrap text in it (or hopefully I haven't found it yet). Is there any way to do this, and if not, is there any similarly good IDE for Java with this functionality (hopefully free as well).</p>
[ { "answer_id": 4059100, "author": "Sidarta", "author_id": 269056, "author_profile": "https://Stackoverflow.com/users/269056", "pm_score": 6, "selected": false, "text": "-J-Dorg.netbeans.editor.linewrap=true\n" }, { "answer_id": 4975838, "author": "Hoffa", "author_id": 613852, "author_profile": "https://Stackoverflow.com/users/613852", "pm_score": 1, "selected": false, "text": "-J-Dorg.netbeans.editor.linewrap=true\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
255,876
<p>I want to make an MVC route for a list of news, which can be served in several formats.</p> <ul> <li>news -> (X)HTML</li> <li>news.rss -> RSS</li> <li>news.atom -> ATOM</li> </ul> <p>Is it possible to do this (the more general "optional extension" situation crops up in several places in my planned design) with one route? Or do I need to make two routes like this:</p> <pre><code>routes.MapRoute("News-ImplicitFormat", "news", new { controller = "News", action = "Browse", format = "" }); routes.MapRoute("News-ExplicitFormat", "news.{format}" new { controller = "News", action = "Browse" }); </code></pre> <p>It seems like it would be useful to have the routing system support something like:</p> <pre><code>routes.MapRoute("News", "news(.{format})?", new { controller = "News", action = "Browse" }); </code></pre>
[ { "answer_id": 255880, "author": "Doug McClean", "author_id": 11173, "author_profile": "https://Stackoverflow.com/users/11173", "pm_score": 5, "selected": true, "text": "public static void MapRouteWithOptionalFormat(this RouteCollection routes,\n string name,\n string url,\n object defaults)\n{\n Route implicitRoute = routes.MapRoute(name + \"-ImplicitFormat\",\n url,\n defaults);\n implicitRoute.Defaults.Add(\"format\", string.Empty);\n\n Route explicitRoute = routes.MapRoute(name + \"-ExplicitFormat\",\n url + \".{format}\",\n defaults);\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11173/" ]
255,879
<p>I need some help with WPF binding syntax:</p> <pre><code>public class ApplicationPresenter { public ObservableCollection&lt;Quotes&gt; PriceList {get;} } public class WebSitePricesView { private IApplicationPresenter presenter { get { return (ApplicationPresenter)DataContext; } } // public ObservableCollection&lt;Quotes&gt; PriceList // { // get {return presenter.PriceList; } } } </code></pre> <p>This XAML works fine:</p> <pre><code>&lt;UserControl.Resources&gt; &lt;ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type local:ApplicationPresenter}" /&gt; &lt;xcdg:DataGridCollectionViewSource x:Key="price_list" Source="{Binding Path=PriceList} /&gt; &lt;/UserControl.Resources&gt; &lt;xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}} /&gt; </code></pre> <p>However I don't want WebSitePricesView to expose PriceList, I want to bind the DataGridCollectionViewSource directly to ApplicationPresenter.PriceList.</p> <p>This XAML doesn't bind any values to the grid. Obviously I'm doing something wrong in defining the Binding Source for price_list .....</p> <pre><code>&lt;UserControl.Resources&gt; &lt;ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type local:ApplicationPresenter}" /&gt; &lt;xcdg:DataGridCollectionViewSource x:Key="price_list" Source="{Binding Source={StaticResource ApplicationPresenterDS}, Path=PriceList /&gt; &lt;/UserControl.Resources&gt; &lt;xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}} /&gt; </code></pre> <p>The debug output for the first successful binding is:</p> <pre><code>Step into: Stepping over method without symbols 'Fenix.App.App' System.Windows.Data Warning: 52 : Created BindingExpression (hash=35059110) for Binding (hash=15586314) System.Windows.Data Warning: 54 : Path: 'PriceList' System.Windows.Data Warning: 56 : BindingExpression (hash=35059110): Default mode resolved to OneWay System.Windows.Data Warning: 57 : BindingExpression (hash=35059110): Default update trigger resolved to PropertyChanged System.Windows.Data Warning: 58 : BindingExpression (hash=35059110): Attach to Xceed.Wpf.DataGrid.DataGridCollectionViewSource.Source (hash=28137373) System.Windows.Data Warning: 60 : BindingExpression (hash=35059110): Use Framework mentor &lt;null&gt; System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source System.Windows.Data Warning: 65 : BindingExpression (hash=35059110): Framework mentor not found System.Windows.Data Warning: 61 : BindingExpression (hash=35059110): Resolve source deferred System.Windows.Data Warning: 91 : BindingExpression (hash=35059110): Got InheritanceContextChanged event from DataGridCollectionViewSource (hash=28137373) System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: WebSitePricesXc (hash=11090012) (OK) System.Windows.Data Warning: 67 : BindingExpression (hash=35059110): DataContext is null System.Windows.Data Warning: 52 : Created BindingExpression (hash=53154844) for Binding (hash=52037308) System.Windows.Data Warning: 54 : Path: '' System.Windows.Data Warning: 56 : BindingExpression (hash=53154844): Default mode resolved to OneWay System.Windows.Data Warning: 57 : BindingExpression (hash=53154844): Default update trigger resolved to PropertyChanged System.Windows.Data Warning: 58 : BindingExpression (hash=53154844): Attach to Xceed.Wpf.DataGrid.DataGridControl.ItemsSource (hash=16991442) System.Windows.Data Warning: 63 : BindingExpression (hash=53154844): Resolving source System.Windows.Data Warning: 66 : BindingExpression (hash=53154844): Found data context element: &lt;null&gt; (OK) System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373) System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item &lt;null&gt; System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with &lt;null&gt;, using accessor {DependencyProperty.UnsetValue} System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from &lt;null&gt; using &lt;null&gt;: &lt;null&gt; System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value &lt;null&gt; System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value &lt;null&gt; A first chance exception of type 'System.FormatException' occurred in mscorlib.dll System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: WebSitePricesXc (hash=11090012) (OK) System.Windows.Data Warning: 74 : BindingExpression (hash=35059110): Activate with root item ApplicationPresenter (hash=22260412) System.Windows.Data Warning: 104 : BindingExpression (hash=35059110): At level 0 - for ApplicationPresenter.PriceList found accessor RuntimePropertyInfo(PriceList) System.Windows.Data Warning: 100 : BindingExpression (hash=35059110): Replace item at level 0 with ApplicationPresenter (hash=22260412), using accessor RuntimePropertyInfo(PriceList) System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=22260412) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=40261689 Count=0) System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=40261689 Count=0) System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=40261689 Count=0) System.Windows.Data Warning: 92 : BindingExpression (hash=53154844): Got PropertyChanged event from DataGridCollectionViewSource (hash=28137373) for View System.Windows.Data Warning: 75 : BindingExpression (hash=53154844): Deactivate System.Windows.Data Warning: 99 : BindingExpression (hash=53154844): Replace item at level 0 with {NullDataItem} System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373) System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item DataGridCollectionView (hash=22444475 Count=0) System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with DataGridCollectionView (hash=22444475 Count=0), using accessor {DependencyProperty.UnsetValue} System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from DataGridCollectionView (hash=22444475 Count=0) using &lt;null&gt;: DataGridCollectionView (hash=22444475 Count=0) System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value DataGridCollectionView (hash=22444475 Count=0) System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value DataGridCollectionView (hash=22444475 Count=0) System.Windows.Data Warning: 91 : BindingExpression (hash=35059110): Got PropertyChanged event from ApplicationPresenter (hash=22260412) System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=22260412) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=6408547 Count=27) System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=6408547 Count=27) System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=6408547 Count=27) System.Windows.Data Warning: 92 : BindingExpression (hash=53154844): Got PropertyChanged event from DataGridCollectionViewSource (hash=28137373) for View System.Windows.Data Warning: 75 : BindingExpression (hash=53154844): Deactivate System.Windows.Data Warning: 99 : BindingExpression (hash=53154844): Replace item at level 0 with {NullDataItem} System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373) System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item DataGridCollectionView (hash=61423861 Count=27) System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with DataGridCollectionView (hash=61423861 Count=27), using accessor {DependencyProperty.UnsetValue} System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from DataGridCollectionView (hash=61423861 Count=27) using &lt;null&gt;: DataGridCollectionView (hash=61423861 Count=27) System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value DataGridCollectionView (hash=61423861 Count=27) System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value DataGridCollectionView (hash=61423861 Count=27) </code></pre> <p>The debug output for the second binding is:</p> <pre><code>Step into: Stepping over method without symbols 'Fenix.App.App' System.Windows.Data Warning: 52 : Created BindingExpression (hash=35059110) for Binding (hash=15586314) System.Windows.Data Warning: 54 : Path: 'PriceList' System.Windows.Data Warning: 56 : BindingExpression (hash=35059110): Default mode resolved to OneWay System.Windows.Data Warning: 57 : BindingExpression (hash=35059110): Default update trigger resolved to PropertyChanged System.Windows.Data Warning: 58 : BindingExpression (hash=35059110): Attach to Xceed.Wpf.DataGrid.DataGridCollectionViewSource.Source (hash=28137373) System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: &lt;null&gt; (OK) System.Windows.Data Warning: 73 : BindingExpression (hash=35059110): Use Data from ObjectDataProvider (hash=61302538) System.Windows.Data Warning: 74 : BindingExpression (hash=35059110): Activate with root item ApplicationPresenter (hash=20390146) System.Windows.Data Warning: 104 : BindingExpression (hash=35059110): At level 0 - for ApplicationPresenter.PriceList found accessor RuntimePropertyInfo(PriceList) System.Windows.Data Warning: 100 : BindingExpression (hash=35059110): Replace item at level 0 with ApplicationPresenter (hash=20390146), using accessor RuntimePropertyInfo(PriceList) System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=20390146) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=12781633 Count=0) System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=12781633 Count=0) System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=12781633 Count=0) System.Windows.Data Warning: 52 : Created BindingExpression (hash=12661120) for Binding (hash=31408037) System.Windows.Data Warning: 54 : Path: '' System.Windows.Data Warning: 56 : BindingExpression (hash=12661120): Default mode resolved to OneWay System.Windows.Data Warning: 57 : BindingExpression (hash=12661120): Default update trigger resolved to PropertyChanged System.Windows.Data Warning: 58 : BindingExpression (hash=12661120): Attach to Xceed.Wpf.DataGrid.DataGridControl.ItemsSource (hash=16991442) System.Windows.Data Warning: 63 : BindingExpression (hash=12661120): Resolving source System.Windows.Data Warning: 66 : BindingExpression (hash=12661120): Found data context element: &lt;null&gt; (OK) System.Windows.Data Warning: 72 : BindingExpression (hash=12661120): Use View from DataGridCollectionViewSource (hash=28137373) System.Windows.Data Warning: 74 : BindingExpression (hash=12661120): Activate with root item DataGridCollectionView (hash=49343907 Count=0) System.Windows.Data Warning: 100 : BindingExpression (hash=12661120): Replace item at level 0 with DataGridCollectionView (hash=49343907 Count=0), using accessor {DependencyProperty.UnsetValue} System.Windows.Data Warning: 97 : BindingExpression (hash=12661120): GetValue at level 0 from DataGridCollectionView (hash=49343907 Count=0) using &lt;null&gt;: Data``GridCollectionView (hash=49343907 Count=0) System.Windows.Data Warning: 76 : BindingExpression (hash=12661120): TransferValue - got raw value DataGridCollectionView (hash=49343907 Count=0) System.Windows.Data Warning: 85 : BindingExpression (hash=12661120): TransferValue - using final value DataGridCollectionView (hash=49343907 Count=0) A first chance exception of type 'System.FormatException' occurred in mscorlib.dll </code></pre>
[ { "answer_id": 256249, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 1, "selected": false, "text": "public class Quotes\n{\n public string Description { get; set; }\n public decimal Value { get; set; }\n}\n\npublic class ApplicationPresenter\n{\n public ApplicationPresenter()\n {\n PriceList = new ObservableCollection<Quotes>()\n {\n new Quotes(){Description=\"Quote One\", Value=10m},\n new Quotes(){Description=\"Quote Two\", Value=10m},\n new Quotes(){Description=\"Quote Three\", Value=10m},\n new Quotes(){Description=\"Quote Four\", Value=10m},\n };\n }\n public ObservableCollection<Quotes> PriceList { get; private set; }\n}\n\n<Window \n x:Class=\"ObjectDataProviderPresenterSample.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:xcdg=\"http://schemas.xceed.com/wpf/xaml/datagrid\"\n xmlns:local=\"clr-namespace:ObjectDataProviderPresenterSample\"\n Title=\"Window1\" \n Height=\"300\" \n Width=\"300\" \n >\n <Window.Resources>\n <ObjectDataProvider \n x:Key=\"ApplicationPresenterDS\" \n ObjectType=\"{x:Type local:ApplicationPresenter}\" \n />\n <xcdg:DataGridCollectionViewSource \n x:Key=\"price_list\" \n Source=\"{Binding \n Source={StaticResource ApplicationPresenterDS}, \n Path=PriceList}\" \n /> \n </Window.Resources> \n\n <Grid>\n <xcdg:DataGridControl ItemsSource=\"{Binding Source={StaticResource price_list}}\" />\n </Grid>\n</Window>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30046/" ]
255,898
<p>I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of <code>$1</code> easily:</p> <pre><code>foo $1 args -o $1.ext </code></pre> <p>I want to be able to pass multiple input names to the script. What's the right way to do it? </p> <p>And, of course, I want to handle filenames with spaces in them.</p>
[ { "answer_id": 255913, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 12, "selected": true, "text": "\"$@\"" }, { "answer_id": 256225, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 8, "selected": false, "text": "\"$@\"" }, { "answer_id": 1987331, "author": "Alok Singhal", "author_id": 226621, "author_profile": "https://Stackoverflow.com/users/226621", "pm_score": 7, "selected": false, "text": "sh" }, { "answer_id": 13118192, "author": "nuoritoveri", "author_id": 1065693, "author_profile": "https://Stackoverflow.com/users/1065693", "pm_score": 6, "selected": false, "text": "shift" }, { "answer_id": 34791882, "author": "g24l", "author_id": 4345926, "author_profile": "https://Stackoverflow.com/users/4345926", "pm_score": 3, "selected": false, "text": "aparse() {\nwhile [[ $# > 0 ]] ; do\n case \"$1\" in\n --arg1)\n varg1=${2}\n shift\n ;;\n --arg2)\n varg2=true\n ;;\n esac\n shift\ndone\n}\n\naparse \"$@\"\n" }, { "answer_id": 47006836, "author": "baz", "author_id": 6421877, "author_profile": "https://Stackoverflow.com/users/6421877", "pm_score": 5, "selected": false, "text": "argc=$#\nargv=(\"$@\")\n\nfor (( j=0; j<argc; j++ )); do\n echo \"${argv[j]}\"\ndone\n" }, { "answer_id": 60022895, "author": "Rich Kadel", "author_id": 10826737, "author_profile": "https://Stackoverflow.com/users/10826737", "pm_score": 3, "selected": false, "text": " toolwrapper() {\n for i in $(seq 1 $#); do\n [[ \"${!i}\" == \"--\" ]] && break\n done || return $? # returns error status if we don't \"break\"\n\n echo \"dashes at $i\"\n echo \"Before dashes: ${@:1:i-1}\"\n echo \"After dashes: ${@:i+1:$#}\"\n }\n" }, { "answer_id": 60510590, "author": "JimmyLandStudios", "author_id": 4231306, "author_profile": "https://Stackoverflow.com/users/4231306", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n# Extract command line options & values with getopt\n#\nset -- $(getopt -q ab:cd \"$@\")\n#\necho\nwhile [ -n \"$1\" ]\ndo\ncase \"$1\" in\n-a) echo \"Found the -a option\" ;;\n-b) param=\"$2\"\necho \"Found the -b option, with parameter value $param\"\nshift ;;\n-c) echo \"Found the -c option\" ;;\n--) shift\nbreak ;;\n*) echo \"$1 is not an option\";;\nesac\nshift\n" }, { "answer_id": 65982417, "author": "Iceberg", "author_id": 7935057, "author_profile": "https://Stackoverflow.com/users/7935057", "pm_score": 4, "selected": false, "text": "#! /bin/bash\n\nfor ((i=1; i<=$#; i++))\ndo\n printf \"${!i}\\n\"\ndone\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12874/" ]
255,907
<p>In Visual Studio 2008 in a C# WinForms project, there is a button on a form. In the properties view, the property "Font" is set to "Arial Unicode MS".</p> <p>What do I need to put into the property "Text", so I get the unicode character \u0D15 displayed on the button?</p> <p>When I put \u0D15 into the "Text" property, the button displays the six characters "\u0D15" instead of one unicode character.</p> <p>In the following PDF, you can see the unicode character for \u0D15: <a href="http://unicode.org/charts/PDF/U0D00.pdf" rel="noreferrer">http://unicode.org/charts/PDF/U0D00.pdf</a></p>
[ { "answer_id": 255918, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 4, "selected": true, "text": "button1.Text = \"日本\";\n" }, { "answer_id": 67694137, "author": "Ragheed Al-Tayeb", "author_id": 12519801, "author_profile": "https://Stackoverflow.com/users/12519801", "pm_score": -1, "selected": false, "text": "button.Text = \"0x0D15\";\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33311/" ]
255,916
<p>I use BIRT since early days and still have riddles regarding PDF emitter. </p> <p><strong>Short story</strong>: Can I configure fontsConfig.xml to load fonts from relative path or from jars?</p> <p><strong>Long story:</strong> We are using both FOP and BIRT for generating PDF in our web application. It would be nice to share fonts between libraries. Unfortunately, I can't find a way to do it with BIRT 2.3.1</p> <p>The root of evil is fontsConfig.xml If I configure it like shown below it works fine:</p> <pre><code>&lt;font-paths&gt; &lt;path path="fonts"/&gt; &lt;/font-paths&gt; </code></pre> <p>But path doesn't allow me using neither relative paths not classpath (or I can't find an appropriate way how to configure it). Neither config1 nor config2 works.</p> <p>Config1:</p> <pre><code>&lt;font-paths&gt; &lt;path path="../fonts"/&gt; &lt;/font-paths&gt; </code></pre> <p>Config2:</p> <pre><code>&lt;font-paths&gt; &lt;path path="classpath:fonts"/&gt; &lt;/font-paths&gt; </code></pre> <p>Any thoughts will be appreciated.</p>
[ { "answer_id": 21705054, "author": "hvb", "author_id": 2814025, "author_profile": "https://Stackoverflow.com/users/2814025", "pm_score": 3, "selected": true, "text": "EngineConfig engineConfig = new EngineConfig();\nURL fontsConfigurationURL = new URL(\"file:///path/to/my/fontsConfig.xml\");\nengineConfig.setFontConfig(fontsConfigurationURL);\n\nPlatform.startup(engineConfig);\n" }, { "answer_id": 22227211, "author": "Saurabh Singhal", "author_id": 3231802, "author_profile": "https://Stackoverflow.com/users/3231802", "pm_score": 1, "selected": false, "text": "FontFactory.registerDirectory( scContext.getRealPath(\"/Reports\") );\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19347/" ]
255,927
<p>I'm writing an iOS app with a table view inside a tab view. In my <code>UITableViewController</code>, I implemented <code>-tableView:didSelectRowAtIndexPath:</code>, but when I select a row at runtime, the method isn't being called. The table view is being populated though, so I know that other tableView methods in my controller are being called.</p> <p>Does anyone have any ideas what I may have screwed up to make this happen?</p>
[ { "answer_id": 255961, "author": "Hunter", "author_id": 555, "author_profile": "https://Stackoverflow.com/users/555", "pm_score": 8, "selected": true, "text": "UITableViewDelegate" }, { "answer_id": 4023700, "author": "JackPearse", "author_id": 487612, "author_profile": "https://Stackoverflow.com/users/487612", "pm_score": 6, "selected": false, "text": "- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {\n return nil;\n}\n" }, { "answer_id": 6559604, "author": "Steve", "author_id": 813461, "author_profile": "https://Stackoverflow.com/users/813461", "pm_score": 3, "selected": false, "text": "tableViewController" }, { "answer_id": 10466158, "author": "Old McStopher", "author_id": 205926, "author_profile": "https://Stackoverflow.com/users/205926", "pm_score": 7, "selected": false, "text": "[tableView setAllowsSelection:YES];" }, { "answer_id": 12587624, "author": "CGee", "author_id": 1035741, "author_profile": "https://Stackoverflow.com/users/1035741", "pm_score": 9, "selected": false, "text": "didSelect" }, { "answer_id": 12855662, "author": "Dennis Krut", "author_id": 286643, "author_profile": "https://Stackoverflow.com/users/286643", "pm_score": 9, "selected": false, "text": "Single Selection" }, { "answer_id": 15008016, "author": "Carlos", "author_id": 1210389, "author_profile": "https://Stackoverflow.com/users/1210389", "pm_score": 3, "selected": false, "text": "[self.tableView setDelegate:self];\n\n[self.tableView setDataSource:self];\n" }, { "answer_id": 17378032, "author": "juanignaciosl", "author_id": 351721, "author_profile": "https://Stackoverflow.com/users/351721", "pm_score": 2, "selected": false, "text": "didSelectRowAtIndexPath" }, { "answer_id": 17801854, "author": "cpt.neverm1nd", "author_id": 2609194, "author_profile": "https://Stackoverflow.com/users/2609194", "pm_score": 5, "selected": false, "text": "- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{\n return NO;\n}\n" }, { "answer_id": 17840861, "author": "Taum", "author_id": 286671, "author_profile": "https://Stackoverflow.com/users/286671", "pm_score": 1, "selected": false, "text": "UITableView" }, { "answer_id": 21686537, "author": "Groot", "author_id": 1075405, "author_profile": "https://Stackoverflow.com/users/1075405", "pm_score": 4, "selected": false, "text": "UITapGestureRecognizer" }, { "answer_id": 22892352, "author": "karlbecker_com", "author_id": 192141, "author_profile": "https://Stackoverflow.com/users/192141", "pm_score": 1, "selected": false, "text": "- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n" }, { "answer_id": 24029137, "author": "Diego Maye", "author_id": 512969, "author_profile": "https://Stackoverflow.com/users/512969", "pm_score": 2, "selected": false, "text": "UITableView" }, { "answer_id": 24135582, "author": "Jeyhun Karimov", "author_id": 991607, "author_profile": "https://Stackoverflow.com/users/991607", "pm_score": 4, "selected": false, "text": "UITapGestureRecognizer" }, { "answer_id": 24946777, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "tableView:didDeselectRowAtIndexPath" }, { "answer_id": 24947606, "author": "GK100", "author_id": 2274829, "author_profile": "https://Stackoverflow.com/users/2274829", "pm_score": 2, "selected": false, "text": "TableView" }, { "answer_id": 25502224, "author": "Hot'n'Young", "author_id": 2230992, "author_profile": "https://Stackoverflow.com/users/2230992", "pm_score": 0, "selected": false, "text": "didSelectRow" }, { "answer_id": 25515806, "author": "Imju", "author_id": 2809848, "author_profile": "https://Stackoverflow.com/users/2809848", "pm_score": 2, "selected": false, "text": "cell.content.scrollEnabled = NO;\ncell.content.editable = NO;\ncell.content.userInteractionEnabled = NO;\ncell.content.delegate = nil;\n" }, { "answer_id": 27406901, "author": "Mark Bridges", "author_id": 1731532, "author_profile": "https://Stackoverflow.com/users/1731532", "pm_score": 1, "selected": false, "text": "didSelectItemAtIndexPath" }, { "answer_id": 28232698, "author": "Bartłomiej Semańczyk", "author_id": 2725435, "author_profile": "https://Stackoverflow.com/users/2725435", "pm_score": 7, "selected": false, "text": "UITapGestureRecognizer" }, { "answer_id": 29026761, "author": "SleepsOnNewspapers", "author_id": 2855836, "author_profile": "https://Stackoverflow.com/users/2855836", "pm_score": 3, "selected": false, "text": "tableView:didSelectRowAtIndexPath" }, { "answer_id": 29159968, "author": "benvolioT", "author_id": 87696, "author_profile": "https://Stackoverflow.com/users/87696", "pm_score": 2, "selected": false, "text": "override func viewDidAppear(animated: Bool) {\n tableView.reloadData()\n}\n" }, { "answer_id": 31224470, "author": "Yannick Winters", "author_id": 1067125, "author_profile": "https://Stackoverflow.com/users/1067125", "pm_score": 2, "selected": false, "text": "cell.imgView.userInteractionEnabled = YES;\n" }, { "answer_id": 33202812, "author": "0xKayvan", "author_id": 2399979, "author_profile": "https://Stackoverflow.com/users/2399979", "pm_score": 2, "selected": false, "text": "UITableViewCell" }, { "answer_id": 35596744, "author": "Vinu David Jose", "author_id": 5388289, "author_profile": "https://Stackoverflow.com/users/5388289", "pm_score": 5, "selected": false, "text": "didSelectRowAtIndexPath" }, { "answer_id": 35896903, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 2, "selected": false, "text": "errorMessageView.setUserInteractionEnabled = NO;\n// or\nerrorMessageView.hidden = YES;\n" }, { "answer_id": 38066334, "author": "yvetterowe", "author_id": 839929, "author_profile": "https://Stackoverflow.com/users/839929", "pm_score": 3, "selected": false, "text": "[tableView setEditing:YES animated:NO];" }, { "answer_id": 38566023, "author": "Mohsin Qureshi", "author_id": 6224724, "author_profile": "https://Stackoverflow.com/users/6224724", "pm_score": 5, "selected": false, "text": "UITableView" }, { "answer_id": 40608344, "author": "dip", "author_id": 1690965, "author_profile": "https://Stackoverflow.com/users/1690965", "pm_score": 0, "selected": false, "text": "@interface ExampleViewController () <UITableViewDelegate, UITableViewDataSource>" }, { "answer_id": 42789127, "author": "HonkyHonk", "author_id": 804906, "author_profile": "https://Stackoverflow.com/users/804906", "pm_score": 3, "selected": false, "text": "- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath\n{\n return YES;\n}\n" }, { "answer_id": 45707365, "author": "John Doe", "author_id": 7214631, "author_profile": "https://Stackoverflow.com/users/7214631", "pm_score": 2, "selected": false, "text": "override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)\n" }, { "answer_id": 47168719, "author": "Lucas van Dongen", "author_id": 2804585, "author_profile": "https://Stackoverflow.com/users/2804585", "pm_score": 0, "selected": false, "text": "@objc" }, { "answer_id": 48082718, "author": "Supertecnoboff", "author_id": 1598906, "author_profile": "https://Stackoverflow.com/users/1598906", "pm_score": 0, "selected": false, "text": "reloadData" }, { "answer_id": 48934003, "author": "Mithra Singam", "author_id": 6342609, "author_profile": "https://Stackoverflow.com/users/6342609", "pm_score": 3, "selected": false, "text": "viewController" }, { "answer_id": 49529841, "author": "Paul.V", "author_id": 7528840, "author_profile": "https://Stackoverflow.com/users/7528840", "pm_score": 0, "selected": false, "text": "tableView.isUserInteractionEnabled = false\n" }, { "answer_id": 50890020, "author": "Dilapidus", "author_id": 2954839, "author_profile": "https://Stackoverflow.com/users/2954839", "pm_score": 0, "selected": false, "text": "didSelect" }, { "answer_id": 53935897, "author": "Prasanna Ramaswamy", "author_id": 5023213, "author_profile": "https://Stackoverflow.com/users/5023213", "pm_score": 0, "selected": false, "text": "private func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n" }, { "answer_id": 55193990, "author": "Sasi", "author_id": 1402675, "author_profile": "https://Stackoverflow.com/users/1402675", "pm_score": 1, "selected": false, "text": "segue" }, { "answer_id": 63783571, "author": "Serg Smyk", "author_id": 4247449, "author_profile": "https://Stackoverflow.com/users/4247449", "pm_score": 2, "selected": false, "text": "tableView?.allowsSelection = true\n" }, { "answer_id": 66092414, "author": "Denis Kutlubaev", "author_id": 751641, "author_profile": "https://Stackoverflow.com/users/751641", "pm_score": 0, "selected": false, "text": "class name" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5815/" ]
255,928
<p>The MSI stores the installation directory for the future uninstall tasks.</p> <p>Using the <code>INSTALLPROPERTY_INSTALLLOCATION</code> property (that is <code>"InstallLocation"</code>) works only the installer has set the <code>ARPINSTALLLOCATION</code> property during the installation. But this property is optional and almost nobody uses it.</p> <p>How could I retrieve the installation directory?</p>
[ { "answer_id": 48016963, "author": "eduardomozart", "author_id": 1031340, "author_profile": "https://Stackoverflow.com/users/1031340", "pm_score": 0, "selected": false, "text": "%ProgramFiles(x86)%\\Natural Docs" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23372/" ]
255,941
<p>Is there anything out there freeware or commercial that can facilitate analysis of memory usage by a PHP application? I know xdebug can produce trace files that shows memory usage by function call but without a graphical tool the data is hard to interpret. </p> <p>Ideally I would like to be able to view not only total memory usage but also what objects are on the heap and who references them similar to <a href="http://www.codework.com/jprofiler/product.htm" rel="noreferrer">Jprofiler</a>.</p>
[ { "answer_id": 329809, "author": "EvilPuppetMaster", "author_id": 20851, "author_profile": "https://Stackoverflow.com/users/20851", "pm_score": 3, "selected": false, "text": "sort -bgrk 3 -o sorted.txt mytracefile.xt \n" }, { "answer_id": 23829872, "author": "Francesco Casula", "author_id": 828366, "author_profile": "https://Stackoverflow.com/users/828366", "pm_score": 5, "selected": true, "text": "sudo apt-get install libjudy-dev libjudydebian1\nsudo pecl install memprof\necho \"extension=memprof.so\" > /etc/php5/mods-available/memprof.ini\nsudo php5enmod memprof\nservice apache2 restart\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2043539/" ]
255,942
<p>I'm using Castle ActiveRecord for persistence, and I'm trying to write a base class for my persistence tests which will do the following:</p> <ul> <li>Open a transaction for each test case and roll it back at the end of the test case, so that I get a clean DB for each test case without me having to rebuild the schema for each test case.</li> <li>Provide the ability to flush my NHibernate session and get a new one in the middle of a test, so that I know that my persistence operations have really hit the DB rather than just the NHibernate session.</li> </ul> <p>In order to prove that my base class (<code>ARTestBase</code>) is working, I've come up with the following sample tests.</p> <pre><code>[TestFixture] public class ARTestBaseTest : ARTestBase { [Test] public void object_created_in_this_test_should_not_get_committed_to_db() { ActiveRecordMediator&lt;Entity&gt;.Save(new Entity {Name = "test"}); Assert.That(ActiveRecordMediator&lt;Entity&gt;.Count(), Is.EqualTo(1)); } [Test] public void object_created_in_previous_test_should_not_have_been_committed_to_db() { ActiveRecordMediator&lt;Entity&gt;.Save(new Entity {Name = "test"}); Assert.That(ActiveRecordMediator&lt;Entity&gt;.Count(), Is.EqualTo(1)); } [Test] public void calling_flush_should_make_nhibernate_retrieve_fresh_objects() { var savedEntity = new Entity {Name = "test"}; ActiveRecordMediator&lt;Entity&gt;.Save(savedEntity); Flush(); // Could use FindOne, but then this test would fail if the transactions aren't being rolled back foreach (var entity in ActiveRecordMediator&lt;Entity&gt;.FindAll()) { Assert.That(entity, Is.Not.SameAs(savedEntity)); } } } </code></pre> <p>Here is my best effort at the base class. It correctly implements <code>Flush()</code>, so the third test case passes. However it does not rollback the transactions, so the second test fails.</p> <pre><code>public class ARTestBase { private SessionScope sessionScope; private TransactionScope transactionScope; [TestFixtureSetUp] public void InitialiseAR() { ActiveRecordStarter.ResetInitializationFlag(); ActiveRecordStarter.Initialize(typeof (Entity).Assembly, ActiveRecordSectionHandler.Instance); ActiveRecordStarter.CreateSchema(); } [SetUp] public virtual void SetUp() { transactionScope = new TransactionScope(OnDispose.Rollback); sessionScope = new SessionScope(); } [TearDown] public virtual void TearDown() { sessionScope.Dispose(); transactionScope.Dispose(); } protected void Flush() { sessionScope.Dispose(); sessionScope = new SessionScope(); } [TestFixtureTearDown] public virtual void TestFixtureTearDown() { SQLiteProvider.ExplicitlyDestroyConnection(); } } </code></pre> <p>Note that I'm using a custom SQLite provider with an in-memory database. My custom provider, taken from <a href="http://brian.genisio.org/2008/07/active-record-mock-framework.html" rel="nofollow noreferrer">this blog post</a>, keeps the connection open at all times to maintain the schema. Removing this and using a regular SQL Server database doesn't change the behaviour.</p> <p>Is there a way to acheive the required behaviour?</p>
[ { "answer_id": 258313, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "IDbTransaction" }, { "answer_id": 258560, "author": "Alex Scordellis", "author_id": 12006, "author_profile": "https://Stackoverflow.com/users/12006", "pm_score": 0, "selected": false, "text": "SessionScope.Flush()" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12006/" ]
255,955
<p>Returning to WinForms in VS2008 after a long time.. Tinkering with a OOD problem in VS2008 Express Edition.</p> <p>I need some controls to be "display only" widgets. The user should not be able to change the value of these controls... the widgets are updated by a periodic update tick event. I vaguely remember there being a ReadOnly property that you could set to have this behavior... can't find it now.</p> <p>The <strong>Enabled</strong> property set to false: grays out the control content. I want the control to look normal. The <strong>Locked</strong> property set to false: seems to be protecting the user from accidentally distorting the control in the Visual Form Designer.</p> <p>What am I missing? </p>
[ { "answer_id": 255965, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 5, "selected": true, "text": " Color clr = textBox1.BackColor;\n textBox1.ReadOnly = true;\n textBox1.BackColor = clr;\n" }, { "answer_id": 256035, "author": "Grant", "author_id": 407, "author_profile": "https://Stackoverflow.com/users/407", "pm_score": 1, "selected": false, "text": "public class ReadOnlyTextBox : TextBox\n{\n const uint WM_SETFOCUS = 0x0007;\n\n public ReadOnlyTextBox()\n {\n this.ReadOnly = true;\n this.BackColor = System.Drawing.SystemColors.Window;\n this.ForeColor = System.Drawing.SystemColors.WindowText;\n }\n\n protected override void WndProc(ref Message m)\n {\n // eat all setfocus messages, pass rest to base\n if (m.Msg != WM_SETFOCUS)\n base.WndProc(ref m);\n }\n}\n" }, { "answer_id": 3862349, "author": "Rajan Arora", "author_id": 466639, "author_profile": "https://Stackoverflow.com/users/466639", "pm_score": 3, "selected": false, "text": " public void LockControlValues(System.Windows.Forms.Control Container)\n {\n try\n {\n foreach (Control ctrl in Container.Controls)\n {\n if (ctrl.GetType() == typeof(TextBox))\n ((TextBox)ctrl).ReadOnly = true;\n if (ctrl.GetType() == typeof(ComboBox))\n ((ComboBox)ctrl).Enabled= false;\n if (ctrl.GetType() == typeof(CheckBox))\n ((CheckBox)ctrl).Enabled = false;\n\n if (ctrl.GetType() == typeof(DateTimePicker))\n ((DateTimePicker)ctrl).Enabled = false;\n\n if (ctrl.Controls.Count > 0)\n LockControlValues(ctrl);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.ToString());\n }\n }\n" }, { "answer_id": 18882848, "author": "C.J.", "author_id": 321866, "author_profile": "https://Stackoverflow.com/users/321866", "pm_score": 0, "selected": false, "text": "form->Enabled = false;\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
255,969
<p>I'm struggling with Test::Unit. When I think of unit tests, I think of one simple test per file. But in Ruby's framework, I must instead write: </p> <pre><code>class MyTest &lt; Test::Unit::TestCase def setup end def test_1 end def test_1 end end </code></pre> <p>But setup and teardown run for every invocation of a test_* method. This is exactly what I don't want. Rather, I want a setup method that runs just once for the whole class. But I can't seem to write my own initialize() without breaking TestCase's initialize.</p> <p>Is that possible? Or am I making this hopelessly complicated?</p>
[ { "answer_id": 256063, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 3, "selected": false, "text": "setup" }, { "answer_id": 256104, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 1, "selected": false, "text": "Test::Unit::TestCase" }, { "answer_id": 369709, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "require 'test/unit'\nrequire 'setuponce'\n\n\nclass MyTest < Test::Unit::TestCase\n include SetupOnce\n\n def self.setup_once\n puts \"doing one-time setup\"\n end\n\n def self.teardown_once\n puts \"doing one-time teardown\"\n end\n\nend\n" }, { "answer_id": 778701, "author": "Matt Wolfe", "author_id": 94557, "author_profile": "https://Stackoverflow.com/users/94557", "pm_score": 5, "selected": false, "text": "def self.suite\n mysuite = super\n def mysuite.run(*args)\n MyTest.startup()\n super\n MyTest.shutdown()\n end\n mysuite\nend\n" }, { "answer_id": 1126566, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "class MyTests < Test::Unit::TestCase\ndef test_AASetup # I have a few tests that start with \"A\", but I doubt any will start with \"Aardvark\" or \"Aargh!\"\n #Run setup code\nend\n\ndef MoreTests\nend\n\ndef test_ZTeardown\n #Run teardown code\nend\n" }, { "answer_id": 4120184, "author": "Bouke Woudstra", "author_id": 500158, "author_profile": "https://Stackoverflow.com/users/500158", "pm_score": 2, "selected": false, "text": "class TC_001 << Test::Unit::TestCase\n def setup\n # do stuff once\n end\n\n def testSuite\n falseArguments()\n arguments()\n end\n\n def falseArguments\n # do stuff\n end\n\n def arguments\n # do stuff\n end\nend\n" }, { "answer_id": 7052032, "author": "remi", "author_id": 544304, "author_profile": "https://Stackoverflow.com/users/544304", "pm_score": 0, "selected": false, "text": "before(:all)" }, { "answer_id": 12585596, "author": "jpgeek", "author_id": 454246, "author_profile": "https://Stackoverflow.com/users/454246", "pm_score": 4, "selected": false, "text": "Test::Unit.at_start do\n # initialization stuff here\nend\n" }, { "answer_id": 18850444, "author": "aerostitch", "author_id": 2787693, "author_profile": "https://Stackoverflow.com/users/2787693", "pm_score": 2, "selected": false, "text": "class MyTest < Test::Unit::TestCase\n @@cmptr = nil\n def setup\n if @@cmptr.nil?\n @@cmptr = 0\n puts \"runs at first test only\"\n @@var_shared_between_fcs = \"value\"\n end\n puts 'runs before each test'\n end\n def test_stuff\n assert(true)\n end\nend\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/255969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8913/" ]
256,021
<p>I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list. </p> <p>I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory. </p> <p>Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.</p>
[ { "answer_id": 303086, "author": "PyNEwbie", "author_id": 30105, "author_profile": "https://Stackoverflow.com/users/30105", "pm_score": 1, "selected": true, "text": "def OnDelete(self, event):\n assert self.current, \"invalid delete operation\"\n try:\n os.remove(os.path.join(self.cwd, self.current))\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30105/" ]
256,027
<p>I am developing an application which will be connected to Access database at the beginning and the plan is to switch to MS SQL or SQL Express in the near future. The datatables structures are same for both types of databases and I am trying to avoid duplicating the code and trying to find the way to minimize the code.</p> <p>For example I wrote the following function for retrieving data from Access database:</p> <pre><code>public static DataTable GetActiveCalls() { string select = "SELECT call_id, call_time, msisdn, status FROM call WHERE status = 0 OR status = 1 ORDER by call_id ASC"; OleDbCommand cmd = new OleDbCommand(select, conn); DataTable dt = new DataTable("Active Calls"); OleDbDataAdapter DA = new OleDbDataAdapter(cmd); try { conn.Open(); DA.Fill(dt); } catch (Exception ex) { string sDummy = ex.ToString(); } finally { conn.Close(); } return dt; } </code></pre> <p>and the following code is for SQL Express database:</p> <pre><code>public static DataTable GetActiveCalls() { string select = "SELECT call_id, call_time, msisdn, status FROM call WHERE status = 0 OR status = 1 ORDER by call_id ASC"; SqlCommand cmd = new SqlCommand(select, conn); DataTable dt = new DataTable("Active Calls"); SqlDataAdapter DA = new SqlDataAdapter(cmd); try { conn.Open(); DA.Fill(dt); } catch (Exception ex) { string sDummy = ex.ToString(); } finally { conn.Close(); } return dt; } </code></pre> <p>These two methods are almost the same. The only differences are SqlCommand/OleDbCommand and SqlDataAdapter/OleDbDataAdapter. There are also some methods which take arguments for example:</p> <pre><code>public static void AddMessage(string callID, string content) { string select = "INSERT INTO message(key, direction, content, read, write_time) VALUES (@callId, 0, @content, 0, @insertTime)"; OleDbCommand cmd = new OleDbCommand(select, conn); cmd.Parameters.AddWithValue("callId", callID.ToString()); cmd.Parameters.AddWithValue("content", content); cmd.Parameters.AddWithValue("insertTime", DateTime.Now.ToString()); try { conn.Open(); cmd.ExecuteScalar(); } catch (Exception ex) { string sDummy = ex.ToString(); } finally { conn.Close(); } } </code></pre> <p>In this case SQL query string is also the same for both databases but there is the difference between the type of cmd (SqlCommand/OleDbCommand).</p> <p>I would really appreciate if anyone could give any suggestion about how to avoid duplicating the code and optimize the given problem.</p>
[ { "answer_id": 303086, "author": "PyNEwbie", "author_id": 30105, "author_profile": "https://Stackoverflow.com/users/30105", "pm_score": 1, "selected": true, "text": "def OnDelete(self, event):\n assert self.current, \"invalid delete operation\"\n try:\n os.remove(os.path.join(self.cwd, self.current))\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
256,033
<p>Is std::string size() a O(1) operation?</p> <p>The implementation of STL I'm using is the one built into VC++</p>
[ { "answer_id": 256045, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "size_type __CLR_OR_THIS_CALL size() const\n\n{ // return length of sequence\n\n return (_Mysize);\n\n}\n" }, { "answer_id": 256309, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 6, "selected": true, "text": "size()" }, { "answer_id": 259806, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 3, "selected": false, "text": "string happy;\nhappy.size();\n" }, { "answer_id": 7914674, "author": "David Rodríguez - dribeas", "author_id": 36565, "author_profile": "https://Stackoverflow.com/users/36565", "pm_score": 3, "selected": false, "text": "size()" }, { "answer_id": 59337432, "author": "Palak Jain", "author_id": 8494971, "author_profile": "https://Stackoverflow.com/users/8494971", "pm_score": 0, "selected": false, "text": "size()" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
256,038
<p>I'm using a <code>std::map</code> (VC++ implementation) and it's a little slow for lookups via the map's find method. </p> <p>The key type is <code>std::string</code>.</p> <p>Can I increase the performance of this <code>std::map</code> lookup via a custom key compare override for the map? For example, maybe <code>std::string</code> &lt; compare doesn't take into consideration a simple <code>string::size()</code> compare before comparing its data?</p> <p>Any other ideas to speed up the compare?</p> <p>In my situation the map will always contain &lt; 15 elements, but it is being queried non stop and performance is critical. Maybe there is a better data structure that I can use that would be faster?</p> <p>Update: The map contains file paths.</p> <p>Update2: The map's elements are changing often.</p>
[ { "answer_id": 256089, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 4, "selected": false, "text": "set" }, { "answer_id": 256095, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 2, "selected": false, "text": "string" }, { "answer_id": 256096, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 0, "selected": false, "text": "hash_map" }, { "answer_id": 256243, "author": "Phil Hord", "author_id": 33342, "author_profile": "https://Stackoverflow.com/users/33342", "pm_score": 5, "selected": true, "text": "map<string,int> names;\nnames[\"larry\"] = 1;\nnames[\"david\"] = 2;\nnames[\"juanita\"] = 3;\n\nmap<string,int>::iterator iter = names.find(\"daniel\");\n" }, { "answer_id": 256290, "author": "Andrew Top", "author_id": 30036, "author_profile": "https://Stackoverflow.com/users/30036", "pm_score": 2, "selected": false, "text": "class HashedString\n{\n unsigned m_hash;\n std::string m_string;\n\npublic:\n HashedString(const std::string& str)\n : m_hash(HashString(str))\n , m_string(str)\n {};\n // ... copy constructor and etc...\n\n unsigned GetHash() const {return m_hash;}\n const std::string& GetString() const {return m_string;}\n};\n" }, { "answer_id": 1168691, "author": "navigator", "author_id": 115387, "author_profile": "https://Stackoverflow.com/users/115387", "pm_score": 0, "selected": false, "text": "#define \"STRING_1\" STRING_1\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
256,065
<p><strong>NOTE</strong>: I mention the next couple of paragraphs as background. If you just want a TL;DR, feel free to skip down to the numbered questions as they are only indirectly related to this info.</p> <p>I'm currently writing a python script that does some stuff with POSIX dates (among other things). Unit testing these seems a little bit difficult though, since there's such a wide range of dates and times that can be encountered.</p> <p>Of course, it's impractical for me to try to test every single date/time combination possible, so I think I'm going to try a unit test that randomizes the inputs and then reports what the inputs were if the test failed. Statisically speaking, I figure that I can achieve a bit more completeness of testing than I could if I tried to think of all potential problem areas (due to missing things) or testing all cases (due to sheer infeasability), assuming that I run it enough times.</p> <p>So here are a few questions (mainly indirectly related to the above ):</p> <ol> <li>What types of code are good candidates for randomized testing? What types of code aren't? <ul> <li>How do I go about determining the number of times to run the code with randomized inputs? I ask this because I want to have a large enough sample to determine any bugs, but don't want to wait a week to get my results.</li> <li>Are these kinds of tests well suited for unit tests, or is there another kind of test that it works well with?</li> <li>Are there any other best practices for doing this kind of thing?</li> </ul></li> </ol> <h3>Related topics:</h3> <ul> <li><a href="https://stackoverflow.com/questions/32458/random-data-in-unit-tests">Random data in unit tests?</a></li> </ul>
[ { "answer_id": 796933, "author": "mouviciel", "author_id": 45249, "author_profile": "https://Stackoverflow.com/users/45249", "pm_score": 0, "selected": false, "text": "if (a > 0)\n // Do Foo\nelse (if b < 0)\n // Do Bar\nelse\n // Do Foobar\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
256,073
<p>I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized? </p> <pre><code>public static void Main(String[] args) { Byte maxSize; Queue queue; if(args.Length != 0) { if(Byte.TryParse(args[0], out maxSize)) queue = new Queue(){MaxSize = maxSize}; else Environment.Exit(0); } else { Environment.Exit(0); } for(Byte j = 0; j &lt; queue.MaxSize; j++) queue.Insert(j); for(Byte j = 0; j &lt; queue.MaxSize; j++) Console.WriteLine(queue.Remove()); } </code></pre> <p>So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?</p> <p>Hope ya'll can give me some pointers :)</p> <p>Thanks.</p>
[ { "answer_id": 256078, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 7, "selected": true, "text": "queue" }, { "answer_id": 256375, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "static void Main(string[] args) {\n if(args.Length != 0) {\n if(Byte.TryParse(args[0], out maxSize))\n queue = new Queue(){MaxSize = maxSize};\n else\n return;\n } else {\n return; \n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33324/" ]
256,077
<p>What is the right way to perform some static finallization? </p> <p>There is no static destructor. The <code>AppDomain.DomainUnload</code> event is not raised in the default domain. The <code>AppDomain.ProcessExit</code> event shares the total time of the three seconds (default settings) between all event handlers, so it's not really usable.</p>
[ { "answer_id": 256085, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "AppDomain.ProcessExit" }, { "answer_id": 256278, "author": "Michael Damatov", "author_id": 23372, "author_profile": "https://Stackoverflow.com/users/23372", "pm_score": 6, "selected": false, "text": "static readonly Finalizer finalizer = new Finalizer();\n\nsealed class Finalizer {\n ~Finalizer() {\n Thread.Sleep(1000);\n Console.WriteLine(\"one\");\n Thread.Sleep(1000);\n Console.WriteLine(\"two\");\n Thread.Sleep(1000);\n Console.WriteLine(\"three\");\n Thread.Sleep(1000);\n Console.WriteLine(\"four\");\n Thread.Sleep(1000);\n Console.WriteLine(\"five\");\n }\n}\n" }, { "answer_id": 25067964, "author": "ILIA BROUDNO", "author_id": 788301, "author_profile": "https://Stackoverflow.com/users/788301", "pm_score": 1, "selected": false, "text": "ref class MyClass\n{\n ref class StaticFinalizer sealed\n {\n !StaticFinalizer();\n };\n static initonly StaticFinalizer^ stDestr = gcnew StaticFinalizer();\n}\n\nMyClass::StaticFinalizer::!StaticFinalizer()\n{\n System::Diagnostics::Debug::WriteLine(\"In StaticFinalizer!\");\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23372/" ]
256,093
<p>I'm trying to use class names to change the color of a link after it has been selected, so that It will remain the new color, but only until another link is selected, and then it will change back.</p> <p>I'm using this code that was posted by Martin Kool in <a href="https://stackoverflow.com/questions/206689/changing-the-bg-color-of-a-selected-link">this</a> question:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; document.onclick = function(evt) { var el = window.event? event.srcElement : evt.target; if (el &amp;&amp; el.className == "unselected") { el.className = "selected"; var siblings = el.parentNode.childNodes; for (var i = 0, l = siblings.length; i &lt; l; i++) { var sib = siblings[i]; if (sib != el &amp;&amp; sib.className == "selected") sib.className = "unselected"; } } } &lt;/script&gt; &lt;style&gt; .selected { background: #f00; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#" class="selected"&gt;One&lt;/a&gt; &lt;a href="#" class="unselected"&gt;Two&lt;/a&gt; &lt;a href="#" class="unselected"&gt;Three&lt;/a&gt; &lt;/body&gt; </code></pre> <p>It works fine until I try to out the links in a table. Why is this? Be easy, I'm a beginner.</p> <hr> <p>There is no error, the links are changing to the "selected" class, but when another link is selected, the old links are keeping the "selected" class instead of changing to "unselected". Basically, as far as I can tell, it's functioning like a vlink attribute, which is not what I'm going for.</p> <p>And yes, the links are all in different cells, how would you suggest I change the code so that it works correctly?</p> <hr> <p>OK, actually, I spoke too soon.</p> <pre><code>document.onclick = function(evt) { var el = window.event? event.srcElement : evt.target; if (el &amp;&amp; el.className == 'unselected') { var links = document.getElementsByTagName('a'); for (var i = links.length - 1; i &gt;= 0; i--) { if (links[i].className == 'selected') links[i].className = 'unselected'; } el.className = 'selected'; } return false; } </code></pre> <p>This code you gave me works great, visually, it does exactly what I want it to do. However, It makes my links stop working... They change color, but dont link to anything, and then when I remove the script, they work fine. What am I doing wrong/what do I have to change to make this work?</p> <p>Also, I want to do the same thing somewhere else in my website, where the links are all in one <code>&lt;div&gt;</code> tag, separated by <code>&lt;p&gt;</code> tags. How can I make this work?</p>
[ { "answer_id": 256113, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "var siblings = el.parentNode.childNodes;\n" }, { "answer_id": 256143, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": true, "text": "<td>" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
256,142
<p>When I try to commit the first revision to my git repository (git commit) from Cygwin, I'm getting an error in gvim which says "Unable to open swap file for "foo\.git\COMMIT_EDITMSG" [New Directory]. I think it might be some sort of permission problem, but I've tried removing the read-only flag from the folder, as well as recursively adjusting the owner (using the windows property tab, not chown under Cygwin) to be the account I'm running under, without any luck. If I change the default editor to notepad, I get "The system cannot find the file specified", even though the file (COMMIT_EDITMSG) does exist and even contains:</p> <pre><code># Please enter the commit message for your changes. # (Comment lines starting with '#' will not be included) # etc... </code></pre> <p>How can I troubleshoot this problem further?</p>
[ { "answer_id": 256168, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "git commit" }, { "answer_id": 4774715, "author": "zerox", "author_id": 586454, "author_profile": "https://Stackoverflow.com/users/586454", "pm_score": 0, "selected": false, "text": "cygdrive -a -m COMMIT_EDITMSG" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32539/" ]
256,146
<p>Delphi 2009, among some cool stuff, has also just got Anonymous methods. I've seen the examples, and the blog posts regarding anonymous methods, but I don't get them yet. Can someone explain why I should be excited?</p>
[ { "answer_id": 256167, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 4, "selected": false, "text": "type\n TAnonFunc = reference to procedure;\n TForm2 = class(TForm)\n Memo1: TMemo;\n Button1: TButton;\n Button2: TButton;\n Button3: TButton;\n procedure Button1Click(Sender: TObject);\n procedure Button2Click(Sender: TObject);\n procedure Button3Click(Sender: TObject);\n private\n F1 : TAnonFunc;\n F2 : TAnonFunc;\n end;\n\nprocedure TForm2.Button1Click(Sender: TObject);\nvar\n a : Integer;\nbegin\n a := 1;\n\n F1 := procedure\n begin\n a := a + 1;\n end;\n\n F2 := procedure\n begin\n Memo1.Lines.Add(IntToStr(a));\n end;\nend;\n" }, { "answer_id": 257142, "author": "Uwe Raabe", "author_id": 26833, "author_profile": "https://Stackoverflow.com/users/26833", "pm_score": 4, "selected": false, "text": "type\n TDisplayProc = TProc<TCanvas>;\n\ntype\n TFrmExample3 = class(TForm)\n pbxMain: TPaintBox;\n trkZoom: TTrackBar;\n procedure FormCreate(Sender: TObject);\n procedure FormDestroy(Sender: TObject);\n procedure pbxMainClick(Sender: TObject);\n procedure pbxMainMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);\n procedure pbxMainPaint(Sender: TObject);\n procedure trkZoomChange(Sender: TObject);\n private\n FDisplayList: TList<TDisplayProc>;\n FMouseX: Integer;\n FMouseY: Integer;\n FZoom: Extended;\n procedure SetZoom(const Value: Extended);\n protected\n procedure CreateCircle(X, Y: Integer);\n procedure CreateRectangle(X, Y: Integer);\n function MakeRect(X, Y, R: Integer): TRect;\n public\n property Zoom: Extended read FZoom write SetZoom;\n end;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TFrmExample3.PaintBox1Paint(Sender: TObject);\nvar\n displayProc: TDisplayProc;\nbegin\n for displayProc in FDisplayList do\n displayProc((Sender as TPaintBox).Canvas);\nend;\n\nprocedure TFrmExample3.CreateCircle(X, Y: Integer);\nbegin\n FDisplayList.Add(\n procedure (Canvas: TCanvas)\n begin\n Canvas.Brush.Color := clYellow;\n Canvas.Ellipse(MakeRect(X, Y, 20));\n end\n );\nend;\n\nprocedure TFrmExample3.CreateRectangle(X, Y: Integer);\nbegin\n FDisplayList.Add(\n procedure (Canvas: TCanvas)\n begin\n Canvas.Brush.Color := clBlue;\n Canvas.FillRect(MakeRect(X, Y, 20));\n end\n );\nend;\n\nprocedure TFrmExample3.FormCreate(Sender: TObject);\nbegin\n FDisplayList := TList<TDisplayProc>.Create;\nend;\n\nprocedure TFrmExample3.FormDestroy(Sender: TObject);\nbegin\n FreeAndNil(FDisplayList);\nend;\n\nfunction TFrmExample3.MakeRect(X, Y, R: Integer): TRect;\nbegin\n Result := Rect(Round(Zoom*(X - R)), Round(Zoom*(Y - R)), Round(Zoom*(X + R)), Round(Zoom*(Y + R)));\nend;\n\nprocedure TFrmExample3.pbxMainClick(Sender: TObject);\nbegin\n case Random(2) of\n 0: CreateRectangle(Round(FMouseX/Zoom), Round(FMouseY/Zoom));\n 1: CreateCircle(Round(FMouseX/Zoom), Round(FMouseY/Zoom));\n end;\n pbxMain.Invalidate;\nend;\n\nprocedure TFrmExample3.pbxMainMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);\nbegin\n FMouseX := X;\n FMouseY := Y;\nend;\n\nprocedure TFrmExample4.SetZoom(const Value: Extended);\nbegin\n FZoom := Value;\n trkZoom.Position := Round(2*(FZoom - 1));\nend;\n\nprocedure TFrmExample4.trkZoomChange(Sender: TObject);\nbegin\n Zoom := 0.5*(Sender as TTrackBar).Position + 1;\n pbxMain.Invalidate;\nend;\n" }, { "answer_id": 257164, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 3, "selected": false, "text": "filter" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ]
256,148
<p>This is going to sound like a silly question, but I'm still learning C, so please bear with me. :)</p> <p>I'm working on chapter 6 of K&amp;R (structs), and thus far through the book have seen great success. I decided to work with structs pretty heavily, and therefore did a lot of work early in the chapter with the point and rect examples. One of the things I wanted to try was changing the <code>canonrect</code> function (2nd Edition, p 131) work via pointers, and hence return <code>void</code>.</p> <p>I have this working, but ran into a hiccup I was hoping you guys could help me out with. I wanted <code>canonRect</code> to create a temporary rectangle object, perform its changes, then reassign the pointer it's passed to the temporary rectangle, thus simplifying the code. </p> <p>However, if I do that, the rect doesn't change. Instead, I find myself manually repopulating the fields of the rect I'm passed in, which does work.</p> <p>The code follows:</p> <pre><code>#include &lt;stdio.h&gt; #define min(a, b) ((a) &lt; (b) ? (a) : (b)) #define max(a, b) ((a) &gt; (b) ? (a) : (b)) struct point { int x; int y; }; struct rect { struct point lowerLeft; struct point upperRight; }; // canonicalize coordinates of rectangle void canonRect(struct rect *r); int main(void) { struct point p1, p2; struct rect r; p1.x = 10; p1.y = 10; p2.x = 20; p2.y = 40; r.lowerLeft = p2; // note that I'm inverting my points intentionally r.upperRight = p1; printf("Rectangle, lower left: %d, %d; upper right: %d %d\n\n", r.lowerLeft.x, r.lowerLeft.y, r.upperRight.x, r.upperRight.y); // can't pass a pointer, only a reference. // (Passing pointers results in illegal indirection compile time errors) canonRect(&amp;r); printf("Rectangle, lower left: %d, %d; upper right: %d %d\n\n", r.lowerLeft.x, r.lowerLeft.y, r.upperRight.x, r.upperRight.y); } void canonRect(struct rect *r) { struct rect temp; temp.lowerLeft.x = min(r-&gt;lowerLeft.x, r-&gt;upperRight.x); temp.lowerLeft.y = min(r-&gt;lowerLeft.y, r-&gt;upperRight.y); temp.upperRight.x = max(r-&gt;lowerLeft.x, r-&gt;upperRight.x); temp.upperRight.y = max(r-&gt;lowerLeft.y, r-&gt;upperRight.y); r = &amp;temp; // doesn't work; my passed-in rect remains the same // I wind up doing the following instead, to reassign all // the members of my passed-in rect //r-&gt;lowerLeft = temp.lowerLeft; //r-&gt;upperRight = temp.upperRight; } </code></pre> <p>So here are the questions:</p> <ol> <li>Why does <code>r = &amp;temp;</code> not work? (I <strong>think</strong> this is because I pass in a reference instead of a pointer; am I correct in thinking that references are not modifiable but pointers are?)</li> <li>Why might I get an illegal indirection compile-time error if I try to pass in a pointer to <code>canonRect</code>? (IE, if I had <code>canonRect(*r);</code> in <code>main()</code>.)</li> </ol> <p>I suspect I already know the answer to #1, but #2 perplexes me -- I thought it was legal to pass pointers around.</p> <p>Anyway ... please forgive the C newb.</p>
[ { "answer_id": 256153, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": true, "text": "void canonRect(struct rect *r) {\n struct rect temp;\n temp.lowerLeft.x = min(r->lowerLeft.x, r->upperRight.x);\n temp.lowerLeft.y = min(r->lowerLeft.y, r->upperRight.y);\n temp.upperRight.x = max(r->lowerLeft.x, r->upperRight.x);\n temp.upperRight.y = max(r->lowerLeft.y, r->upperRight.y);\n\n *r = temp; \n}\n" }, { "answer_id": 256166, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "*" }, { "answer_id": 256170, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "struct rect* canonRect(struct rect* r)\n{\n struct rect* cr = (struct rect*) malloc(sizeof(struct rect));\n ...\n return cr;\n}\n" }, { "answer_id": 256171, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "&" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
256,169
<p>What is the best OS for Java development? People from Sun are pushing the Solaris, yes Solaris have some extra features included in itself such as (dTrace, possibility for Performance tuning the JVM, etc.. ). Some friends of mine, had port their application on solaris, and they said to me that the performances was brilliant. I'm not happy with switching my OS, and use Solaris instead.</p> <p>What were your experiences?</p>
[ { "answer_id": 256670, "author": "bendin", "author_id": 33396, "author_profile": "https://Stackoverflow.com/users/33396", "pm_score": 6, "selected": true, "text": "linux32" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16039/" ]
256,172
<p>The company I work for has recently been hit with many header injection and file upload exploits on the sites we host and while we have fixed the problem with respect to header injection attacks, we have yet to get the upload exploits under control.</p> <p>I'm trying to set up a plug-and-play-type series of upload scripts to use in-house that a designer can copy into their site's structure, modify a few variables, and have a ready-to-go upload form on their site. We're looking to limit our exposure as much as possible (we've already shut down fopen and shell commands).</p> <p>I've searched the site for the last hour and found many different answers dealing with specific methods that rely on outside sources. What do you all think is the best script-only solution that is specific enough to use as a reliable method of protection? Also, I'd like to keep the language limited to PHP or pseudo-code if possible.</p> <p><strong>Edit:</strong> I've found my answer (posted below) and, while it does make use of the shell command exec(), if you block script files from being uploaded (which this solution does very well), you won't run into any problems.</p>
[ { "answer_id": 18530956, "author": "inf3rno", "author_id": 607033, "author_profile": "https://Stackoverflow.com/users/607033", "pm_score": 6, "selected": false, "text": "MAX_FILE_SIZE" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25375/" ]
256,195
<p>I'm using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in <code>$(document).ready</code> . For example:</p> <pre><code>$(function() { $('div._Foo').bind("mouseover", function(e) { // Do something exciting }); }); </code></pre> <p>Of course, this works fine the first time the page is loaded, but when the UpdatePanel does a partial page update, it's not run and the mouseover effects don't work any more inside the UpdatePanel. </p> <p>What's the recommended approach for wiring stuff up in jQuery not only on the first page load, but every time an UpdatePanel fires a partial page update? Should I be using the ASP.NET ajax lifecycle instead of <code>$(document).ready</code>?</p>
[ { "answer_id": 256253, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 10, "selected": true, "text": "$(document).ready()" }, { "answer_id": 259168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var prm = Sys.WebForms.PageRequestManager.getInstance();\nprm.add_endRequest(function() {... \n" }, { "answer_id": 443015, "author": "Barbaros Alp", "author_id": 51734, "author_profile": "https://Stackoverflow.com/users/51734", "pm_score": 7, "selected": false, "text": "<script type=\"text/javascript\">\n\n function BindEvents() {\n $(document).ready(function() {\n $(\".tr-base\").mouseover(function() {\n $(this).toggleClass(\"trHover\");\n }).mouseout(function() {\n $(this).removeClass(\"trHover\");\n });\n }\n</script>\n" }, { "answer_id": 518693, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 5, "selected": false, "text": "$(function() {\n\n $('div._Foo').live(\"mouseover\", function(e) {\n // Do something exciting\n });\n\n});\n" }, { "answer_id": 2916278, "author": "Brian MacKay", "author_id": 16082, "author_profile": "https://Stackoverflow.com/users/16082", "pm_score": 6, "selected": false, "text": "<script type=\"text/javascript\">\n function BindControlEvents() {\n //jQuery is wrapped in BindEvents function so it can be re-bound after each callback.\n //Your code would replace the following line:\n $('#<%= TextProtocolDrugInstructions.ClientID %>').limit('100', '#charsLeft_Instructions'); \n }\n\n //Initial bind\n $(document).ready(function () {\n BindControlEvents();\n });\n\n //Re-bind for callbacks\n var prm = Sys.WebForms.PageRequestManager.getInstance(); \n\n prm.add_endRequest(function() { \n BindControlEvents();\n }); \n\n</script>\n" }, { "answer_id": 4569642, "author": "Daniel Hursan", "author_id": 510109, "author_profile": "https://Stackoverflow.com/users/510109", "pm_score": 4, "selected": false, "text": "<asp:UpdatePanel runat=\"server\" ID=\"myUpdatePanel\">\n <ContentTemplate>\n\n <script type=\"text/javascript\" language=\"javascript\">\n function pageLoad() {\n $('div._Foo').bind(\"mouseover\", function(e) {\n // Do something exciting\n });\n }\n </script>\n\n </ContentTemplate>\n</asp:UpdatePanel>\n" }, { "answer_id": 5145710, "author": "Jono", "author_id": 638147, "author_profile": "https://Stackoverflow.com/users/638147", "pm_score": 4, "selected": false, "text": "function pageLoad() {\n\n $(document).ready(function(){\n" }, { "answer_id": 13588643, "author": "Abhishek Shrivastava", "author_id": 328116, "author_profile": "https://Stackoverflow.com/users/328116", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\"> \n var prm = Sys.WebForms.PageRequestManager.getInstance();\n prm.add_endRequest(EndRequestHandler);\n function EndRequestHandler(sender, args) {\n if (args.get_error() == undefined) {\n UPDATEPANELFUNCTION();\n } \n }\n\n function UPDATEPANELFUNCTION() {\n jQuery(document).ready(function ($) {\n /* Insert all your jQuery events and function calls */\n });\n }\n\n UPDATEPANELFUNCTION(); \n\n</script>\n" }, { "answer_id": 16927547, "author": "fujiiface", "author_id": 1047907, "author_profile": "https://Stackoverflow.com/users/1047907", "pm_score": 0, "selected": false, "text": "private void ShowForm(bool pShowForm) {\n //other code here...\n if (pShowForm) {\n FocusOnControl(GetFocusOnFormScript(yourControl.ClientID), yourControl.ClientID);\n }\n}\n\nprivate void FocusOnControl(string pScript, string pControlId) {\n ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), \"focusControl_\" + pControlId, pScript, true);\n}\n\n/// <summary>\n/// Scrolls to the form that is made visible\n/// </summary>\n/// <param name=\"pControlId\">The ClientID of the control to focus on after the form is made visible</param>\n/// <returns></returns>\nprivate string GetFocusOnFormScript(string pControlId) {\n string script = @\"\n function FocusOnForm() {\n var scrollToForm = $('#\" + pControlId + @\"').offset().top;\n $('html, body').animate({ \n scrollTop: scrollToForm}, \n 'slow'\n );\n /* This removes the event from the PageRequestManager immediately after the desired functionality is completed so that multiple events are not added */\n prm.remove_endRequest(ScrollFocusToFormCaller);\n }\n prm.add_endRequest(ScrollFocusToFormCaller);\n function ScrollFocusToFormCaller(sender, args) {\n if (args.get_error() == undefined) {\n FocusOnForm();\n }\n }\";\n return script;\n}\n" }, { "answer_id": 24864697, "author": "Rohit Sharma", "author_id": 3172106, "author_profile": "https://Stackoverflow.com/users/3172106", "pm_score": 2, "selected": false, "text": "Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest)\n function onEndRequest(sender, args) {\n // your jquery code here\n });\n" }, { "answer_id": 24900805, "author": "Duane", "author_id": 3862312, "author_profile": "https://Stackoverflow.com/users/3862312", "pm_score": 2, "selected": false, "text": "pageLoad = function () {\n $('#div').unbind();\n //jquery here\n}\n" }, { "answer_id": 31445710, "author": "Pradeep More", "author_id": 4733252, "author_profile": "https://Stackoverflow.com/users/4733252", "pm_score": 3, "selected": false, "text": "$(document).ready(function (){...})" }, { "answer_id": 47877311, "author": "Tony Dong", "author_id": 760139, "author_profile": "https://Stackoverflow.com/users/760139", "pm_score": 0, "selected": false, "text": "Sys.Application.add_load(LoadHandler); //This load handler solved update panel did not bind control after partial postback\nfunction LoadHandler() {\n $(document).ready(function () {\n //rebind any events here for controls under update panel\n });\n}\n" }, { "answer_id": 50942963, "author": "mzonerz", "author_id": 2582841, "author_profile": "https://Stackoverflow.com/users/2582841", "pm_score": 1, "selected": false, "text": " <script>\n //Re-Create for on page postbacks\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n prm.add_endRequest(function () {\n //your codes here!\n });\n </script>\n" }, { "answer_id": 72405957, "author": "Christopher", "author_id": 826308, "author_profile": "https://Stackoverflow.com/users/826308", "pm_score": 0, "selected": false, "text": "<script>\nfunction myDocReadyFunction(){ /* do stuff */ }\n</script>\n\n<dx:ASPxCallbackPanel ID=\"myCallbackPanel\" ... >\n <ClientSideEvents EndCallback=\"function(){ myDocReadyFunction();}\"> \n </ClientSideEvents>\n <PanelCollection ...>\n</dx:ASPxCallbackPanel>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
256,204
<p>I use the <code>:e</code> and <code>:w</code> commands to edit and to write a file. I am not sure if there is "close" command to close the current file without leaving Vim?</p> <p>I know that the <code>:q</code> command can be used to close a file, but if it is the last file, Vim is closed as well; Actually on Mac OS MacVim does quit. Only the Vim window is closed and I could use <kbd>Control</kbd>-<kbd>N</kbd> to open a blank Vim window again. I would like Vim to remain open with a blank screen.</p>
[ { "answer_id": 256206, "author": "Rytmis", "author_id": 266, "author_profile": "https://Stackoverflow.com/users/266", "pm_score": 3, "selected": false, "text": ":enew" }, { "answer_id": 256208, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 10, "selected": true, "text": ":bd \n" }, { "answer_id": 290110, "author": "Gowri", "author_id": 3253, "author_profile": "https://Stackoverflow.com/users/3253", "pm_score": 5, "selected": false, "text": ":bd" }, { "answer_id": 2531039, "author": "wbogacz", "author_id": 123931, "author_profile": "https://Stackoverflow.com/users/123931", "pm_score": 2, "selected": false, "text": ":bd" }, { "answer_id": 4334306, "author": "sebnow", "author_id": 64423, "author_profile": "https://Stackoverflow.com/users/64423", "pm_score": 6, "selected": false, "text": ":bd" }, { "answer_id": 12531154, "author": "blueyed", "author_id": 15690, "author_profile": "https://Stackoverflow.com/users/15690", "pm_score": 2, "selected": false, "text": "BD" }, { "answer_id": 19825539, "author": "pablofiumara", "author_id": 2623074, "author_profile": "https://Stackoverflow.com/users/2623074", "pm_score": 3, "selected": false, "text": ":bd!" }, { "answer_id": 39252624, "author": "Stryker", "author_id": 1406420, "author_profile": "https://Stackoverflow.com/users/1406420", "pm_score": 2, "selected": false, "text": ":map <F4> :bd<CR>\n" }, { "answer_id": 71458320, "author": "Joannes", "author_id": 5941807, "author_profile": "https://Stackoverflow.com/users/5941807", "pm_score": 0, "selected": false, "text": ":Bdelete this" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62776/" ]
256,218
<p>Let's say I have a <code>char* str = "0123456789"</code> and I want to cut the first and the last three letters and print just the middle, what is the simplest, and safest, way of doing it?</p> <p>Now the trick: The portion to cut and the portion to print are of variable size, so I could have a very long char*, or a very small one.</p>
[ { "answer_id": 256223, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 7, "selected": true, "text": "printf()" }, { "answer_id": 256224, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": false, "text": "char string[] = \"0123456789\";\nchar *str = string;\n\nstr += 3; // \"removes\" the first 3 items\nstr[4] = '\\0'; // sets the 5th item to NULL, effectively truncating the string\n\nprintf(str); // prints \"3456\"\n" }, { "answer_id": 256232, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "void print_substring(const char *str, int skip, int tail)\n{\n int len = strlen(str);\n assert(skip >= 0);\n assert(tail >= 0 && tail < len);\n assert(len > skip + tail);\n printf(\"%.*s\", len - skip - tail, str + skip);\n}\n" }, { "answer_id": 257731, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 0, "selected": false, "text": "char *\nsubstr(const char *src, size_t start, size_t len)\n{\n char *dest = malloc(len+1);\n if (dest) {\n memcpy(dest, src+start, len);\n dest[len] = '\\0';\n }\n return dest;\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21648/" ]
256,222
<p>I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:</p> <pre><code>def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass </code></pre> <p>The only annoyance with this is that every package has its own, usually slightly differing <code>BadValueError</code>. I know that in Java there exists <code>java.lang.IllegalArgumentException</code> -- is it well understood that everybody will be creating their own <code>BadValueError</code>s in Python or is there another, preferred method?</p>
[ { "answer_id": 256235, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": false, "text": "ValueError" }, { "answer_id": 256236, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 7, "selected": false, "text": "ValueError" }, { "answer_id": 256239, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": -1, "selected": false, "text": "ValueError" }, { "answer_id": 256260, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 11, "selected": true, "text": "def import_to_orm(name, save=False, recurse=False):\n if recurse and not save:\n raise ValueError(\"save must be True if recurse is True\")\n" }, { "answer_id": 46589274, "author": "BobHy", "author_id": 2036651, "author_profile": "https://Stackoverflow.com/users/2036651", "pm_score": 0, "selected": false, "text": "class BadCallError(ValueError):\n pass\n" }, { "answer_id": 51638010, "author": "J Bones", "author_id": 9540833, "author_profile": "https://Stackoverflow.com/users/9540833", "pm_score": 5, "selected": false, "text": "$ python -c 'print(sum())'\nTraceback (most recent call last):\nFile \"<string>\", line 1, in <module>\nTypeError: sum expected at least 1 arguments, got 0\n" }, { "answer_id": 56750114, "author": "Gloweye", "author_id": 4331885, "author_profile": "https://Stackoverflow.com/users/4331885", "pm_score": 5, "selected": false, "text": "if not isinstance(save, bool):\n raise TypeError(f\"Argument save must be of type bool, not {type(save)}\")\n" }, { "answer_id": 68747161, "author": "thing10", "author_id": 16476731, "author_profile": "https://Stackoverflow.com/users/16476731", "pm_score": 3, "selected": false, "text": "ValueError" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
256,228
<p>I'm trying to read data from a photocell resistor and my Arduino Decimila and then graph it in real-time with Processing.</p> <p>Should be painfully simple; but its growing into a little bit of a nightmare for me.</p> <p>code I'm running on my Arduino:</p> <pre class="lang-java prettyprint-override"><code>int photoPin; void setup(){ photoPin = 0; Serial.begin( 9600 ); } void loop(){ int val = int( map( analogRead( photoPin ), 0, 1023, 0, 254 ) ); Serial.println( val ); //sending data over Serial } </code></pre> <p>code I'm running in Processing: </p> <pre class="lang-java prettyprint-override"><code>import processing.serial.*; Serial photocell; int[] yvals; void setup(){ size( 300, 150 ); photocell = new Serial( this, Serial.list()[0], 9600 ); photocell.bufferUntil( 10 ); yvals = new int[width]; } void draw(){ background( 0 ); for( int i = 1; i &lt; width; i++ ){ yvals[i - 1] = yvals[i]; } if( photocell.available() &gt; 0 ){ yvals[width - 1] = photocell.read(); } for( int i = 1; i &lt; width; i++ ){ stroke( #ff0000 ); line( i, yvals[i], i, height ); } println( photocell.read() ); // for debugging } </code></pre> <p>I've tested both bits of code separately and I know that they work. It's only when I try to have the input from the Arduino going to Processing that the problems start.</p> <p>When I view the data in Arduino's "Serial Monitor", I get a nice constant flow of data that seems to look valid.</p> <p>But when I read that same data through Processing, I get a repeating pattern of random values.</p> <p>Halp?</p>
[ { "answer_id": 19803246, "author": "Mateo Sanchez", "author_id": 2741380, "author_profile": "https://Stackoverflow.com/users/2741380", "pm_score": 3, "selected": true, "text": "<iframe id=\"igraph\" src=\"https://plot.ly/~abhishek.mitra.963/1/400/250/\" width=\"400\" height=\"250\" seamless=\"seamless\" scrolling=\"no\"></iframe>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13293/" ]
256,229
<p>I'm building an ASP.NET web application, and all of my strings are stored in a resource file. I'd like to add a second language to my application, and ideally, I'd like to auto-detect the user's browser language (or windows language) and default to that, instead of making them choose something besides English. Currently, I'm handling all the resource population manually, so adding a second resource file and language is trivial from my point of view, if I had an easy way to automatically figure out what language to display.</p> <p>Has anybody done this, or do you have any thoughts about how I might retrieve that value? Since ASP.NET is server-based, I don't seem to have any access to specific browser settings.</p> <p><strong>RESOLUTION</strong>: Here's what I ended up doing. I used a "For Each" to go through "HttpContext.Current.Request.UserLanguages" and search for one I support. I'm actually just checking the left two characters, since we don't support any dialects yet - just English and Spanish. Thanks for all the help!</p>
[ { "answer_id": 256244, "author": "Jeff Fritz", "author_id": 29156, "author_profile": "https://Stackoverflow.com/users/29156", "pm_score": 2, "selected": false, "text": "CultureInfo.CurrentCulture" }, { "answer_id": 256250, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 4, "selected": false, "text": "<globalization culture=\"auto\" uiCulture=\"auto\" />\n" }, { "answer_id": 17532016, "author": "Mazdak Shojaie", "author_id": 1442157, "author_profile": "https://Stackoverflow.com/users/1442157", "pm_score": 1, "selected": false, "text": " /// <summary>\n /// Sets a user's Locale based on the browser's Locale setting. If no setting\n /// is provided the default Locale is used.\n /// </summary>\n\npublic static void SetUserLocale(string CurrencySymbol, bool SetUiCulture)\n{\n HttpRequest Request = HttpContext.Current.Request;\n if (Request.UserLanguages == null)\n return;\n\n string Lang = Request.UserLanguages[0];\n if (Lang != null)\n {\n // *** Problems with Turkish Locale and upper/lower case\n // *** DataRow/DataTable indexes\n if (Lang.StartsWith(\"tr\"))\n return;\n\n if (Lang.Length < 3)\n Lang = Lang + \"-\" + Lang.ToUpper();\n try\n {\n System.Globalization.CultureInfo Culture = new System.Globalization.CultureInfo(Lang);\n if (CurrencySymbol != null && CurrencySymbol != \"\")\n Culture.NumberFormat.CurrencySymbol = CurrencySymbol;\n\n System.Threading.Thread.CurrentThread.CurrentCulture = Culture;\n\n if (SetUiCulture)\n System.Threading.Thread.CurrentThread.CurrentUICulture = Culture;\n }\n catch\n { ;}\n }\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8114/" ]
256,234
<p>(If anything here needs clarification/ more detail please let me know.)</p> <p>I have an application (C#, 2.* framework) that interfaces with a third-party webservice using SOAP. I used thinktecture's WSCF add-in against a supplied WSDL to create the client-side implementation. For reasons beyond my control the SOAP message exchange uses WSE2.0 for security (the thinctecture implementation had to be modified to include the WSE2.0 reference). In addition to the 'normal' data package I attach a stored X509 cert and a binary security token from a previous call to a different web service. We are using SSL encryption of some sort - I don't know the details. </p> <p>All the necessary serialization/deserialization is contained in the web service client - meaning when control is returned to me after calling the client the entire XML string contained in the SOAP response is not available to me - just the deserialized components. Don't get me wrong - I think that's good because it means I don't have to do it myself.</p> <p>However, in order for me to have something worth storing/archiving I am having to re-serialize the data at the root element. This seems like a waste of resources since my result was in the SOAP response. </p> <p><strong>Now for my question: How can I get access to a 'clear' version of the SOAP response so that I don't have to re-serialize everything for storage/archiving?</strong></p> <p>Edit- My application is a 'formless' windows app running as a network service - triggered by a WebsphereMQ client trigger monitor. I don't <em>think</em> ASP.NET solutions will apply.</p> <p>Edit - Since the consensus so far is that it doesn't matter whether my app is ASP.NET or not then I will give CodeMelt's (and by extension Chris's) solution a shot.</p>
[ { "answer_id": 256273, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 4, "selected": true, "text": "public class MyClientSOAPExtension : SoapExtension\n{\n\n Stream oldStream;\n Stream newStream;\n\n // Save the Stream representing the SOAP request or SOAP response into\n // a local memory buffer.\n public override Stream ChainStream( Stream stream )\n {\n oldStream = stream;\n newStream = new MemoryStream();\n return newStream;\n }\n\n public override void ProcessMessage(SoapMessage message)\n {\n switch (message.Stage)\n {\n case SoapMessageStage.BeforeDeserialize:\n // before the XML deserialized into object.\n break;\n case SoapMessageStage.AfterDeserialize:\n break; \n case SoapMessageStage.BeforeSerialize:\n break;\n case SoapMessageStage.AfterSerialize:\n break; \n default:\n throw new Exception(\"Invalid stage...\");\n } \n }\n}\n" }, { "answer_id": 5180947, "author": "jfburdet", "author_id": 129368, "author_profile": "https://Stackoverflow.com/users/129368", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Net;\nusing System.IO;\nusing System.Reflection;\nusing System.Xml;\n\n\nnamespace ConsoleApplication1 {\n\n public class XmlReaderSpy : XmlReader {\n XmlReader _me;\n public XmlReaderSpy(XmlReader parent) {\n _me = parent;\n }\n\n /// <summary>\n /// Extracted XML.\n /// </summary>\n public string Xml;\n\n #region Abstract method that must be implemented\n public override XmlNodeType NodeType {\n get {\n\n return _me.NodeType;\n }\n }\n\n public override string LocalName {\n get {\n return _me.LocalName;\n }\n }\n\n public override string NamespaceURI {\n get {\n return _me.NamespaceURI;\n }\n }\n\n public override string Prefix {\n get {\n return _me.Prefix;\n }\n }\n\n public override bool HasValue {\n get { return _me.HasValue; }\n }\n\n public override string Value {\n get { return _me.Value; }\n }\n\n public override int Depth {\n get { return _me.Depth; }\n }\n\n public override string BaseURI {\n get { return _me.BaseURI; }\n }\n\n public override bool IsEmptyElement {\n get { return _me.IsEmptyElement; }\n }\n\n public override int AttributeCount {\n get { return _me.AttributeCount; }\n }\n\n public override string GetAttribute(int i) {\n return _me.GetAttribute(i);\n }\n\n public override string GetAttribute(string name) {\n return _me.GetAttribute(name);\n }\n\n public override string GetAttribute(string name, string namespaceURI) {\n return _me.GetAttribute(name, namespaceURI);\n }\n\n public override void MoveToAttribute(int i) {\n _me.MoveToAttribute(i);\n }\n\n public override bool MoveToAttribute(string name) {\n return _me.MoveToAttribute(name);\n }\n\n public override bool MoveToAttribute(string name, string ns) {\n return _me.MoveToAttribute(name, ns);\n }\n\n public override bool MoveToFirstAttribute() {\n return _me.MoveToFirstAttribute();\n }\n\n public override bool MoveToNextAttribute() {\n return _me.MoveToNextAttribute();\n }\n\n public override bool MoveToElement() {\n return _me.MoveToElement();\n }\n\n public override bool ReadAttributeValue() {\n return _me.ReadAttributeValue();\n }\n\n public override bool Read() {\n bool res = _me.Read();\n\n Xml += StringView();\n\n\n return res;\n }\n\n public override bool EOF {\n get { return _me.EOF; }\n }\n\n public override void Close() {\n _me.Close();\n }\n\n public override ReadState ReadState {\n get { return _me.ReadState; }\n }\n\n public override XmlNameTable NameTable {\n get { return _me.NameTable; }\n }\n\n public override string LookupNamespace(string prefix) {\n return _me.LookupNamespace(prefix);\n }\n\n public override void ResolveEntity() {\n _me.ResolveEntity();\n }\n\n #endregion\n\n\n protected string StringView() {\n string result = \"\";\n\n if (_me.NodeType == XmlNodeType.Element) {\n result = \"<\" + _me.Name;\n\n if (_me.HasAttributes) {\n _me.MoveToFirstAttribute();\n do {\n result += \" \" + _me.Name + \"=\\\"\" + _me.Value + \"\\\"\";\n } while (_me.MoveToNextAttribute());\n\n //Let's put cursor back to Element to avoid messing up reader state.\n _me.MoveToElement();\n }\n\n if (_me.IsEmptyElement) {\n result += \"/\";\n }\n\n result += \">\";\n }\n\n if (_me.NodeType == XmlNodeType.EndElement) {\n result = \"</\" + _me.Name + \">\";\n }\n\n if (_me.NodeType == XmlNodeType.Text || _me.NodeType == XmlNodeType.Whitespace) {\n result = _me.Value;\n }\n\n\n\n if (_me.NodeType == XmlNodeType.XmlDeclaration) {\n result = \"<?\" + _me.Name + \" \" + _me.Value + \"?>\";\n }\n\n return result;\n\n }\n }\n\n public class MyInfo : ConsoleApplication1.eu.dataaccess.footballpool.Info { \n\n protected XmlReaderSpy _xmlReaderSpy;\n\n public string Xml {\n get {\n if (_xmlReaderSpy != null) {\n return _xmlReaderSpy.Xml;\n }\n else {\n return \"\";\n }\n }\n }\n\n\n protected override XmlReader GetReaderForMessage(System.Web.Services.Protocols.SoapClientMessage message, int bufferSize) { \n XmlReader rdr = base.GetReaderForMessage(message, bufferSize);\n _xmlReaderSpy = new XmlReaderSpy((XmlReader)rdr);\n return _xmlReaderSpy;\n }\n\n }\n\n class Program {\n static void Main(string[] args) {\n\n MyInfo info = new MyInfo();\n string[] rest = info.Cities();\n\n System.Console.WriteLine(\"RAW Soap XML response :\\n\"+info.Xml);\n System.Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 8414492, "author": "Wout", "author_id": 241015, "author_profile": "https://Stackoverflow.com/users/241015", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Services.Protocols;\nusing System.Xml;\n\nusing Test.MyWebReference;\n\nnamespace Test {\n /// <summary>\n /// Adds the ability to retrieve the SOAP request/response.\n /// </summary>\n public class ServiceSpy : OriginalService {\n private StreamSpy writerStreamSpy;\n private XmlTextWriter xmlWriter;\n\n private StreamSpy readerStreamSpy;\n private XmlTextReader xmlReader;\n\n public MemoryStream WriterStream {\n get { return writerStreamSpy == null ? null : writerStreamSpy.ClonedStream; }\n }\n\n public XmlTextWriter XmlWriter {\n get { return xmlWriter; }\n }\n\n public MemoryStream ReaderStream {\n get { return readerStreamSpy == null ? null : readerStreamSpy.ClonedStream; }\n }\n\n public XmlTextReader XmlReader {\n get { return xmlReader; }\n }\n\n protected override void Dispose(bool disposing) {\n base.Dispose(disposing);\n DisposeWriterStreamSpy();\n DisposeReaderStreamSpy();\n }\n\n protected override XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize) {\n // Dispose previous writer stream spy.\n DisposeWriterStreamSpy();\n\n writerStreamSpy = new StreamSpy(message.Stream);\n // XML should always support UTF8.\n xmlWriter = new XmlTextWriter(writerStreamSpy, Encoding.UTF8);\n\n return xmlWriter;\n }\n\n protected override XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize) {\n // Dispose previous reader stream spy.\n DisposeReaderStreamSpy();\n\n readerStreamSpy = new StreamSpy(message.Stream);\n xmlReader = new XmlTextReader(readerStreamSpy);\n\n return xmlReader;\n }\n\n private void DisposeWriterStreamSpy() {\n if (writerStreamSpy != null) {\n writerStreamSpy.Dispose();\n writerStreamSpy.ClonedStream.Dispose();\n writerStreamSpy = null;\n }\n }\n\n private void DisposeReaderStreamSpy() {\n if (readerStreamSpy != null) {\n readerStreamSpy.Dispose();\n readerStreamSpy.ClonedStream.Dispose();\n readerStreamSpy = null;\n }\n }\n\n /// <summary>\n /// Wrapper class to clone read/write bytes.\n /// </summary>\n public class StreamSpy : Stream {\n private Stream wrappedStream;\n private long startPosition;\n private MemoryStream clonedStream = new MemoryStream();\n\n public StreamSpy(Stream wrappedStream) {\n this.wrappedStream = wrappedStream;\n startPosition = wrappedStream.Position;\n }\n\n public MemoryStream ClonedStream {\n get { return clonedStream; }\n }\n\n public override bool CanRead {\n get { return wrappedStream.CanRead; }\n }\n\n public override bool CanSeek {\n get { return wrappedStream.CanSeek; }\n }\n\n public override bool CanWrite {\n get { return wrappedStream.CanWrite; }\n }\n\n public override void Flush() {\n wrappedStream.Flush();\n }\n\n public override long Length {\n get { return wrappedStream.Length; }\n }\n\n public override long Position {\n get { return wrappedStream.Position; }\n set { wrappedStream.Position = value; }\n }\n\n public override int Read(byte[] buffer, int offset, int count) {\n long relativeOffset = wrappedStream.Position - startPosition;\n int result = wrappedStream.Read(buffer, offset, count);\n if (clonedStream.Position != relativeOffset) {\n clonedStream.Position = relativeOffset;\n }\n clonedStream.Write(buffer, offset, result);\n return result;\n }\n\n public override long Seek(long offset, SeekOrigin origin) {\n return wrappedStream.Seek(offset, origin);\n }\n\n public override void SetLength(long value) {\n wrappedStream.SetLength(value);\n }\n\n public override void Write(byte[] buffer, int offset, int count) {\n long relativeOffset = wrappedStream.Position - startPosition;\n wrappedStream.Write(buffer, offset, count);\n if (clonedStream.Position != relativeOffset) {\n clonedStream.Position = relativeOffset;\n }\n clonedStream.Write(buffer, offset, count);\n }\n\n public override void Close() {\n wrappedStream.Close();\n base.Close();\n }\n\n protected override void Dispose(bool disposing) {\n if (wrappedStream != null) {\n wrappedStream.Dispose();\n wrappedStream = null;\n }\n base.Dispose(disposing);\n }\n }\n }\n}\n" }, { "answer_id": 63497474, "author": "Andy Gray", "author_id": 163901, "author_profile": "https://Stackoverflow.com/users/163901", "pm_score": 3, "selected": false, "text": "public class SoapMessageInspector : IClientMessageInspector\n{\n public string LastRequestXml { get; private set; }\n public string LastResponseXml { get; private set; }\n\n public object BeforeSendRequest(ref Message request, IClientChannel channel)\n {\n LastRequestXml = request.ToString();\n return request;\n }\n\n public void AfterReceiveReply(ref Message reply, object correlationState)\n {\n LastResponseXml = reply.ToString();\n }\n}\n\npublic class SoapInspectorBehavior : IEndpointBehavior\n{\n private readonly SoapMessageInspector inspector_ = new SoapMessageInspector();\n\n public string LastRequestXml => inspector_.LastRequestXml;\n public string LastResponseXml => inspector_.LastResponseXml;\n\n public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)\n {\n }\n\n public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)\n {\n }\n\n public void Validate(ServiceEndpoint endpoint)\n {\n }\n\n public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)\n {\n clientRuntime.ClientMessageInspectors.Add(inspector_);\n }\n}\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30901/" ]
256,254
<p>I have been researching and playing with functional programming lately, solely to broaden my thinking about programming, because I find thinking "functionally" difficult.</p> <p>I have downloaded Glasgow Haskell and experimented with that.</p> <p>What I am wondering is, what is the best platform for Windows to experiment with FP? I would prefer a JVM based approach, but another post on SO has indicated that a real FP language cannot be implemented on the JVM due to a lack of support for tail recursion. What say you?</p> <p>EDIT: As I've said, I've experimented a fair bit with Haskell; on the advice of one of the answers I've been reviewing the Scala website. Looking over the Scala examples, the code seems more "familiar" (my background is C and Java), but it seems decidedly more OO/procedural and less functional. A huge advantage of Scala would be that it gives me another language tool to use side by side with Java and could become another arrow in my current professional quiver, as opposed to solely being a learning exercise. When I get further into Scala, will the functional aspects become more predominant, or will I tend to end up just writing OO code with some functional influence? In other words, will Haskell challenge my preconceptions harder and faster than Scala?</p>
[ { "answer_id": 256332, "author": "Loopo", "author_id": 32763, "author_profile": "https://Stackoverflow.com/users/32763", "pm_score": 0, "selected": false, "text": "?- bend(your_mind).\nYes\n\n\n?- bend(X).\nX = your_mind\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8946/" ]