qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
211,118
<p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach?</p> <pre><code>def by_tag(tag): return ''' function(doc) { if (doc.tags.length &gt; 0) { for (var tag in doc.tags) { if (doc.tags[tag] == "%s") { emit(doc.published, doc) } } } }; ''' % tag </code></pre>
[ { "answer_id": 211144, "author": "Paul J. Davis", "author_id": 129506, "author_profile": "https://Stackoverflow.com/users/129506", "pm_score": 1, "selected": false, "text": "<p>You are very much on the right track with the view. A list of thoughts though:</p>\n\n<p>View generation is incremental. If you're read traffic is greater than you're write traffic, then your views won't cause an issue at all. People that are concerned about this generally shouldn't be. Frame of reference, you should be worried if you're dumping hundreds of records into the view without an update.</p>\n\n<p>Emitting an entire document will slow things down. You should only emit what is necessary for use of the view.</p>\n\n<p>Not sure what the val == \"%s\" performance would be, but you shouldn't over think things. If there's a tag array you should emit the tags. Granted if you expect a tags array that will contain non-strings, then ignore this.</p>\n" }, { "answer_id": 213138, "author": "Bahadır Yağan", "author_id": 3812, "author_profile": "https://Stackoverflow.com/users/3812", "pm_score": 4, "selected": true, "text": "<p><em>Disclaimer: I didn't test this and don't know if it can perform better.</em> </p>\n\n<p>Create a single perm view:</p>\n\n<pre><code>function(doc) {\n for (var tag in doc.tags) {\n emit([tag, doc.published], doc)\n }\n};\n</code></pre>\n\n<p>And query with \n_view/your_view/all?startkey=['your_tag_here']&amp;endkey=['your_tag_here', {}]</p>\n\n<p>Resulting JSON structure will be slightly different but you will still get the publish date sorting.</p>\n" }, { "answer_id": 216543, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 2, "selected": false, "text": "<p>You can define a single permanent view, as Bahadir suggests. when doing this sort of indexing, though, <em>don't</em> output the doc for each key. Instead, emit([tag, doc.published], null). In current release versions you'd then have to do a separate lookup for each doc, but SVN trunk now has support for specifying \"include_docs=True\" in the query string and CouchDB will automatically merge the docs into your view for you, without the space overhead.</p>\n" }, { "answer_id": 312181, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 0, "selected": false, "text": "<pre><code># Works on CouchDB 0.8.0\nfrom couchdb import Server # http://code.google.com/p/couchdb-python/\n\nbyTag = \"\"\"\nfunction(doc) {\nif (doc.type == 'post' &amp;&amp; doc.tags) {\n doc.tags.forEach(function(tag) {\n emit(tag, doc);\n });\n}\n}\n\"\"\"\n\ndef findPostsByTag(self, tag):\n server = Server(\"http://localhost:1234\")\n db = server['my_table']\n return [row for row in db.query(byTag, key = tag)]\n</code></pre>\n\n<p>The byTag map function returns the data with each unique tag in the \"key\", then each post with that tag in <code>value</code>, so when you grab key = \"mytag\", it will retrieve all posts with the tag \"mytag\".</p>\n\n<p>I've tested it against about 10 entries and it seems to take about 0.0025 seconds per query, not sure how efficient it is with large data sets..</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28809/" ]
I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach? ``` def by_tag(tag): return ''' function(doc) { if (doc.tags.length > 0) { for (var tag in doc.tags) { if (doc.tags[tag] == "%s") { emit(doc.published, doc) } } } }; ''' % tag ```
*Disclaimer: I didn't test this and don't know if it can perform better.* Create a single perm view: ``` function(doc) { for (var tag in doc.tags) { emit([tag, doc.published], doc) } }; ``` And query with \_view/your\_view/all?startkey=['your\_tag\_here']&endkey=['your\_tag\_here', {}] Resulting JSON structure will be slightly different but you will still get the publish date sorting.
211,122
<p>In an application that is hosting several WCF services, what would be the best way to add custom configuration information for each service? For example you may want to pass or set a company name or specify the connectionString a service or some other parameter. </p> <p>I'm guessing this might be possible by implementing IServiceBehavior.</p> <p>i.e something like....</p> <pre><code>&lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="MyBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug /&gt; &lt;customBehavior myCompany="ABC" /&gt; &lt;/behavior&gt; &lt;behavior name="MyOtherBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug /&gt; &lt;customBehavior myCompany="DEF" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;services&gt; &lt;service behaviorConfiguration="MyBehavior" name="MyNameSpace.MyService"&gt; &lt;endpoint address="" behaviorConfiguration="" binding="netTcpBinding" name="TcpEndpoint" contract="MyNameSpace.IMyService" /&gt; &lt;endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="TcpMexEndpoint" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="net.tcp://localhost:4000/MyService" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;service behaviorConfiguration="MyOtherBehavior" name="MyNameSpace.MyOtherService"&gt; &lt;endpoint address="" behaviorConfiguration="" binding="netTcpBinding" name="TcpEndpoint" contract="MyNameSpace.IMyOtherService" /&gt; &lt;endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="TcpMexEndpoint" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="net.tcp://localhost:4000/MyOtherService" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/services&gt; </code></pre> <p>Would set ABC on MyService and DEF on MyOtherService (assuming they have some common interface with a company name).</p> <p>Can anyone elaborate on how you implement this?</p> <p>TIA</p> <p>Michael</p>
[ { "answer_id": 211993, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 0, "selected": false, "text": "<p>It depends a lot of where and how you expect to use said information. If it's not something that's going to do a lot with the infrastructure (i.e. getting the services to run and processing requests), I'd be tempted to say that trying to push that into the WCF behaviors might be adding more complexity than it's worth. It would probably be simpler to just use a custom configuration section of your own.</p>\n\n<p>Could you clarify how you expect to use this information at runtime? Maybe that way we can provide more explicit advice...</p>\n" }, { "answer_id": 217182, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Well, I thought the example I've given was pretty elaborate. I'll try to elaborate further...</p>\n\n<p>Basically I want to be able to pass custom configuration data to a WCF service in an application where there may be several WCF services running. </p>\n\n<p>So what that means is in the an instance of a service running in the application I want to access data that has been configured specifically for that service (and not another service). I guess I could do this simply by using the application settings and using the service's type as the key. I was hoping WCF might have some better constructs for this.</p>\n" }, { "answer_id": 619295, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 3, "selected": false, "text": "<p>I know this is old, but it was never marked answered, so I thought I'd take a shot. If I understand what you're after, you can do it with a custom ServiceHostFactory.<br>\nGood post on this <a href=\"http://blogs.msdn.com/dotnetinterop/archive/2008/09/22/custom-service-config-file-for-a-wcf-service-hosted-in-iis.aspx\" rel=\"noreferrer\">here</a>. </p>\n\n<p>You set up yuour custom ServiceHostFactory like so:</p>\n\n<pre><code>&lt;%@ ServiceHost\n Language=\"C#\"\n Debug=\"true\"\n Service=\"Ionic.Samples.Webservices.Sep20.CustomConfigService\"\n Factory=\"Ionic.ServiceModel.ServiceHostFactory\"%&gt;\n</code></pre>\n\n<p>Then, in your ServiceHostFactory, you can override a method called ApplyConfiguration. Normally for WCF apps hosted in IIS, WCF would automatically look for config in web.config. In this example, we override that behavior to first look for a config file named after the WCF Service Description. </p>\n\n<pre><code>protected override void ApplyConfiguration()\n{\n // generate the name of the custom configFile, from the service name:\n string configFilename = System.IO.Path.Combine ( physicalPath,\n String.Format(\"{0}.config\", this.Description.Name));\n\n if (string.IsNullOrEmpty(configFilename) || !System.IO.File.Exists(configFilename))\n base.ApplyConfiguration();\n else\n LoadConfigFromCustomLocation(configFilename);\n}\n</code></pre>\n\n<p>You could replace this with \"anything\" - for example, looking for config in a database table. </p>\n\n<p>A few more methods complete the puzzle.</p>\n\n<pre><code>private string _physicalPath = null;\nprivate string physicalPath\n{\n get\n {\n if (_physicalPath == null)\n {\n // if hosted in IIS\n _physicalPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;\n\n if (String.IsNullOrEmpty(_physicalPath))\n {\n // for hosting outside of IIS\n _physicalPath= System.IO.Directory.GetCurrentDirectory();\n }\n }\n return _physicalPath;\n }\n}\n\n\nprivate void LoadConfigFromCustomLocation(string configFilename)\n{\n var filemap = new System.Configuration.ExeConfigurationFileMap();\n filemap.ExeConfigFilename = configFilename;\n System.Configuration.Configuration config =\n System.Configuration.ConfigurationManager.OpenMappedExeConfiguration\n (filemap,\n System.Configuration.ConfigurationUserLevel.None);\n var serviceModel = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);\n bool loaded= false;\n foreach (System.ServiceModel.Configuration.ServiceElement se in serviceModel.Services.Services)\n {\n if(!loaded)\n if (se.Name == this.Description.ConfigurationName)\n {\n base.LoadConfigurationSection(se);\n loaded= true;\n }\n }\n\n if (!loaded)\n throw new ArgumentException(\"ServiceElement doesn't exist\");\n}\n</code></pre>\n" }, { "answer_id": 2085416, "author": "Pablo Retyk", "author_id": 30729, "author_profile": "https://Stackoverflow.com/users/30729", "pm_score": 2, "selected": false, "text": "<p>I was having a similar issue, but I was using DuplexChannel.\nBased on a <a href=\"http://www.mssoftwareconsulting.com/msswc/blog/post/Override-WCF-Client-Settings-From-Custom-Config-File.aspx\" rel=\"nofollow noreferrer\">post</a> i found I found I solved this way:</p>\n\n<pre><code>public class CustomDuplexChannelFactory&lt;TChannel&gt; : DuplexChannelFactory&lt;TChannel&gt;\n{\n public static string ConfigurationPath { get; set; }\n\n public CustomDuplexChannelFactory(InstanceContext callbackInstance)\n : base(callbackInstance)\n {\n }\n\n protected override ServiceEndpoint CreateDescription()\n {\n ServiceEndpoint serviceEndpoint = base.CreateDescription();\n\n if(ConfigurationPath == null || !File.Exists(ConfigurationPath))\n return base.CreateDescription();\n\n ExeConfigurationFileMap executionFileMap = new ExeConfigurationFileMap();\n executionFileMap.ExeConfigFilename = ConfigurationPath;\n System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(executionFileMap, ConfigurationUserLevel.None);\n ServiceModelSectionGroup serviceModeGroup = ServiceModelSectionGroup.GetSectionGroup(config);\n ChannelEndpointElement selectedEndpoint = null;\n foreach(ChannelEndpointElement endpoint in serviceModeGroup.Client.Endpoints)\n {\n if(endpoint.Contract == serviceEndpoint.Contract.ConfigurationName)\n {\n selectedEndpoint = endpoint; break;\n }\n }\n if(selectedEndpoint != null)\n {\n if(serviceEndpoint.Binding == null)\n {\n serviceEndpoint.Binding = CreateBinding(selectedEndpoint.Binding, serviceModeGroup);\n } if(serviceEndpoint.Address == null)\n {\n serviceEndpoint.Address = new EndpointAddress(selectedEndpoint.Address,\n GetIdentity(selectedEndpoint.Identity), selectedEndpoint.Headers.Headers);\n } if(serviceEndpoint.Behaviors.Count == 0 &amp;&amp; !String.IsNullOrEmpty(selectedEndpoint.BehaviorConfiguration))\n {\n AddBehaviors(selectedEndpoint.BehaviorConfiguration,\n serviceEndpoint, serviceModeGroup);\n }\n serviceEndpoint.Name = selectedEndpoint.Contract;\n }\n return serviceEndpoint;\n }\n\n private Binding CreateBinding(string bindingName, ServiceModelSectionGroup group)\n {\n BindingCollectionElement bindingElementCollection = group.Bindings[bindingName];\n if(bindingElementCollection.ConfiguredBindings.Count &gt; 0)\n {\n IBindingConfigurationElement be = bindingElementCollection.ConfiguredBindings[0];\n Binding binding = GetBinding(be); if(be != null)\n {\n be.ApplyConfiguration(binding);\n }\n return binding;\n }\n return null;\n }\n\n private void AddBehaviors(string behaviorConfiguration, ServiceEndpoint serviceEndpoint, ServiceModelSectionGroup group)\n {\n EndpointBehaviorElement behaviorElement = group.Behaviors.EndpointBehaviors[behaviorConfiguration];\n for(int i = 0; i &lt; behaviorElement.Count; i++)\n {\n BehaviorExtensionElement behaviorExtension = behaviorElement[i];\n object extension = behaviorExtension.GetType().InvokeMember(\"CreateBehavior\", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, behaviorExtension, null);\n if(extension != null)\n {\n serviceEndpoint.Behaviors.Add((IEndpointBehavior)extension);\n }\n }\n }\n\n private EndpointIdentity GetIdentity(IdentityElement element)\n {\n EndpointIdentity identity = null;\n PropertyInformationCollection properties = element.ElementInformation.Properties;\n if(properties[\"userPrincipalName\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n return EndpointIdentity.CreateUpnIdentity(element.UserPrincipalName.Value);\n }\n if(properties[\"servicePrincipalName\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n return EndpointIdentity.CreateSpnIdentity(element.ServicePrincipalName.Value);\n }\n if(properties[\"dns\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n return EndpointIdentity.CreateDnsIdentity(element.Dns.Value);\n }\n if(properties[\"rsa\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n return EndpointIdentity.CreateRsaIdentity(element.Rsa.Value);\n }\n if(properties[\"certificate\"].ValueOrigin != PropertyValueOrigin.Default)\n {\n X509Certificate2Collection supportingCertificates = new X509Certificate2Collection();\n supportingCertificates.Import(Convert.FromBase64String(element.Certificate.EncodedValue));\n\n if(supportingCertificates.Count == 0)\n {\n throw new InvalidOperationException(\"UnableToLoadCertificateIdentity\");\n }\n\n X509Certificate2 primaryCertificate = supportingCertificates[0]; supportingCertificates.RemoveAt(0);\n return EndpointIdentity.CreateX509CertificateIdentity(primaryCertificate, supportingCertificates);\n }\n return identity;\n }\n\n private Binding GetBinding(IBindingConfigurationElement configurationElement)\n {\n if(configurationElement is CustomBindingElement)\n return new CustomBinding();\n else if(configurationElement is BasicHttpBindingElement)\n return new BasicHttpBinding();\n else if(configurationElement is NetMsmqBindingElement)\n return new NetMsmqBinding();\n else if(configurationElement is NetNamedPipeBindingElement)\n return new NetNamedPipeBinding();\n else if(configurationElement is NetPeerTcpBindingElement)\n return new NetPeerTcpBinding();\n else if(configurationElement is NetTcpBindingElement)\n return new NetTcpBinding();\n else if(configurationElement is WSDualHttpBindingElement)\n return new WSDualHttpBinding();\n else if(configurationElement is WSHttpBindingElement)\n return new WSHttpBinding();\n else if(configurationElement is WSFederationHttpBindingElement)\n return new WSFederationHttpBinding();\n return null;\n }\n}\n</code></pre>\n\n<p>I summarized this in my <a href=\"http://weblogs.asp.net/pabloretyk/archive/2010/01/17/override-wcf-client-settings-for-custom-config-file-using-duplexchannel.aspx\" rel=\"nofollow noreferrer\">blog</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In an application that is hosting several WCF services, what would be the best way to add custom configuration information for each service? For example you may want to pass or set a company name or specify the connectionString a service or some other parameter. I'm guessing this might be possible by implementing IServiceBehavior. i.e something like.... ``` <behaviors> <serviceBehaviors> <behavior name="MyBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug /> <customBehavior myCompany="ABC" /> </behavior> <behavior name="MyOtherBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug /> <customBehavior myCompany="DEF" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="MyBehavior" name="MyNameSpace.MyService"> <endpoint address="" behaviorConfiguration="" binding="netTcpBinding" name="TcpEndpoint" contract="MyNameSpace.IMyService" /> <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="TcpMexEndpoint" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:4000/MyService" /> </baseAddresses> </host> </service> <service behaviorConfiguration="MyOtherBehavior" name="MyNameSpace.MyOtherService"> <endpoint address="" behaviorConfiguration="" binding="netTcpBinding" name="TcpEndpoint" contract="MyNameSpace.IMyOtherService" /> <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="TcpMexEndpoint" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:4000/MyOtherService" /> </baseAddresses> </host> </service> </services> ``` Would set ABC on MyService and DEF on MyOtherService (assuming they have some common interface with a company name). Can anyone elaborate on how you implement this? TIA Michael
I know this is old, but it was never marked answered, so I thought I'd take a shot. If I understand what you're after, you can do it with a custom ServiceHostFactory. Good post on this [here](http://blogs.msdn.com/dotnetinterop/archive/2008/09/22/custom-service-config-file-for-a-wcf-service-hosted-in-iis.aspx). You set up yuour custom ServiceHostFactory like so: ``` <%@ ServiceHost Language="C#" Debug="true" Service="Ionic.Samples.Webservices.Sep20.CustomConfigService" Factory="Ionic.ServiceModel.ServiceHostFactory"%> ``` Then, in your ServiceHostFactory, you can override a method called ApplyConfiguration. Normally for WCF apps hosted in IIS, WCF would automatically look for config in web.config. In this example, we override that behavior to first look for a config file named after the WCF Service Description. ``` protected override void ApplyConfiguration() { // generate the name of the custom configFile, from the service name: string configFilename = System.IO.Path.Combine ( physicalPath, String.Format("{0}.config", this.Description.Name)); if (string.IsNullOrEmpty(configFilename) || !System.IO.File.Exists(configFilename)) base.ApplyConfiguration(); else LoadConfigFromCustomLocation(configFilename); } ``` You could replace this with "anything" - for example, looking for config in a database table. A few more methods complete the puzzle. ``` private string _physicalPath = null; private string physicalPath { get { if (_physicalPath == null) { // if hosted in IIS _physicalPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; if (String.IsNullOrEmpty(_physicalPath)) { // for hosting outside of IIS _physicalPath= System.IO.Directory.GetCurrentDirectory(); } } return _physicalPath; } } private void LoadConfigFromCustomLocation(string configFilename) { var filemap = new System.Configuration.ExeConfigurationFileMap(); filemap.ExeConfigFilename = configFilename; System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration (filemap, System.Configuration.ConfigurationUserLevel.None); var serviceModel = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config); bool loaded= false; foreach (System.ServiceModel.Configuration.ServiceElement se in serviceModel.Services.Services) { if(!loaded) if (se.Name == this.Description.ConfigurationName) { base.LoadConfigurationSection(se); loaded= true; } } if (!loaded) throw new ArgumentException("ServiceElement doesn't exist"); } ```
211,133
<p>Oracle has this concept of allowing database users to be identified by the operating system user who is running the program that is connecting to Oracle. See <a href="http://www.oracle-base.com/articles/misc/OsAuthentication.php" rel="noreferrer">here</a>.</p> <p>This allows you to do, as that user on a unix machine for example, a command such as:</p> <pre><code>sqlplus / </code></pre> <p>I am attempting to write a Java program for Oracle 10.2 which connects without a username or password. The obvious choice of url:</p> <pre><code>jdbc:oracle:thin:/@localhost:1521:MYDBSID </code></pre> <p>doesn't work, giving an error (Sorry I don't have the error available right now).</p> <p>I have attempted many other forms of doing this as well, but with no luck.</p> <p>Does anyone have any suggestions on how I can connect a Java program to Oracle using the OS identification method?</p>
[ { "answer_id": 211178, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 1, "selected": false, "text": "<p>The jdbc driver that oracle ships does NOT have the capability of gathering the OS username and password from the URL that you provide it. Suppose, there are 3rd party JDBC driver providers for ORACLE, one of them might provide the functionality that you're asking for. you should google around.</p>\n" }, { "answer_id": 211228, "author": "Tony BenBrahim", "author_id": 80075, "author_profile": "https://Stackoverflow.com/users/80075", "pm_score": 4, "selected": true, "text": "<p>The JDBC Thin driver is a 100% pure Java implementation that cannot collect the needed information from the operating system. </p>\n\n<p>The JDBC OCI driver can do this! Use <code>jdbc:oracle:oci8:/@MYDBSID</code>, it will require that the Oracle driver be installed on that machine, not a problem if this is a server (and is faster to boot and supports many more features than the thin driver)</p>\n" }, { "answer_id": 211246, "author": "tunaranch", "author_id": 27708, "author_profile": "https://Stackoverflow.com/users/27708", "pm_score": 0, "selected": false, "text": "<p>If you're accessing Oracle from a J2EE appserver, you could achieve a similar end by using JNDI to acquire a datasource.</p>\n" }, { "answer_id": 216934, "author": "Jamie Love", "author_id": 27308, "author_profile": "https://Stackoverflow.com/users/27308", "pm_score": 1, "selected": false, "text": "<p>Thanks to those that answered. We've gone with the OCI driver.</p>\n\n<p>I did find documentation to suggest that Oracle 11g <strong>does</strong> support OS user authentication via the thin driver though:</p>\n\n<p><a href=\"http://www.orindasoft.com/public/Oracle_JDBC_JavaDoc/javadoc1110/oracle/jdbc/OracleConnection.html#CONNECTION_PROPERTY_THIN_VSESSION_OSUSER\" rel=\"nofollow noreferrer\">http://www.orindasoft.com/public/Oracle_JDBC_JavaDoc/javadoc1110/oracle/jdbc/OracleConnection.html#CONNECTION_PROPERTY_THIN_VSESSION_OSUSER</a></p>\n\n<p>I don't have an 11g setup to test this on, so I can't be certain this works.</p>\n" }, { "answer_id": 3408890, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 0, "selected": false, "text": "<p>The 11g thin driver can connect using Kerberos authentication.</p>\n\n<p>See <a href=\"http://www.rgagnon.com/javadetails/java-oracle-jdbc-connect-with-kerberos.html\" rel=\"nofollow noreferrer\">Connect to an Oracle database using Kerberos</a></p>\n" }, { "answer_id": 8500122, "author": "Ricky", "author_id": 687479, "author_profile": "https://Stackoverflow.com/users/687479", "pm_score": 0, "selected": false, "text": "<p>try following\njdbc:oracle:thin:username/password@localhost:1521:MYDBSID</p>\n\n<p>you need to specify the account information</p>\n\n<p>sqlplus / as sysdba on a unix machine which go through the operation system autentication</p>\n" }, { "answer_id": 30893239, "author": "evgeny", "author_id": 5019899, "author_profile": "https://Stackoverflow.com/users/5019899", "pm_score": -1, "selected": false, "text": "<p><code>jdbc:oracle:oci:@</code> works with ojdbc6.jar and Oracle 11g2</p>\n" }, { "answer_id": 30902935, "author": "Jean de Lavarene", "author_id": 4612499, "author_profile": "https://Stackoverflow.com/users/4612499", "pm_score": 1, "selected": false, "text": "<p>OS authentication support in the JDBC thin driver was added in 11g (you can download the JDBC thin driver from 11.2.0.4 on OTN).</p>\n\n<p>Note that you have to allow remote OS authentication on the server (over TCP) otherwise it will only work with sqlplus using IPC or BEQ locally. In your init.ora file, add this:</p>\n\n<pre><code>REMOTE_OS_AUTHENT = TRUE\n</code></pre>\n\n<p>Then if you user is \"osuserdemo\" on the client machine, create a database user like this and restart the DB:</p>\n\n<pre><code> CREATE USER OSUSERDEMO IDENTIFIED EXTERNALLY;\n GRANT CONNECT,CREATE SESSION,RESOURCE TO OSUSERDEMO; \n</code></pre>\n\n<p>And the JDBC thin driver should be able to connect without any username or password.</p>\n\n<p>It's worth noting that this feature - considered as highly unsecured - has been de-supported in 12c.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27308/" ]
Oracle has this concept of allowing database users to be identified by the operating system user who is running the program that is connecting to Oracle. See [here](http://www.oracle-base.com/articles/misc/OsAuthentication.php). This allows you to do, as that user on a unix machine for example, a command such as: ``` sqlplus / ``` I am attempting to write a Java program for Oracle 10.2 which connects without a username or password. The obvious choice of url: ``` jdbc:oracle:thin:/@localhost:1521:MYDBSID ``` doesn't work, giving an error (Sorry I don't have the error available right now). I have attempted many other forms of doing this as well, but with no luck. Does anyone have any suggestions on how I can connect a Java program to Oracle using the OS identification method?
The JDBC Thin driver is a 100% pure Java implementation that cannot collect the needed information from the operating system. The JDBC OCI driver can do this! Use `jdbc:oracle:oci8:/@MYDBSID`, it will require that the Oracle driver be installed on that machine, not a problem if this is a server (and is faster to boot and supports many more features than the thin driver)
211,137
<p>I have ASP.Net code similar to the following (this is inside a FIELDSET):</p> <pre><code>&lt;ol&gt; &lt;li&gt; &lt;label&gt;Some label&lt;/label&gt; &lt;one or more form controls, ASP.Net controls, labels, etc.&gt; &lt;/li&gt; &lt;li&gt; &lt;label&gt;Another label&lt;/label&gt; &lt;... more of the same...&gt; &lt;/li&gt; ... &lt;/ol&gt; </code></pre> <p>I'm trying to keep my markup as clean as I possibly can, but I've decided that for various reasons, I need to wrap a DIV around everything in the list item after the first label, like this:</p> <pre><code>&lt;ol&gt; &lt;li&gt; &lt;label&gt;Some label&lt;/label&gt; &lt;div class="GroupThese"&gt; &lt;one or more form controls, ASP.Net controls, labels, etc.&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;label&gt;Another label&lt;/label&gt; &lt;div class="GroupThese"&gt; &lt;... more of the same...&gt; &lt;/div&gt; &lt;/li&gt; ... &lt;/ol&gt; </code></pre> <p>I would rather do this with "unobtrusive Javascript" via jQuery instead of littering my page with extra markup so I can keep the form semantically "clean".</p> <p>I know how to write a jQuery selector to get to the first label in each list item $("li+label") or use :first-child. I also know how to insert things after the selection.</p> <p>What I can't figure out (at least this late at night) is how to find everything after the first label in the list item (or basically everything in the list item except for the first label would be another way to put it) and wrap a DIV around that in the document ready function. </p> <p><strong>UPDATE:</strong></p> <p>Owen's code worked once I removed the single quotes from around: <pre>$('this')</pre> and set the proper decendent selector: <pre>$("li label:first-child")</pre> in order to only select the first label that occurs after a list item.</p> <p>Here is what I did:</p> <pre><code>$(document).ready(function() { $('li label:first-child').each(function() { $(this).siblings().wrapAll('&lt;div class="GroupThese"&gt;&lt;/div&gt;'); }); }); </code></pre>
[ { "answer_id": 211150, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 2, "selected": false, "text": "<p>One approach would be to just wrap everything inside the &lt;li&gt; and then move the label out, e.g.</p>\n\n<pre><code>var $div = $('li').wrapInner('&lt;div&gt;&lt;/div&gt;').children('div');\n$div.children('label').prependTo($div.parent());\n</code></pre>\n" }, { "answer_id": 211159, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "<p><strong>edit</strong>: corrected code (see old code in revision history and comments for more info)</p>\n\n<p>ok this should work:</p>\n\n<pre><code>$('li label:first-child').each(function() {\n $(this).siblings().wrapAll('&lt;div class=\"li-non-label-child-wrapper\"&gt;');\n});\n</code></pre>\n\n<p>from:</p>\n\n<pre><code>&lt;li&gt;\n &lt;label&gt;Some label&lt;/label&gt;\n &lt;div&gt;stuff&lt;/div&gt;\n &lt;div&gt;other stuff&lt;/div&gt;\n&lt;/li&gt;\n&lt;li&gt;\n &lt;label&gt;Another label&lt;/label&gt;\n &lt;div&gt;stuff3&lt;/div&gt;\n&lt;/li&gt;\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>&lt;li&gt;\n &lt;label&gt;Some label&lt;/label&gt;\n &lt;div class=\"li-non-label-child-wrapper\"&gt;\n &lt;div&gt;stuff&lt;/div&gt;\n &lt;div&gt;other stuff&lt;/div&gt;\n &lt;/div&gt;\n&lt;/li&gt;\n&lt;li&gt;\n &lt;label&gt;Another label&lt;/label&gt;\n &lt;div class=\"li-non-label-child-wrapper\"&gt;\n &lt;div&gt;stuff3&lt;/div&gt;\n &lt;/div&gt;\n&lt;/li&gt;\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14894/" ]
I have ASP.Net code similar to the following (this is inside a FIELDSET): ``` <ol> <li> <label>Some label</label> <one or more form controls, ASP.Net controls, labels, etc.> </li> <li> <label>Another label</label> <... more of the same...> </li> ... </ol> ``` I'm trying to keep my markup as clean as I possibly can, but I've decided that for various reasons, I need to wrap a DIV around everything in the list item after the first label, like this: ``` <ol> <li> <label>Some label</label> <div class="GroupThese"> <one or more form controls, ASP.Net controls, labels, etc.> </div> </li> <li> <label>Another label</label> <div class="GroupThese"> <... more of the same...> </div> </li> ... </ol> ``` I would rather do this with "unobtrusive Javascript" via jQuery instead of littering my page with extra markup so I can keep the form semantically "clean". I know how to write a jQuery selector to get to the first label in each list item $("li+label") or use :first-child. I also know how to insert things after the selection. What I can't figure out (at least this late at night) is how to find everything after the first label in the list item (or basically everything in the list item except for the first label would be another way to put it) and wrap a DIV around that in the document ready function. **UPDATE:** Owen's code worked once I removed the single quotes from around: ``` $('this') ``` and set the proper decendent selector: ``` $("li label:first-child") ``` in order to only select the first label that occurs after a list item. Here is what I did: ``` $(document).ready(function() { $('li label:first-child').each(function() { $(this).siblings().wrapAll('<div class="GroupThese"></div>'); }); }); ```
**edit**: corrected code (see old code in revision history and comments for more info) ok this should work: ``` $('li label:first-child').each(function() { $(this).siblings().wrapAll('<div class="li-non-label-child-wrapper">'); }); ``` from: ``` <li> <label>Some label</label> <div>stuff</div> <div>other stuff</div> </li> <li> <label>Another label</label> <div>stuff3</div> </li> ``` produces: ``` <li> <label>Some label</label> <div class="li-non-label-child-wrapper"> <div>stuff</div> <div>other stuff</div> </div> </li> <li> <label>Another label</label> <div class="li-non-label-child-wrapper"> <div>stuff3</div> </div> </li> ```
211,143
<p>I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum:</p> <pre><code>class Enum&lt;E extends Enum&lt;E&gt;&gt; </code></pre> <p>Could someone explain how to interpret this type parameter? Bonus points for providing other examples of where a similar type parameter could be used.</p>
[ { "answer_id": 211161, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "<p>It means that the type argument for enum has to derive from an enum which itself has the same type argument. How can this happen? By making the type argument the new type itself. So if I've got an enum called StatusCode, it would be equivalent to:</p>\n\n<pre><code>public class StatusCode extends Enum&lt;StatusCode&gt;\n</code></pre>\n\n<p>Now if you check the constraints, we've got <code>Enum&lt;StatusCode&gt;</code> - so <code>E=StatusCode</code>. Let's check: does <code>E</code> extend <code>Enum&lt;StatusCode&gt;</code>? Yes! We're okay.</p>\n\n<p>You may well be asking yourself what the point of this is :) Well, it means that the API for Enum can refer to itself - for instance, being able to say that <code>Enum&lt;E&gt;</code> implements <code>Comparable&lt;E&gt;</code>. The base class is able to do the comparisons (in the case of enums) but it can make sure that it only compares the right kind of enums with each other. (EDIT: Well, nearly - see the edit at the bottom.)</p>\n\n<p>I've used something similar in my C# port of ProtocolBuffers. There are \"messages\" (immutable) and \"builders\" (mutable, used to build a message) - and they come as pairs of types. The interfaces involved are:</p>\n\n<pre><code>public interface IBuilder&lt;TMessage, TBuilder&gt;\n where TMessage : IMessage&lt;TMessage, TBuilder&gt; \n where TBuilder : IBuilder&lt;TMessage, TBuilder&gt;\n\npublic interface IMessage&lt;TMessage, TBuilder&gt;\n where TMessage : IMessage&lt;TMessage, TBuilder&gt; \n where TBuilder : IBuilder&lt;TMessage, TBuilder&gt;\n</code></pre>\n\n<p>This means that from a message you can get an appropriate builder (e.g. to take a copy of a message and change some bits) and from a builder you can get an appropriate message when you've finished building it. It's a good job users of the API don't need to actually care about this though - it's horrendously complicated, and took several iterations to get to where it is.</p>\n\n<p>EDIT: Note that this doesn't stop you from creating odd types which use a type argument which itself is okay, but which isn't the same type. The purpose is to give benefits in the <em>right</em> case rather than protect you from the <em>wrong</em> case.</p>\n\n<p>So if <code>Enum</code> weren't handled \"specially\" in Java anyway, you could (as noted in comments) create the following types:</p>\n\n<pre><code>public class First extends Enum&lt;First&gt; {}\npublic class Second extends Enum&lt;First&gt; {}\n</code></pre>\n\n<p><code>Second</code> would implement <code>Comparable&lt;First&gt;</code> rather than <code>Comparable&lt;Second&gt;</code>... but <code>First</code> itself would be fine.</p>\n" }, { "answer_id": 211163, "author": "kpirkkal", "author_id": 15040, "author_profile": "https://Stackoverflow.com/users/15040", "pm_score": 2, "selected": false, "text": "<p>You are not the only one wondering what that means; see <a href=\"http://chaoticjava.com/posts/class-enume-extends-enume/\" rel=\"nofollow noreferrer\">Chaotic Java blog</a>.</p>\n\n<p>“If a class extends this class, it should pass a parameter E. The parameter E’s bounds are for a class which extends this class with the same parameter E”.</p>\n" }, { "answer_id": 758595, "author": "Maurice Naftalin", "author_id": 1859863, "author_profile": "https://Stackoverflow.com/users/1859863", "pm_score": 5, "selected": false, "text": "<p>The following is a modified version of the explanation from the book <em>Java Generics and Collections</em>:\nWe have an <code>Enum</code> declared</p>\n\n<pre><code>enum Season { WINTER, SPRING, SUMMER, FALL }\n</code></pre>\n\n<p>which will be expanded to a class</p>\n\n<pre><code>final class Season extends ...\n</code></pre>\n\n<p>where <code>...</code> is to be the somehow-parameterised base class for Enums. Let's work \nout what that has to be. Well, one of the requirements for <code>Season</code> is that it should implement <code>Comparable&lt;Season&gt;</code>. So we're going to need</p>\n\n<pre><code>Season extends ... implements Comparable&lt;Season&gt;\n</code></pre>\n\n<p>What could you use for <code>...</code> that would allow this to work? Given that it has to be a parameterisation of <code>Enum</code>, the only choice is <code>Enum&lt;Season&gt;</code>, so that you can have:</p>\n\n<pre><code>Season extends Enum&lt;Season&gt;\nEnum&lt;Season&gt; implements Comparable&lt;Season&gt;\n</code></pre>\n\n<p>So <code>Enum</code> is parameterised on types like <code>Season</code>. Abstract from <code>Season</code> and\nyou get that the parameter of <code>Enum</code> is any type that satisfies </p>\n\n<pre><code> E extends Enum&lt;E&gt;\n</code></pre>\n\n<hr>\n\n<p>Maurice Naftalin (co-author, Java Generics and Collections)</p>\n" }, { "answer_id": 1562221, "author": "nozebacle", "author_id": 114564, "author_profile": "https://Stackoverflow.com/users/114564", "pm_score": 1, "selected": false, "text": "<p>This post has totally clarified to me these problem of 'recursive generic types'.\nI just wanted to add another case where this particular structure is necessary.</p>\n\n<p>Suppose you have generic nodes in a generic graph:</p>\n\n<pre><code>public abstract class Node&lt;T extends Node&lt;T&gt;&gt;\n{\n public void addNeighbor(T);\n\n public void addNeighbors(Collection&lt;? extends T&gt; nodes);\n\n public Collection&lt;T&gt; getNeighbor();\n}\n</code></pre>\n\n<p>Then you can have graphs of specialized types:</p>\n\n<pre><code>public class City extends Node&lt;City&gt;\n{\n public void addNeighbor(City){...}\n\n public void addNeighbors(Collection&lt;? extends City&gt; nodes){...}\n\n public Collection&lt;City&gt; getNeighbor(){...}\n}\n</code></pre>\n" }, { "answer_id": 20253960, "author": "Andrey Chaschev", "author_id": 1851024, "author_profile": "https://Stackoverflow.com/users/1851024", "pm_score": 3, "selected": false, "text": "<p>This can be illustrated by a simple example and a technique which can be used to implement chained method calls for sub-classes. In an example below <code>setName</code> returns a <code>Node</code> so chaining won't work for the <code>City</code>:</p>\n\n<pre><code>class Node {\n String name;\n\n Node setName(String name) {\n this.name = name;\n return this;\n }\n}\n\nclass City extends Node {\n int square;\n\n City setSquare(int square) {\n this.square = square;\n return this;\n }\n}\n\npublic static void main(String[] args) {\n City city = new City()\n .setName(\"LA\")\n .setSquare(100); // won't compile, setName() returns Node\n}\n</code></pre>\n\n<p>So we could reference a sub-class in a generic declaration, so that the <code>City</code> now returns the correct type:</p>\n\n<pre><code>abstract class Node&lt;SELF extends Node&lt;SELF&gt;&gt;{\n String name;\n\n SELF setName(String name) {\n this.name = name;\n return self();\n }\n\n protected abstract SELF self();\n}\n\nclass City extends Node&lt;City&gt; {\n int square;\n\n City setSquare(int square) {\n this.square = square;\n return self();\n }\n\n @Override\n protected City self() {\n return this;\n }\n\n public static void main(String[] args) {\n City city = new City()\n .setName(\"LA\")\n .setSquare(100); // ok!\n }\n}\n</code></pre>\n" }, { "answer_id": 30667912, "author": "EpicPandaForce", "author_id": 2413303, "author_profile": "https://Stackoverflow.com/users/2413303", "pm_score": 1, "selected": false, "text": "<p>If you look at the <code>Enum</code> source code, it has the following:</p>\n\n<pre><code>public abstract class Enum&lt;E extends Enum&lt;E&gt;&gt;\n implements Comparable&lt;E&gt;, Serializable {\n\n public final int compareTo(E o) {\n Enum&lt;?&gt; other = (Enum&lt;?&gt;)o;\n Enum&lt;E&gt; self = this;\n if (self.getClass() != other.getClass() &amp;&amp; // optimization\n self.getDeclaringClass() != other.getDeclaringClass())\n throw new ClassCastException();\n return self.ordinal - other.ordinal;\n }\n\n @SuppressWarnings(\"unchecked\")\n public final Class&lt;E&gt; getDeclaringClass() {\n Class&lt;?&gt; clazz = getClass();\n Class&lt;?&gt; zuper = clazz.getSuperclass();\n return (zuper == Enum.class) ? (Class&lt;E&gt;)clazz : (Class&lt;E&gt;)zuper;\n }\n\n public static &lt;T extends Enum&lt;T&gt;&gt; T valueOf(Class&lt;T&gt; enumType,\n String name) {\n T result = enumType.enumConstantDirectory().get(name);\n if (result != null)\n return result;\n if (name == null)\n throw new NullPointerException(\"Name is null\");\n throw new IllegalArgumentException(\n \"No enum constant \" + enumType.getCanonicalName() + \".\" + name);\n } \n}\n</code></pre>\n\n<p>First thing first, what does <code>E extends Enum&lt;E&gt;</code> mean? It means the type parameter is something that extends from Enum, and isn't parametrized with a raw type (it's parametrized by itself).</p>\n\n<p>This is relevant if you have an enum</p>\n\n<pre><code>public enum MyEnum {\n THING1,\n THING2;\n}\n</code></pre>\n\n<p>which, if I know correctly, is translated to</p>\n\n<pre><code>public final class MyEnum extends Enum&lt;MyEnum&gt; {\n public static final MyEnum THING1 = new MyEnum();\n public static final MyEnum THING2 = new MyEnum();\n}\n</code></pre>\n\n<p>So this means that MyEnum receives the following methods:</p>\n\n<pre><code>public final int compareTo(MyEnum o) {\n Enum&lt;?&gt; other = (Enum&lt;?&gt;)o;\n Enum&lt;MyEnum&gt; self = this;\n if (self.getClass() != other.getClass() &amp;&amp; // optimization\n self.getDeclaringClass() != other.getDeclaringClass())\n throw new ClassCastException();\n return self.ordinal - other.ordinal;\n}\n</code></pre>\n\n<p>And even more importantly,</p>\n\n<pre><code> @SuppressWarnings(\"unchecked\")\n public final Class&lt;MyEnum&gt; getDeclaringClass() {\n Class&lt;?&gt; clazz = getClass();\n Class&lt;?&gt; zuper = clazz.getSuperclass();\n return (zuper == Enum.class) ? (Class&lt;MyEnum&gt;)clazz : (Class&lt;MyEnum&gt;)zuper;\n }\n</code></pre>\n\n<p>This makes <code>getDeclaringClass()</code> cast to the proper <code>Class&lt;T&gt;</code> object.</p>\n\n<p>A way clearer example is the one that I answered on <a href=\"https://stackoverflow.com/questions/30616864/how-to-make-type-safety-with-generics/30616937#30616937\">this question</a> where you cannot avoid this construct if you want to specify a generic bound.</p>\n" }, { "answer_id": 59368848, "author": "Hanzhou Tang", "author_id": 9931448, "author_profile": "https://Stackoverflow.com/users/9931448", "pm_score": 0, "selected": false, "text": "<p>According to wikipedia, this pattern is called <a href=\"https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"nofollow noreferrer\">Curiously recurring template pattern</a>. \nBasically, by using the CRTP pattern, we can easily refer to subclass type without type casting, which means by using the pattern, we can imitate virtual function. </p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum: ``` class Enum<E extends Enum<E>> ``` Could someone explain how to interpret this type parameter? Bonus points for providing other examples of where a similar type parameter could be used.
It means that the type argument for enum has to derive from an enum which itself has the same type argument. How can this happen? By making the type argument the new type itself. So if I've got an enum called StatusCode, it would be equivalent to: ``` public class StatusCode extends Enum<StatusCode> ``` Now if you check the constraints, we've got `Enum<StatusCode>` - so `E=StatusCode`. Let's check: does `E` extend `Enum<StatusCode>`? Yes! We're okay. You may well be asking yourself what the point of this is :) Well, it means that the API for Enum can refer to itself - for instance, being able to say that `Enum<E>` implements `Comparable<E>`. The base class is able to do the comparisons (in the case of enums) but it can make sure that it only compares the right kind of enums with each other. (EDIT: Well, nearly - see the edit at the bottom.) I've used something similar in my C# port of ProtocolBuffers. There are "messages" (immutable) and "builders" (mutable, used to build a message) - and they come as pairs of types. The interfaces involved are: ``` public interface IBuilder<TMessage, TBuilder> where TMessage : IMessage<TMessage, TBuilder> where TBuilder : IBuilder<TMessage, TBuilder> public interface IMessage<TMessage, TBuilder> where TMessage : IMessage<TMessage, TBuilder> where TBuilder : IBuilder<TMessage, TBuilder> ``` This means that from a message you can get an appropriate builder (e.g. to take a copy of a message and change some bits) and from a builder you can get an appropriate message when you've finished building it. It's a good job users of the API don't need to actually care about this though - it's horrendously complicated, and took several iterations to get to where it is. EDIT: Note that this doesn't stop you from creating odd types which use a type argument which itself is okay, but which isn't the same type. The purpose is to give benefits in the *right* case rather than protect you from the *wrong* case. So if `Enum` weren't handled "specially" in Java anyway, you could (as noted in comments) create the following types: ``` public class First extends Enum<First> {} public class Second extends Enum<First> {} ``` `Second` would implement `Comparable<First>` rather than `Comparable<Second>`... but `First` itself would be fine.
211,160
<p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
[ { "answer_id": 211174, "author": "Mapad", "author_id": 28165, "author_profile": "https://Stackoverflow.com/users/28165", "pm_score": 8, "selected": true, "text": "<p>You should have a look at <a href=\"http://www.scipy.org/Tentative_NumPy_Tutorial\" rel=\"noreferrer\">numpy</a> if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.</p>\n\n<pre><code>from numpy import matrix\nfrom numpy import linalg\nA = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.\nx = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).\ny = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).\nprint A.T # Transpose of A.\nprint A*x # Matrix multiplication of A and x.\nprint A.I # Inverse of A.\nprint linalg.solve(A, x) # Solve the linear equation system.\n</code></pre>\n\n<p>You can also have a look at the <a href=\"https://docs.python.org/3.4/library/array.html\" rel=\"noreferrer\">array</a> module, which is a much more efficient implementation of lists when you have to deal with only one data type.</p>\n" }, { "answer_id": 213717, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 1, "selected": false, "text": "<p>If you hate numpy, get out RPy and your local copy of R, and use it instead.</p>\n\n<p>(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)</p>\n" }, { "answer_id": 215523, "author": "John D. Cook", "author_id": 25188, "author_profile": "https://Stackoverflow.com/users/25188", "pm_score": 6, "selected": false, "text": "<p>Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.</p>\n\n<p>See <a href=\"http://www.johndcook.com/blog/2010/01/19/dont-invert-that-matrix/\" rel=\"noreferrer\">Don't invert that matrix</a>.</p>\n" }, { "answer_id": 605460, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You could calculate the determinant of the matrix which is recursive\nand then form the adjoined matrix</p>\n\n<p><a href=\"http://www.easycalculation.com/matrix/inverse-matrix-tutorial.php\" rel=\"noreferrer\">Here is a short tutorial</a></p>\n\n<p>I think this only works for square matrices</p>\n\n<p>Another way of computing these involves gram-schmidt orthogonalization and then transposing the matrix, the transpose of an orthogonalized matrix is its inverse!</p>\n" }, { "answer_id": 3128931, "author": "user377367", "author_id": 377367, "author_profile": "https://Stackoverflow.com/users/377367", "pm_score": 3, "selected": false, "text": "<p>It is a pity that the chosen matrix, repeated here again, is either singular or badly conditioned:</p>\n<pre class=\"lang-py prettyprint-override\"><code>A = matrix( [[1,2,3],[11,12,13],[21,22,23]])\n</code></pre>\n<p>By definition, the inverse of A when multiplied by the matrix A itself must give a unit matrix. The A chosen in the much praised explanation does not do that. In fact just looking at the inverse gives a clue that the inversion did not work correctly. Look at the magnitude of the individual terms - they are very, very big compared with the terms of the original A matrix...</p>\n<p>It is remarkable that the humans when picking an example of a matrix so often manage to pick a singular matrix!</p>\n<p>I did have a problem with the solution, so looked into it further. On the ubuntu-kubuntu platform, the debian package numpy does not have the matrix and the linalg sub-packages, so in addition to import of numpy, scipy needs to be imported also.</p>\n<p>If the diagonal terms of A are multiplied by a large enough factor, say 2, the matrix will most likely cease to be singular or near singular. So</p>\n<pre class=\"lang-py prettyprint-override\"><code>A = matrix( [[2,2,3],[11,24,13],[21,22,46]])\n</code></pre>\n<p>becomes neither singular nor nearly singular and the example gives meaningful results... When dealing with floating numbers one must be watchful for the effects of inavoidable round off errors.</p>\n" }, { "answer_id": 21126480, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 3, "selected": false, "text": "<p>Numpy will be suitable for most people, but you can also do <a href=\"http://docs.sympy.org/latest/tutorial/matrices.html\" rel=\"nofollow\">matrices in Sympy</a></p>\n\n<p>Try running these commands at <a href=\"http://live.sympy.org/\" rel=\"nofollow\">http://live.sympy.org/</a></p>\n\n<pre><code>M = Matrix([[1, 3], [-2, 3]])\nM\nM**-1\n</code></pre>\n\n<p>For fun, try <code>M**(1/2)</code></p>\n" }, { "answer_id": 62940942, "author": "Vladimir Salin", "author_id": 839518, "author_profile": "https://Stackoverflow.com/users/839518", "pm_score": 3, "selected": false, "text": "<p>For those like me, who were looking for a pure Python solution without <code>pandas</code> or <code>numpy</code> involved, check out the following GitHub project: <a href=\"https://github.com/ThomIves/MatrixInverse\" rel=\"noreferrer\">https://github.com/ThomIves/MatrixInverse</a>.</p>\n<p>It generously provides a very good explanation of how the process looks like &quot;behind the scenes&quot;. The author has nicely described the step-by-step approach and presented some practical examples, all easy to follow.</p>\n<p>This is just a little code snippet from there to illustrate the approach very briefly (<code>AM</code> is the source matrix, <code>IM</code> is the identity matrix of the same size):</p>\n<pre><code>def invert_matrix(AM, IM):\n for fd in range(len(AM)):\n fdScaler = 1.0 / AM[fd][fd]\n for j in range(len(AM)):\n AM[fd][j] *= fdScaler\n IM[fd][j] *= fdScaler\n for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:\n crScaler = AM[i][fd]\n for j in range(len(AM)):\n AM[i][j] = AM[i][j] - crScaler * AM[fd][j]\n IM[i][j] = IM[i][j] - crScaler * IM[fd][j]\n return IM\n</code></pre>\n<p><strong>But please do follow the entire thing, you'll learn a lot more than just copy-pasting this code!</strong> There's a Jupyter notebook as well, btw.</p>\n<p>Hope that helps someone, I personally found it extremely useful for my very particular task (<a href=\"https://en.wikipedia.org/wiki/Absorbing_Markov_chain\" rel=\"noreferrer\">Absorbing Markov Chain</a>) where I wasn't able to use any non-standard packages.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.
You should have a look at [numpy](http://www.scipy.org/Tentative_NumPy_Tutorial) if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation. ``` from numpy import matrix from numpy import linalg A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix. x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector). y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector). print A.T # Transpose of A. print A*x # Matrix multiplication of A and x. print A.I # Inverse of A. print linalg.solve(A, x) # Solve the linear equation system. ``` You can also have a look at the [array](https://docs.python.org/3.4/library/array.html) module, which is a much more efficient implementation of lists when you have to deal with only one data type.
211,176
<p>I am seeing following exception when I try to use dynamic proxy </p> <pre><code> com.intellij.rt.execution.application.AppMain DynamicProxy.DynamicProxy Exception in thread "main" java.lang.IllegalArgumentException: interface Interfaces.IPerson is not visible from class loader at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353) at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:581) at DynamicProxy.Creator.getProxy(Creator.java:18) at DynamicProxy.DynamicProxy.main(DynamicProxy.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) </code></pre> <p>Any idea what I need to do to resolve it</p>
[ { "answer_id": 211226, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 3, "selected": false, "text": "<p>When your <code>DynamicProxy</code> tries to do <code>Class.forName(youInterfaceClass.getName())</code> the resulting <code>java.lang.Class</code> instance is different from the one you passed when you created the proxy. In other words you have two class objects with the same name and the proxy is not sure which one is the right one (doesn't matter whether they are the same).</p>\n\n<p>Usually, this happens when the interface you are trying to proxy is in a library loaded through two different classloaders (i.e. Tomcat's 'common' and 'application'). </p>\n\n<p>If this doesn't help, please post more info on your application - especially if you are using any application server, Spring or OSGi.</p>\n" }, { "answer_id": 13379769, "author": "omnomnom", "author_id": 577812, "author_profile": "https://Stackoverflow.com/users/577812", "pm_score": 4, "selected": false, "text": "<p>If this is web application, then you should use the web application classloader when creating dynamic proxy. So, for example instead of:</p>\n\n<pre><code>Proxy.newProxyInstance(\n ClassLoader.getSystemClassLoader(),\n new Class &lt; ? &gt;[] {MyInterface.class},\n new InvocationHandler() {\n // (...)\n});\n</code></pre>\n\n<p>try:</p>\n\n<pre><code>Proxy.newProxyInstance(\n this.getClass().getClassLoader(), // here is the trick\n new Class &lt; ? &gt;[] {MyInterface.class},\n new InvocationHandler() {\n // (...)\n});\n</code></pre>\n\n<p>For instance, hierarchy of tomcat class loaders (other web containers have similar) is following:</p>\n\n<pre><code> Bootstrap\n |\n System\n |\n Common\n / \\\n Webapp1 Webapp2 ... \n</code></pre>\n\n<p>And it is the webapp classloader which contains classes and resources in the /WEB-INF/classes directory of your web application, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application.</p>\n" }, { "answer_id": 65004457, "author": "malloc32", "author_id": 3804377, "author_profile": "https://Stackoverflow.com/users/3804377", "pm_score": 0, "selected": false, "text": "<p>I had the same problem using spring boot, I solve it injecting ResourceLoader, getting its class loader.</p>\n<pre><code>@Autowired\nprivate ResourceLoader resourceLoader;\n\n....\nClassLoader classLoader = resourceLoader.getClassLoader();\n...\n\n\nProxy.newProxyInstance(\n classLoader, //for example...\n new Class &lt; ? &gt;[] {MyInterface.class},\n new InvocationHandler() {\n // (...)\n});\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am seeing following exception when I try to use dynamic proxy ``` com.intellij.rt.execution.application.AppMain DynamicProxy.DynamicProxy Exception in thread "main" java.lang.IllegalArgumentException: interface Interfaces.IPerson is not visible from class loader at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353) at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:581) at DynamicProxy.Creator.getProxy(Creator.java:18) at DynamicProxy.DynamicProxy.main(DynamicProxy.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ``` Any idea what I need to do to resolve it
If this is web application, then you should use the web application classloader when creating dynamic proxy. So, for example instead of: ``` Proxy.newProxyInstance( ClassLoader.getSystemClassLoader(), new Class < ? >[] {MyInterface.class}, new InvocationHandler() { // (...) }); ``` try: ``` Proxy.newProxyInstance( this.getClass().getClassLoader(), // here is the trick new Class < ? >[] {MyInterface.class}, new InvocationHandler() { // (...) }); ``` For instance, hierarchy of tomcat class loaders (other web containers have similar) is following: ``` Bootstrap | System | Common / \ Webapp1 Webapp2 ... ``` And it is the webapp classloader which contains classes and resources in the /WEB-INF/classes directory of your web application, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application.
211,184
<p>What's the best way to implement user controls that require AJAX callbacks? </p> <p>I want to accomplish a few things:</p> <ul> <li>Have events done in the browser (eg, drag and drop) trigger an AJAX notification that can raise a control event, which causes code on the page using the control to do whatever it needs to do (eg, change a value in a database). </li> <li>Have partial updates (NOT using an updatepanel) that can do things like populate an auto-complete dropdown underneath a textbox. </li> <li>Implement a single user control that is generic enough to be reused on several pages</li> <li>Avoid having to implement logic on the page itself that passes events back to the control, because that is repetitive and hard to maintain </li> </ul> <p>I'm using jQuery for most of the client side stuff, but for the actual AJAX calls I don't really care if it's jQuery or the ASP AJAX libraries. </p> <p>Effectively what would be perfect is PageMethods on the user control, that would be easily callable from client-side script. Unfortunately, as far as I'm aware, pagemethods do not work on user controls.</p> <hr> <p>I'll use an autocomplete control as an example: </p> <p>I should be able to put the autocomplete control on the page, and then in the page code, have eg:</p> <pre><code>Public Sub HandleLookup(ByVal input As String, ByRef list As List(Of String) Handles MyControl.LookupEntries list = New List(Of String) ' Query database for list of items.. For Each item as String in FullItemList If item.StartsWith(input) then list.Add(item) Next Return list End Sub </code></pre> <p>And do nothing else .. the rest of the code should be in the usercontrol. </p> <hr> <p>Note, the controls I'm trying to make are much more specific than eg, autocomplete. They do not exist in any 3rd party libraries and I really need to be able to make them myself.</p>
[ { "answer_id": 211939, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": true, "text": "<p>Look into implementing ICallbackEventHandler in your Page -- it's a simple way to make a call back to a page function from JavaScript.</p>\n\n<p>Here's a good tutorial:</p>\n\n<p><a href=\"http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=119\" rel=\"nofollow noreferrer\">http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=119</a></p>\n" }, { "answer_id": 304771, "author": "Thomas Hansen", "author_id": 29746, "author_profile": "https://Stackoverflow.com/users/29746", "pm_score": 0, "selected": false, "text": "<p>You might want to check out; <a href=\"http://ra-ajax.org/samples/Combining.aspx\" rel=\"nofollow noreferrer\">Ra-Ajax UserControl Sample</a> and combine that knowledge with <a href=\"http://ra-ajax.org/samples/Behaviors.aspx\" rel=\"nofollow noreferrer\">Ra-Ajax Drag and Drop</a></p>\n\n<p>Click the \"Show code\" C# icon to the left to see the usage of the code...</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7913/" ]
What's the best way to implement user controls that require AJAX callbacks? I want to accomplish a few things: * Have events done in the browser (eg, drag and drop) trigger an AJAX notification that can raise a control event, which causes code on the page using the control to do whatever it needs to do (eg, change a value in a database). * Have partial updates (NOT using an updatepanel) that can do things like populate an auto-complete dropdown underneath a textbox. * Implement a single user control that is generic enough to be reused on several pages * Avoid having to implement logic on the page itself that passes events back to the control, because that is repetitive and hard to maintain I'm using jQuery for most of the client side stuff, but for the actual AJAX calls I don't really care if it's jQuery or the ASP AJAX libraries. Effectively what would be perfect is PageMethods on the user control, that would be easily callable from client-side script. Unfortunately, as far as I'm aware, pagemethods do not work on user controls. --- I'll use an autocomplete control as an example: I should be able to put the autocomplete control on the page, and then in the page code, have eg: ``` Public Sub HandleLookup(ByVal input As String, ByRef list As List(Of String) Handles MyControl.LookupEntries list = New List(Of String) ' Query database for list of items.. For Each item as String in FullItemList If item.StartsWith(input) then list.Add(item) Next Return list End Sub ``` And do nothing else .. the rest of the code should be in the usercontrol. --- Note, the controls I'm trying to make are much more specific than eg, autocomplete. They do not exist in any 3rd party libraries and I really need to be able to make them myself.
Look into implementing ICallbackEventHandler in your Page -- it's a simple way to make a call back to a page function from JavaScript. Here's a good tutorial: <http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=119>
211,216
<p>What are the lesser-known but useful features of the Haskell programming language. (I understand the language itself is lesser-known, but work with me. Even explanations of the simple things in Haskell, like defining the Fibonacci sequence with one line of code, will get upvoted by me.) </p> <ul> <li>Try to limit answers to the Haskell core</li> <li>One feature per answer</li> <li>Give an example and short description of the feature, not just a link to documentation</li> <li>Label the feature using bold title as the first line</li> </ul>
[ { "answer_id": 212014, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 4, "selected": false, "text": "<p><strong>Optional Layout</strong></p>\n\n<p>You can use explicit braces and semicolons instead of whitespace (aka layout) to delimit blocks.</p>\n\n<pre><code>let {\n x = 40;\n y = 2\n } in\n x + y\n</code></pre>\n\n<p>... or equivalently...</p>\n\n<pre><code>let { x = 40; y = 2 } in x + y\n</code></pre>\n\n<p>... instead of ...</p>\n\n<pre><code>let x = 40\n y = 2\n in x + y\n</code></pre>\n\n<p>Because layout is not required, Haskell programs can be straightforwardly produced by other programs.</p>\n" }, { "answer_id": 212103, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 4, "selected": false, "text": "<p><strong>Operator Fixity</strong></p>\n\n<p>You can use the <a href=\"http://haskell.org/tutorial/functions.html#sect4.4.2\" rel=\"nofollow noreferrer\">infix, infixl or infixr</a> keywords to define operators associativity and precedence. Example taken from the <a href=\"http://www.zvon.org/other/haskell/Outputsyntax/fixityQdeclaration_reference.html\" rel=\"nofollow noreferrer\">reference</a>:</p>\n\n<pre><code>main = print (1 +++ 2 *** 3)\n\ninfixr 6 +++\ninfixr 7 ***,///\n\n(+++) :: Int -&gt; Int -&gt; Int\na +++ b = a + 2*b\n\n(***) :: Int -&gt; Int -&gt; Int\na *** b = a - 4*b\n\n(///) :: Int -&gt; Int -&gt; Int\na /// b = 2*a - 3*b\nOutput: -19\n</code></pre>\n\n<p>The number (0 to 9) after the infix allows you to define the precedence of the operator, being 9 the strongest. Infix means no associativity, whereas infixl associates left and infixr associates right.</p>\n\n<p>This allows you to define complex operators to do high level operations written as simple expressions.</p>\n\n<p>Note that you can also use binary functions as operators if you place them between backticks:</p>\n\n<pre><code>main = print (a `foo` b)\n\nfoo :: Int -&gt; Int -&gt; Int\nfoo a b = a + b\n</code></pre>\n\n<p>And as such, you can also define precedence for them:</p>\n\n<pre><code>infixr 4 `foo`\n</code></pre>\n" }, { "answer_id": 212131, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 4, "selected": false, "text": "<p><strong><code>seq</code> and <code>($!)</code> <a href=\"http://users.aber.ac.uk/afc/stricthaskell.html#seq\" rel=\"nofollow noreferrer\">only evaluate</a> enough to check that something is not bottom.</strong></p>\n\n<p>The following program will only print \"there\".</p>\n\n<pre><code>main = print \"hi \" `seq` print \"there\"\n</code></pre>\n\n<p>For those unfamiliar with Haskell, Haskell is non-strict in general, meaning that an argument to a function is only evaluated if it is needed.</p>\n\n<p>For example, the following prints \"ignored\" and terminates with success.</p>\n\n<pre><code>main = foo (error \"explode!\")\n where foo _ = print \"ignored\"\n</code></pre>\n\n<p><code>seq</code> is known to change that behavior by evaluating to bottom if its first argument is bottom.</p>\n\n<p>For example:</p>\n\n<pre><code>main = error \"first\" `seq` print \"impossible to print\"\n</code></pre>\n\n<p>... or equivalently, without infix ...</p>\n\n<pre><code>main = seq (error \"first\") (print \"impossible to print\")\n</code></pre>\n\n<p>... will blow up with an error on \"first\". It will never print \"impossible to print\".</p>\n\n<p>So it might be a little surprising that even though <code>seq</code> is strict, it won't evaluate something the way eager languages evaluate. In particular, it won't try to force all the positive integers in the following program. Instead, it will check that <code>[1..]</code> isn't bottom (which can be found immediately), print \"done\", and exit.</p>\n\n<pre><code>main = [1..] `seq` print \"done\"\n</code></pre>\n" }, { "answer_id": 212767, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 3, "selected": false, "text": "<p><strong>Infinite Lists</strong></p>\n\n<p>Since you mentioned fibonacci, there is a very elegant way of <a href=\"http://www.haskell.org/tutorial/patterns.html#tut-lazy-patterns\" rel=\"nofollow noreferrer\">generating fibonacci numbers</a> from an infinite list like this:</p>\n\n<pre><code>fib@(1:tfib) = 1 : 1 : [ a+b | (a,b) &lt;- zip fib tfib ]\n</code></pre>\n\n<p>The @ operator allows you to use pattern matching on the 1:tfib structure while still referring to the whole pattern as fib. </p>\n\n<p>Note that the comprehension list enters an infinite recursion, generating an infinite list. However, you can request elements from it or operate them, as long as you request a finite amount:</p>\n\n<pre><code>take 10 fib\n</code></pre>\n\n<p>You can also apply an operation to all elements before requesting them:</p>\n\n<pre><code>take 10 (map (\\x -&gt; x+1) fib)\n</code></pre>\n\n<p>This is thanks to Haskell's lazy evaluation of parameters and lists.</p>\n" }, { "answer_id": 213229, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "<p><strong>Shorthand for a common list operation</strong></p>\n\n<p>The following are equivalent:</p>\n\n<pre><code>concat $ map f list\nconcatMap f list\nlist &gt;&gt;= f\n</code></pre>\n\n<h2>Edit</h2>\n\n<p>Since more details were requested...</p>\n\n<pre><code>concat :: [[a]] -&gt; [a]\n</code></pre>\n\n<p><code>concat</code> takes a list of lists and concatenates them into a single list.</p>\n\n<pre><code>map :: (a -&gt; b) -&gt; [a] -&gt; [b]\n</code></pre>\n\n<p><code>map</code> maps a function over a list.</p>\n\n<pre><code>concatMap :: (a -&gt; [b]) -&gt; [a] -&gt; [b]\n</code></pre>\n\n<p><code>concatMap</code> is equivalent to <code>(.) concat . map</code>: map a function over a list, and concatenate the results.</p>\n\n<pre><code>class Monad m where\n (&gt;&gt;=) :: m a -&gt; (a -&gt; m b) -&gt; m b\n return :: a -&gt; m a\n</code></pre>\n\n<p>A <code>Monad</code> has a <em>bind</em> operation, which is called <code>&gt;&gt;=</code> in Haskell (or its sugared <code>do</code>-equivalent). List, aka <code>[]</code>, is a <code>Monad</code>. If we substitute <code>[]</code> for <code>m</code> in the above:</p>\n\n<pre><code>instance Monad [] where\n (&gt;&gt;=) :: [a] -&gt; (a -&gt; [b]) -&gt; [b]\n return :: a -&gt; [a]\n</code></pre>\n\n<p>What's the natural thing for the <code>Monad</code> operations to do on a list? We have to satisfy the monad laws,</p>\n\n<pre><code>return a &gt;&gt;= f == f a\nma &gt;&gt;= (\\a -&gt; return a) == ma\n(ma &gt;&gt;= f) &gt;&gt;= g == ma &gt;&gt;= (\\a -&gt; f a &gt;&gt;= g)\n</code></pre>\n\n<p>You can verify that these laws hold if we use the implementation</p>\n\n<pre><code>instance Monad [] where\n (&gt;&gt;=) = concatMap\n return = (:[])\n\nreturn a &gt;&gt;= f == [a] &gt;&gt;= f == concatMap f [a] == f a\nma &gt;&gt;= (\\a -&gt; return a) == concatMap (\\a -&gt; [a]) ma == ma\n(ma &gt;&gt;= f) &gt;&gt;= g == concatMap g (concatMap f ma) == concatMap (concatMap g . f) ma == ma &gt;&gt;= (\\a -&gt; f a &gt;&gt;= g)\n</code></pre>\n\n<p>This is, in fact, the behavior of <code>Monad []</code>. As a demonstration,</p>\n\n<pre><code>double x = [x,x]\nmain = do\n print $ map double [1,2,3]\n -- [[1,1],[2,2],[3,3]]\n print . concat $ map double [1,2,3]\n -- [1,1,2,2,3,3]\n print $ concatMap double [1,2,3]\n -- [1,1,2,2,3,3]\n print $ [1,2,3] &gt;&gt;= double\n -- [1,1,2,2,3,3]\n</code></pre>\n" }, { "answer_id": 213426, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "<p><strong>Readable function composition</strong></p>\n\n<p><code>Prelude</code> defines <code>(.)</code> to be mathematical function composition; that is, <code>g . f</code> first applies <code>f</code>, then applies <code>g</code> to the result.</p>\n\n<p>If you <code>import Control.Arrow</code>, the following are equivalent:</p>\n\n<pre><code>g . f\nf &gt;&gt;&gt; g\n</code></pre>\n\n<p><code>Control.Arrow</code> provides an <code>instance Arrow (-&gt;)</code>, and this is nice for people who don't like to read function application backwards.</p>\n" }, { "answer_id": 213428, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "<p><strong>Avoiding parentheses</strong></p>\n\n<p>The <code>(.)</code> and <code>($)</code> functions in <code>Prelude</code> have very convenient fixities, letting you avoid parentheses in many places. The following are equivalent:</p>\n\n<pre><code>f (g (h x))\nf $ g $ h x\nf . g $ h x\nf . g . h $ x\n</code></pre>\n\n<p><code>flip</code> helps too, the following are equivalent:</p>\n\n<pre><code>map (\\a -&gt; {- some long expression -}) list\nflip map list $ \\a -&gt;\n {- some long expression -}\n</code></pre>\n" }, { "answer_id": 213431, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "<p><strong>Nestable multiline comments</strong>.</p>\n\n<pre><code>{- inside a comment,\n {- inside another comment, -}\nstill commented! -}\n</code></pre>\n" }, { "answer_id": 213434, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "<p><strong>Pretty guards</strong></p>\n\n<p><code>Prelude</code> defines <code>otherwise = True</code>, making complete guard conditions read very naturally.</p>\n\n<pre><code>fac n\n | n &lt; 1 = 1\n | otherwise = n * fac (n-1)\n</code></pre>\n" }, { "answer_id": 213436, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "<p><strong>If you're looking for a list or higher-order function, it's already there</strong></p>\n\n<p>There's sooo many convenience and higher-order functions in the standard library.</p>\n\n<pre><code>-- factorial can be written, using the strict HOF foldl':\nfac n = Data.List.foldl' (*) 1 [1..n]\n-- there's a shortcut for that:\nfac n = product [1..n]\n-- and it can even be written pointfree:\nfac = product . enumFromTo 1\n</code></pre>\n" }, { "answer_id": 213438, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "<p><strong>Flexible specification of module imports and exports</strong></p>\n\n<p>Importing and exporting is nice.</p>\n\n<pre><code>module Foo (module Bar, blah) -- this is module Foo, export everything that Bar expored, plus blah\n\nimport qualified Some.Long.Name as Short\nimport Some.Long.Name (name) -- can import multiple times, with different options\n\nimport Baz hiding (blah) -- import everything from Baz, except something named 'blah'\n</code></pre>\n" }, { "answer_id": 213441, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 6, "selected": true, "text": "<p><strong>My brain just exploded</strong></p>\n\n<p>If you try to compile this code:</p>\n\n<pre><code>{-# LANGUAGE ExistentialQuantification #-}\ndata Foo = forall a. Foo a\nignorefoo f = 1 where Foo a = f\n</code></pre>\n\n<p>You will get this error message:</p>\n\n<pre>$ ghc Foo.hs\n\nFoo.hs:3:22:\n My brain just exploded.\n I can't handle pattern bindings for existentially-quantified constructors.\n Instead, use a case-expression, or do-notation, to unpack the constructor.\n In the binding group for\n Foo a\n In a pattern binding: Foo a = f\n In the definition of `ignorefoo':\n ignorefoo f = 1\n where\n Foo a = f\n</pre>\n" }, { "answer_id": 213956, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 5, "selected": false, "text": "<p><strong>User-defined control structures</strong></p>\n\n<p>Haskell has no shorthand ternary operator. The built-in <code>if</code>-<code>then</code>-<code>else</code> is always ternary, and is an expression (imperative languages tend to have <code>?:</code>=expression, <code>if</code>=statement). If you want, though,</p>\n\n<pre><code>True ? x = const x\nFalse ? _ = id\n</code></pre>\n\n<p>will define <code>(?)</code> to be the ternary operator:</p>\n\n<pre><code>(a ? b $ c) == (if a then b else c)\n</code></pre>\n\n<p>You'd have to resort to macros in most other languages to define your own short-circuiting logical operators, but Haskell is a fully lazy language, so it just works.</p>\n\n<pre><code>-- prints \"I'm alive! :)\"\nmain = True ? putStrLn \"I'm alive! :)\" $ error \"I'm dead :(\"\n</code></pre>\n" }, { "answer_id": 750002, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 4, "selected": false, "text": "<p>Generalized algebraic data types. Here's an example interpreter where the type system lets you cover all the cases:</p>\n\n<pre><code>{-# LANGUAGE GADTs #-}\nmodule Exp\nwhere\n\ndata Exp a where\n Num :: (Num a) =&gt; a -&gt; Exp a\n Bool :: Bool -&gt; Exp Bool\n Plus :: (Num a) =&gt; Exp a -&gt; Exp a -&gt; Exp a\n If :: Exp Bool -&gt; Exp a -&gt; Exp a -&gt; Exp a \n Lt :: (Num a, Ord a) =&gt; Exp a -&gt; Exp a -&gt; Exp Bool\n Lam :: (a -&gt; Exp b) -&gt; Exp (a -&gt; b) -- higher order abstract syntax\n App :: Exp (a -&gt; b) -&gt; Exp a -&gt; Exp b\n -- deriving (Show) -- failse\n\neval :: Exp a -&gt; a\neval (Num n) = n\neval (Bool b) = b\neval (Plus e1 e2) = eval e1 + eval e2\neval (If p t f) = eval $ if eval p then t else f\neval (Lt e1 e2) = eval e1 &lt; eval e2\neval (Lam body) = \\x -&gt; eval $ body x\neval (App f a) = eval f $ eval a\n\ninstance Eq a =&gt; Eq (Exp a) where\n e1 == e2 = eval e1 == eval e2\n\ninstance Show (Exp a) where\n show e = \"&lt;exp&gt;\" -- very weak show instance\n\ninstance (Num a) =&gt; Num (Exp a) where\n fromInteger = Num\n (+) = Plus\n</code></pre>\n" }, { "answer_id": 954901, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": 4, "selected": false, "text": "<p><strong>Patterns in top-level bindings</strong></p>\n\n<pre><code>five :: Int\nJust five = Just 5\n\na, b, c :: Char\n[a,b,c] = \"abc\"\n</code></pre>\n\n<p>How cool is that! Saves you that call to <code>fromJust</code> and <code>head</code> every now and then.</p>\n" }, { "answer_id": 1035661, "author": "yairchu", "author_id": 40916, "author_profile": "https://Stackoverflow.com/users/40916", "pm_score": 5, "selected": false, "text": "<p><strong>Hoogle</strong></p>\n\n<p>Hoogle is your friend. I admit, it's not part of the \"core\", so <code>cabal install hoogle</code></p>\n\n<p>Now you know how \"if you're looking for a higher-order function, it's already there\" (<a href=\"https://stackoverflow.com/questions/211216/hidden-features-of-haskell/213436#213436\">ephemient's comment</a>). But how do you find that function? With hoogle!</p>\n\n<pre><code>$ hoogle \"Num a =&gt; [a] -&gt; a\"\nPrelude product :: Num a =&gt; [a] -&gt; a\nPrelude sum :: Num a =&gt; [a] -&gt; a\n\n$ hoogle \"[Maybe a] -&gt; [a]\"\nData.Maybe catMaybes :: [Maybe a] -&gt; [a]\n\n$ hoogle \"Monad m =&gt; [m a] -&gt; m [a]\"\nPrelude sequence :: Monad m =&gt; [m a] -&gt; m [a]\n\n$ hoogle \"[a] -&gt; [b] -&gt; (a -&gt; b -&gt; c) -&gt; [c]\"\nPrelude zipWith :: (a -&gt; b -&gt; c) -&gt; [a] -&gt; [b] -&gt; [c]\n</code></pre>\n\n<p>The hoogle-google programmer is not able to write his programs on paper by himself the same way he does with the help of the computer. But he and the machine together are a forced not* to be reckoned with.</p>\n\n<p>Btw, if you liked hoogle be sure to check out hlint!</p>\n" }, { "answer_id": 1088284, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 3, "selected": false, "text": "<p><strong>Equational Reasoning</strong></p>\n\n<p>Haskell, being purely functional allows you to read an equal sign as a real equal sign (in the absence of non-overlapping patterns).</p>\n\n<p>This allows you to substitute definitions directly into code, and in terms of optimization gives a lot of leeway to the compiler about when stuff happens.</p>\n\n<p>A good example of this form of reasoning can be found here:</p>\n\n<p><a href=\"http://www.haskell.org/pipermail/haskell-cafe/2009-March/058603.html\" rel=\"nofollow noreferrer\">http://www.haskell.org/pipermail/haskell-cafe/2009-March/058603.html</a></p>\n\n<p>This also manifests itself nicely in the form of laws or RULES pragmas expected for valid members of an instance, for instance the Monad laws:</p>\n\n<ol>\n<li>returrn a >>= f == f a</li>\n<li>m >>= return == m</li>\n<li>(m >>= f) >>= g == m >>= (\\x -> f x >>= g)</li>\n</ol>\n\n<p>can often be used to simplify monadic code.</p>\n" }, { "answer_id": 1088316, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 5, "selected": false, "text": "<p><strong>Free Theorems</strong></p>\n\n<p>Phil Wadler introduced us to the notion of a <a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.38.9875\" rel=\"nofollow noreferrer\">free theorem</a> and we've been abusing them in Haskell ever since.</p>\n\n<p>These wonderful artifacts of Hindley-Milner-style type systems help out with equational reasoning by using parametricity to tell you about what a function <em>will not</em> do.</p>\n\n<p>For instance, there are two laws that every instance of Functor should satisfy:</p>\n\n<ol>\n<li>forall f g. fmap f . fmap g = fmap (f . g)</li>\n<li>fmap id = id</li>\n</ol>\n\n<p>But, the free theorem tells us we need not bother proving the first one, but given the second it comes for 'free' just from the type signature!</p>\n\n<pre><code>fmap :: Functor f =&gt; (a -&gt; b) -&gt; f a -&gt; f b\n</code></pre>\n\n<p>You need to be a bit careful with laziness, but this is partially covered in the original paper, and in Janis Voigtlaender's <a href=\"http://portal.acm.org/citation.cfm?id=982962.964010\" rel=\"nofollow noreferrer\">more recent paper</a> on free theorems in the presence of <code>seq</code>.</p>\n" }, { "answer_id": 1088522, "author": "Dario", "author_id": 105459, "author_profile": "https://Stackoverflow.com/users/105459", "pm_score": 3, "selected": false, "text": "<p><strong>Enhanced pattern matching</strong></p>\n\n<ul>\n<li>Lazy patterns</li>\n<li><p>Irrefutable patterns</p>\n\n<pre><code>let ~(Just x) = someExpression\n</code></pre></li>\n</ul>\n\n<p>See <a href=\"http://www.haskell.org/tutorial/patterns.html\" rel=\"nofollow noreferrer\">pattern matching</a></p>\n" }, { "answer_id": 1088529, "author": "Dario", "author_id": 105459, "author_profile": "https://Stackoverflow.com/users/105459", "pm_score": 2, "selected": false, "text": "<p><strong>Monads</strong></p>\n\n<p>They are not that hidden, but they are simply everywhere, even where you don't think of them (Lists, Maybe-Types) ...</p>\n" }, { "answer_id": 1088546, "author": "Dario", "author_id": 105459, "author_profile": "https://Stackoverflow.com/users/105459", "pm_score": 3, "selected": false, "text": "<p><strong>Parallel list comprehension</strong></p>\n\n<p>(Special GHC-feature)</p>\n\n<pre><code> fibs = 0 : 1 : [ a + b | a &lt;- fibs | b &lt;- tail fibs ]\n</code></pre>\n" }, { "answer_id": 1092209, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 3, "selected": false, "text": "<p><strong>Laziness</strong></p>\n\n<p>Ubiquitous laziness means you can do things like define </p>\n\n<pre><code>fibs = 1 : 1 : zipWith (+) fibs (tail fibs)\n</code></pre>\n\n<p>But it also provides us with a lot of more subtle benefits in terms of syntax and reasoning.</p>\n\n<p>For instance, due to strictness ML has to deal with the <a href=\"http://www.strangelights.com/fsharp/wiki/default.aspx/FSharpWiki/ValueRestriction.html\" rel=\"nofollow noreferrer\">value restriction</a>, and is very careful to track circular let bindings, but in Haskell, we can let every let be recursive and have no need to distinguish between <code>val</code> and <code>fun</code>. This removes a major syntactic wart from the language.</p>\n\n<p>This indirectly gives rise to our lovely <code>where</code> clause, because we can safely move computations that may or may not be used out of the main control flow and let laziness deal with sharing the results.</p>\n\n<p>We can replace (almost) all of those ML style functions that need to take () and return a value, with just a lazy computation of the value. There are reasons to avoid doing so from time to time to avoid leaking space with <a href=\"http://www.haskell.org/haskellwiki/Constant_applicative_form\" rel=\"nofollow noreferrer\">CAFs</a>, but such cases are rare.</p>\n\n<p>Finally, it permits unrestricted eta-reduction (<code>\\x -&gt; f x</code> can be replaced with f). This makes combinator oriented programming for things like parser combinators much more pleasant than working with similar constructs in a strict language.</p>\n\n<p>This helps you when reasoning about programs in point-free style, or about rewriting them into point-free style and reduces argument noise.</p>\n" }, { "answer_id": 1536510, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": 4, "selected": false, "text": "<p><code>let 5 = 6 in ...</code> is valid Haskell.</p>\n" }, { "answer_id": 1901118, "author": "beerboy", "author_id": 231299, "author_profile": "https://Stackoverflow.com/users/231299", "pm_score": 3, "selected": false, "text": "<p><strong>Enumerations</strong></p>\n\n<p>Any type which is an instance of <strong>Enum</strong> can be used in an arithmetic sequence, not just numbers:</p>\n\n<pre><code>alphabet :: String\nalphabet = ['A' .. 'Z']\n</code></pre>\n\n<p>Including your own datatypes, just derive from Enum to get a default implementation:</p>\n\n<pre><code>data MyEnum = A | B | C deriving(Eq, Show, Enum)\n\nmain = do\n print $ [A ..] -- prints \"[A,B,C]\"\n print $ map fromEnum [A ..] -- prints \"[0,1,2]\"\n</code></pre>\n" }, { "answer_id": 1901146, "author": "beerboy", "author_id": 231299, "author_profile": "https://Stackoverflow.com/users/231299", "pm_score": 4, "selected": false, "text": "<p><strong>C-Style Enumerations</strong></p>\n\n<p>Combining top-level pattern matching and arithmetic sequences gives us a handy way to define consecutive values:</p>\n\n<pre><code>foo : bar : baz : _ = [100 ..] -- foo = 100, bar = 101, baz = 102\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
What are the lesser-known but useful features of the Haskell programming language. (I understand the language itself is lesser-known, but work with me. Even explanations of the simple things in Haskell, like defining the Fibonacci sequence with one line of code, will get upvoted by me.) * Try to limit answers to the Haskell core * One feature per answer * Give an example and short description of the feature, not just a link to documentation * Label the feature using bold title as the first line
**My brain just exploded** If you try to compile this code: ``` {-# LANGUAGE ExistentialQuantification #-} data Foo = forall a. Foo a ignorefoo f = 1 where Foo a = f ``` You will get this error message: ``` $ ghc Foo.hs Foo.hs:3:22: My brain just exploded. I can't handle pattern bindings for existentially-quantified constructors. Instead, use a case-expression, or do-notation, to unpack the constructor. In the binding group for Foo a In a pattern binding: Foo a = f In the definition of `ignorefoo': ignorefoo f = 1 where Foo a = f ```
211,236
<p>Since we cannot setup Eclipse's RSE to use at the tool for remote editing, I have installed <a href="http://www.cis.upenn.edu/~bcpierce/unison/docs.html" rel="nofollow noreferrer">Unison</a>. But how can I get Eclipse to automatically run unison on every file save? Is there an eclipse plugin available for this?</p> <p>TIA</p>
[ { "answer_id": 271641, "author": "javamonkey79", "author_id": 27657, "author_profile": "https://Stackoverflow.com/users/27657", "pm_score": 3, "selected": false, "text": "<p>Depending on the importance, I would write a simple plugin to handle this. </p>\n\n<p>EDIT:\nAll you <em>really</em> need to do is this:</p>\n\n<p>1) Create the plugin from the templates with the RCP\\PDE Eclipse install<br>\n2) Add the following code to your activator...<br></p>\n\n<pre><code>@Override\npublic void start( final BundleContext context ) throws Exception {\n super.start( context );\n plugin = this;\n\n ICommandService commandService = (ICommandService)plugin.getWorkbench().getService( ICommandService.class );\n commandService.addExecutionListener( new IExecutionListener() {\n\n public void notHandled( final String commandId, final NotHandledException exception ) {}\n\n public void postExecuteFailure( final String commandId, final ExecutionException exception ) {}\n\n public void postExecuteSuccess( final String commandId, final Object returnValue ) {\n if ( commandId.equals( \"org.eclipse.ui.file.save\" ) ) {\n // add in your action here...\n // personally, I would use a custom preference page, \n // but hard coding would work ok too\n }\n }\n\n public void preExecute( final String commandId, final ExecutionEvent event ) {}\n\n } );\n}\n</code></pre>\n" }, { "answer_id": 633393, "author": "Andrey Tarantsov", "author_id": 58146, "author_profile": "https://Stackoverflow.com/users/58146", "pm_score": 3, "selected": false, "text": "<p>You can setup it to be run on every build. Any external tool can be run on every build, just open project's preferences, go to Builders page, click “New…”.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14351/" ]
Since we cannot setup Eclipse's RSE to use at the tool for remote editing, I have installed [Unison](http://www.cis.upenn.edu/~bcpierce/unison/docs.html). But how can I get Eclipse to automatically run unison on every file save? Is there an eclipse plugin available for this? TIA
Depending on the importance, I would write a simple plugin to handle this. EDIT: All you *really* need to do is this: 1) Create the plugin from the templates with the RCP\PDE Eclipse install 2) Add the following code to your activator... ``` @Override public void start( final BundleContext context ) throws Exception { super.start( context ); plugin = this; ICommandService commandService = (ICommandService)plugin.getWorkbench().getService( ICommandService.class ); commandService.addExecutionListener( new IExecutionListener() { public void notHandled( final String commandId, final NotHandledException exception ) {} public void postExecuteFailure( final String commandId, final ExecutionException exception ) {} public void postExecuteSuccess( final String commandId, final Object returnValue ) { if ( commandId.equals( "org.eclipse.ui.file.save" ) ) { // add in your action here... // personally, I would use a custom preference page, // but hard coding would work ok too } } public void preExecute( final String commandId, final ExecutionEvent event ) {} } ); } ```
211,243
<p>I have code looking something like this:</p> <pre><code>$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory $hash = md5($data); $query = "INSERT INTO some_table SET BlobData = '" . mysql_real_escape_string($data) . "', BlobHash = '$hash' "; mysql_query($query); </code></pre> <p>I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.</p> <p>Is there anything more efficient than the following solution?</p> <pre><code>$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory $hash = md5($data); $query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'"; mysql_query(sprintf($query, mysql_real_escape_string($data))); </code></pre>
[ { "answer_id": 211265, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 0, "selected": false, "text": "<p>Have you benchmarked the output buffering trick?</p>\n\n<pre><code>ob_start();\necho 'INSERT INTO some_table SET BlobData = \\'', mysql_real_escape_string( $data ), '\\', BlobHash = \\'', $hash, '\\'';\nmysql_query( ob_get_clean() );\n</code></pre>\n\n<p>Another thing you could do is convert to mysqli or MDB2, which support bound parameters. That would allow you to skip the mysql_real_escape_string call <strong>and</strong> the string concatenations.</p>\n" }, { "answer_id": 211271, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": -1, "selected": false, "text": "<p>Well if memory usage is your problem, you can read the large file in chunks and insert these chunks with CONCAT into the database field.</p>\n\n<p>Sample code (not tested):</p>\n\n<pre><code> $id = 1337;\n$h = fopen(\"path/to/file.ext\", \"r\");\nwhile (!feof($h)) \n {\n $buffer = fread($h, 4096);\n $sql = \"UPDATE table SET my_field = CONCAT(my_field, '\" . mysql_real_escape_string($buffer) . \"') WHERE Id = \" . $id;\n mysql_query($sql);\n }\n</code></pre>\n\n<p>This method will be slower but you'll require only 4Kb of your memory.</p>\n" }, { "answer_id": 211272, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 2, "selected": false, "text": "<p>If you are using PDO, and prepared statments you can use the PDO::PARAM_LOB type. See example #2 on the LOB page showing how to insert an image to a database using the file pointer.</p>\n\n<p><a href=\"http://us2.php.net/manual/en/pdo.lobs.php\" rel=\"nofollow noreferrer\">http://us2.php.net/manual/en/pdo.lobs.php</a></p>\n" }, { "answer_id": 214393, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>Would it make any difference if you didn't put the query into another variable, but instead passed it directly into the MySQL command. I've never tried this, but it may make a difference as the whole string isn't stored in another variable.</p>\n" }, { "answer_id": 214794, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 4, "selected": true, "text": "<p>You have two issues here:</p>\n\n<p>#1, there are several different ways you can compute the MD5 hash:</p>\n\n<ul>\n<li>Do as you do and load into PHP as a string and use PHP's <code>md5()</code></li>\n<li>Use PHP's <code>md5_file()</code></li>\n<li>As of PHP 5.1+ you can use PHP's streams API with either of <code>md5</code> or <code>md5_file</code> to avoid loading entirely into memory</li>\n<li>Use <code>exec()</code> to call the system's <code>md5sum</code> command</li>\n<li>Use MySQL's <code>MD5()</code> function to compute the hash</li>\n</ul>\n\n<p>Since these are all trivial to implement it would be easy for you to implement and benchmark them all for memory usage and speed. Here are <a href=\"http://www.php.net/manual/en/function.md5-file.php#81751\" rel=\"nofollow noreferrer\">some benchmarks</a> showing system md5 via <code>exec</code> to be a lot faster than PHP's <code>md5_file</code> as file size increases. Doing it your way is definitely the worst way as far as memory usage is concerned.</p>\n\n<p>#2, <code>mysql_real_escape_string</code> performs a database query, so you're actually transmitting your blob data to the database, getting it back as a string, and transmitting it again(!) with the INSERT query. So it's traveling to/from the DB server 3x instead of 1x and using 2x the memory in PHP.</p>\n\n<p>It's going to be more efficient to use <a href=\"http://devzone.zend.com/node/view/id/686#Heading11\" rel=\"nofollow noreferrer\">PHP5 prepared statements</a> and only send this data to the database once. Read the linked article section, you'll see it mentions that when you are binding parameters, you can use the blob type to stream blob data to the DB in chunks. The <a href=\"http://www.php.net/manual/en/mysqli-stmt.send-long-data.php\" rel=\"nofollow noreferrer\">PHP docs for <code>mysqli_stmt::send_long_data</code></a> have a great simple example of this that INSERTs a file into a blob column just like you are.</p>\n\n<p>By doing that, and by using either the streams API, <code>md5_file</code> or <code>exec</code> with the system md5 command, you can do your entire INSERT without ever loading the entire file into memory, which means memory usage for your series of operations can be as low as you want!</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
I have code looking something like this: ``` $data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory $hash = md5($data); $query = "INSERT INTO some_table SET BlobData = '" . mysql_real_escape_string($data) . "', BlobHash = '$hash' "; mysql_query($query); ``` I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times. Is there anything more efficient than the following solution? ``` $data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory $hash = md5($data); $query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'"; mysql_query(sprintf($query, mysql_real_escape_string($data))); ```
You have two issues here: #1, there are several different ways you can compute the MD5 hash: * Do as you do and load into PHP as a string and use PHP's `md5()` * Use PHP's `md5_file()` * As of PHP 5.1+ you can use PHP's streams API with either of `md5` or `md5_file` to avoid loading entirely into memory * Use `exec()` to call the system's `md5sum` command * Use MySQL's `MD5()` function to compute the hash Since these are all trivial to implement it would be easy for you to implement and benchmark them all for memory usage and speed. Here are [some benchmarks](http://www.php.net/manual/en/function.md5-file.php#81751) showing system md5 via `exec` to be a lot faster than PHP's `md5_file` as file size increases. Doing it your way is definitely the worst way as far as memory usage is concerned. #2, `mysql_real_escape_string` performs a database query, so you're actually transmitting your blob data to the database, getting it back as a string, and transmitting it again(!) with the INSERT query. So it's traveling to/from the DB server 3x instead of 1x and using 2x the memory in PHP. It's going to be more efficient to use [PHP5 prepared statements](http://devzone.zend.com/node/view/id/686#Heading11) and only send this data to the database once. Read the linked article section, you'll see it mentions that when you are binding parameters, you can use the blob type to stream blob data to the DB in chunks. The [PHP docs for `mysqli_stmt::send_long_data`](http://www.php.net/manual/en/mysqli-stmt.send-long-data.php) have a great simple example of this that INSERTs a file into a blob column just like you are. By doing that, and by using either the streams API, `md5_file` or `exec` with the system md5 command, you can do your entire INSERT without ever loading the entire file into memory, which means memory usage for your series of operations can be as low as you want!
211,260
<p>No extracted data output to data2.txt? What goes wrong to the code?</p> <p><strong>MyFile.txt</strong></p> <pre><code>ex1,fx2,xx1 mm1,nn2,gg3 EX1,hh2,ff7 </code></pre> <p>This is my desired output in data2.txt:</p> <pre><code>ex1,fx2,xx1 EX1,hh2,ff7 </code></pre> <p><br></p> <pre><code>#! /DATA/PLUG/pvelasco/Softwares/PERLINUX/bin/perl -w my $infile ='My1.txt'; my $outfile ='data2.txt'; open IN, '&lt;', $infile or die "Cant open $infile:$!"; open OUT, '&gt;', $outfile or die "Cant open $outfile:$!"; while (&lt;IN&gt;) { if (m/EX$HF|ex$HF/) { print OUT $_, "\n"; print $_; } } close IN; close OUT; </code></pre>
[ { "answer_id": 211269, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 1, "selected": false, "text": "<p>When I run your code, but name the input file <code>My1.txt</code> instead of <code>MyFile.txt</code> I get the desired output - except with empty lines, which you can remove by removing the <code>, \"\\n\"</code> from the print statement.</p>\n" }, { "answer_id": 211279, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 3, "selected": false, "text": "<p>This regex makes no sense:</p>\n\n<pre><code>m/EX$HF|ex$HF/\n</code></pre>\n\n<p>Is $HF supposed to be a variable? What are you trying to match? </p>\n\n<p>Also, the second line in <em>every</em> Perl script you write should be:</p>\n\n<pre><code>use strict;\n</code></pre>\n\n<p>It will make Perl catch such mistakes and tell you about them, rather than silently ignoring them.</p>\n" }, { "answer_id": 211282, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 2, "selected": false, "text": "<pre><code>while (&lt;IN&gt;) {\n if (m/^(EX|ex)\\d.*/) { \n print OUT \"$_\"; \n print $_; \n }\n}\n</code></pre>\n" }, { "answer_id": 213165, "author": "Berserk", "author_id": 26313, "author_profile": "https://Stackoverflow.com/users/26313", "pm_score": 1, "selected": false, "text": "<p>The filenames don't match.</p>\n\n<pre><code>open(my $inhandle, '&lt;', $infile) or die \"Cant open $infile: $!\";\nopen(my $outhandle, '&gt;', $outfile) or die \"Cant open $outfile: $!\";\n\nwhile(my $line = &lt;$inhandle&gt;) { \n\n # Assumes that ex, Ex, eX, EX all are valid first characters\n if($line =~ m{^ex}i) { # or if(lc(substr $line, 0 =&gt; 2) eq 'ex') {\n print { $outhandle } $line; \n print $line;\n }\n}\n</code></pre>\n\n<p>And yes, always <strong>always</strong> <em>use strict;</em></p>\n\n<p>You could also <em>chomp $line</em> and (if using perl 5.10) <em>say $line</em> instead of <em>print \"$line\\n\"</em>.</p>\n" }, { "answer_id": 214736, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 2, "selected": false, "text": "<p>Sorry if this seems like stating the bleeding obvious, but what's wrong with</p>\n\n<pre><code>grep -i ^ex &lt; My1.txt &gt; data2.txt\n</code></pre>\n\n<p>... or if you really want to do it in perl (and there's nothing wrong with that):</p>\n\n<pre><code>perl -ne '/^ex/i &amp;&amp; print' &lt; My1.txt &gt; data2.txt\n</code></pre>\n\n<p>This assumes the purpose of the request is to find lines that start with EX, with case-insensitivity.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28607/" ]
No extracted data output to data2.txt? What goes wrong to the code? **MyFile.txt** ``` ex1,fx2,xx1 mm1,nn2,gg3 EX1,hh2,ff7 ``` This is my desired output in data2.txt: ``` ex1,fx2,xx1 EX1,hh2,ff7 ``` ``` #! /DATA/PLUG/pvelasco/Softwares/PERLINUX/bin/perl -w my $infile ='My1.txt'; my $outfile ='data2.txt'; open IN, '<', $infile or die "Cant open $infile:$!"; open OUT, '>', $outfile or die "Cant open $outfile:$!"; while (<IN>) { if (m/EX$HF|ex$HF/) { print OUT $_, "\n"; print $_; } } close IN; close OUT; ```
This regex makes no sense: ``` m/EX$HF|ex$HF/ ``` Is $HF supposed to be a variable? What are you trying to match? Also, the second line in *every* Perl script you write should be: ``` use strict; ``` It will make Perl catch such mistakes and tell you about them, rather than silently ignoring them.
211,319
<p>i wonder if it is possible to cascade converters when using wpf databinding. e.g. something like </p> <pre><code>&lt;SomeControl Visibility="{Binding Path=SomeProperty, Converter={StaticResource firstConverter}, Converter={StaticResource secondConverter}}"/&gt; </code></pre> <p>is it possible at all or do i have to create a custom converter that combines the functionality of converter A and B?</p>
[ { "answer_id": 211812, "author": "Brad Leach", "author_id": 708, "author_profile": "https://Stackoverflow.com/users/708", "pm_score": 4, "selected": false, "text": "<p>You may be looking for a solution similar to Josh Smith's \"<a href=\"http://www.codeproject.com/KB/WPF/PipingValueConverters_WPF.aspx\" rel=\"noreferrer\">Piping Value Converters</a>\".</p>\n\n<p>In his article, he presents the following:</p>\n\n<pre><code>&lt;local:ValueConverterGroup x:Key=\"statusDisplayNameGroup\"&gt;\n &lt;local:IntegerStringToProcessingStateConverter /&gt;\n &lt;local:EnumToDisplayNameConverter /&gt;\n&lt;/local:ValueConverterGroup&gt; \n</code></pre>\n\n<p>And then uses the multi-value converters as follows:</p>\n\n<pre><code>&lt;TextBlock Text=\"{Binding XPath=@Status, \n Converter={StaticResource statusDisplayNameGroup}}\" /&gt;\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 211856, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 4, "selected": true, "text": "<p>You could try to use a <strong>MultiBinding</strong>, and bind twice to the same source, but with different converts on the single bindings. Something like:</p>\n\n<pre><code>&lt;SomeControl&gt;\n &lt;SomeControl.Visibility&gt;\n &lt;MultiBinding Converter=\"{StaticResource combiningConverter}\"&gt;\n &lt;Binding Path=\"SomeProperty\" Converter=\"{StaticResource firstConverter}\"/&gt;\n &lt;Binding Path=\"SomeProperty\" Converter=\"{StaticResource secondConverter}\"/&gt;\n &lt;/MultiBinding&gt;\n &lt;/SomeControl.Visibility&gt;\n&lt;/SomeControl&gt;\n</code></pre>\n\n<p>Then in '<em>combiningConverter</em>' you put the logic to combine the values coming from the two bindings.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20227/" ]
i wonder if it is possible to cascade converters when using wpf databinding. e.g. something like ``` <SomeControl Visibility="{Binding Path=SomeProperty, Converter={StaticResource firstConverter}, Converter={StaticResource secondConverter}}"/> ``` is it possible at all or do i have to create a custom converter that combines the functionality of converter A and B?
You could try to use a **MultiBinding**, and bind twice to the same source, but with different converts on the single bindings. Something like: ``` <SomeControl> <SomeControl.Visibility> <MultiBinding Converter="{StaticResource combiningConverter}"> <Binding Path="SomeProperty" Converter="{StaticResource firstConverter}"/> <Binding Path="SomeProperty" Converter="{StaticResource secondConverter}"/> </MultiBinding> </SomeControl.Visibility> </SomeControl> ``` Then in '*combiningConverter*' you put the logic to combine the values coming from the two bindings.
211,335
<p>I have a swf file that is not controlled by me. The swf expects a javascript call to set some variables after initialization. </p> <p>The swf is embedded using the swfobject and I'm trying to call the as function right after the embed. This appears to be too soon because I get an error. Everything else should be fine since calling the as function manually via firebug does not produce the error.</p> <p>So the question is how do I call the function when the embed is complete?</p>
[ { "answer_id": 211489, "author": "jcoder", "author_id": 417292, "author_profile": "https://Stackoverflow.com/users/417292", "pm_score": 1, "selected": false, "text": "<p>Are you doing this while the page is still loading? Or from am onload handler?\nIf it's inline javascript I would suggest doing it in the onload handler from javascript which you can do like this -</p>\n\n<pre><code>window.onload = function() {\n // your code here \n}\n</code></pre>\n\n<p>it will run your code once the page is fully loaded.</p>\n\n<p>This doesn't guarentee that the flash is initialised though. You could do that by having the flash make a callback to javascript once it is ready, but you said that the swf is not in your control. All I can really think of us using the onload method to make sure the page is finished loading, and then insert a short delay before trying to use it. Look at the setTimeout javascript function for that. Not a great solution though.</p>\n" }, { "answer_id": 217690, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 0, "selected": false, "text": "<p>I <a href=\"http://www.idealog.us/2007/02/check_if_a_java.html\" rel=\"nofollow noreferrer\">found some code</a> for checking whether the function exists yet. In summary:</p>\n\n<pre><code>if (typeof yourFunctionName == 'function') {\n yourFunctionName();\n}\n</code></pre>\n\n<p>Does that work for you? If it does then you can just wrap in a <code>while</code> loop. A bit less nasty than a setTimeOut!</p>\n" }, { "answer_id": 2956719, "author": "Fenton", "author_id": 75525, "author_profile": "https://Stackoverflow.com/users/75525", "pm_score": 0, "selected": false, "text": "<p>When integrating Flash and HTML / JavaScript, there are several common approaches, which have been designed to eliminate this problem.</p>\n\n<ol>\n<li><p>Pass in the variables as flashvars. They will be available to the flash movie immediately.</p></li>\n<li><p>When the flash has loaded, it should call out to your page, normally there is a contract that defines the methods you can / must implement for the flash movie to call. For example, it would state that it will call <code>MovieLoaded()</code> when the flash file has loaded, and you could then put any scripts dependent on the movie being loaded within this method...</p>\n\n<pre><code>function MovieLoaded() {\n doSomething();\n}\n</code></pre></li>\n</ol>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22673/" ]
I have a swf file that is not controlled by me. The swf expects a javascript call to set some variables after initialization. The swf is embedded using the swfobject and I'm trying to call the as function right after the embed. This appears to be too soon because I get an error. Everything else should be fine since calling the as function manually via firebug does not produce the error. So the question is how do I call the function when the embed is complete?
Are you doing this while the page is still loading? Or from am onload handler? If it's inline javascript I would suggest doing it in the onload handler from javascript which you can do like this - ``` window.onload = function() { // your code here } ``` it will run your code once the page is fully loaded. This doesn't guarentee that the flash is initialised though. You could do that by having the flash make a callback to javascript once it is ready, but you said that the swf is not in your control. All I can really think of us using the onload method to make sure the page is finished loading, and then insert a short delay before trying to use it. Look at the setTimeout javascript function for that. Not a great solution though.
211,345
<p>To use <a href="http://en.wikipedia.org/wiki/Modular_exponentiation" rel="noreferrer">modular exponentiation</a> as you would require when using the <a href="http://en.wikipedia.org/wiki/Fermat_primality_test" rel="noreferrer">Fermat Primality Test</a> with large numbers (100,000+), it calls for some very large calculations.</p> <p>When I multiply two large numbers (eg: 62574 and 62574) PHP seems to cast the result to a float. Getting the modulus value of that returns strange values.</p> <pre><code>$x = 62574 * 62574; var_dump($x); // float(3915505476) ... correct var_dump($x % 104659); // int(-72945) ... wtf. </code></pre> <p>Is there any way to make PHP perform these calculations properly? Alternatively, is there another method for finding modulus values that would work for large numbers?</p>
[ { "answer_id": 211365, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 2, "selected": false, "text": "<p>I suggest you try <a href=\"http://pear.php.net/package/Math_BigInteger\" rel=\"nofollow noreferrer\">BigInteger</a>. If that doesn't work out, you may use <a href=\"http://www.swig.org/\" rel=\"nofollow noreferrer\">SWIG</a> to add C/C++ code for the big integer calculations and link it into your code.</p>\n" }, { "answer_id": 211371, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": false, "text": "<p>have you taken a look at <a href=\"http://php.net/manual/en/function.bcmod.php\" rel=\"noreferrer\"><code>bcmod()</code></a>? php has issues with integers over 2^31 - 1 on 32 bit platforms.</p>\n\n<pre><code>var_dump(bcmod(\"$x\", '104659') ); // string(4) \"2968\"\n</code></pre>\n" }, { "answer_id": 211548, "author": "Ivan Krechetov", "author_id": 6430, "author_profile": "https://Stackoverflow.com/users/6430", "pm_score": 7, "selected": true, "text": "<p>For some reason, there are two standard libraries in PHP handling the arbitrary length/precision numbers: <a href=\"http://www.php.net/manual/en/book.bc.php\" rel=\"noreferrer\">BC Math</a> and <a href=\"http://www.php.net/manual/en/book.gmp.php\" rel=\"noreferrer\">GMP</a>. I personally prefer GMP, as it's fresher and has richer API.</p>\n\n<p>Based on GMP I've implemented <a href=\"https://github.com/ikr/money-math-php\" rel=\"noreferrer\">Decimal2 class</a> for storing and processing currency amounts (like USD 100.25). <em>A lot</em> of mod calculations there w/o any problems. Tested with <em>very</em> large numbers.</p>\n" }, { "answer_id": 6027015, "author": "K.Sya", "author_id": 756824, "author_profile": "https://Stackoverflow.com/users/756824", "pm_score": 6, "selected": false, "text": "<p>use this</p>\n\n<pre><code> $num1 = \"123456789012345678901234567890\";\n $num2 = \"9876543210\";\n $r = mysql_query(\"Select @sum:=$num1 + $num2\");\n $sumR = mysql_fetch_row($r);\n $sum = $sumR[0];\n</code></pre>\n" }, { "answer_id": 12435667, "author": "bob", "author_id": 1088866, "author_profile": "https://Stackoverflow.com/users/1088866", "pm_score": 2, "selected": false, "text": "<pre><code>$x = 62574 * 62574;\n\n// Cast to an integer\n$asInt = intval($x);\nvar_dump($asInt);\nvar_dump($asInt % 104659);\n\n// Use use sprintf to convert to integer (%d), which will casts to string\n$asIntStr = sprintf('%d', $x);\nvar_dump($asIntStr);\nvar_dump($asIntStr % 104659);\n</code></pre>\n" }, { "answer_id": 21509321, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I found another solution, but the number will be stored as a string. As soon as you cast it back to a numeric, you'll be restricted to the precision of the underlying platform. On a 32 bit platform, the largest int you can represent as an int type is 2,147,483,647:</p>\n<pre><code>/**\n * @param string $a\n * @param string $b\n * @return string\n */\nfunction terminal_add($a,$b)\n{\n exec('echo &quot;'.$a.'+'.$b.'&quot;|bc',$result);\n $ret = &quot;&quot;;\n foreach($result as $line) $ret .= str_replace(&quot;\\\\&quot;,&quot;&quot;,$line);\n return $ret;\n}\n\n// terminal_add(&quot;123456789012345678901234567890&quot;, &quot;9876543210&quot;)\n// output: &quot;123456789012345678911111111100&quot;\n</code></pre>\n" }, { "answer_id": 30286733, "author": "gauravparmar", "author_id": 3700385, "author_profile": "https://Stackoverflow.com/users/3700385", "pm_score": 2, "selected": false, "text": "<p>I wrote a very small code for you that will surely work in case of big numbers-</p>\n\n<pre><code>&lt;?php\n $x = gmp_strval(gmp_mul(\"62574\",\"62574\")); // $x=\"3915505476\"\n $mod=gmp_strval(gmp_mod($x,\"104659\")); //$mod=\"2968\"\n\n echo \"x : \".$x.\"&lt;br&gt;\";\n echo \"mod : \".$mod;\n\n /* Output:\n x : 3915505476\n mod : 2968\n */\n?&gt;\n</code></pre>\n\n<p>You simply have to use strings for storing big numbers and to operate on them use GMP functions in PHP.</p>\n\n<p>You may check some good GMP functions in the official PHP manual here-\n<a href=\"http://php.net/manual/en/ref.gmp.php\" rel=\"nofollow\">http://php.net/manual/en/ref.gmp.php</a></p>\n" }, { "answer_id": 58050412, "author": "Mrigank Shekhar", "author_id": 12103098, "author_profile": "https://Stackoverflow.com/users/12103098", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;?php\nfunction add($int1,$int2){\n $int1 = str_pad($int1, strlen($int2), '0', STR_PAD_LEFT);\n $int2 = str_pad($int2, strlen($int1), '0', STR_PAD_LEFT);\n $carry = 0;\n $str = \"\";\n for($i=strlen($int1);$i&gt;0;$i--){\n $var = $int1[$i-1] + $int2[$i-1] + $carry;\n $var = str_pad($var, 2, '0', STR_PAD_LEFT);\n $var = (string) $var;\n $carry = $var[0];\n $str = $str . $var[1];\n }\n $res = strrev($str.$carry);\n echo ltrim($res,\"0\");\n}\nadd($int1,$int2);\n?&gt;\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
To use [modular exponentiation](http://en.wikipedia.org/wiki/Modular_exponentiation) as you would require when using the [Fermat Primality Test](http://en.wikipedia.org/wiki/Fermat_primality_test) with large numbers (100,000+), it calls for some very large calculations. When I multiply two large numbers (eg: 62574 and 62574) PHP seems to cast the result to a float. Getting the modulus value of that returns strange values. ``` $x = 62574 * 62574; var_dump($x); // float(3915505476) ... correct var_dump($x % 104659); // int(-72945) ... wtf. ``` Is there any way to make PHP perform these calculations properly? Alternatively, is there another method for finding modulus values that would work for large numbers?
For some reason, there are two standard libraries in PHP handling the arbitrary length/precision numbers: [BC Math](http://www.php.net/manual/en/book.bc.php) and [GMP](http://www.php.net/manual/en/book.gmp.php). I personally prefer GMP, as it's fresher and has richer API. Based on GMP I've implemented [Decimal2 class](https://github.com/ikr/money-math-php) for storing and processing currency amounts (like USD 100.25). *A lot* of mod calculations there w/o any problems. Tested with *very* large numbers.
211,348
<p>I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.</p> <p>However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:</p> <pre><code>[System.Web.Script.Services.ScriptService] public class _default : System.Web.Services.WebService { [WebMethod] [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)] public string[] UserDetails() { return new string[] { "abc", "def" }; } } </code></pre>
[ { "answer_id": 211671, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 6, "selected": true, "text": "<p>From <a href=\"http://forums.asp.net/p/1327142/2652827.aspx\" rel=\"noreferrer\">WebService returns XML even when ResponseFormat set to JSON</a>:</p>\n<blockquote>\n<p>Make sure that the request is a POST request, not a GET. Scott Guthrie has a <a href=\"http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx\" rel=\"noreferrer\">post explaining why</a>.</p>\n<p>Though it's written specifically for jQuery, this may also be useful to you:<br />\n<a href=\"http://web.archive.org/web/20160424034823/http://encosia.com/using-jquery-to-consume-aspnet-json-web-services\" rel=\"noreferrer\">Using jQuery to Consume ASP.NET JSON Web Services</a></p>\n</blockquote>\n" }, { "answer_id": 211676, "author": "bitsprint", "author_id": 9948, "author_profile": "https://Stackoverflow.com/users/9948", "pm_score": 2, "selected": false, "text": "<p>Are you calling the web service from client script or on the server side?</p>\n\n<p>You may find sending a content type header to the server will help, e.g. </p>\n\n<p>'application/json; charset=utf-8'</p>\n\n<p>On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.</p>\n" }, { "answer_id": 223546, "author": "Astra", "author_id": 5862, "author_profile": "https://Stackoverflow.com/users/5862", "pm_score": 3, "selected": false, "text": "<p>A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.</p>\n\n<p>Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the <a href=\"http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/\" rel=\"noreferrer\">3 Mistakes To Avoid When Using jQuery</a> article was very enlightening - its from the same website mentioned in another answer here).</p>\n" }, { "answer_id": 10214090, "author": "marc", "author_id": 12260, "author_profile": "https://Stackoverflow.com/users/12260", "pm_score": 4, "selected": false, "text": "<p>This is probably old news by now, but the magic seems to be:</p>\n\n<ul>\n<li>[ScriptService] attribute on web service class</li>\n<li>[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] on method</li>\n<li>Content-type: application/json in request</li>\n</ul>\n\n<p>With those pieces in place, a GET request is successful.</p>\n\n<p>For a HTTP POST</p>\n\n<ul>\n<li>[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] on method</li>\n</ul>\n\n<p>and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):</p>\n\n<pre><code> $.ajax({\n url: \"MyWebService.asmx/MethodName\",\n type: \"POST\",\n contentType: \"application/json\",\n data: JSON.stringify({ searchString: q }),\n success: function (response) { \n },\n error: function (jqXHR, textStatus, errorThrown) {\n alert(textStatus + \": \" + jqXHR.responseText);\n }\n });\n</code></pre>\n" }, { "answer_id": 12359207, "author": "Kevin", "author_id": 345606, "author_profile": "https://Stackoverflow.com/users/345606", "pm_score": 2, "selected": false, "text": "<p>Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON. </p>\n\n<p>I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.</p>\n" }, { "answer_id": 13511873, "author": "iCorrect", "author_id": 1844892, "author_profile": "https://Stackoverflow.com/users/1844892", "pm_score": 6, "selected": false, "text": "<p>To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the <code>HttpResponse</code> and change the <code>WebMethod</code> return type to <code>void</code>.</p>\n\n<pre><code> [System.Web.Script.Services.ScriptService]\n public class WebServiceClass : System.Web.Services.WebService {\n [WebMethod]\n public void WebMethodName()\n {\n HttpContext.Current.Response.Write(\"{property: value}\");\n }\n }\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56/" ]
I created an ASMX file with a code behind file. It's working fine, but it is outputting XML. However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is: ``` [System.Web.Script.Services.ScriptService] public class _default : System.Web.Services.WebService { [WebMethod] [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)] public string[] UserDetails() { return new string[] { "abc", "def" }; } } ```
From [WebService returns XML even when ResponseFormat set to JSON](http://forums.asp.net/p/1327142/2652827.aspx): > > Make sure that the request is a POST request, not a GET. Scott Guthrie has a [post explaining why](http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx). > > > Though it's written specifically for jQuery, this may also be useful to you: > > [Using jQuery to Consume ASP.NET JSON Web Services](http://web.archive.org/web/20160424034823/http://encosia.com/using-jquery-to-consume-aspnet-json-web-services) > > >
211,353
<p>I'm porting an application from Crystal Reports 8 to Crystal Reports XI in Delphi 5, using the RDC/ActiveX interface.</p> <p>In Crystal Reports 8, I was able to bring up the crystal reports default report viewer window for a report like so:</p> <pre><code>RptInvoicing.Destination := 0; // To: window RptInvoicing.Action := 1; // Execute </code></pre> <p>However, this does not fly with CR XI. Printing and exporting I've figured out to work like this:</p> <pre><code>crReport.PrintOut(True); ... crReport.Export(True); </code></pre> <p>But I haven't been able to find anything relevant to show the default preview window. I've tried implementing my own using the report viewer component, but it has a lot of problems like locking up when resizing, freezing and crashes, so it's not a viable solution for a production app.</p> <p>Even the official support forums weren't of help, I only got a nasty answer to go look at the manuals, which I've been through several times and can only refer to as bad. It's not every day you see such bad documentation for an enterprise product. I found nothing relevant to this in their manuals, so I'm led to think their own staff have no idea about this either.</p> <p>So I'm hoping someone here could tell me if the default report viewer still exists in CR XI, and if it does, how to invoke it? If it doesn't, is using the report designer component really the only solution to create one?</p>
[ { "answer_id": 255130, "author": "Arvo", "author_id": 35777, "author_profile": "https://Stackoverflow.com/users/35777", "pm_score": 0, "selected": false, "text": "<p>I can't say anything about Delphi, but in VB we are using CRViewer ActiveX Control. Using it is straightforward - you put viewer control on form and assign RDC object to it. This is covered in CR help somewhere. (I can't look at code ATM to provide working exmples.)</p>\n" }, { "answer_id": 334225, "author": "GregD", "author_id": 38317, "author_profile": "https://Stackoverflow.com/users/38317", "pm_score": 1, "selected": false, "text": "<p>From their documentation:</p>\n<blockquote>\n<p>Craxddrt.dll (Crystal Reports ActiveX\nDesigner Design and Runtime Library)\nis a unified object model that\ncombines the runtime capabilities of\nthe Craxdrt.dll (Crystal Reports\nActiveX Designer Run Time Library)\nwith the design time capabilities of\nthe Craxddt.dll (Crystal Reports\nActiveX Designer Design Time Library).\nCraxddrt.dll will replace Craxddt.dll\nfor versions 8.5 and up. Both the\nCraxddrt.dll and the Craxdrt.dll\ncontain all the objects and associated\nmethods, properties, and events needed\nfor creating, opening, exporting,\nsaving, and printing a report at run\ntime. In addition, Craxddrt.dll is\neither used with the RDC ActiveX\nDesigner when designing reports at\ndesign time, or used with the\nEmbeddable Designer when designing\nreports at run time. See “Embeddable\nCrystal Reports Designer Control\nObject Model” on page 343 for more\ninformation.</p>\n<p><strong>Note: The RDC ActiveX</strong>\n<strong>Designer is only available in</strong>\n<strong>Microsoft Visual Basic</strong>.</p>\n<p>Prior to\nversion 8.5, the Craxdrt.dll would be\ndistributed with an application. Now\nthe developer has a choice of two\nautomation servers to distribute.\nCraxdrt.dll is backwards-compatible\nwith previous versions and contains\nall the features introduced in this\nversion. Use the Craxdrt.dll for any\nclient-side application that does not\ncontain the Embeddable Designer, or\nuse it for any server-side\napplication. Craxddrt.dll is\napartment-model threaded, but is not\nthread safe, and can only be used in a\nclient-side application. Although the\nCraxddrt.dll is a fully functional\nautomation server for the RDC, and can\nwork in any client-side application,\nit will increase the install size.\nTherefore, it is recommended that you\nonly use Craxddrt.dll with the\nEmbeddable Crystal Reports Designer\nControl.</p>\n</blockquote>\n" }, { "answer_id": 381427, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "<p>I recently had the same problem, and <a href=\"https://stackoverflow.com/questions/378089/how-can-i-display-crystal-xi-reports-inside-a-delphi-2007-application#378099\">described the solution here</a>. I am using Delphi 2007, but since the code involves calls to an external ActiveX DLL, it should work for you too.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15477/" ]
I'm porting an application from Crystal Reports 8 to Crystal Reports XI in Delphi 5, using the RDC/ActiveX interface. In Crystal Reports 8, I was able to bring up the crystal reports default report viewer window for a report like so: ``` RptInvoicing.Destination := 0; // To: window RptInvoicing.Action := 1; // Execute ``` However, this does not fly with CR XI. Printing and exporting I've figured out to work like this: ``` crReport.PrintOut(True); ... crReport.Export(True); ``` But I haven't been able to find anything relevant to show the default preview window. I've tried implementing my own using the report viewer component, but it has a lot of problems like locking up when resizing, freezing and crashes, so it's not a viable solution for a production app. Even the official support forums weren't of help, I only got a nasty answer to go look at the manuals, which I've been through several times and can only refer to as bad. It's not every day you see such bad documentation for an enterprise product. I found nothing relevant to this in their manuals, so I'm led to think their own staff have no idea about this either. So I'm hoping someone here could tell me if the default report viewer still exists in CR XI, and if it does, how to invoke it? If it doesn't, is using the report designer component really the only solution to create one?
I recently had the same problem, and [described the solution here](https://stackoverflow.com/questions/378089/how-can-i-display-crystal-xi-reports-inside-a-delphi-2007-application#378099). I am using Delphi 2007, but since the code involves calls to an external ActiveX DLL, it should work for you too.
211,355
<p>A while ago I had a query that I ran quite a lot for one of my users. It was still being evolved and tweaked but eventually it stablised and ran quite quickly, so we created a stored procedure from it. </p> <p>So far, so normal. </p> <p>The stored procedure, though, was dog slow. No material difference between the query and the proc, but the speed change was massive. </p> <p>[Background, we're running SQL Server 2005.]</p> <p>A friendly local DBA (who no longer works here) took one look at the stored procedure and said "parameter spoofing!" (<strong>Edit:</strong> although it seems that it is possibly also known as 'parameter sniffing', which might explain the paucity of Google hits when I tried to search it out.) </p> <p>We abstracted some of the stored procedure to a second one, wrapped the call to this new inner proc into the pre-existing outer one, called the outer one and, hey presto, it was as quick as the original query. </p> <p>So, what gives? Can someone explain parameter spoofing? </p> <p>Bonus credit for </p> <ul> <li>highlighting how to avoid it </li> <li>suggesting how to recognise possible cause</li> <li>discuss alternative strategies, e.g. stats, indices, keys, for mitigating the situation</li> </ul>
[ { "answer_id": 211847, "author": "nkav", "author_id": 6828, "author_profile": "https://Stackoverflow.com/users/6828", "pm_score": 5, "selected": false, "text": "<p>Yes, I think you mean parameter sniffing, which is a technique the SQL Server optimizer uses to try to figure out parameter values/ranges so it can choose the best execution plan for your query. In some instances SQL Server does a poor job at parameter sniffing &amp; doesn't pick the best execution plan for the query.</p>\n\n<p>I believe this blog article <a href=\"http://blogs.msdn.com/queryoptteam/archive/2006/03/31/565991.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/queryoptteam/archive/2006/03/31/565991.aspx</a> has a good explanation.</p>\n\n<p>It seems that the DBA in your example chose option #4 to move the query to another sproc to a separate procedural context.</p>\n\n<p>You could have also used the <em>with recompile</em> on the original sproc or used the <em>optimize for</em> option on the parameter.</p>\n" }, { "answer_id": 215785, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 5, "selected": false, "text": "<p>A simple way to speed that up is to reassign the input parameters to local parameters in the very beginning of the sproc, e.g.</p>\n\n<pre><code>CREATE PROCEDURE uspParameterSniffingAvoidance\n @SniffedFormalParameter int\nAS\nBEGIN\n\n DECLARE @SniffAvoidingLocalParameter int\n SET @SniffAvoidingLocalParameter = @SniffedFormalParameter\n\n --Work w/ @SniffAvoidingLocalParameter in sproc body \n -- ...\n</code></pre>\n" }, { "answer_id": 215861, "author": "Brent Ozar", "author_id": 26837, "author_profile": "https://Stackoverflow.com/users/26837", "pm_score": 7, "selected": true, "text": "<p>FYI - you need to be aware of something else when you're working with SQL 2005 and stored procs with parameters.</p>\n\n<p>SQL Server will compile the stored proc's execution plan with the first parameter that's used. So if you run this:</p>\n\n<pre><code>usp_QueryMyDataByState 'Rhode Island'\n</code></pre>\n\n<p>The execution plan will work best with a small state's data. But if someone turns around and runs:</p>\n\n<pre><code>usp_QueryMyDataByState 'Texas'\n</code></pre>\n\n<p>The execution plan designed for Rhode-Island-sized data may not be as efficient with Texas-sized data. This can produce surprising results when the server is restarted, because the newly generated execution plan will be targeted at whatever parameter is used first - not necessarily the best one. The plan won't be recompiled until there's a big reason to do it, like if statistics are rebuilt.</p>\n\n<p>This is where query plans come in, and SQL Server 2008 offers a lot of new features that help DBAs pin a particular query plan in place long-term no matter what parameters get called first.</p>\n\n<p>My concern is that when you rebuilt your stored proc, you forced the execution plan to recompile. You called it with your favorite parameter, and then of course it was fast - but the problem may not have been the stored proc. It might have been that the stored proc was recompiled at some point with an unusual set of parameters and thus, an inefficient query plan. You might not have fixed anything, and you might face the same problem the next time the server restarts or the query plan gets recompiled.</p>\n" }, { "answer_id": 225015, "author": "Jan", "author_id": 25727, "author_profile": "https://Stackoverflow.com/users/25727", "pm_score": 3, "selected": false, "text": "<p>Parameter sniffing is a technique SQL Server uses to optimize the query execution plan for a stored procedure. When you first call the stored procedure, SQL Server looks at the given parameter values of your call and decides which indices to use based on the parameter values.</p>\n\n<p>So when the first call contains not very typical parameters, SQL Server might select and store a sub-optimal execution plan in regard to the following calls of the stored procedure.</p>\n\n<p>You can work around this by either </p>\n\n<ul>\n<li>using <code>WITH RECOMPILE</code></li>\n<li>copying the parameter values to local variables inside the stored procedure and using the locals in your queries.</li>\n</ul>\n\n<p>I even heard that it's better to not use stored procedures at all but to send your queries directly to the server.\nI recently came across the same problem where I have no real solution yet.\nFor some queries the copy to local vars helps getting back to the right execution plan, for some queries performance degrades with local vars.</p>\n\n<p>I still have to do more research on how SQL Server caches and reuses (sub-optimal) execution plans.</p>\n" }, { "answer_id": 4129375, "author": "Sadhir", "author_id": 498732, "author_profile": "https://Stackoverflow.com/users/498732", "pm_score": 3, "selected": false, "text": "<p>In my experience, the best solution for parameter sniffing is 'Dynamic SQL'. Two important things to note is that 1. you should use parameters in your dynamic sql query 2. you should use sp_executesql (and not sp_execute), which saves the execution plan for each parameter values</p>\n" }, { "answer_id": 11524368, "author": "katlego.nkosi", "author_id": 1532058, "author_profile": "https://Stackoverflow.com/users/1532058", "pm_score": -1, "selected": false, "text": "<p>Changing your store procedure to execute as a batch should increase the speed.</p>\n\n<p>Batch file select i.e.: </p>\n\n<pre><code>exec ('select * from order where order id ='''+ @ordersID')\n</code></pre>\n\n<p>Instead of the normal stored procedure select:</p>\n\n<pre><code>select * from order where order id = @ordersID\n</code></pre>\n\n<p>Just pass in the parameter as <code>nvarchar</code> and you should get quicker results.</p>\n" }, { "answer_id": 15637607, "author": "Khuzaima Shajapurwala", "author_id": 2211645, "author_profile": "https://Stackoverflow.com/users/2211645", "pm_score": 0, "selected": false, "text": "<p>I had similar problem. My stored procedure's execution plan took 30-40 seconds. I tried using the SP Statements in query window and it took few ms to execute the same. \nThen I worked out declaring local variables within stored procedure and transferring the values of parameters to local variables. This made the SP execution very fast and now the same SP executes within few milliseconds instead of 30-40 seconds.</p>\n" }, { "answer_id": 32148375, "author": "Anvesh", "author_id": 2281778, "author_profile": "https://Stackoverflow.com/users/2281778", "pm_score": -1, "selected": false, "text": "<p>Very simple and sort, Query optimizer use old query plan for frequently running queries. but actually the size of data is also increasing so at that time new optimized plan is require and still query optimizer using old plan of query. This is called Parameter Sniffing. \nI have also created detailed post on this. Please visit this url:\n<a href=\"http://www.dbrnd.com/2015/05/sql-server-parameter-sniffing/\" rel=\"nofollow\">http://www.dbrnd.com/2015/05/sql-server-parameter-sniffing/</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2902/" ]
A while ago I had a query that I ran quite a lot for one of my users. It was still being evolved and tweaked but eventually it stablised and ran quite quickly, so we created a stored procedure from it. So far, so normal. The stored procedure, though, was dog slow. No material difference between the query and the proc, but the speed change was massive. [Background, we're running SQL Server 2005.] A friendly local DBA (who no longer works here) took one look at the stored procedure and said "parameter spoofing!" (**Edit:** although it seems that it is possibly also known as 'parameter sniffing', which might explain the paucity of Google hits when I tried to search it out.) We abstracted some of the stored procedure to a second one, wrapped the call to this new inner proc into the pre-existing outer one, called the outer one and, hey presto, it was as quick as the original query. So, what gives? Can someone explain parameter spoofing? Bonus credit for * highlighting how to avoid it * suggesting how to recognise possible cause * discuss alternative strategies, e.g. stats, indices, keys, for mitigating the situation
FYI - you need to be aware of something else when you're working with SQL 2005 and stored procs with parameters. SQL Server will compile the stored proc's execution plan with the first parameter that's used. So if you run this: ``` usp_QueryMyDataByState 'Rhode Island' ``` The execution plan will work best with a small state's data. But if someone turns around and runs: ``` usp_QueryMyDataByState 'Texas' ``` The execution plan designed for Rhode-Island-sized data may not be as efficient with Texas-sized data. This can produce surprising results when the server is restarted, because the newly generated execution plan will be targeted at whatever parameter is used first - not necessarily the best one. The plan won't be recompiled until there's a big reason to do it, like if statistics are rebuilt. This is where query plans come in, and SQL Server 2008 offers a lot of new features that help DBAs pin a particular query plan in place long-term no matter what parameters get called first. My concern is that when you rebuilt your stored proc, you forced the execution plan to recompile. You called it with your favorite parameter, and then of course it was fast - but the problem may not have been the stored proc. It might have been that the stored proc was recompiled at some point with an unusual set of parameters and thus, an inefficient query plan. You might not have fixed anything, and you might face the same problem the next time the server restarts or the query plan gets recompiled.
211,369
<p>I'm writing a MFC app that uses the MS Mappoint OCX. I need to display the locations of people and vehicles on the map and the best of doing this appears to be with Pushpin objects. I have no problem displaying a stock pushpin icon with some text but want to change the icon to a custom designed one. From the limited amount of Mappoint programming info out there it appears the way to do this is to create a symbol object from a symbols object then assign this to a pushpin like this ..</p> <pre><code>CSymbols symbols; CSymbol symbol; symbol=symbols.Add("c:/temp/myicon.ico"); pushpin.put_Symbol(symbol.get_ID()); </code></pre> <p>But the program crashes with a unhandled exception on the symbols.add instruction.</p> <p>Can anyone tell me what I am doing wrong here ? or am I on totally the wrong track ?</p> <p>Thanks for your time</p> <p>Ian</p>
[ { "answer_id": 221651, "author": "IanW", "author_id": 3875, "author_profile": "https://Stackoverflow.com/users/3875", "pm_score": 2, "selected": false, "text": "<p>I found the solution to this one myself. The following code works ..</p>\n\n<pre><code>CSymbols symbols;\nCSymbol symbol;\n\nsymbols=map.get_Symbols();\nsymbol=symbols.Add(\"c:/temp/myicon.ico\");\npushpin.put_Symbol(symbol.get_ID());\n</code></pre>\n\n<p>Where map is the Mappoint control.</p>\n" }, { "answer_id": 4777737, "author": "winwaed", "author_id": 481927, "author_profile": "https://Stackoverflow.com/users/481927", "pm_score": 0, "selected": false, "text": "<p>So it looks like your error was that the symbols collection had not been created: so yes of course it will throw an exception.</p>\n\n<p>As you have found, the symbols collection can be accessed using the Symbols property on your MapPoint.Map object.</p>\n\n<p>All this is in the MapPoint reference, but it is primarily in the reference form with few tutorials. Websites such as <a href=\"http://www.mp2kmag.com\" rel=\"nofollow\">http://www.mp2kmag.com</a> , <a href=\"http://www.mapforums.com\" rel=\"nofollow\">http://www.mapforums.com</a> , and <a href=\"http://www.mapping-tools.com/howto/\" rel=\"nofollow\">http://www.mapping-tools.com/howto/</a> are a good start to find out more.</p>\n\n<p>(Full Disclosure: the last site is mine, information is in the \"howto\" path, whilst the rest of the site is commercial in nature)</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3875/" ]
I'm writing a MFC app that uses the MS Mappoint OCX. I need to display the locations of people and vehicles on the map and the best of doing this appears to be with Pushpin objects. I have no problem displaying a stock pushpin icon with some text but want to change the icon to a custom designed one. From the limited amount of Mappoint programming info out there it appears the way to do this is to create a symbol object from a symbols object then assign this to a pushpin like this .. ``` CSymbols symbols; CSymbol symbol; symbol=symbols.Add("c:/temp/myicon.ico"); pushpin.put_Symbol(symbol.get_ID()); ``` But the program crashes with a unhandled exception on the symbols.add instruction. Can anyone tell me what I am doing wrong here ? or am I on totally the wrong track ? Thanks for your time Ian
I found the solution to this one myself. The following code works .. ``` CSymbols symbols; CSymbol symbol; symbols=map.get_Symbols(); symbol=symbols.Add("c:/temp/myicon.ico"); pushpin.put_Symbol(symbol.get_ID()); ``` Where map is the Mappoint control.
211,376
<p>I've got a big big code base that includes two main namespaces: the engine and the application. </p> <p>The engine defines a vector3 class as a typedef of another vector3 class, with equality operators that sit in the engine namespace, not in the vector3 class. I added a class to the application that also had equality operators in the application namespace. </p> <p>When I tried to compile, unrelated but near-by vector3 comparisons failed because it couldn't find an appropriate equality operator. I suspected I was causing a conflict so moved my equality operators into the class I added, and the compile succeeded.</p> <pre><code>// engine.h namespace Engine { class Vector3Impl { ... }; typedef Vector3Impl Vector3; bool operator==(Vector3 const &amp;lhs, Vector3 const &amp;rhs) { ... } } // myfile.cpp #include "engine.h" namespace application { class MyClass { ... }; bool operator==(MyClass const &amp;lhs, MyClass const &amp;rhs) { ... } void myFunc(...) { if ( myClassA == myClassB ) { ... } // builds } void anotherFunc(...) { Engine::Vector3 a, b; ... if ( a == b ) { ... } // fails } } </code></pre> <p>However after thinking about it I can't see why the compile failed. There are no implicit conversions from vector3s to my class or vice-versa, and argument-dependent look-up should be pulling in the equality operator from the engine namespace and matching it.</p> <p>I've tried reproducing this bug in a sample C++ project but that refuses to break. There must be something in the big big code base that is causing this problem, but I'm not sure where to start looking. Something like the opposite of a rogue "using Engine"? Anyone got any ideas?</p>
[ { "answer_id": 211386, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": -1, "selected": false, "text": "<pre><code>bool operator==(Vector3 const &amp;lhs, Vector3 const &amp;rhs) { ... }\n</code></pre>\n\n<p>The canonical definition of an equality operator defined on a class should only have one argument, namely the rhs. The lhs is this.\nDon't know if this would be a solution to your problem though.</p>\n\n<p>This is what I would write :</p>\n\n<p>class Vector3 {\n bool operator==( const Vector3 &amp; rhs) const { ... } \n};</p>\n" }, { "answer_id": 211417, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "<p>I once ran into the same problem with a compiler that didn't have Argument Dependent Lookup (Koenig Lookup - thanks @igor) (VC6 I think). This means that when it sees an operator, it just looks in the enclosing namespaces.</p>\n\n<p>So can you tell us what compiler you use?</p>\n\n<p>Moving to another compiler solved it.</p>\n\n<p>Very inconvenient indeed.</p>\n" }, { "answer_id": 211419, "author": "Igor Semenov", "author_id": 11401, "author_profile": "https://Stackoverflow.com/users/11401", "pm_score": 3, "selected": true, "text": "<p>C++ Standard, 3.4.4.2 declares:</p>\n\n<blockquote>\n <p>For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero\n or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of\n the function arguments (and the namespace of any template template argument). <strong>Typedef names and using-declarations\n used to specify the types do not contribute to this set</strong>.</p>\n</blockquote>\n\n<p>ADL doesn't work with typedef's.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11801/" ]
I've got a big big code base that includes two main namespaces: the engine and the application. The engine defines a vector3 class as a typedef of another vector3 class, with equality operators that sit in the engine namespace, not in the vector3 class. I added a class to the application that also had equality operators in the application namespace. When I tried to compile, unrelated but near-by vector3 comparisons failed because it couldn't find an appropriate equality operator. I suspected I was causing a conflict so moved my equality operators into the class I added, and the compile succeeded. ``` // engine.h namespace Engine { class Vector3Impl { ... }; typedef Vector3Impl Vector3; bool operator==(Vector3 const &lhs, Vector3 const &rhs) { ... } } // myfile.cpp #include "engine.h" namespace application { class MyClass { ... }; bool operator==(MyClass const &lhs, MyClass const &rhs) { ... } void myFunc(...) { if ( myClassA == myClassB ) { ... } // builds } void anotherFunc(...) { Engine::Vector3 a, b; ... if ( a == b ) { ... } // fails } } ``` However after thinking about it I can't see why the compile failed. There are no implicit conversions from vector3s to my class or vice-versa, and argument-dependent look-up should be pulling in the equality operator from the engine namespace and matching it. I've tried reproducing this bug in a sample C++ project but that refuses to break. There must be something in the big big code base that is causing this problem, but I'm not sure where to start looking. Something like the opposite of a rogue "using Engine"? Anyone got any ideas?
C++ Standard, 3.4.4.2 declares: > > For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero > or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of > the function arguments (and the namespace of any template template argument). **Typedef names and using-declarations > used to specify the types do not contribute to this set**. > > > ADL doesn't work with typedef's.
211,383
<p>I have the age-old problem of a <code>div</code> wrapping a two-column layout. My sidebar is floated, so my container <code>div</code> fails to wrap the content and sidebar.</p> <pre class="lang-html prettyprint-override"><code>&lt;div id="container"&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;div id="sidebar"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>There seem to be numerous methods of fixing the clear bug in Firefox:</p> <ul> <li><code>&lt;br clear="all"/&gt;</code></li> <li><code>overflow:auto</code></li> <li><code>overflow:hidden</code></li> </ul> <p>In my situation, the only one that seems to work correctly is the <code>&lt;br clear="all"/&gt;</code> solution, which is a little bit scruffy. <code>overflow:auto</code> gives me nasty scrollbars, and <code>overflow:hidden</code> must surely have side effects. Also, IE7 apparently shouldn't suffer from this problem due to its incorrect behaviour, but in my situation it's suffering the same as Firefox.</p> <p>Which method currently available to us is the most robust?</p>
[ { "answer_id": 211415, "author": "Torkel", "author_id": 24425, "author_profile": "https://Stackoverflow.com/users/24425", "pm_score": -1, "selected": false, "text": "<p>Have you tried this:</p>\n\n<pre><code>&lt;div style=\"clear:both;\"/&gt;\n</code></pre>\n\n<p>I haven't had any problems with this method.</p>\n" }, { "answer_id": 461858, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I've found a bug in the official CLEARFIX-Method:\nThe DOT doesn't have a font-size.\nAnd if you set the <code>height = 0</code> and the first Element in your DOM-Tree has the class \"clearfix\" you'll allways have a margin at the bottom of the page of 12px :)</p>\n\n<p>You have to fix it like this:</p>\n\n<pre><code>/* float clearing for everyone else */\n.clearfix:after{\n clear: both;\n content: \".\";\n display: block;\n height: 0;\n visibility: hidden;\n font-size: 0;\n}\n</code></pre>\n\n<p>It's now part of the YAML-Layout ... Just take a look at it - it's very interesting!\n<a href=\"http://www.yaml.de/en/home.html\" rel=\"noreferrer\">http://www.yaml.de/en/home.html</a></p>\n" }, { "answer_id": 531906, "author": "Jack Sleight", "author_id": 39428, "author_profile": "https://Stackoverflow.com/users/39428", "pm_score": 5, "selected": false, "text": "<p>The overflow property can be used to clear floats with no additional mark-up:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container { overflow: hidden; }\n</code></pre>\n\n<p>This works for all browsers except IE6, where all you need to do is enable hasLayout (zoom being my preferred method):</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container { zoom: 1; }\n</code></pre>\n\n<p><a href=\"http://www.quirksmode.org/css/clearing.html\" rel=\"noreferrer\">http://www.quirksmode.org/css/clearing.html</a></p>\n" }, { "answer_id": 1341057, "author": "draco", "author_id": 92776, "author_profile": "https://Stackoverflow.com/users/92776", "pm_score": 3, "selected": false, "text": "<p>Using <code>overflow:hidden</code>/<code>auto</code> and height for ie6 will suffice if the floating container has a parent element. </p>\n\n<p>Either one of the #test could work, for the HTML stated below to clear floats.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#test {\n overflow:hidden; // or auto;\n _height:1%; forces hasLayout in IE6\n}\n\n&lt;div id=\"test\"&gt;\n &lt;div style=\"floatLeft\"&gt;&lt;/div&gt;\n &lt;div style=\"random\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>In cases when this refuses to work with ie6, just float the parent to clear float. </p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#test {\n float: left; // using float to clear float\n width: 99%;\n}\n</code></pre>\n\n<p>Never really needed any other kind of clearing yet. Maybe it's the way I write my HTML.</p>\n" }, { "answer_id": 1633170, "author": "Beau Smith", "author_id": 101290, "author_profile": "https://Stackoverflow.com/users/101290", "pm_score": 11, "selected": true, "text": "<p>Depending upon the design being produced, each of the below clearfix CSS solutions has its own benefits.</p>\n\n<p>The clearfix does have useful applications but it has also been used as a hack. Before you use a clearfix perhaps these modern css solutions can be useful:</p>\n\n<ul>\n<li><a href=\"https://css-tricks.com/snippets/css/a-guide-to-flexbox/\" rel=\"noreferrer\">css flexbox</a></li>\n<li><a href=\"https://css-tricks.com/snippets/css/complete-guide-grid/\" rel=\"noreferrer\">css grid</a></li>\n</ul>\n\n<hr>\n\n<h1>Modern Clearfix Solutions</h1>\n\n<hr>\n\n<h2>Container with <code>overflow: auto;</code></h2>\n\n<p>The simplest way to clear floated elements is using the style <code>overflow: auto</code> on the containing element. This solution works in every modern browsers.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div style=\"overflow: auto;\"&gt;\n &lt;img\n style=\"float: right;\"\n src=\"path/to/floated-element.png\"\n width=\"500\"\n height=\"500\"\n &gt; \n &lt;p&gt;Your content here…&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>One downside, using certain combinations of margin and padding on the external element can cause scrollbars to appear but this can be solved by placing the margin and padding on another parent containing element.</p>\n\n<p>Using ‘overflow: hidden’ is also a clearfix solution, but will not have scrollbars, however using <code>hidden</code> will crop any content positioned outside of the containing element.</p>\n\n<p><em>Note:</em> The floated element is an <code>img</code> tag in this example, but could be any html element.</p>\n\n<hr>\n\n<h2>Clearfix Reloaded</h2>\n\n<p>Thierry Koblentz on CSSMojo wrote: <a href=\"http://cssmojo.com/the-very-latest-clearfix-reloaded/\" rel=\"noreferrer\">The very latest clearfix reloaded</a>. He noted that by dropping support for oldIE, the solution can be simplified to one css statement. Additionally, using <code>display: block</code> (instead of <code>display: table</code>) allows margins to collapse properly when elements with clearfix are siblings.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container::after {\n content: \"\";\n display: block;\n clear: both;\n}\n</code></pre>\n\n<p>This is the most modern version of the clearfix.</p>\n\n<hr>\n\n<p>⋮</p>\n\n<p>⋮</p>\n\n<h1>Older Clearfix Solutions</h1>\n\n<p>The below solutions are not necessary for modern browsers, but may be useful for targeting older browsers.</p>\n\n<p>Note that these solutions rely upon browser bugs and therefore should be used only if none of the above solutions work for you.</p>\n\n<p>They are listed roughly in chronological order.</p>\n\n<hr>\n\n<h2>\"Beat That ClearFix\", a clearfix for modern browsers</h2>\n\n<p>Thierry Koblentz' of <a href=\"http://www.cssmojo.com/latest_new_clearfix_so_far/\" rel=\"noreferrer\">CSS Mojo</a> has pointed out that when targeting modern browsers, we can now drop the <code>zoom</code> and <code>::before</code> property/values and simply use:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container::after {\n content: \"\";\n display: table;\n clear: both;\n}\n</code></pre>\n\n<p><em>This solution does not support for IE 6/7 …on purpose!</em></p>\n\n<p>Thierry also offers: \"<a href=\"http://www.cssmojo.com/latest_new_clearfix_so_far/#why-is-that\" rel=\"noreferrer\">A word of caution</a>: if you start a new project from scratch, go for it, but don’t swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins.\"</p>\n\n<hr>\n\n<h2>Micro Clearfix</h2>\n\n<p>The most recent and globally adopted clearfix solution, the <a href=\"http://nicolasgallagher.com/micro-clearfix-hack/\" rel=\"noreferrer\">Micro Clearfix by Nicolas Gallagher</a>.</p>\n\n<p><em>Known support: Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+</em></p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container::before, .container::after {\n content: \"\";\n display: table;\n}\n.container::after {\n clear: both;\n}\n.container {\n zoom: 1;\n}\n</code></pre>\n\n<hr>\n\n<h2>Overflow Property</h2>\n\n<p>This basic method is preferred for the usual case, when positioned content will not show outside the bounds of the container.</p>\n\n<p><a href=\"http://www.quirksmode.org/css/clearing.html\" rel=\"noreferrer\">http://www.quirksmode.org/css/clearing.html</a>\n- <em>explains how to resolve common issues related to this technique, namely, setting <code>width: 100%</code> on the container.</em></p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n overflow: hidden;\n display: inline-block;\n display: block;\n}\n</code></pre>\n\n<p>Rather than using the <code>display</code> property to set \"hasLayout\" for IE, other properties can be used for <a href=\"http://www.satzansatz.de/cssd/onhavinglayout.html\" rel=\"noreferrer\">triggering \"hasLayout\" for an element</a>.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n overflow: hidden;\n zoom: 1;\n display: block;\n}\n</code></pre>\n\n<p>Another way to clear floats using the <code>overflow</code> property is to use the <a href=\"http://wellstyled.com/css-underscore-hack.html\" rel=\"noreferrer\">underscore hack</a>. IE will apply the values prefixed with the underscore, other browsers will not. The <code>zoom</code> property triggers <a href=\"http://www.satzansatz.de/cssd/onhavinglayout.html\" rel=\"noreferrer\">hasLayout</a> in IE:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n overflow: hidden;\n _overflow: visible; /* for IE */\n _zoom: 1; /* for IE */\n}\n</code></pre>\n\n<p>While this works... it is not ideal to use hacks.</p>\n\n<hr>\n\n<h2>PIE: Easy Clearing Method</h2>\n\n<p>This older \"Easy Clearing\" method has the advantage of allowing positioned elements to hang outside the bounds of the container, at the expense of more tricky CSS.</p>\n\n<p>This solution is quite old, but you can learn all about Easy Clearing on Position Is Everything: <a href=\"http://www.positioniseverything.net/easyclearing.html\" rel=\"noreferrer\">http://www.positioniseverything.net/easyclearing.html</a></p>\n\n<hr>\n\n<h2>Element using \"clear\" property</h2>\n\n<p>The quick and dirty solution (with some drawbacks) for when you’re quickly slapping something together:</p>\n\n<pre><code>&lt;br style=\"clear: both\" /&gt; &lt;!-- So dirty! --&gt;\n</code></pre>\n\n<h3>Drawbacks</h3>\n\n<ul>\n<li>It's not responsive and thus may not provide the desired effect if layout styles change based upon media queries. A solution in pure CSS is more ideal.</li>\n<li>It adds html markup without necessarily adding any semantic value.</li>\n<li>It requires a inline definition and solution for each instance rather than a class reference to a single solution of a “clearfix” in the css and class references to it in the html.</li>\n<li>It makes code difficult to work with for others as they may have to write more hacks to work around it.</li>\n<li>In the future when you need/want to use another clearfix solution, you won't have to go back and remove every <code>&lt;br style=\"clear: both\" /&gt;</code> tag littered around the markup.</li>\n</ul>\n" }, { "answer_id": 2909912, "author": "Thierry Koblentz", "author_id": 350504, "author_profile": "https://Stackoverflow.com/users/350504", "pm_score": 2, "selected": false, "text": "<p>I'd float <code>#content</code> too, that way both columns contain floats. Also because it will allow you to clear elements inside <code>#content</code> without clearing the side bar.</p>\n\n<p>Same thing with the wrapper, you'd need to make it a block formatting context to wrap the two columns.</p>\n\n<p>This article mentions a few triggers you can use:\n<a href=\"http://www.tjkdesign.com/articles/block-formatting-contexts_and_hasLayout.asp\" rel=\"nofollow noreferrer\">block formatting contexts</a>.</p>\n" }, { "answer_id": 3196924, "author": "duggi", "author_id": 262942, "author_profile": "https://Stackoverflow.com/users/262942", "pm_score": 3, "selected": false, "text": "<p>honestly; all solutions seem to be a hack to fix a rendering bug ... am i wrong?</p>\n\n<p>i've found <code>&lt;br clear=\"all\" /&gt;</code> to be the easiest, simplest. seeing <code>class=\"clearfix\"</code> everywhere can't stroke the sensibilities of someone who objects to extraneous markeup elements, can it? you're just painting the problem on a different canvas.</p>\n\n<p>i also use the <code>display: hidden</code> solution, which is great and requires no extra class declarations or html markup ... but sometimes you need the elements to overflow the container, for eg. pretty ribbons and sashes</p>\n" }, { "answer_id": 3805213, "author": "Eric the Red", "author_id": 86537, "author_profile": "https://Stackoverflow.com/users/86537", "pm_score": 5, "selected": false, "text": "<p>I recommend using the following, which is taken from <a href=\"http://html5boilerplate.com/\" rel=\"noreferrer\">http://html5boilerplate.com/</a></p>\n\n<pre><code>/* &gt;&gt; The Magnificent CLEARFIX &lt;&lt; */\n</code></pre>\n\n<pre class=\"lang-css prettyprint-override\"><code>.clearfix:after { \n content: \".\"; \n display: block; \n height: 0; \n clear: both; \n visibility: hidden; \n}\n.clearfix { \n display: inline-block; \n}\n* html .clearfix { \n height: 1%; \n} /* Hides from IE-mac \\*/\n.clearfix { \n display: block; \n}\n</code></pre>\n" }, { "answer_id": 5066285, "author": "Salman von Abbas", "author_id": 362006, "author_profile": "https://Stackoverflow.com/users/362006", "pm_score": 3, "selected": false, "text": "<p>I just use :-</p>\n\n<pre><code>.clear:after{\n clear: both;\n content: \"\";\n display: block;\n}\n</code></pre>\n\n<p>Works best and compatible with IE8+ :)</p>\n" }, { "answer_id": 5519692, "author": "Hakan", "author_id": 673108, "author_profile": "https://Stackoverflow.com/users/673108", "pm_score": 0, "selected": false, "text": "<p>You could also put this in your CSS:</p>\n\n<pre><code>.cb:after{\n visibility: hidden;\n display: block;\n content: \".\";\n clear: both;\n height: 0;\n}\n\n*:first-child+html .cb{zoom: 1} /* for IE7 */\n</code></pre>\n\n<p>And add class \"cb\" to your parent div:</p>\n\n<pre><code>&lt;div id=\"container\" class=\"cb\"&gt;\n</code></pre>\n\n<p>You will not need to add anything else to your original code...</p>\n" }, { "answer_id": 5745706, "author": "paulslater19", "author_id": 705752, "author_profile": "https://Stackoverflow.com/users/705752", "pm_score": 4, "selected": false, "text": "<p>This is quite a tidy solution: </p>\n\n<pre class=\"lang-css prettyprint-override\"><code>/* For modern browsers */\n.cf:before,\n.cf:after {\n content:\"\";\n display:table;\n}\n\n.cf:after {\n clear:both;\n}\n\n/* For IE 6/7 (trigger hasLayout) */\n.cf {\n zoom:1;\n}\n</code></pre>\n\n<blockquote>\n <p>It's known to work in Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+</p>\n \n <p>Including the :before selector is not necessary to clear the floats,\n but it prevents top-margins from collapsing in modern browsers. This\n ensures that there is visual consistency with IE 6/7 when zoom:1 is\n applied.</p>\n</blockquote>\n\n<p>From <a href=\"http://nicolasgallagher.com/micro-clearfix-hack/\" rel=\"noreferrer\">http://nicolasgallagher.com/micro-clearfix-hack/</a></p>\n" }, { "answer_id": 6072143, "author": "Phpascal", "author_id": 762759, "author_profile": "https://Stackoverflow.com/users/762759", "pm_score": 2, "selected": false, "text": "<p>Why just trying to use css hack to do what 1 line of HTML do the job. And why not to use semantic html tu put break to return to the line?</p>\n\n<p>Fo me is realy better to use : </p>\n\n<pre><code>&lt;br style=\"clear:both\" /&gt;\n</code></pre>\n\n<p>And if you don't want any style in your html you just have to use class for your break\n\nand put <code>.clear { clear:both; }</code> in your CSS.</p>\n\n<p>Advantage of this:</p>\n\n<ul>\n<li>Semantic use of html for return to the line</li>\n<li>If no CSS load it will be working</li>\n<li>No need extra CSS code and Hack</li>\n<li>no need to simulate the br with CSS, it's already exist in HTML</li>\n</ul>\n" }, { "answer_id": 6404718, "author": "Tim Huynh", "author_id": 576066, "author_profile": "https://Stackoverflow.com/users/576066", "pm_score": 2, "selected": false, "text": "<p>Assuming you're using this HTML structure:</p>\n\n<pre><code>&lt;div id=\"container\"&gt;\n &lt;div id=\"content\"&gt;\n &lt;/div&gt;\n &lt;div id=\"sidebar\"&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Here's the CSS that I would use:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>div#container {\n overflow: hidden; /* makes element contain floated child elements */\n}\n\ndiv#content, div#sidebar {\n float: left;\n display: inline; /* preemptively fixes IE6 dobule-margin bug */\n}\n</code></pre>\n\n<p>I use this set all the time and it works fine for me, even in IE6.</p>\n" }, { "answer_id": 7101649, "author": "Neil G", "author_id": 899758, "author_profile": "https://Stackoverflow.com/users/899758", "pm_score": 3, "selected": false, "text": "<p>I always float the main sections of my grid and apply <code>clear: both;</code> to the footer. That doesn't require an extra div or class.</p>\n" }, { "answer_id": 9932508, "author": "Chris Calo", "author_id": 101869, "author_profile": "https://Stackoverflow.com/users/101869", "pm_score": 6, "selected": false, "text": "<h2>What problems are we trying to solve?</h2>\n\n<p>There are two important considerations when floating stuff:</p>\n\n<ol>\n<li><p><strong>Containing descendant floats.</strong> This means that the element in question makes itself tall enough to wrap all floating descendants. (They don't hang outside.)</p>\n\n<p><img src=\"https://i.stack.imgur.com/3AUJp.png\" alt=\"Floating content hanging outside its container\"></p></li>\n<li><p><strong>Insulating descendants from outside floats.</strong> This means that descendants inside of an element should be able to use <code>clear: both</code> and have it not interact with floats outside the element.</p>\n\n<p><img src=\"https://i.stack.imgur.com/XIMXt.png\" alt=\"&lt;code&gt;clear: both&lt;/code&gt; interacting with a float elsewhere in the DOM\"></p></li>\n</ol>\n\n<h2>Block formatting contexts</h2>\n\n<p>There's only one way to do both of these. And that is to establish a new <a href=\"https://developer.mozilla.org/en/CSS/block_formatting_context\" rel=\"noreferrer\">block formatting context</a>. Elements that establish a block formatting context are an insulated rectangle in which floats interact with each other. A block formatting context will always be tall enough to visually wrap its floating descendants, and no floats outside of a block formatting context may interact with elements inside. This two-way insulation is exactly what you want. In IE, this same concept is called <a href=\"http://www.satzansatz.de/cssd/onhavinglayout.html\" rel=\"noreferrer\">hasLayout</a>, which can be set via <code>zoom: 1</code>.</p>\n\n<p>There are several ways to establish a block formatting context, but the solution I recommend is <code>display: inline-block</code> with <code>width: 100%</code>. (Of course, there are the <a href=\"https://stackoverflow.com/questions/5219175/width-100-padding\">usual caveats</a> with using <code>width: 100%</code>, so use <code>box-sizing: border-box</code> or put <code>padding</code>, <code>margin</code>, and <code>border</code> on a different element.)</p>\n\n<h2>The most robust solution</h2>\n\n<p>Probably the most common application of floats is the two-column layout. (Can be extended to three columns.)</p>\n\n<p>First the markup structure.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div class=\"container\"&gt;\n &lt;div class=\"sidebar\"&gt;\n sidebar&lt;br/&gt;sidebar&lt;br/&gt;sidebar\n &lt;/div&gt;\n &lt;div class=\"main\"&gt;\n &lt;div class=\"main-content\"&gt;\n main content\n &lt;span style=\"clear: both\"&gt;\n main content that uses &lt;code&gt;clear: both&lt;/code&gt;\n &lt;/span&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>And now the CSS.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>/* Should contain all floated and non-floated content, so it needs to\n * establish a new block formatting context without using overflow: hidden.\n */\n.container {\n display: inline-block;\n width: 100%;\n zoom: 1; /* new block formatting context via hasLayout for IE 6/7 */\n}\n\n/* Fixed-width floated sidebar. */\n.sidebar {\n float: left;\n width: 160px;\n}\n\n/* Needs to make space for the sidebar. */\n.main {\n margin-left: 160px;\n}\n\n/* Establishes a new block formatting context to insulate descendants from\n * the floating sidebar. */\n.main-content {\n display: inline-block;\n width: 100%;\n zoom: 1; /* new block formatting context via hasLayout for IE 6/7 */\n}\n</code></pre>\n\n<h2>Try it yourself</h2>\n\n<p>Go to <a href=\"http://jsbin.com/eciwev/1/edit\" rel=\"noreferrer\">JS Bin</a> to play around with the code and see how this solution is built from the ground up.</p>\n\n<h2>Traditional clearfix methods considered harmful</h2>\n\n<p>The problem with the traditional <a href=\"http://www.positioniseverything.net/easyclearing.html\" rel=\"noreferrer\">clearfix</a> <a href=\"http://nicolasgallagher.com/micro-clearfix-hack/\" rel=\"noreferrer\">solutions</a> is that they use two different rendering concepts to achieve the same goal for IE and everyone else. In IE they use hasLayout to establish a new block formatting context, but for everyone else they use generated boxes (<code>:after</code>) with <code>clear: both</code>, which does not establish a new block formatting context. This means things won't behave the same in all situations. For an explanation of why this is bad, see <a href=\"http://www.cssmojo.com/clearfix_block-formatting-context_and_hasLayout/\" rel=\"noreferrer\">Everything you Know about Clearfix is Wrong</a>.</p>\n" }, { "answer_id": 12235179, "author": "John Xiao", "author_id": 1252528, "author_profile": "https://Stackoverflow.com/users/1252528", "pm_score": 2, "selected": false, "text": "<p>I have tried all these solutions, a big margin will be added to <code>&lt;html&gt;</code> element automatically when I use the code below:</p>\n\n<pre><code>.clearfix:after { \n visibility: hidden; \n display: block; \n content: \".\"; \n clear: both; \n height: 0;\n}\n</code></pre>\n\n<p>Finally, I solved the margin problem by adding <code>font-size: 0;</code> to the above CSS.</p>\n" }, { "answer_id": 13081256, "author": "Gaurang", "author_id": 1453858, "author_profile": "https://Stackoverflow.com/users/1453858", "pm_score": 2, "selected": false, "text": "<p>A clearfix is a way for an element to automatically clear after itself, \nso that you don't need to add additional markup.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.clearfix:after {\n content: \" \"; /* Older browser do not support empty content */\n visibility: hidden;\n display: block;\n height: 0;\n clear: both;\n}\n.cleaner {\n clear: both;\n}\n</code></pre>\n\n<p>Normally you would need to do something as follows:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div style=\"float: left;\"&gt;Sidebar&lt;/div&gt;\n&lt;div class=\"cleaner\"&gt;&lt;/div&gt; &lt;!-- Clear the float --&gt;\n</code></pre>\n\n<p>With clearfix, you only need to</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div style=\"float: left;\" class=\"clearfix\"&gt;Sidebar&lt;/div&gt;\n&lt;!-- No Clearing div! --&gt;\n</code></pre>\n" }, { "answer_id": 13718078, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Clearfix from bootstrap:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.clearfix {\n *zoom: 1;\n}\n\n.clearfix:before,\n.clearfix:after {\n display: table;\n line-height: 0;\n content: \"\";\n}\n\n.clearfix:after {\n clear: both;\n}\n</code></pre>\n" }, { "answer_id": 15291536, "author": "Vipul Vaghasiya", "author_id": 937911, "author_profile": "https://Stackoverflow.com/users/937911", "pm_score": 0, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#content{float:left;}\r\n#sidebar{float:left;}\r\n.clear{clear:both; display:block; height:0px; width:0px; overflow:hidden;}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"container\"&gt;\r\n &lt;div id=\"content\"&gt;text 1 &lt;/div&gt;\r\n &lt;div id=\"sidebar\"&gt;text 2&lt;/div&gt;\r\n &lt;div class=\"clear\"&gt;&lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 15437402, "author": "Musa Butt", "author_id": 2174728, "author_profile": "https://Stackoverflow.com/users/2174728", "pm_score": 3, "selected": false, "text": "<pre class=\"lang-css prettyprint-override\"><code>.clearFix:after { \n content: \"\";\n display: table; \n clear: both; \n}\n</code></pre>\n" }, { "answer_id": 15522931, "author": "jmu", "author_id": 454985, "author_profile": "https://Stackoverflow.com/users/454985", "pm_score": 3, "selected": false, "text": "<p>With LESS (<a href=\"http://lesscss.org/\" rel=\"noreferrer\">http://lesscss.org/</a>), one can create a handy clearfix helper:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.clearfix() {\n zoom: 1;\n &amp;:before { \n content: ''; \n display: block; \n }\n &amp;:after { \n content: ''; \n display: table; \n clear: both; \n }\n}\n</code></pre>\n\n<p>And then use it with problematic containers, for example:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;!-- HTML --&gt;\n&lt;div id=\"container\"&gt;\n &lt;div id=\"content\"&gt;&lt;/div&gt;\n &lt;div id=\"sidebar\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<pre class=\"lang-css prettyprint-override\"><code>/* LESS */\ndiv#container {\n .clearfix();\n}\n</code></pre>\n" }, { "answer_id": 16099501, "author": "iono", "author_id": 1129420, "author_profile": "https://Stackoverflow.com/users/1129420", "pm_score": 6, "selected": false, "text": "<p>The newest standard, as used by <a href=\"http://inuitcss.com/\" rel=\"nofollow noreferrer\">Inuit.css</a> and <a href=\"http://bourbon.io\" rel=\"nofollow noreferrer\">Bourbon</a> - two very widely used and well-maintained CSS/Sass frameworks:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.btcf:after {\n content:&quot;&quot;;\n display:block;\n clear:both;\n}\n</code></pre>\n<hr />\n<h3>Notes</h3>\n<p>Keep in mind that clearfixes are essentially a hack for what flexbox layouts can now provide in a <a href=\"https://philipwalton.github.io/solved-by-flexbox/\" rel=\"nofollow noreferrer\">much easier and smarter way</a>. CSS floats were originally designed for inline content to flow around - like images in a long textual article - and not for grid layouts and the like. Unless you're specifically targeting old (not Edge) Internet Explorer, your <a href=\"http://caniuse.com/#feat=flexbox\" rel=\"nofollow noreferrer\">target browsers support flexbox</a>, so it's worth the time to learn.</p>\n<p>This doesn't support IE7. You <strong>shouldn't</strong> be supporting IE7. Doing so continues to expose users to unfixed security exploits and makes life harder for all other web developers, as it reduces the pressure on users and organisations to switch to safer modern browsers.</p>\n<p>This clearfix was <a href=\"http://www.css-101.org/articles/clearfix/latest-new-clearfix-so-far.php\" rel=\"nofollow noreferrer\">announced and explained by Thierry Koblentz</a> in July 2012. It sheds unnecessary weight from <a href=\"http://nicolasgallagher.com/micro-clearfix-hack/\" rel=\"nofollow noreferrer\">Nicolas Gallagher's 2011 micro-clearfix</a>. In the process, it frees a pseudo-element for your own use. This has been updated to use <code>display: block</code> rather than <code>display: table</code> (again, credit to Thierry Koblentz).</p>\n" }, { "answer_id": 20979670, "author": "John Slegers", "author_id": 1946501, "author_profile": "https://Stackoverflow.com/users/1946501", "pm_score": 2, "selected": false, "text": "<p>I always use the <a href=\"http://nicolasgallagher.com/micro-clearfix-hack/\" rel=\"nofollow noreferrer\"><strong>micro-clearfix</strong></a> :</p>\n\n<pre><code>.cf:before,\n.cf:after {\n content: \" \";\n display: table;\n}\n\n.cf:after {\n clear: both;\n}\n\n/**\n * For IE 6/7 only\n */\n.cf {\n *zoom: 1;\n}\n</code></pre>\n\n<p>In <a href=\"http://jslegers.github.io/cascadeframework/\" rel=\"nofollow noreferrer\"><strong>Cascade Framework</strong></a> I even apply it by default on block level elements. IMO, applying it by default on block level elements gives block level elements more intuitive behavior than their traditonal behavior. It also made it a lot easier for me to add support for older browsers to Cascade Framework (which supports IE6-8 as well as modern browsers).</p>\n" }, { "answer_id": 23479523, "author": "fernandopasik", "author_id": 1877754, "author_profile": "https://Stackoverflow.com/users/1877754", "pm_score": 3, "selected": false, "text": "<p>With SASS, the clearfix is:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>@mixin clearfix {\n &amp;:before, &amp;:after {\n content: '';\n display: table;\n }\n &amp;:after {\n clear: both;\n }\n *zoom: 1;\n}\n</code></pre>\n\n<p>and it's used like:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n @include clearfix;\n}\n</code></pre>\n\n<p>if you want the new clearfix:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>@mixin newclearfix {\n &amp;:after {\n content:\"\";\n display:table;\n clear:both;\n }\n}\n</code></pre>\n" }, { "answer_id": 29156752, "author": "Omar", "author_id": 931377, "author_profile": "https://Stackoverflow.com/users/931377", "pm_score": 3, "selected": false, "text": "<p>Given the huge amount of replies I was not gonna post. However, this method may help someone, as it did help me.</p>\n<h2>Stay way from floats whenever possible</h2>\n<p>It's worth to mention, I avoid floats like Ebola. There are many reasons and I am not alone; Read Rikudo answer about <a href=\"https://stackoverflow.com/questions/8554043/what-is-clearfix\">what is a clearfix</a> and you'll see what I mean. In his own words: <code>...the use of floated elements for layout is getting more and more discouraged with the use of better alternatives...</code></p>\n<p>There are other good (and sometimes better) options out there other than floats. As technology advances and improves, <a href=\"https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_flexible_boxes\" rel=\"nofollow noreferrer\">flexbox</a> (and other methods) are going to be widely adopted and floats will become just a bad memory. Maybe a CSS4?</p>\n<hr />\n<h2>Float misbehavior and failed clears</h2>\n<p>First off, sometimes, you may think that you are safe from floats until your lifesaver is punctured and your html flow starts to sink:</p>\n<p>In the codepen <a href=\"http://codepen.io/omarjuvera/pen/jEXBya\" rel=\"nofollow noreferrer\">http://codepen.io/omarjuvera/pen/jEXBya</a> below, the practice of clearing a float with <code>&lt;div classs=&quot;clear&quot;&gt;&lt;/div&gt;</code> (or other element) is common but frown upon and anti-semantic.</p>\n<pre><code>&lt;div class=&quot;floated&quot;&gt;1st&lt;/div&gt;\n&lt;div class=&quot;floated&quot;&gt;2nd&lt;/div&gt;\n&lt;div class=&quot;floated&quot;&gt;3nd&lt;/div&gt;\n&lt;div classs=&quot;clear&quot;&gt;&lt;/div&gt; &lt;!-- Acts as a wall --&gt;\n&lt;section&gt;Below&lt;/section&gt;\n</code></pre>\n<p><strong>CSS</strong></p>\n<pre><code>div {\n border: 1px solid #f00;\n width: 200px;\n height: 100px;\n}\n\ndiv.floated {\n float: left;\n}\n\n.clear {\n clear: both;\n}\nsection {\n border: 1px solid #f0f;\n}\n</code></pre>\n<p><strong>However</strong>, just when you thought your float is sail worthy...boom! As the screen size becomes smaller and smaller you see weird behaviors in like the graphic below (Same <a href=\"http://codepen.io/omarjuvera/pen/jEXBya\" rel=\"nofollow noreferrer\">http://codepen.io/omarjuvera/pen/jEXBya</a>):</p>\n<p><img src=\"https://i.stack.imgur.com/BHCiv.png\" alt=\"float bug sample 1\" /></p>\n<p><strong>Why should you care?</strong>\nRoughly, about 80% (or more) of the devices used are mobile devices with small screens. Desktop computers/laptops are no longer king.</p>\n<hr />\n<h2>It does not end there</h2>\n<p>This is not the only problem with floats. There are many, but in this example, some may say <code>all you have to do is to place your floats in a container</code>. But as you can see in the <a href=\"http://codepen.io/omarjuvera/pen/XJoMYG\" rel=\"nofollow noreferrer\">codepen</a> and graphic, that is not the case. It apparently made things worst:</p>\n<p>HTML</p>\n<pre><code>&lt;div id=&quot;container&quot; class=&quot;&quot;&gt;\n &lt;div class=&quot;floated&quot;&gt;1st&lt;/div&gt;\n &lt;div class=&quot;floated&quot;&gt;2nd&lt;/div&gt;\n &lt;div class=&quot;floated&quot;&gt;3nd&lt;/div&gt;\n&lt;/div&gt; &lt;!-- /#conteiner --&gt;\n&lt;div classs=&quot;clear&quot;&gt;&lt;/div&gt; &lt;!-- Acts as a wall --&gt;\n&lt;section&gt;Below&lt;/section&gt;\n</code></pre>\n<p>CSS</p>\n<pre><code>#container {\n min-height: 100px; /* To prevent it from collapsing */\n border: 1px solid #0f0;\n}\n.floated {\n float: left;\n border: 1px solid #f00;\n width: 200px;\n height: 100px;\n}\n\n.clear {\n clear: both;\n}\nsection {\n border: 1px solid #f0f;\n}\n</code></pre>\n<p>As for the result?</p>\n<p>It's the *** same!\n<img src=\"https://i.stack.imgur.com/SDY1J.png\" alt=\"float bug sample 2\" /></p>\n<p>Least you know, you'll start a CSS party, inviting all kinds of selectors and properties to the party; making a bigger mess of your CSS than what you started with. Just to fix your float.</p>\n<hr />\n<h2>CSS Clearfix to the rescue</h2>\n<p>This simple and very adaptable piece of CSS is a beauty and a &quot;savior&quot;:</p>\n<pre><code>.clearfix:before, .clearfix:after { \n content: &quot;&quot;;\n display: table;\n clear: both;\n zoom: 1; /* ie 6/7 */\n}\n</code></pre>\n<p>That's it! It really works without breaking semantics and did I mention <a href=\"http://codepen.io/omarjuvera/pen/wBRJaz\" rel=\"nofollow noreferrer\">it works?</a>:</p>\n<p>From the same sample...<strong>HTML</strong></p>\n<pre><code>&lt;div class=&quot;clearfix&quot;&gt;\n &lt;div class=&quot;floated&quot;&gt;1st&lt;/div&gt;\n &lt;div class=&quot;floated&quot;&gt;2nd&lt;/div&gt;\n &lt;div class=&quot;floated&quot;&gt;3nd&lt;/div&gt;\n&lt;/div&gt;\n&lt;section&gt;Below&lt;/section&gt;\n</code></pre>\n<p><strong>CSS</strong></p>\n<pre><code>div.floated {\n float: left;\n border: 1px solid #f00;\n width: 200px;\n height: 100px;\n}\nsection {\n border: 4px solid #00f;\n}\n\n\n.clearfix:before, .clearfix:after { \n content: &quot;&quot;;\n display: table;\n clear: both;\n zoom: 1; /* ie 6/7 */\n}\n</code></pre>\n<hr />\n<p>Now we no longer need <code>&lt;div classs=&quot;clear&quot;&gt;&lt;/div&gt; &lt;!-- Acts as a wall --&gt;</code> and keep the semantic police happy. This is not the only benefit. This clearfix is responsive to any screen size without the use of <code>@media</code> in it's simplest form. In other words, it will keep your float container in check and preventing floodings. Lastly, it provides support for old browsers all in one small karate chop =)</p>\n<h1>Here's the clearfix again</h1>\n<pre><code>.clearfix:before, .clearfix:after { \n content: &quot;&quot;;\n display: table;\n clear: both;\n zoom: 1; /* ie 6/7 */\n}\n</code></pre>\n" }, { "answer_id": 29513176, "author": "Serge Stroobandt", "author_id": 2192488, "author_profile": "https://Stackoverflow.com/users/2192488", "pm_score": 2, "selected": false, "text": "<h1>Unlike other clearfixes, here is an open-ended one without containers</h1>\n<p>Other clearfixes either require the floated element to be in a well marked off container or need an extra, semantically empty <code>&lt;div&gt;</code>. Conversely, clear separation of content and markup requires <strong>a strict CSS solution</strong> to this problem.</p>\n<p>The mere fact that one needs to mark off the end of a float, does not allow for <a href=\"https://tex.stackexchange.com/a/340365/26348\"><strong>unattended CSS typesetting</strong></a>.</p>\n<p>If the latter is your goal, the float should be left open for anything (paragraphs, ordered and unordered lists etc.) to wrap around it, until a &quot;clearfix&quot; is encountered. For example, the clearfix might be set by a new heading.</p>\n<p>This is why I use the following clearfix with new headings:</p>\n<pre class=\"lang-css prettyprint-override\"><code>h1 {\n clear: both;\n display: inline-block;\n width: 100%;\n}\n</code></pre>\n<p>This solution gets used extensively on <a href=\"http://hamwaves.com/capacitors/en/index.html\" rel=\"nofollow noreferrer\">my website</a> to solve the problem: The text next to a floated miniature is short and the top-margin of the next clearing object is not respected.</p>\n<p>It also prevents any manual intervention when automatically generating <a href=\"http://hamwaves.com/capacitors/en/capacitors.letter.pdf\" rel=\"nofollow noreferrer\">PDFs</a> from the site.\nHere is an <a href=\"http://hamwaves.com/capacitors/en/index.html\" rel=\"nofollow noreferrer\">example page</a>.</p>\n" }, { "answer_id": 35912310, "author": "Eric", "author_id": 4872291, "author_profile": "https://Stackoverflow.com/users/4872291", "pm_score": -1, "selected": false, "text": "<p>My Favourite Method is to create a clearfix class in my css / scss document as below</p>\n<pre><code>.clearfix{\n clear:both;\n}\n</code></pre>\n<p>And then call it in my html document as shown below</p>\n<pre><code>&lt;html&gt;\n &lt;div class=&quot;div-number-one&quot;&gt;\n Some Content before the clearfix\n &lt;/div&gt;\n\n &lt;!-- Let's say we need to clearfix Here between these two divs ---&gt;\n &lt;div class=&quot;clearfix&quot;&gt;&lt;/div&gt;\n\n &lt;div class=&quot;div-number-two&quot;&gt;\n Some more content after the clearfix\n &lt;/div&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 45734276, "author": "Damien Golding", "author_id": 1764521, "author_profile": "https://Stackoverflow.com/users/1764521", "pm_score": 3, "selected": false, "text": "<p>A new display value seems to the job in one line.</p>\n\n<pre><code>display: flow-root;\n</code></pre>\n\n<p>From the W3 spec: \"The element generates a block container box, and lays out its contents using flow layout. It always establishes a new block formatting context for its contents.\"</p>\n\n<p>Information:\n<a href=\"https://www.w3.org/TR/css-display-3/#valdef-display-flow-root\" rel=\"nofollow noreferrer\">https://www.w3.org/TR/css-display-3/#valdef-display-flow-root</a>\n<a href=\"https://www.chromestatus.com/feature/5769454877147136\" rel=\"nofollow noreferrer\">https://www.chromestatus.com/feature/5769454877147136</a></p>\n\n<p>※As shown in the link above, support is currently limited so fallback support like below may be of use:\n<a href=\"https://github.com/fliptheweb/postcss-flow-root\" rel=\"nofollow noreferrer\">https://github.com/fliptheweb/postcss-flow-root</a></p>\n" }, { "answer_id": 57074101, "author": "Mohamed Aasif", "author_id": 11796031, "author_profile": "https://Stackoverflow.com/users/11796031", "pm_score": -1, "selected": false, "text": "<p>It is so simple clearfix clears the issue by when we using the float properties inside the div element.If we use two div elements one as float:left; and other one as float:right; we can use clearfix for the parent of the two div element. If we refuse to use clearfix unnecessary spaces fill with contents below and site structure will be broken. </p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
I have the age-old problem of a `div` wrapping a two-column layout. My sidebar is floated, so my container `div` fails to wrap the content and sidebar. ```html <div id="container"> <div id="content"></div> <div id="sidebar"></div> </div> ``` There seem to be numerous methods of fixing the clear bug in Firefox: * `<br clear="all"/>` * `overflow:auto` * `overflow:hidden` In my situation, the only one that seems to work correctly is the `<br clear="all"/>` solution, which is a little bit scruffy. `overflow:auto` gives me nasty scrollbars, and `overflow:hidden` must surely have side effects. Also, IE7 apparently shouldn't suffer from this problem due to its incorrect behaviour, but in my situation it's suffering the same as Firefox. Which method currently available to us is the most robust?
Depending upon the design being produced, each of the below clearfix CSS solutions has its own benefits. The clearfix does have useful applications but it has also been used as a hack. Before you use a clearfix perhaps these modern css solutions can be useful: * [css flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) * [css grid](https://css-tricks.com/snippets/css/complete-guide-grid/) --- Modern Clearfix Solutions ========================= --- Container with `overflow: auto;` -------------------------------- The simplest way to clear floated elements is using the style `overflow: auto` on the containing element. This solution works in every modern browsers. ```html <div style="overflow: auto;"> <img style="float: right;" src="path/to/floated-element.png" width="500" height="500" > <p>Your content here…</p> </div> ``` One downside, using certain combinations of margin and padding on the external element can cause scrollbars to appear but this can be solved by placing the margin and padding on another parent containing element. Using ‘overflow: hidden’ is also a clearfix solution, but will not have scrollbars, however using `hidden` will crop any content positioned outside of the containing element. *Note:* The floated element is an `img` tag in this example, but could be any html element. --- Clearfix Reloaded ----------------- Thierry Koblentz on CSSMojo wrote: [The very latest clearfix reloaded](http://cssmojo.com/the-very-latest-clearfix-reloaded/). He noted that by dropping support for oldIE, the solution can be simplified to one css statement. Additionally, using `display: block` (instead of `display: table`) allows margins to collapse properly when elements with clearfix are siblings. ```css .container::after { content: ""; display: block; clear: both; } ``` This is the most modern version of the clearfix. --- ⋮ ⋮ Older Clearfix Solutions ======================== The below solutions are not necessary for modern browsers, but may be useful for targeting older browsers. Note that these solutions rely upon browser bugs and therefore should be used only if none of the above solutions work for you. They are listed roughly in chronological order. --- "Beat That ClearFix", a clearfix for modern browsers ---------------------------------------------------- Thierry Koblentz' of [CSS Mojo](http://www.cssmojo.com/latest_new_clearfix_so_far/) has pointed out that when targeting modern browsers, we can now drop the `zoom` and `::before` property/values and simply use: ```css .container::after { content: ""; display: table; clear: both; } ``` *This solution does not support for IE 6/7 …on purpose!* Thierry also offers: "[A word of caution](http://www.cssmojo.com/latest_new_clearfix_so_far/#why-is-that): if you start a new project from scratch, go for it, but don’t swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins." --- Micro Clearfix -------------- The most recent and globally adopted clearfix solution, the [Micro Clearfix by Nicolas Gallagher](http://nicolasgallagher.com/micro-clearfix-hack/). *Known support: Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+* ```css .container::before, .container::after { content: ""; display: table; } .container::after { clear: both; } .container { zoom: 1; } ``` --- Overflow Property ----------------- This basic method is preferred for the usual case, when positioned content will not show outside the bounds of the container. <http://www.quirksmode.org/css/clearing.html> - *explains how to resolve common issues related to this technique, namely, setting `width: 100%` on the container.* ```css .container { overflow: hidden; display: inline-block; display: block; } ``` Rather than using the `display` property to set "hasLayout" for IE, other properties can be used for [triggering "hasLayout" for an element](http://www.satzansatz.de/cssd/onhavinglayout.html). ```css .container { overflow: hidden; zoom: 1; display: block; } ``` Another way to clear floats using the `overflow` property is to use the [underscore hack](http://wellstyled.com/css-underscore-hack.html). IE will apply the values prefixed with the underscore, other browsers will not. The `zoom` property triggers [hasLayout](http://www.satzansatz.de/cssd/onhavinglayout.html) in IE: ```css .container { overflow: hidden; _overflow: visible; /* for IE */ _zoom: 1; /* for IE */ } ``` While this works... it is not ideal to use hacks. --- PIE: Easy Clearing Method ------------------------- This older "Easy Clearing" method has the advantage of allowing positioned elements to hang outside the bounds of the container, at the expense of more tricky CSS. This solution is quite old, but you can learn all about Easy Clearing on Position Is Everything: <http://www.positioniseverything.net/easyclearing.html> --- Element using "clear" property ------------------------------ The quick and dirty solution (with some drawbacks) for when you’re quickly slapping something together: ``` <br style="clear: both" /> <!-- So dirty! --> ``` ### Drawbacks * It's not responsive and thus may not provide the desired effect if layout styles change based upon media queries. A solution in pure CSS is more ideal. * It adds html markup without necessarily adding any semantic value. * It requires a inline definition and solution for each instance rather than a class reference to a single solution of a “clearfix” in the css and class references to it in the html. * It makes code difficult to work with for others as they may have to write more hacks to work around it. * In the future when you need/want to use another clearfix solution, you won't have to go back and remove every `<br style="clear: both" />` tag littered around the markup.
211,399
<p>I need to execute a select and then update some of the rows in the <code>ResultSet</code> in an atomic way.</p> <p>The code I am using looks like (simplified):</p> <pre><code>stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery("SELECT ..."); while (rs.next()) { if (conditions_to_update) { rs.updateString(...); rs.updateRow(); } } </code></pre> <ul> <li>Can I guarantee that the updates are going to be executed atomically ? If not, how could I assure that ?</li> <li>What happens if any other process has changed the database row that you are updating via <code>updateRow()</code> ? Is there any way to lock the rows in the <code>ResultSet</code> ?</li> </ul>
[ { "answer_id": 211401, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>Use transactions.</p>\n" }, { "answer_id": 211502, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 3, "selected": true, "text": "<p>There's probably a whole heap of technologies and concepts that come into play here, and things start to get fairly sticky when you start considering multi-threaded / multi request applications.</p>\n\n<p>As Iassevk stated, you should look into using <a href=\"http://java.sun.com/docs/books/tutorial/jdbc/basics/transactions.html\" rel=\"nofollow noreferrer\">Transactions</a> to ensure the atomic nature of your updates - a very low-level example would be to do something along the lines of:</p>\n\n<pre><code>...\ncon.setAutoCommit(false);\ntry {\n while (rs.next()) {\n if (conditions_to_update) {\n rs.updateString(...);\n rs.updateRow();\n }\n }\n con.setAutoCommit(true);\n} catch (Exception ex) {\n //log the exception and rollback\n con.rollback();\n} finally {\n con.close();\n}\n</code></pre>\n\n<p>All the updates would then be batched into the same transaction. If any of the updates generated an Exception (such as an invalid value or the connection failing part way through the results), the whole lot would be rolled back. (Finally added because I am a champion of it ;p )</p>\n\n<p>This however, won't address your second issue which is two competing methods trying to update the same table - a race condition. There are, in my mind, two main approaches here - each has it's merits and drawbacks.</p>\n\n<p>The easiest approach would be to <a href=\"http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html\" rel=\"nofollow noreferrer\">Lock the table</a> - this would require minimal code changes but has a pretty big drawback. Working on the assumption that, as with most applications, it's more read that write: locking the table will prevent all other users from viewing the data, with the likelihood the code will hang, waiting for the lock to release before the connection time-out kicks in and throws an exception.</p>\n\n<p>The more complex approach is to ensure that the methods for performing these updates are implemented in a thread-safe manner. To that end:</p>\n\n<ul>\n<li>All the updates for this table pass through a single Class</li>\n<li>That class implements a Singleton pattern, or exposes the update methods as Static methods</li>\n<li>The update methods utilise the <a href=\"http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html\" rel=\"nofollow noreferrer\">Synchronized</a> keyword to prevent race conditions</li>\n</ul>\n" }, { "answer_id": 212457, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>What happens if any other process has changed the database row that you are updating via updateRow() ? Is there any way to lock the rows in the ResultSet ?</p>\n</blockquote>\n\n<p>In Oracle, you can kinda mark certain rows for update by issuing the following SQL.</p>\n\n<pre><code>select cola, colB from tabA for update;\n</code></pre>\n\n<p>The next transaction/thread/app that tries to update this row will get an exception. see this for more details -- <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:4530093713805\" rel=\"nofollow noreferrer\">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:4530093713805</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
I need to execute a select and then update some of the rows in the `ResultSet` in an atomic way. The code I am using looks like (simplified): ``` stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery("SELECT ..."); while (rs.next()) { if (conditions_to_update) { rs.updateString(...); rs.updateRow(); } } ``` * Can I guarantee that the updates are going to be executed atomically ? If not, how could I assure that ? * What happens if any other process has changed the database row that you are updating via `updateRow()` ? Is there any way to lock the rows in the `ResultSet` ?
There's probably a whole heap of technologies and concepts that come into play here, and things start to get fairly sticky when you start considering multi-threaded / multi request applications. As Iassevk stated, you should look into using [Transactions](http://java.sun.com/docs/books/tutorial/jdbc/basics/transactions.html) to ensure the atomic nature of your updates - a very low-level example would be to do something along the lines of: ``` ... con.setAutoCommit(false); try { while (rs.next()) { if (conditions_to_update) { rs.updateString(...); rs.updateRow(); } } con.setAutoCommit(true); } catch (Exception ex) { //log the exception and rollback con.rollback(); } finally { con.close(); } ``` All the updates would then be batched into the same transaction. If any of the updates generated an Exception (such as an invalid value or the connection failing part way through the results), the whole lot would be rolled back. (Finally added because I am a champion of it ;p ) This however, won't address your second issue which is two competing methods trying to update the same table - a race condition. There are, in my mind, two main approaches here - each has it's merits and drawbacks. The easiest approach would be to [Lock the table](http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html) - this would require minimal code changes but has a pretty big drawback. Working on the assumption that, as with most applications, it's more read that write: locking the table will prevent all other users from viewing the data, with the likelihood the code will hang, waiting for the lock to release before the connection time-out kicks in and throws an exception. The more complex approach is to ensure that the methods for performing these updates are implemented in a thread-safe manner. To that end: * All the updates for this table pass through a single Class * That class implements a Singleton pattern, or exposes the update methods as Static methods * The update methods utilise the [Synchronized](http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html) keyword to prevent race conditions
211,436
<p>In my database, in one of the table I have a GUID column with allow nulls. I have a method with a Guid? parameter that inserts a new data row in the table. However when I say myNewRow.myGuidColumn = myGuid I get the following error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'." </p>
[ { "answer_id": 211462, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 6, "selected": true, "text": "<p>The ADO.NET API has some problems when it comes to handling nullable value types (i.e. it simply doesn't work correctly). We've had no end of issues with it, and so have arrived at the conclusion that it's best to manually set the value to null, e.g.</p>\n\n<pre><code>myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : myGuid.Value\n</code></pre>\n\n<p>It's painful extra work that ADO.NET should handle, but it doesn't seem to do so reliably (even in 3.5 SP1). This at least works correctly.</p>\n\n<p>We've also seen issues with passing nullable value types to SqlParameters where the generated SQL includes the keyword <code>DEFAULT</code> instead of <code>NULL</code> for the value so I'd recommend the same approach when building parameters.</p>\n" }, { "answer_id": 211463, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>OK; how is myGuidColumn defined, and how is myGuid defined?</p>\n\n<p>If myGuid is <code>Guid?</code> and myGuidColumn is <code>Guid</code>, then the error is correct: you will need to use <code>myGuid.Value</code>, or <code>(Guid)myGuid</code> to get the value (which will throw if it is null), or perhaps <code>myGuid.GetValueOrDefault()</code> to return the zero guid if null.</p>\n\n<p>If myGuid is <code>Guid</code> and myGuidColumn is <code>Guid?</code>, then it should work.</p>\n\n<p>If myGuidColumn is <code>object</code>, you probably need <code>DBNull.Value</code> instead of the regular null.</p>\n\n<p>Of course, if the column is truly nullable, you might simply want to ensure that it is <code>Guid?</code> in the C# code ;-p</p>\n" }, { "answer_id": 211522, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "<p>You can use a helper method:</p>\n\n<pre><code>public static class Ado {\n public static void SetParameterValue&lt;T&gt;( IDataParameter parameter, T? value ) where T : struct {\n if ( null == value ) { parameter.Value = DBNull.Value; }\n else { parameter.Value = value.Value; }\n }\n public static void SetParameterValue( IDataParameter parameter, string value ) {\n if ( null == value ) { parameter.Value = DBNull.Value; }\n else { parameter.Value = value; }\n }\n}\n</code></pre>\n" }, { "answer_id": 211645, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>or:</p>\n\n<pre><code> internal static T CastTo&lt;T&gt;(object value)\n {\n return value != DBNull.Value ? (T)value : default(T);\n }\n</code></pre>\n" }, { "answer_id": 211667, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 2, "selected": false, "text": "<p>If you want to avoid working with nullable GUIDs in your c# code (personally, I often find it cumbersome to work with nullable types) you could somewhere early assign <a href=\"http://msdn.microsoft.com/en-us/library/system.guid.empty.aspx\" rel=\"nofollow noreferrer\">Guid.Empty</a> to the .NET data which is null in the db. That way, you don't have to bother with all the .HasValue stuff and just check if <code>myGuid != Guid.Empty</code> instead.</p>\n" }, { "answer_id": 211882, "author": "cheeves", "author_id": 15826, "author_profile": "https://Stackoverflow.com/users/15826", "pm_score": 3, "selected": false, "text": "<p>same as Greg Beech's answer</p>\n\n<pre><code>myNewRow.myGuidColumn = (object)myGuid ?? DBNull.Value\n</code></pre>\n" }, { "answer_id": 6358944, "author": "Imran", "author_id": 799744, "author_profile": "https://Stackoverflow.com/users/799744", "pm_score": 2, "selected": false, "text": "<p>Try System.Guid.Empty where you want it to be null</p>\n" }, { "answer_id": 16443648, "author": "Justin", "author_id": 945875, "author_profile": "https://Stackoverflow.com/users/945875", "pm_score": 1, "selected": false, "text": "<p>If you are into extension methods...</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Returns nullable Guid (Guid?) value if not null or Guid.Empty, otherwise returns DBNull.Value\n/// &lt;/summary&gt;\npublic static object GetValueOrDBNull(this Guid? aGuid)\n{\n return (!aGuid.IsNullOrEmpty()) ? (object)aGuid : DBNull.Value;\n}\n\n/// &lt;summary&gt;\n/// Determines if a nullable Guid (Guid?) is null or Guid.Empty\n/// &lt;/summary&gt;\npublic static bool IsNullOrEmpty(this Guid? aGuid)\n{\n return (!aGuid.HasValue || aGuid.Value == Guid.Empty);\n}\n</code></pre>\n\n<p>Then you could say:\n<code>myNewRow.myGuidColumn = myGuid.GetValueOrDBNull();</code></p>\n\n<p>NOTE: This will insert null when <code>myGuid == Guid.Empty</code>, you could easily tweak the method if you want to allow empty Guids in your column.</p>\n" }, { "answer_id": 26699430, "author": "Chtioui Malek", "author_id": 1254684, "author_profile": "https://Stackoverflow.com/users/1254684", "pm_score": 3, "selected": false, "text": "<p>You have to cast <code>null</code> to a <code>nullable Guid</code>, this how it worked for me :</p>\n\n<pre><code>myRecord.myGuidCol = (myGuid == null) ? (Guid?)null : myGuid.Value\n</code></pre>\n" }, { "answer_id": 33213838, "author": "maurox", "author_id": 662403, "author_profile": "https://Stackoverflow.com/users/662403", "pm_score": 0, "selected": false, "text": "<pre><code>Guid? _field = null;\nif (myValue!=\"\")//test if myValue has value\n{\n_field = Guid.Parse(myValue)\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
In my database, in one of the table I have a GUID column with allow nulls. I have a method with a Guid? parameter that inserts a new data row in the table. However when I say myNewRow.myGuidColumn = myGuid I get the following error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'."
The ADO.NET API has some problems when it comes to handling nullable value types (i.e. it simply doesn't work correctly). We've had no end of issues with it, and so have arrived at the conclusion that it's best to manually set the value to null, e.g. ``` myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : myGuid.Value ``` It's painful extra work that ADO.NET should handle, but it doesn't seem to do so reliably (even in 3.5 SP1). This at least works correctly. We've also seen issues with passing nullable value types to SqlParameters where the generated SQL includes the keyword `DEFAULT` instead of `NULL` for the value so I'd recommend the same approach when building parameters.
211,448
<p>I have a custom class that implements <code>ICollection</code>, and this class is readonly, ie. <code>IsReadOnly</code> returns true (as opposed to using the <code>readonly</code> keyword), and all functions that would normally modify the data in the collection throw <code>InvalidOperationException</code>'s.</p> <p>Now, given such a construct, and a quick skim over the thread-safety issues when implementing <code>ICollection</code> (specifically <a href="http://msdn.microsoft.com/en-us/library/system.collections.icollection.issynchronized.aspx" rel="noreferrer"><code>ICollection.IsSynchronized</code></a> and friends), I came up with this quick and dirty solution.</p> <pre><code>bool ICollection.IsSynchronised { get{ return true; } } object ICollection.SyncRoot { get{ return new Object(); } } </code></pre> <p>Now, given the examples in MSDN, this won't cause different threads to lock properly, because they are getting different objects from <code>SyncRoot</code>. Given that this is a readonly collection though, is this an issue? Are there memory/GC issues with returning <code>new Object()</code>? Any other issues you can see with this implementation?</p>
[ { "answer_id": 211469, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>I guess the issue would be if clients used your sync root to achieve locking of not only your collection, but something else. Supposed they cached the size of the collection - or maybe \"what subset of this collection matches a predicate\" - they would reasonably assume that they could use your SyncRoot to guard both your collection and their other member.</p>\n\n<p>Personally I hardly use SyncRoot at all, but I think it would be sensible to always return the same thing.</p>\n" }, { "answer_id": 211479, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>It seems very odd to return a different object each time... actually, I very rarely (if ever) use the SyncRoot approach, as often I need to synchronize between multiple objects etc, so a separate object is more meaningful.</p>\n\n<p>But if the data is truly immutable (readonly), why not just return false from IsSynchronized?</p>\n\n<p>Re GC - any such object would typically be short lived and be collected in GEN0. If you have a field with an object (for the lock), it would last as long as the collection, but most likely won't hurt anyway...</p>\n\n<p>If you need a lock, I'd be tempted to just have a:</p>\n\n<pre><code>private readonly object lockObj = new object();\n</code></pre>\n\n<p>You could also use a lazy approach to only \"new\" it when needed, which makes a certain amount of sense if you don't actually expect anyone to ask for the sync-lock (by returns false to IsSynchronized).</p>\n\n<p>Another common approach is to return \"this\"; it keeps things simple, but risks conflicts with some other code using your object as a lock for an unrelated purpose. Rare, but possible. This is actually the approach that <code>[MethodImpl]</code> uses to synchronize.</p>\n" }, { "answer_id": 211491, "author": "Kimoz", "author_id": 7753, "author_profile": "https://Stackoverflow.com/users/7753", "pm_score": 3, "selected": true, "text": "<p>Yes this is an issue in some cases. Even though the collection is read only and cannot be changed, the objects the collection references are not read only. Thus if the clients use the SyncRoot to perform locking they will not be thread safe when modifying the objects referenced by the collection.</p>\n\n<p>I would recommend adding:</p>\n\n<pre><code>private readonly object syncRoot = new object();\n</code></pre>\n\n<p>to your class. Return this as the SyncRoot and you're good to go.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
I have a custom class that implements `ICollection`, and this class is readonly, ie. `IsReadOnly` returns true (as opposed to using the `readonly` keyword), and all functions that would normally modify the data in the collection throw `InvalidOperationException`'s. Now, given such a construct, and a quick skim over the thread-safety issues when implementing `ICollection` (specifically [`ICollection.IsSynchronized`](http://msdn.microsoft.com/en-us/library/system.collections.icollection.issynchronized.aspx) and friends), I came up with this quick and dirty solution. ``` bool ICollection.IsSynchronised { get{ return true; } } object ICollection.SyncRoot { get{ return new Object(); } } ``` Now, given the examples in MSDN, this won't cause different threads to lock properly, because they are getting different objects from `SyncRoot`. Given that this is a readonly collection though, is this an issue? Are there memory/GC issues with returning `new Object()`? Any other issues you can see with this implementation?
Yes this is an issue in some cases. Even though the collection is read only and cannot be changed, the objects the collection references are not read only. Thus if the clients use the SyncRoot to perform locking they will not be thread safe when modifying the objects referenced by the collection. I would recommend adding: ``` private readonly object syncRoot = new object(); ``` to your class. Return this as the SyncRoot and you're good to go.
211,477
<p>I'd like to know how to - if even possible - reflect what method calls are executed inside the method during execution. I'm especially interested in either external method calls (that is, methods in other classes) or calling some specific method like getDatabaseConnection().</p> <p>My intention would be to monitor predefined objects' actions inside methods and execute additional code if some specific conditions are met like some method is called with specific values. The monitor would be completely external class or a set of classes with no direct access to the object to be monitored by no other way than reflection.</p>
[ { "answer_id": 211482, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>I'd expect <a href=\"http://jakarta.apache.org/bcel/index.html\" rel=\"nofollow noreferrer\">BCEL</a> to be able to do this. From the web site:</p>\n\n<blockquote>\n <p>The Byte Code Engineering Library is\n intended to give users a convenient\n possibility to analyze, create, and\n manipulate (binary) Java class files\n (those ending with .class).</p>\n</blockquote>\n\n<p>The \"analyze\" part being the important bit here. The JavaDoc isn't visible on the web site (as far as I can see) so I can't easily be sure whether or not it'll help you, but it's a reasonable starting point.</p>\n" }, { "answer_id": 211528, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>BCEL should offer this capability, but ...</p>\n\n<p>... your requirements sound a lot like Aspect-Oriented Programming (AOP), so you should probably also look at <a href=\"http://www.eclipse.org/aspectj/\" rel=\"nofollow noreferrer\">AspectJ</a> (with <a href=\"http://www.eclipse.org/ajdt/\" rel=\"nofollow noreferrer\">Eclipse tooling</a>).</p>\n\n<p>The main advantage of AspectJ is that it offers a well-designed way to express your specific conditions.</p>\n" }, { "answer_id": 212474, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.eclipse.org/aspectj/\" rel=\"nofollow noreferrer\">Aspect J</a> will solve your problem.</p>\n\n<p>Try to define a pointcut like this: </p>\n\n<pre><code>pointcut profilling(): execution(public * *(..)) &amp;&amp; (\n within(com.myPackage..*) ||\n</code></pre>\n\n<p>In this way you will catch all the call to any public method within the package com.myPackage. Add as many within clauses you need.</p>\n\n<p>Then add the following code:</p>\n\n<pre><code>Object around(): profilling() {\n\n //Do wherever you need before method call\n proceed();\n //Do wherever you need after method call\n\n}\n</code></pre>\n\n<p>IF you want to learn something more about aspectJ follow this <a href=\"http://www.eclipse.org/aspectj/doc/released/progguide/index.html\" rel=\"nofollow noreferrer\">guide</a>.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'd like to know how to - if even possible - reflect what method calls are executed inside the method during execution. I'm especially interested in either external method calls (that is, methods in other classes) or calling some specific method like getDatabaseConnection(). My intention would be to monitor predefined objects' actions inside methods and execute additional code if some specific conditions are met like some method is called with specific values. The monitor would be completely external class or a set of classes with no direct access to the object to be monitored by no other way than reflection.
[Aspect J](http://www.eclipse.org/aspectj/) will solve your problem. Try to define a pointcut like this: ``` pointcut profilling(): execution(public * *(..)) && ( within(com.myPackage..*) || ``` In this way you will catch all the call to any public method within the package com.myPackage. Add as many within clauses you need. Then add the following code: ``` Object around(): profilling() { //Do wherever you need before method call proceed(); //Do wherever you need after method call } ``` IF you want to learn something more about aspectJ follow this [guide](http://www.eclipse.org/aspectj/doc/released/progguide/index.html).
211,483
<p>I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g.</p> <pre><code>hashlib.sha256(str(user_id)+str(expiry_time)) hmac.new(str(random.randbits(256))) </code></pre> <p>(ignore for the moment that random.randbits() might not be cryptographically good). edit: I realise that the hmac example is silly because I'm not storing the key anywhere!</p>
[ { "answer_id": 211503, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>You can.</p>\n\n<p>However, for the HMAC, you actually want to store the key somewhere. Without the key, there is no way for you to verify the hash value later. :-)</p>\n" }, { "answer_id": 211506, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>Well, usually hash-functions (and cryptographic functions generally) work on bytes. The Python strings are basically byte-strings. If you want to compute the hash of some object you have to convert it to a string representation. Just make sure to apply the same operation later if you want to check if the hash is correct. And make sure that your string representation doesn't contain any changing data that you don't want to be checked.</p>\n\n<p>Edit: Due to popular request a short reminder that Python unicode strings don't contain bytes but unicode code points. Each unicode code point contains <em>multiple</em> bytes (2 or 4, depending on how the Python interpreter was compiled). Python strings only contain bytes. So Python strings (type <em>str</em>) are the type most similar to an array of bytes.</p>\n" }, { "answer_id": 211509, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": -1, "selected": false, "text": "<p>Oh and Sha256 isn't really an industrial strength cryptographic function (although unfortunately it's used quite commonly on many sites). It's not a real way to protect passwords or other critical data, but more than good enough for generating temporal tokens</p>\n\n<p>Edit: As mentioned Sha256 needs at least some salt. Without salt, Sha256 has a low barrier to being cracked with a dictionary attack (time-wise) and there are plenty of Rainbow tables to use as well. Personally I'd not use anything less than Blowfish for passwords (but that's because I'm paranoid) </p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23402/" ]
I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g. ``` hashlib.sha256(str(user_id)+str(expiry_time)) hmac.new(str(random.randbits(256))) ``` (ignore for the moment that random.randbits() might not be cryptographically good). edit: I realise that the hmac example is silly because I'm not storing the key anywhere!
Well, usually hash-functions (and cryptographic functions generally) work on bytes. The Python strings are basically byte-strings. If you want to compute the hash of some object you have to convert it to a string representation. Just make sure to apply the same operation later if you want to check if the hash is correct. And make sure that your string representation doesn't contain any changing data that you don't want to be checked. Edit: Due to popular request a short reminder that Python unicode strings don't contain bytes but unicode code points. Each unicode code point contains *multiple* bytes (2 or 4, depending on how the Python interpreter was compiled). Python strings only contain bytes. So Python strings (type *str*) are the type most similar to an array of bytes.
211,487
<p>In JUnit 3 I simply called</p> <pre><code>suite.addTestSuite( MyTest.class ) </code></pre> <p>However if MyTest is a JUnit 4 test which does not extend TestCase this doesn't work. What should I do instead to create a suite of tests?</p>
[ { "answer_id": 211603, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "<p>You can use the Waveform Audio Interface, there is an <a href=\"http://msdn.microsoft.com/en-us/library/aa446573.aspx\" rel=\"nofollow noreferrer\">MSDN article</a> on how to access it per PInvoke.</p>\n\n<p>In order to capture the sound that is being played, you just need to open the playback device instead of the microphone. Open for input, of course, not for output ;-)</p>\n" }, { "answer_id": 212184, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 6, "selected": true, "text": "<p>Assuming that you are talking about Windows, there are essentially three ways to do this. </p>\n\n<p>The first is to open the audio device's main output as a recording source. This is only possible when the driver supports it, although most do these days. Common names for the virtual device are \"What You Hear\" or \"Wave Out\". You will need to use a suitable API (see WaveIn or DirectSound in MSDN) to do the capturing.</p>\n\n<p>The second way is to write a filter driver that can intercept the audio stream before it reaches the physical device. Again, this technique will only work for devices that have a suitable driver topology and it's certainly not for the faint-hearted.</p>\n\n<p>This means that neither of these options will be guaranteed to work on a PC with arbitrary hardware.</p>\n\n<p>The last alternative is to use a virtual audio device, such as <a href=\"http://www.ntonyx.com/vac.htm\" rel=\"noreferrer\">Virtual Audio Cable</a>. If this device is set as the defualt playback device in Windows then all well-behaved apps will play through it. You can then record from the same device to capture the summed output. As long as you have control over the device that the application you want to record uses then this option will always work.</p>\n\n<p>All of these techniques have their pros and cons - it's up to you to decide which would be the most suitable for your needs.</p>\n" }, { "answer_id": 263258, "author": "bastibe", "author_id": 1034, "author_profile": "https://Stackoverflow.com/users/1034", "pm_score": 0, "selected": false, "text": "<p>If you were using OSX, <a href=\"http://rogueamoeba.com/audiohijackpro/\" rel=\"nofollow noreferrer\">Audio Hijack Pro from Rogue Amoeba</a> probably is the easiest way to go. </p>\n\n<p>Anyway, why not just looping your audio back into your line in and recording that? This is a <em>very</em> simple solution. Just plug a cable in your audio output jack and your line in jack and start recordung.</p>\n" }, { "answer_id": 579820, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You have to enable device stero mix. if you do this, direct sound find this device.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
In JUnit 3 I simply called ``` suite.addTestSuite( MyTest.class ) ``` However if MyTest is a JUnit 4 test which does not extend TestCase this doesn't work. What should I do instead to create a suite of tests?
Assuming that you are talking about Windows, there are essentially three ways to do this. The first is to open the audio device's main output as a recording source. This is only possible when the driver supports it, although most do these days. Common names for the virtual device are "What You Hear" or "Wave Out". You will need to use a suitable API (see WaveIn or DirectSound in MSDN) to do the capturing. The second way is to write a filter driver that can intercept the audio stream before it reaches the physical device. Again, this technique will only work for devices that have a suitable driver topology and it's certainly not for the faint-hearted. This means that neither of these options will be guaranteed to work on a PC with arbitrary hardware. The last alternative is to use a virtual audio device, such as [Virtual Audio Cable](http://www.ntonyx.com/vac.htm). If this device is set as the defualt playback device in Windows then all well-behaved apps will play through it. You can then record from the same device to capture the summed output. As long as you have control over the device that the application you want to record uses then this option will always work. All of these techniques have their pros and cons - it's up to you to decide which would be the most suitable for your needs.
211,493
<p>I'm just in the process of upgrading my Preview 5 application to Beta 1, and I'm nearly there save for this one error when trying to render a control:</p> <blockquote> <p>'System.Web.Mvc.HtmlHelper' does not contain a definition for 'RenderPartial' and no extension method 'RenderPartial' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)</p> </blockquote> <p>My markup (in the .aspx View Content Page) is:</p> <pre><code>&lt;% Html.RenderPartial("Controls/UserForm", ViewData); %&gt; </code></pre> <p>I've tried using Microsoft.Web.Mvc but to no avail. Does anyone know where Html.RenderPartial has gone, or what alternative I could use?</p>
[ { "answer_id": 211524, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 3, "selected": false, "text": "<p>Now fixed - the conflict was a difference in Web.config requirements between Preview 5 and Beta 1. The following needs to be added into the system.web compilation assemblies node:</p>\n\n<pre><code>&lt;add assembly=\"System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/&gt;\n</code></pre>\n\n<p>After this change, all of my old HtmlHelper methods magically came back!</p>\n" }, { "answer_id": 212829, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 2, "selected": false, "text": "<p>In addition to adding the assembly reference I also had to add the line</p>\n\n<pre><code> &lt;add namespace=\"System.Web.Mvc.Html\"/&gt;\" \n</code></pre>\n\n<p>to the pages/namespaces section in web.config file.</p>\n" }, { "answer_id": 216867, "author": "spinodal", "author_id": 11374, "author_profile": "https://Stackoverflow.com/users/11374", "pm_score": 4, "selected": true, "text": "<p>And also don't forget to add namespaces like below to the web config, I think preview 5 default web.config does not have System.Web.Mvc.Html in it:</p>\n\n<pre><code>&lt;namespaces&gt;\n &lt;add namespace=\"System.Web.Mvc\"/&gt;\n &lt;add namespace=\"System.Web.Mvc.Ajax\"/&gt;\n &lt;add namespace=\"System.Web.Mvc.Html\"/&gt;\n &lt;add namespace=\"System.Web.Routing\"/&gt;\n &lt;add namespace=\"System.Linq\"/&gt;\n &lt;add namespace=\"System.Collections.Generic\"/&gt;\n&lt;/namespaces&gt;\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
I'm just in the process of upgrading my Preview 5 application to Beta 1, and I'm nearly there save for this one error when trying to render a control: > > 'System.Web.Mvc.HtmlHelper' does not > contain a definition for > 'RenderPartial' and no extension > method 'RenderPartial' accepting a > first argument of type > 'System.Web.Mvc.HtmlHelper' could be > found (are you missing a using > directive or an assembly reference?) > > > My markup (in the .aspx View Content Page) is: ``` <% Html.RenderPartial("Controls/UserForm", ViewData); %> ``` I've tried using Microsoft.Web.Mvc but to no avail. Does anyone know where Html.RenderPartial has gone, or what alternative I could use?
And also don't forget to add namespaces like below to the web config, I think preview 5 default web.config does not have System.Web.Mvc.Html in it: ``` <namespaces> <add namespace="System.Web.Mvc"/> <add namespace="System.Web.Mvc.Ajax"/> <add namespace="System.Web.Mvc.Html"/> <add namespace="System.Web.Routing"/> <add namespace="System.Linq"/> <add namespace="System.Collections.Generic"/> </namespaces> ```
211,496
<p>Is using a handrolled POCO queue class using pseudo code</p> <pre><code>T Dequeue() { lock(syncRoot) { if(queue.Empty) Thread.Wait(); } } void Enqueue(T item) { queue.Enqueue(item); Thread.Notify(); } </code></pre> <p>For WCF is request queueing a scalable approach?</p>
[ { "answer_id": 211524, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 3, "selected": false, "text": "<p>Now fixed - the conflict was a difference in Web.config requirements between Preview 5 and Beta 1. The following needs to be added into the system.web compilation assemblies node:</p>\n\n<pre><code>&lt;add assembly=\"System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/&gt;\n</code></pre>\n\n<p>After this change, all of my old HtmlHelper methods magically came back!</p>\n" }, { "answer_id": 212829, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 2, "selected": false, "text": "<p>In addition to adding the assembly reference I also had to add the line</p>\n\n<pre><code> &lt;add namespace=\"System.Web.Mvc.Html\"/&gt;\" \n</code></pre>\n\n<p>to the pages/namespaces section in web.config file.</p>\n" }, { "answer_id": 216867, "author": "spinodal", "author_id": 11374, "author_profile": "https://Stackoverflow.com/users/11374", "pm_score": 4, "selected": true, "text": "<p>And also don't forget to add namespaces like below to the web config, I think preview 5 default web.config does not have System.Web.Mvc.Html in it:</p>\n\n<pre><code>&lt;namespaces&gt;\n &lt;add namespace=\"System.Web.Mvc\"/&gt;\n &lt;add namespace=\"System.Web.Mvc.Ajax\"/&gt;\n &lt;add namespace=\"System.Web.Mvc.Html\"/&gt;\n &lt;add namespace=\"System.Web.Routing\"/&gt;\n &lt;add namespace=\"System.Linq\"/&gt;\n &lt;add namespace=\"System.Collections.Generic\"/&gt;\n&lt;/namespaces&gt;\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28413/" ]
Is using a handrolled POCO queue class using pseudo code ``` T Dequeue() { lock(syncRoot) { if(queue.Empty) Thread.Wait(); } } void Enqueue(T item) { queue.Enqueue(item); Thread.Notify(); } ``` For WCF is request queueing a scalable approach?
And also don't forget to add namespaces like below to the web config, I think preview 5 default web.config does not have System.Web.Mvc.Html in it: ``` <namespaces> <add namespace="System.Web.Mvc"/> <add namespace="System.Web.Mvc.Ajax"/> <add namespace="System.Web.Mvc.Html"/> <add namespace="System.Web.Routing"/> <add namespace="System.Linq"/> <add namespace="System.Collections.Generic"/> </namespaces> ```
211,498
<p>We use GUIDs for primary key, which you know is clustered by default.</p> <p>When inserting a new row into a table it is inserted at a random page in the table (because GUIDs are random). This has a measurable performance impact because the DB will split data pages all the time (fragmentation). But the main reason I what a sequential GUID is because I want new rows to be inserted as the last row in the table... which will help when debugging.</p> <p>I could make a clustered index on <code>CreateDate</code>, but our DB is auto-generated and in development, we need to do something extra to facilitate this. Also, <code>CreateDate</code> is not a good candidate for a clustered index.</p> <p>Back in the day, I used <a href="http://www.informit.com/articles/article.aspx?p=25862" rel="nofollow noreferrer">Jimmy Nielsons COMB's</a>, but I was wondering if there is something in the .NET framework for this. In SQL 2005 Microsoft introduced <code>newsequentialid()</code> as an alternative to <code>newid()</code>, so I was hoping that they made a .NET equivalent because we generate the ID in the code.</p> <p>PS: Please don't start discussing if this is right or wrong, because GUIDs should be unique etc.</p>
[ { "answer_id": 211514, "author": "BlackWasp", "author_id": 21862, "author_profile": "https://Stackoverflow.com/users/21862", "pm_score": -1, "selected": false, "text": "<p>The key problem is knowing what the last value was in a .NET application. SQL Server keeps track of this for you. You will need to hold the last value yourself and use the Guid constructor with a byte array containing the next value. Of course, on a distributed application this probably isn't going to help and you may have to use the randomised Guids. (Not that I see anything wrong with this.)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/90ck37x3.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/90ck37x3.aspx</a></p>\n" }, { "answer_id": 211515, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 3, "selected": false, "text": "<p>Perhaps a simple way to determine the order in which rows have been added would be to add an IDENTITY column to the table, avoiding the need to keep your GUIDS in order and hence avoiding the performance hit of maintaining a clustered index on the GUID column.</p>\n\n<p>I can't help but wonder how keeping these rows in order helps you when debugging. Could you expand that a bit?</p>\n" }, { "answer_id": 211542, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "<p>Unfortunatley, no there isn't a .NET equivalent to <code>newsequentialid()</code>. You could continue using a Comb. I actually have a C# implementation of a Comb somewhere...I'll see if I can dig it up.</p>\n" }, { "answer_id": 211757, "author": "John", "author_id": 33, "author_profile": "https://Stackoverflow.com/users/33", "pm_score": 6, "selected": true, "text": "<p>It should be possible to create a sequential GUID in c# or vb.net using an API call to UuidCreateSequential. The API declaration (C#) below has been taken from <a href=\"http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html\" rel=\"noreferrer\">Pinvoke.net</a> where you can also find a full example of how to call the function. </p>\n\n<pre><code>[DllImport(\"rpcrt4.dll\", SetLastError=true)]\nstatic extern int UuidCreateSequential(out Guid guid);\n</code></pre>\n\n<p>The MSDN article related to the UuidCreateSequential function can be <a href=\"http://msdn.microsoft.com/en-us/library/aa379322.aspx\" rel=\"noreferrer\">found here</a> which includes the prerequisites for use.</p>\n" }, { "answer_id": 211822, "author": "Jason Stangroome", "author_id": 20819, "author_profile": "https://Stackoverflow.com/users/20819", "pm_score": 0, "selected": false, "text": "<p>I've been lead to believe that random Guids can be beneficial to performance in some use cases. Apparently inserting to random pages can avoid contention that would otherwise occur in the end page when multiple people are trying to insert at the same time.</p>\n\n<p>John's PInvoke suggestions is probably the closest to SQL's version but the UUidCreateSequential docs state that you shouldn't use it to identify an object that it's strictly local to the machine generating the Guid.</p>\n\n<p>I'd be measuring the actual use case performance hit with realistic data in realistic quantities before I investigated sequential Guid generation any further.</p>\n" }, { "answer_id": 1314226, "author": "Donny V.", "author_id": 1231, "author_profile": "https://Stackoverflow.com/users/1231", "pm_score": 2, "selected": false, "text": "<p>Here is the C# code to generate a COMB GUID.</p>\n\n<pre><code>byte[] guidArray = System.Guid.NewGuid().ToByteArray();\n\nDateTime baseDate = new DateTime(1900, 1, 1);\nDateTime now = DateTime.Now;\n\n// Get the days and milliseconds which will be used to build the byte string \nTimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);\nTimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks));\n\n// Convert to a byte array \n// Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333 \nbyte[] daysArray = BitConverter.GetBytes(days.Days);\nbyte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));\n\n// Reverse the bytes to match SQL Servers ordering \nArray.Reverse(daysArray);\nArray.Reverse(msecsArray);\n\n// Copy the bytes into the guid \nArray.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);\nArray.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);\n\nreturn new System.Guid(guidArray);\n</code></pre>\n" }, { "answer_id": 3936157, "author": "Daniel", "author_id": 169388, "author_profile": "https://Stackoverflow.com/users/169388", "pm_score": 0, "selected": false, "text": "<p>About the selected answer. The docs says... The generated Guid will not give you uniqueId between computers if they don't have ehternet access.</p>\n\n<p>If you must know the guid when inserting, couldn't you let Sql-server return a block of sequential guids that you assign to your data before you insert them?</p>\n\n<pre><code>declare @ids table(id uniqueidentifier default NEWSEQUENTIALID(), dummy char(1))\n\ndeclare @c int\nset @c = 0;\nwhile (@c &lt; 100)\nbegin\n insert into @ids (dummy) values ('a');\n set @c += 1;\nend\n\nselect id from @ids\n</code></pre>\n" }, { "answer_id": 12580020, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 5, "selected": false, "text": "<p><strong>Update 2018:</strong> Also <a href=\"https://stackoverflow.com/a/49256827/66629\">check my other answer</a></p>\n\n<p>This is how NHibernate generate sequantial IDs:</p>\n\n<p><a href=\"https://github.com/nhibernate/nhibernate-core/blob/5e71e83ac45439239b9028e6e87d1a8466aba551/src/NHibernate/Id/GuidCombGenerator.cs\" rel=\"noreferrer\">NHibernate.Id.GuidCombGenerator</a></p>\n\n<pre><code>/// &lt;summary&gt;\n/// Generate a new &lt;see cref=\"Guid\"/&gt; using the comb algorithm.\n/// &lt;/summary&gt;\nprivate Guid GenerateComb()\n{\n byte[] guidArray = Guid.NewGuid().ToByteArray();\n\n DateTime baseDate = new DateTime(1900, 1, 1);\n DateTime now = DateTime.Now;\n\n // Get the days and milliseconds which will be used to build the byte string \n TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);\n TimeSpan msecs = now.TimeOfDay;\n\n // Convert to a byte array \n // Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333 \n byte[] daysArray = BitConverter.GetBytes(days.Days);\n byte[] msecsArray = BitConverter.GetBytes((long) (msecs.TotalMilliseconds / 3.333333));\n\n // Reverse the bytes to match SQL Servers ordering \n Array.Reverse(daysArray);\n Array.Reverse(msecsArray);\n\n // Copy the bytes into the guid \n Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);\n Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);\n\n return new Guid(guidArray);\n}\n</code></pre>\n" }, { "answer_id": 47682820, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 4, "selected": false, "text": "<p>It's important to note that the UUIDs generated by <strong><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa379322(v=vs.85).aspx\" rel=\"noreferrer\">UuidCreateSequential</a></strong> will not be sequential when ordered by SQL Server.</p>\n<ul>\n<li>SQL Server follows the <a href=\"https://www.rfc-editor.org/rfc/rfc4122\" rel=\"noreferrer\">RFC</a> when it comes to sorting UUIDs</li>\n<li>the RFC got it wrong</li>\n<li><code>UuidCreateSequential</code> did it right</li>\n<li>but <code>UuidCreateSequential</code> creates something different from what SQL Server expects</li>\n</ul>\n<h1>Background</h1>\n<p>The Type 1 UUIDs created by UuidCreateSequential don't sort in SQL Server.</p>\n<p>SQL Server's <strong>NewSequentialID</strong> uses <strong>UuidCreateSequential</strong>, with some byte shuffling applied. From the Books Online:</p>\n<blockquote>\n<p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/newsequentialid-transact-sql\" rel=\"noreferrer\"><strong>NEWSEQUENTIALID (Transact-SQL)</strong></a></p>\n<p>NEWSEQUENTIALID is a wrapper over the Windows UuidCreateSequential function, with <a href=\"https://blogs.msdn.microsoft.com/dbrowne/2012/07/03/how-to-generate-sequential-guids-for-sql-server-in-net/\" rel=\"noreferrer\">some byte shuffling applied</a></p>\n</blockquote>\n<p>which then references an MSDN blog post:</p>\n<blockquote>\n<p><a href=\"https://blogs.msdn.microsoft.com/dbrowne/2012/07/03/how-to-generate-sequential-guids-for-sql-server-in-net/\" rel=\"noreferrer\"><strong>How to Generate Sequential GUIDs for SQL Server in .NET</strong></a> <em>(<a href=\"http://archive.is/jJYuK\" rel=\"noreferrer\">archive</a>)</em></p>\n<pre><code>public static Guid NewSequentialId()\n{\n Guid guid;\n UuidCreateSequential(out guid);\n var s = guid.ToByteArray();\n var t = new byte[16];\n \n t[3] = s[0];\n t[2] = s[1];\n t[1] = s[2];\n t[0] = s[3];\n \n t[5] = s[4];\n t[4] = s[5];\n t[7] = s[6];\n t[6] = s[7];\n t[8] = s[8];\n t[9] = s[9];\n t[10] = s[10];\n t[11] = s[11];\n t[12] = s[12];\n t[13] = s[13];\n t[14] = s[14];\n t[15] = s[15];\n \n return new Guid(t);\n}\n</code></pre>\n</blockquote>\n<p>It all starts with the number of ticks since <code>1582-10-15 00:00:00</code> (October 15, 1592, the date of\nGregorian reform to the Christian calendar). Ticks is the number of 100 ns intervals.</p>\n<p>For example:</p>\n<ul>\n<li>12/6/2017 4:09:39 PM UTC</li>\n<li>= 137,318,693,794,503,714 ticks</li>\n<li>= <code>0x01E7DA9FDCA45C22</code> ticks</li>\n</ul>\n<p>The RFC says that we should split this value into three chunks:</p>\n<ul>\n<li>UInt32 low (4 bytes)</li>\n<li>Uint16 mid (2 bytes)</li>\n<li>UInt32 hi (2 bytes)</li>\n</ul>\n<p>So we split it up:</p>\n<pre><code>0x01E7DA9FDCA45C22\n\n| Hi | Mid | Low |\n|--------|--------|------------|\n| 0x01E7 | 0xDA9F | 0xDCA45C22 |\n</code></pre>\n<p>And then the RFC says that these three integers should be written out in the order of:</p>\n<ul>\n<li><strong>Low:</strong> 0xDCA45C22</li>\n<li><strong>Mid:</strong> 0xDA9F</li>\n<li><strong>High:</strong> 0x01E7</li>\n</ul>\n<p>If you follow the RFC, these values must be written in <em>big-endian</em> (aka <em>&quot;network byte order&quot;</em>):</p>\n<pre><code>DC A4 5C 22 DA 9F x1 E7 xx xx xx xx xx xx xx xx\n</code></pre>\n<p>This was a bad design, because you cannot take the first 8 bytes of the UUID and treat them either as a big-endian UInt64, nor as a little-endian UInt64. It's a totally dumb encoding.</p>\n<h2>UuidCreateSequential gets it right</h2>\n<p>Microsoft followed all the same rules so far:</p>\n<ul>\n<li><strong>Low:</strong> 0xDCA45C22</li>\n<li><strong>Mid:</strong> 0xDA9F</li>\n<li><strong>High:</strong> 0x1E7</li>\n</ul>\n<p>But they write it out in Intel <strong>little-endian</strong> order:</p>\n<pre><code>22 5C A4 DC 9F DA E7 x1 xx xx xx xx xx xx xx xx\n</code></pre>\n<p>If you look at that, you've just written out a little-endian <code>Int64</code>:</p>\n<pre><code>225CA4DC9FDAE701\n</code></pre>\n<p>Meaning:</p>\n<ul>\n<li>if you wanted to extract the timestamp</li>\n<li>or sort by the timestamp</li>\n</ul>\n<p>it's trivial; just treat the first 8 bytes as a UInt64.</p>\n<p>With the RFC, you have no choice but to perform all kinds of bit fiddling. Even on big-endian machines, you can't treat the 64-bit timestamp as a 64-bit timestamp.</p>\n<h2>How to reverse it</h2>\n<p>Given a little-endian guid from <code>UuidCreateSequential</code>:</p>\n<pre><code>DCA45C22-DA9F-11E7-DDDD-FFFFFFFFFFFF\n</code></pre>\n<p>with the raw bytes of:</p>\n<pre><code>22 5C A4 DC 9F DA E7 11 DD DD FF FF FF FF FF FF\n</code></pre>\n<p>This decodes into:</p>\n<pre><code>Low Mid Version High\n-------- ---- ------- ---- -----------------\nDCA45C22-DA9F-1 1E7 -DDDD-FFFFFFFFFFFF\n</code></pre>\n<ul>\n<li><strong>Low:</strong> 0xDCA45C22</li>\n<li><strong>Mid:</strong> 0xDA9F</li>\n<li><strong>High:</strong> 0x1E7</li>\n<li><strong>Version:</strong> 1 (type 1)</li>\n</ul>\n<p>We can write this back out in RFC big-endian order:</p>\n<pre><code>DC A4 5C 22 DA 9F 11 E7 DD DD FF FF FF FF FF FF\n</code></pre>\n<h2>Short version</h2>\n<pre><code> | Swap | Swap | Swap | Copy as-is\nStart index | 0 1 2 3 | 4 5 | 6 7 | \nEnd index | 3 2 1 0 | 5 4 | 7 6 | \n---------------|-------------|-------|-------|------------------------ \nLittle-endian: | 22 5C A4 DC | 9F DA | E7 11 | DD DD FF FF FF FF FF FF\nBig-endian: | DC A4 5C 22 | DA 9F | 11 E7 | DD DD FF FF FF FF FF FF\n</code></pre>\n" }, { "answer_id": 49256827, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 3, "selected": false, "text": "<p>You can use the tiny NewId library for this.</p>\n\n<p>Install it via NuGet:</p>\n\n<pre><code>Install-Package NewId\n</code></pre>\n\n<p>And use it like this:</p>\n\n<pre><code>Guid myNewSequentialGuid = NewId.NextGuid();\n</code></pre>\n\n<p>See <a href=\"https://github.com/phatboyg/NewId\" rel=\"noreferrer\">Project Page on GitHub</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
We use GUIDs for primary key, which you know is clustered by default. When inserting a new row into a table it is inserted at a random page in the table (because GUIDs are random). This has a measurable performance impact because the DB will split data pages all the time (fragmentation). But the main reason I what a sequential GUID is because I want new rows to be inserted as the last row in the table... which will help when debugging. I could make a clustered index on `CreateDate`, but our DB is auto-generated and in development, we need to do something extra to facilitate this. Also, `CreateDate` is not a good candidate for a clustered index. Back in the day, I used [Jimmy Nielsons COMB's](http://www.informit.com/articles/article.aspx?p=25862), but I was wondering if there is something in the .NET framework for this. In SQL 2005 Microsoft introduced `newsequentialid()` as an alternative to `newid()`, so I was hoping that they made a .NET equivalent because we generate the ID in the code. PS: Please don't start discussing if this is right or wrong, because GUIDs should be unique etc.
It should be possible to create a sequential GUID in c# or vb.net using an API call to UuidCreateSequential. The API declaration (C#) below has been taken from [Pinvoke.net](http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html) where you can also find a full example of how to call the function. ``` [DllImport("rpcrt4.dll", SetLastError=true)] static extern int UuidCreateSequential(out Guid guid); ``` The MSDN article related to the UuidCreateSequential function can be [found here](http://msdn.microsoft.com/en-us/library/aa379322.aspx) which includes the prerequisites for use.
211,535
<h2>Note</h2> <p>The question below was asked in 2008 about some code from 2003. As the OP's <strong>update</strong> shows, this entire post has been obsoleted by vintage 2008 algorithms and persists here only as a historical curiosity.</p> <hr> <p>I need to do a fast case-insensitive substring search in C/C++. My requirements are as follows:</p> <ul> <li>Should behave like strstr() (i.e. return a pointer to the match point).</li> <li>Must be case-insensitive (doh).</li> <li>Must support the current locale.</li> <li>Must be available on Windows (MSVC++ 8.0) or easily portable to Windows (i.e. from an open source library).</li> </ul> <p>Here is the current implementation I am using (taken from the GNU C Library):</p> <pre><code>/* Return the offset of one string within another. Copyright (C) 1994,1996,1997,1998,1999,2000 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* * My personal strstr() implementation that beats most other algorithms. * Until someone tells me otherwise, I assume that this is the * fastest implementation of strstr() in C. * I deliberately chose not to comment it. You should have at least * as much fun trying to understand it, as I had to write it :-). * * Stephen R. van den Berg, [email protected] */ /* * Modified to use table lookup instead of tolower(), since tolower() isn't * worth s*** on Windows. * * -- Anders Sandvig ([email protected]) */ #if HAVE_CONFIG_H # include &lt;config.h&gt; #endif #include &lt;ctype.h&gt; #include &lt;string.h&gt; typedef unsigned chartype; char char_table[256]; void init_stristr(void) { int i; char string[2]; string[1] = '\0'; for (i = 0; i &lt; 256; i++) { string[0] = i; _strlwr(string); char_table[i] = string[0]; } } #define my_tolower(a) ((chartype) char_table[a]) char * my_stristr (phaystack, pneedle) const char *phaystack; const char *pneedle; { register const unsigned char *haystack, *needle; register chartype b, c; haystack = (const unsigned char *) phaystack; needle = (const unsigned char *) pneedle; b = my_tolower (*needle); if (b != '\0') { haystack--; /* possible ANSI violation */ do { c = *++haystack; if (c == '\0') goto ret0; } while (my_tolower (c) != (int) b); c = my_tolower (*++needle); if (c == '\0') goto foundneedle; ++needle; goto jin; for (;;) { register chartype a; register const unsigned char *rhaystack, *rneedle; do { a = *++haystack; if (a == '\0') goto ret0; if (my_tolower (a) == (int) b) break; a = *++haystack; if (a == '\0') goto ret0; shloop: ; } while (my_tolower (a) != (int) b); jin: a = *++haystack; if (a == '\0') goto ret0; if (my_tolower (a) != (int) c) goto shloop; rhaystack = haystack-- + 1; rneedle = needle; a = my_tolower (*rneedle); if (my_tolower (*rhaystack) == (int) a) do { if (a == '\0') goto foundneedle; ++rhaystack; a = my_tolower (*++needle); if (my_tolower (*rhaystack) != (int) a) break; if (a == '\0') goto foundneedle; ++rhaystack; a = my_tolower (*++needle); } while (my_tolower (*rhaystack) == (int) a); needle = rneedle; /* took the register-poor approach */ if (a == '\0') break; } } foundneedle: return (char*) haystack; ret0: return 0; }</code></pre> <p>Can you make this code faster, or do you know of a better implementation?</p> <p><strong>Note:</strong> I noticed that the GNU C Library now has <a href="http://sources.redhat.com/cgi-bin/cvsweb.cgi/libc/string/strstr.c?rev=1.2&amp;content-type=text/x-cvsweb-markup&amp;cvsroot=glibc" rel="nofollow noreferrer">a new implementation of <code>strstr()</code></a>, but I am not sure how easily it can be modified to be case-insensitive, or if it is in fact faster than the old one (in my case). I also noticed that <a href="http://sources.redhat.com/cgi-bin/cvsweb.cgi/libc/wcsmbs/wcsstr.c?rev=1.4&amp;content-type=text/x-cvsweb-markup&amp;cvsroot=glibc" rel="nofollow noreferrer">the old implementation is still used for wide character strings</a>, so if anyone knows why, please share.</p> <p><strong>Update</strong></p> <p>Just to make things clear&mdash;in case it wasn't already&mdash;I didn't write this function, it's a part of the GNU C Library. I only modified it to be case-insensitive.</p> <p>Also, thanks for the tip about <code>strcasestr()</code> and checking out other implementations from other sources (like OpenBSD, FreeBSD, etc.). It seems to be the way to go. The code above is from 2003, which is why I posted it here in hope for a better version being available, which apparently it is. :)</p>
[ { "answer_id": 211561, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 2, "selected": false, "text": "<p>Why do you use &#95;strlwr(string); in init&#95;stristr()? It's not a standard function. Presumably it's for locale support, but as it's not standard, I'd just use:</p>\n\n<pre><code>char_table[i] = tolower(i);\n</code></pre>\n" }, { "answer_id": 211673, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 1, "selected": false, "text": "<p>I'd advice you to take some of the common strcasestr implementation that already exists. For example of glib, glibc, OpenBSD, FreeBSD, etc. You can search for more with google.com/codesearch. You can then make some performance measurements and compare the different implementation.</p>\n" }, { "answer_id": 211859, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 5, "selected": true, "text": "<p>The code you posted is about half as fast as <code>strcasestr</code>.\n</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ gcc -Wall -o my_stristr my_stristr.c\nsteve@solaris:~/code/tmp\n$ gcc -Wall -o strcasestr strcasestr.c \nsteve@solaris:~/code/tmp\n$ ./bench ./my_stristr &gt; my_stristr.result ; ./bench ./strcasestr &gt; strcasestr.result;\nsteve@solaris:~/code/tmp\n$ cat my_stristr.result \nrun 1... time = 6.32\nrun 2... time = 6.31\nrun 3... time = 6.31\nrun 4... time = 6.31\nrun 5... time = 6.32\nrun 6... time = 6.31\nrun 7... time = 6.31\nrun 8... time = 6.31\nrun 9... time = 6.31\nrun 10... time = 6.31\naverage user time over 10 runs = 6.3120\nsteve@solaris:~/code/tmp\n$ cat strcasestr.result \nrun 1... time = 3.82\nrun 2... time = 3.82\nrun 3... time = 3.82\nrun 4... time = 3.82\nrun 5... time = 3.82\nrun 6... time = 3.82\nrun 7... time = 3.82\nrun 8... time = 3.82\nrun 9... time = 3.82\nrun 10... time = 3.82\naverage user time over 10 runs = 3.8200\nsteve@solaris:~/code/tmp\n</code></pre>\n\n<p>The <code>main</code> function was:\n</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int main(void)\n{\n char * needle=\"hello\";\n char haystack[1024];\n int i;\n\n for(i=0;i&lt;sizeof(haystack)-strlen(needle)-1;++i)\n {\n haystack[i]='A'+i%57;\n }\n memcpy(haystack+i,needle, strlen(needle)+1);\n /*printf(\"%s\\n%d\\n\", haystack, haystack[strlen(haystack)]);*/\n init_stristr();\n\n for (i=0;i&lt;1000000;++i)\n {\n /*my_stristr(haystack, needle);*/\n strcasestr(haystack,needle);\n }\n\n\n return 0;\n}\n</code></pre>\n\n<p>It was suitably modified to test both implementations. I notice as I am typing this up I left in the <code>init_stristr</code> call, but it shouldn't change things too much. <code>bench</code> is just a simple shell script:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#!/bin/bash\nfunction bc_calc()\n{\n echo $(echo \"scale=4;$1\" | bc)\n}\ntime=\"/usr/bin/time -p\"\nprog=\"$1\"\naccum=0\nruns=10\nfor a in $(jot $runs 1 $runs)\ndo\n echo -n \"run $a... \"\n t=$($time $prog 2&gt;&amp;1| grep user | awk '{print $2}')\n echo \"time = $t\"\n accum=$(bc_calc \"$accum+$t\")\ndone\n\necho -n \"average user time over $runs runs = \"\necho $(bc_calc \"$accum/$runs\")\n</code></pre>\n" }, { "answer_id": 211904, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 1, "selected": false, "text": "<p>Assuming both input strings are already lowercase.</p>\n\n<pre><code>int StringInStringFindFirst(const char* p_cText, const char* p_cSearchText)\n{\n int iTextSize = strlen(p_cText);\n int iSearchTextSize = strlen(p_cSearchText);\n\n char* p_cFound = NULL;\n\n if(iTextSize &gt;= iSearchTextSize)\n {\n int iCounter = 0;\n while((iCounter + iSearchTextSize) &lt;= iTextSize)\n {\n if(memcmp( (p_cText + iCounter), p_cSearchText, iSearchTextSize) == 0)\n return iCounter;\n iCounter ++;\n }\n }\n\n return -1;\n}\n</code></pre>\n\n<p>You could also, try using masks... if for example most of the strings you are going to compare only contains chars from a to z, maybe it's worth to do something like this.</p>\n\n<pre><code>long GetStringMask(const char* p_cText)\n{\n long lMask=0;\n\n while(*p_cText != '\\0')\n { \n if (*p_cText&gt;='a' &amp;&amp; *p_cText&lt;='z')\n lMask = lMask | (1 &lt;&lt; (*p_cText - 'a') );\n else if(*p_cText != ' ')\n {\n lMask = 0;\n break; \n }\n\n p_cText ++;\n }\n return lMask;\n}\n</code></pre>\n\n<p>Then...</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n\n char* p_cText = \"this is a test\"; \n char* p_cSearchText = \"test\";\n\n long lTextMask = GetStringMask(p_cText);\n long lSearchMask = GetStringMask(p_cSearchText);\n\n int iFoundAt = -1;\n // If Both masks are Valid\n if(lTextMask != 0 &amp;&amp; lSearchMask != 0)\n {\n if((lTextMask &amp; lSearchMask) == lSearchMask)\n { \n iFoundAt = StringInStringFindFirst(p_cText, p_cSearchText);\n }\n }\n else\n {\n iFoundAt = StringInStringFindFirst(p_cText, p_cSearchText);\n }\n\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 212137, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 0, "selected": false, "text": "<p>If you want to shed CPU cycles, you might consider this - let's assume that we're dealing with ASCII and not Unicode.</p>\n\n<p>Make a static table with 256 entries. Each entry in the table is 256 bits.</p>\n\n<p>To test whether or not two characters are equal, you do something like this:</p>\n\n<pre><code>if (BitLookup(table[char1], char2)) { /* match */ }\n</code></pre>\n\n<p>To build the table, you set a bit everywhere in table[char1] where you consider it a match for char2. So in building the table you would set the bits at the index for 'a' and 'A' in the 'a'th entry (and the 'A'th entry).</p>\n\n<p>Now this is going to be slowish to do the bit lookup (bit look up will be a shift, mask and add most likely), so you could use instead a table of bytes so you use 8 bits to represent 1 bit. This will take 32K - so hooray - you've hit a time/space trade-off! We might want to make the table more flexible, so let's say we do this instead - the table will define congruences instead.</p>\n\n<p>Two characters are considered congruent if and only if there is a function that defines them as equivalent. So 'A' and 'a' are congruent for case insensitivity. 'A', '&Agrave;', '&Aacute;' and '&#194;' are congruent for diacritical insensitivity.</p>\n\n<p>So you define bitfields that correspond to your congruencies</p>\n\n<pre><code>#define kCongruentCase (1 &lt;&lt; 0)\n#define kCongruentDiacritical (1 &lt;&lt; 1)\n#define kCongruentVowel (1 &lt;&lt; 2)\n#define kCongruentConsonant (1 &lt;&lt; 3)\n</code></pre>\n\n<p>Then your test is something like this:</p>\n\n<pre><code>inline bool CharsAreCongruent(char c1, char c2, unsigned char congruency)\n{\n return (_congruencyTable[c1][c2] &amp; congruency) != 0;\n}\n\n#define CaseInsensitiveCharEqual(c1, c2) CharsAreCongruent(c1, c2, kCongruentCase)\n</code></pre>\n\n<p>This kind of bit fiddling with ginormous tables is the heart of ctype, by the by.</p>\n" }, { "answer_id": 213542, "author": "deft_code", "author_id": 28817, "author_profile": "https://Stackoverflow.com/users/28817", "pm_score": 2, "selected": false, "text": "<p>use <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/string_algo.html\" rel=\"nofollow noreferrer\">boost string algo</a>. It is available, cross platform, and only a header file (no library to link in). Not to mention that you should be using boost anyway.</p>\n\n<pre><code>#include &lt;boost/algorithm/string/find.hpp&gt;\n\nconst char* istrstr( const char* haystack, const char* needle )\n{\n using namespace boost;\n iterator_range&lt;char*&gt; result = ifind_first( haystack, needle );\n if( result ) return result.begin();\n\n return NULL;\n}\n</code></pre>\n" }, { "answer_id": 216120, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>If you can control the needle string so that it is always in lower case, then you can write a modified version of stristr() to avoid the lookups for that, and thus speed up the code. It isn't as general, but it can be faster - slightly faster. Similar comments apply to the haystack, but you are more likely to be reading the haystack from sources outside your control for you cannot be certain that the data meets the requirement.</p>\n\n<p>Whether the gain in performance is worth it is another question altogether. For 99% of applications, the answer is \"No, it is not worth it\". Your application might be one of the tiny minority where it matters. More likely, it is not.</p>\n" }, { "answer_id": 15758849, "author": "Lefteris E", "author_id": 1017417, "author_profile": "https://Stackoverflow.com/users/1017417", "pm_score": 1, "selected": false, "text": "<p>This will not consider the locale, but If you can change the IS_ALPHA and TO_UPPER you can make it to consider it.</p>\n\n<pre><code>#define IS_ALPHA(c) (((c) &gt;= 'A' &amp;&amp; (c) &lt;= 'Z') || ((c) &gt;= 'a' &amp;&amp; (c) &lt;= 'z'))\n#define TO_UPPER(c) ((c) &amp; 0xDF)\n\nchar * __cdecl strstri (const char * str1, const char * str2){\n char *cp = (char *) str1;\n char *s1, *s2;\n\n if ( !*str2 )\n return((char *)str1);\n\n while (*cp){\n s1 = cp;\n s2 = (char *) str2;\n\n while ( *s1 &amp;&amp; *s2 &amp;&amp; (IS_ALPHA(*s1) &amp;&amp; IS_ALPHA(*s2))?!(TO_UPPER(*s1) - TO_UPPER(*s2)):!(*s1-*s2))\n ++s1, ++s2;\n\n if (!*s2)\n return(cp);\n\n ++cp;\n }\n return(NULL);\n}\n</code></pre>\n" }, { "answer_id": 21595284, "author": "Nitin Chhabra", "author_id": 1724302, "author_profile": "https://Stackoverflow.com/users/1724302", "pm_score": 3, "selected": false, "text": "<p>You can use StrStrI function which finds the first occurrence of a substring within a string. The comparison is not case-sensitive.\nDon't forget to include its header - Shlwapi.h.\nCheck this out: <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb773439(v=vs.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/windows/desktop/bb773439(v=vs.85).aspx</a></p>\n" }, { "answer_id": 37402374, "author": "Suzuki Keem", "author_id": 6373579, "author_profile": "https://Stackoverflow.com/users/6373579", "pm_score": 2, "selected": false, "text": "<p>For platform independent use:</p>\n\n<pre><code>const wchar_t *szk_wcsstri(const wchar_t *s1, const wchar_t *s2)\n{\n if (s1 == NULL || s2 == NULL) return NULL;\n const wchar_t *cpws1 = s1, *cpws1_, *cpws2;\n char ch1, ch2;\n bool bSame;\n\n while (*cpws1 != L'\\0')\n {\n bSame = true;\n if (*cpws1 != *s2)\n {\n ch1 = towlower(*cpws1);\n ch2 = towlower(*s2);\n\n if (ch1 == ch2)\n bSame = true;\n }\n\n if (true == bSame)\n {\n cpws1_ = cpws1;\n cpws2 = s2;\n while (*cpws1_ != L'\\0')\n {\n ch1 = towlower(*cpws1_);\n ch2 = towlower(*cpws2);\n\n if (ch1 != ch2)\n break;\n\n cpws2++;\n\n if (*cpws2 == L'\\0')\n return cpws1_-(cpws2 - s2 - 0x01);\n cpws1_++;\n }\n }\n cpws1++;\n }\n return NULL;\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709/" ]
Note ---- The question below was asked in 2008 about some code from 2003. As the OP's **update** shows, this entire post has been obsoleted by vintage 2008 algorithms and persists here only as a historical curiosity. --- I need to do a fast case-insensitive substring search in C/C++. My requirements are as follows: * Should behave like strstr() (i.e. return a pointer to the match point). * Must be case-insensitive (doh). * Must support the current locale. * Must be available on Windows (MSVC++ 8.0) or easily portable to Windows (i.e. from an open source library). Here is the current implementation I am using (taken from the GNU C Library): ``` /* Return the offset of one string within another. Copyright (C) 1994,1996,1997,1998,1999,2000 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* * My personal strstr() implementation that beats most other algorithms. * Until someone tells me otherwise, I assume that this is the * fastest implementation of strstr() in C. * I deliberately chose not to comment it. You should have at least * as much fun trying to understand it, as I had to write it :-). * * Stephen R. van den Berg, [email protected] */ /* * Modified to use table lookup instead of tolower(), since tolower() isn't * worth s*** on Windows. * * -- Anders Sandvig ([email protected]) */ #if HAVE_CONFIG_H # include <config.h> #endif #include <ctype.h> #include <string.h> typedef unsigned chartype; char char_table[256]; void init_stristr(void) { int i; char string[2]; string[1] = '\0'; for (i = 0; i < 256; i++) { string[0] = i; _strlwr(string); char_table[i] = string[0]; } } #define my_tolower(a) ((chartype) char_table[a]) char * my_stristr (phaystack, pneedle) const char *phaystack; const char *pneedle; { register const unsigned char *haystack, *needle; register chartype b, c; haystack = (const unsigned char *) phaystack; needle = (const unsigned char *) pneedle; b = my_tolower (*needle); if (b != '\0') { haystack--; /* possible ANSI violation */ do { c = *++haystack; if (c == '\0') goto ret0; } while (my_tolower (c) != (int) b); c = my_tolower (*++needle); if (c == '\0') goto foundneedle; ++needle; goto jin; for (;;) { register chartype a; register const unsigned char *rhaystack, *rneedle; do { a = *++haystack; if (a == '\0') goto ret0; if (my_tolower (a) == (int) b) break; a = *++haystack; if (a == '\0') goto ret0; shloop: ; } while (my_tolower (a) != (int) b); jin: a = *++haystack; if (a == '\0') goto ret0; if (my_tolower (a) != (int) c) goto shloop; rhaystack = haystack-- + 1; rneedle = needle; a = my_tolower (*rneedle); if (my_tolower (*rhaystack) == (int) a) do { if (a == '\0') goto foundneedle; ++rhaystack; a = my_tolower (*++needle); if (my_tolower (*rhaystack) != (int) a) break; if (a == '\0') goto foundneedle; ++rhaystack; a = my_tolower (*++needle); } while (my_tolower (*rhaystack) == (int) a); needle = rneedle; /* took the register-poor approach */ if (a == '\0') break; } } foundneedle: return (char*) haystack; ret0: return 0; } ``` Can you make this code faster, or do you know of a better implementation? **Note:** I noticed that the GNU C Library now has [a new implementation of `strstr()`](http://sources.redhat.com/cgi-bin/cvsweb.cgi/libc/string/strstr.c?rev=1.2&content-type=text/x-cvsweb-markup&cvsroot=glibc), but I am not sure how easily it can be modified to be case-insensitive, or if it is in fact faster than the old one (in my case). I also noticed that [the old implementation is still used for wide character strings](http://sources.redhat.com/cgi-bin/cvsweb.cgi/libc/wcsmbs/wcsstr.c?rev=1.4&content-type=text/x-cvsweb-markup&cvsroot=glibc), so if anyone knows why, please share. **Update** Just to make things clear—in case it wasn't already—I didn't write this function, it's a part of the GNU C Library. I only modified it to be case-insensitive. Also, thanks for the tip about `strcasestr()` and checking out other implementations from other sources (like OpenBSD, FreeBSD, etc.). It seems to be the way to go. The code above is from 2003, which is why I posted it here in hope for a better version being available, which apparently it is. :)
The code you posted is about half as fast as `strcasestr`. ```none $ gcc -Wall -o my_stristr my_stristr.c steve@solaris:~/code/tmp $ gcc -Wall -o strcasestr strcasestr.c steve@solaris:~/code/tmp $ ./bench ./my_stristr > my_stristr.result ; ./bench ./strcasestr > strcasestr.result; steve@solaris:~/code/tmp $ cat my_stristr.result run 1... time = 6.32 run 2... time = 6.31 run 3... time = 6.31 run 4... time = 6.31 run 5... time = 6.32 run 6... time = 6.31 run 7... time = 6.31 run 8... time = 6.31 run 9... time = 6.31 run 10... time = 6.31 average user time over 10 runs = 6.3120 steve@solaris:~/code/tmp $ cat strcasestr.result run 1... time = 3.82 run 2... time = 3.82 run 3... time = 3.82 run 4... time = 3.82 run 5... time = 3.82 run 6... time = 3.82 run 7... time = 3.82 run 8... time = 3.82 run 9... time = 3.82 run 10... time = 3.82 average user time over 10 runs = 3.8200 steve@solaris:~/code/tmp ``` The `main` function was: ```c int main(void) { char * needle="hello"; char haystack[1024]; int i; for(i=0;i<sizeof(haystack)-strlen(needle)-1;++i) { haystack[i]='A'+i%57; } memcpy(haystack+i,needle, strlen(needle)+1); /*printf("%s\n%d\n", haystack, haystack[strlen(haystack)]);*/ init_stristr(); for (i=0;i<1000000;++i) { /*my_stristr(haystack, needle);*/ strcasestr(haystack,needle); } return 0; } ``` It was suitably modified to test both implementations. I notice as I am typing this up I left in the `init_stristr` call, but it shouldn't change things too much. `bench` is just a simple shell script: ```c #!/bin/bash function bc_calc() { echo $(echo "scale=4;$1" | bc) } time="/usr/bin/time -p" prog="$1" accum=0 runs=10 for a in $(jot $runs 1 $runs) do echo -n "run $a... " t=$($time $prog 2>&1| grep user | awk '{print $2}') echo "time = $t" accum=$(bc_calc "$accum+$t") done echo -n "average user time over $runs runs = " echo $(bc_calc "$accum/$runs") ```
211,549
<p>How can I change the system-default regional settings in windows XP for use by services (run by the system user)?</p> <p>Regional and Language Options in the control panel modify the settings for the logged-in user. However, services don't use the user's settings - they use the system settings. I know that they can be found in the registry here: </p> <pre><code>HKEY_USERS\.DEFAULT\Control Panel\International </code></pre> <p>My question is: What mechanism is there for changing the system-language/date/etc from en-us to en-gb?</p>
[ { "answer_id": 211589, "author": "Paul M", "author_id": 28241, "author_profile": "https://Stackoverflow.com/users/28241", "pm_score": 0, "selected": false, "text": "<p>IM not sure if this will help</p>\n\n<p>First type in gpedit.msc from the run command and a dialog box should now open. \nNavigate to User Configuration > Administrative Templates > Control Panel > Regional Settings.</p>\n\n<p>This shows the group polcies for the PC/s, maybe you can just set it so en_gb is the only option!!</p>\n\n<p>Group Policy is not my strong point, but do a google search and go from there, I would imagine that you should be able to set up who and what can do what from here.</p>\n\n<p>HTH</p>\n" }, { "answer_id": 211626, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 2, "selected": false, "text": "<p>Not so easy.</p>\n\n<p>Fast way: define a specific user to run the service, logon with that user, set the regional settings, run the service.</p>\n" }, { "answer_id": 211646, "author": "Rodent43", "author_id": 28869, "author_profile": "https://Stackoverflow.com/users/28869", "pm_score": 2, "selected": false, "text": "<p>Could you not use regedt32 on a machine and make all the correct settings...then export the International folder by right clicking and export the reg file.</p>\n\n<p>you can manually edit the exported reg file if you dont need all the settings</p>\n\n<p>then you can run that reg file on a new machine to import the registry keys etc?</p>\n" }, { "answer_id": 214793, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 4, "selected": true, "text": "<p>There is no documented way to do that. </p>\n\n<p>A quick look in the Regional Settings Applet dll shows that it calls a totally undocumented API: NlsUpdateSystemLocale().</p>\n\n<p>Why do you want to do that? Do you want to control the locale of a service of yours? Then let your service run under a user account you control.</p>\n" }, { "answer_id": 4669008, "author": "Maksim Kulagin", "author_id": 382856, "author_profile": "https://Stackoverflow.com/users/382856", "pm_score": 3, "selected": false, "text": "<p>This was helpfull for me \n\"<a href=\"http://windows.microsoft.com/en-US/windows-vista/Apply-regional-and-language-settings-to-reserved-accounts\">Apply regional and language settings to reserved accounts</a>\".</p>\n\n<p>In short (Windows 7): Open \"<strong>Region and Language</strong>\" dialog, then click the \"<strong>Administrative</strong>\" tab, and then click \"<strong>Copy settings...</strong>\", select \"<strong>Welcome screen and system accounts</strong>\", <strong>OK</strong>.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15698/" ]
How can I change the system-default regional settings in windows XP for use by services (run by the system user)? Regional and Language Options in the control panel modify the settings for the logged-in user. However, services don't use the user's settings - they use the system settings. I know that they can be found in the registry here: ``` HKEY_USERS\.DEFAULT\Control Panel\International ``` My question is: What mechanism is there for changing the system-language/date/etc from en-us to en-gb?
There is no documented way to do that. A quick look in the Regional Settings Applet dll shows that it calls a totally undocumented API: NlsUpdateSystemLocale(). Why do you want to do that? Do you want to control the locale of a service of yours? Then let your service run under a user account you control.
211,550
<p>Having a strange rendering issue with Safari: </p> <p>I have a table inside a div. Inside the table &lt;td&gt; I have lots of div's floated left. So the normal display is all of the divs within the td stacked up to the left until they fill the width, then flow to the next line, and so forth. So something like this:</p> <pre><code>|===========================| | |---------------------| | | | XXX XXX XXX XXX | | | | XXX XXX | | | | | | | |---------------------- | |===========================| </code></pre> <p>That works in all browsers except safari/webkit, where it ends up something like this:</p> <pre><code>|===========================| | |-------------------------------| | | XXX XXX XXX XXX XXX XXX | | | | | |-------------------------------| |===========================| </code></pre> <p>Update: Finally figured out the issue: my inner divs (the "XXX"s) had <code>white-space: nowrap</code>. Apparently webkit was no-wrap'ing the entire list of divs instead of applying the nowrap within the div. </p> <p>That was a nasty one.</p> <p>(This had nothing to do with display:none)</p>
[ { "answer_id": 548640, "author": "Parand", "author_id": 13055, "author_profile": "https://Stackoverflow.com/users/13055", "pm_score": 3, "selected": true, "text": "<p>Answering my own question: </p>\n\n<p>Finally figured out the issue: my inner divs (the \"XXX\"s) had white-space: nowrap. Apparently webkit was no-wrap'ing the entire list of divs instead of applying the nowrap within the div.</p>\n\n<p>That was a nasty one.</p>\n\n<p>(This had nothing to do with display:none)</p>\n" }, { "answer_id": 2397481, "author": "Gabriel R.", "author_id": 170091, "author_profile": "https://Stackoverflow.com/users/170091", "pm_score": 2, "selected": false, "text": "<p>Actually, I asked my above question separately, then I found the solution like a big boy: </p>\n\n<p>Instead of using white-space:nowrap, in this case it's more appropriate to go with display:inline-block.</p>\n\n<p>The CSS needs to be adapted here and there for the change, but it works as expected.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2392344/elements-with-nowrap-get-stuck-to-adjacent-elements-in-webkit/2392360#2392360\">Elements with nowrap get stuck to adjacent elements in WebKit</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
Having a strange rendering issue with Safari: I have a table inside a div. Inside the table <td> I have lots of div's floated left. So the normal display is all of the divs within the td stacked up to the left until they fill the width, then flow to the next line, and so forth. So something like this: ``` |===========================| | |---------------------| | | | XXX XXX XXX XXX | | | | XXX XXX | | | | | | | |---------------------- | |===========================| ``` That works in all browsers except safari/webkit, where it ends up something like this: ``` |===========================| | |-------------------------------| | | XXX XXX XXX XXX XXX XXX | | | | | |-------------------------------| |===========================| ``` Update: Finally figured out the issue: my inner divs (the "XXX"s) had `white-space: nowrap`. Apparently webkit was no-wrap'ing the entire list of divs instead of applying the nowrap within the div. That was a nasty one. (This had nothing to do with display:none)
Answering my own question: Finally figured out the issue: my inner divs (the "XXX"s) had white-space: nowrap. Apparently webkit was no-wrap'ing the entire list of divs instead of applying the nowrap within the div. That was a nasty one. (This had nothing to do with display:none)
211,567
<p>When using a class that has an enum property, one usually gets a naming conflict between the property name and the enum type. Example:</p> <pre><code>enum Day{ Monday, Tuesday, ... } class MyDateClass { private Day day; public Day Day{ get{ return day; } } } </code></pre> <p>Since only flags enums should have plural names, naming the enum "Days" is not the way to go for a non-flag enum. In the above example you could use some variation like "WeekDay" for either the enum or the property. But in the general case there are no good variations like that so you end up using properties like "FooMode" or "BarKind" for an object with enum properties of Foo and Bar type. Not so elegant.</p> <p>How do you usually name enums and properties in this scenario? </p> <hr> <p>Thanks for the quick responses. Another question: why is it not recommended to nest public enums, and how do you resolve the naming issues if you want to nest public enums?</p> <pre><code>class Vehicle { enum Kind{ Car, Bike } public Kind Kind{ get{ return ... } } } class Meal { enum Kind{ Dessert, MainCourse } public Kind Kind{ get{ return ... } } } </code></pre> <p>In the scenario above, given that Meal and Vehicle share the same namespace, I can't move "Kind" outside either of the classes without renaming it MealKind and VehicleKind respectively. I like the look of </p> <pre><code>myVehicle.Kind = Vehicle.Kind.Car </code></pre> <p>But that is not what the guidlines recommend. What would be the best practice here? Never to use nested public enums and instead name them VehicleKind etc.? </p>
[ { "answer_id": 211571, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>So long as the enumeration isn't nested within MyDateClass, I don't see that that's a problem. It's far from uncommon (in my experience) to have a property with the same name as the type it returns. I'll see if I can find some examples in the framework...</p>\n\n<p>EDIT: First example: DateTimeOffset.DateTime (not an enum, but that's somewhat irrelevant)</p>\n" }, { "answer_id": 211576, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 5, "selected": false, "text": "<p>There is no conflict. In fact, the <a href=\"http://msdn.microsoft.com/en-us/library/ms229012.aspx\" rel=\"noreferrer\">.NET Framework style guide encourages you to do this</a>, e.g. if you have a class that has a single property of a type (no matter if enum or class), then you should name it the same. Typical example is a Color property of type Color. It's fine, unless there are two colors - in that case both should add something to the name (i.e. BackColor and ForeColor, instead of Color and BackColor).</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28858/" ]
When using a class that has an enum property, one usually gets a naming conflict between the property name and the enum type. Example: ``` enum Day{ Monday, Tuesday, ... } class MyDateClass { private Day day; public Day Day{ get{ return day; } } } ``` Since only flags enums should have plural names, naming the enum "Days" is not the way to go for a non-flag enum. In the above example you could use some variation like "WeekDay" for either the enum or the property. But in the general case there are no good variations like that so you end up using properties like "FooMode" or "BarKind" for an object with enum properties of Foo and Bar type. Not so elegant. How do you usually name enums and properties in this scenario? --- Thanks for the quick responses. Another question: why is it not recommended to nest public enums, and how do you resolve the naming issues if you want to nest public enums? ``` class Vehicle { enum Kind{ Car, Bike } public Kind Kind{ get{ return ... } } } class Meal { enum Kind{ Dessert, MainCourse } public Kind Kind{ get{ return ... } } } ``` In the scenario above, given that Meal and Vehicle share the same namespace, I can't move "Kind" outside either of the classes without renaming it MealKind and VehicleKind respectively. I like the look of ``` myVehicle.Kind = Vehicle.Kind.Car ``` But that is not what the guidlines recommend. What would be the best practice here? Never to use nested public enums and instead name them VehicleKind etc.?
There is no conflict. In fact, the [.NET Framework style guide encourages you to do this](http://msdn.microsoft.com/en-us/library/ms229012.aspx), e.g. if you have a class that has a single property of a type (no matter if enum or class), then you should name it the same. Typical example is a Color property of type Color. It's fine, unless there are two colors - in that case both should add something to the name (i.e. BackColor and ForeColor, instead of Color and BackColor).
211,583
<p>I am using a microcontroller with a C51 core. I have a fairly timeconsuming and large subroutine that needs to be called every 500ms. An RTOS is not being used. </p> <p>The way I am doing it right now is that I have an existing Timer interrupt of 10 ms. I set a flag after every 50 interrupts that is checked for being true in the main program loop. If the Flag is true the subroutine is called. The issue is that by the time the program loop comes round to servicing the flag, it is already more than 500ms,sometimes even >515 ms in case of certain code paths. The time taken is not accurately predictable.</p> <p>Obviously, the subroutine cannot be called from inside the timer interrupt due to that large time it takes to execute.The subroutine takes 50ms to 89ms depending upon various conditions.</p> <p>Is there a way to ensure that the subroutine is called in exactly 500ms each time?</p>
[ { "answer_id": 211632, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 1, "selected": false, "text": "<p>I think you have some conflicting/not-thought-through requirements here. You say that you can't call this code from the timer ISR because it takes too long to run (implying that it is a lower-priority than something else which would be delayed), but then you are being hit by the fact that something else which should have been lower-priority is delaying it when you run it from the foreground path ('program loop').</p>\n\n<p>If this work <em>must</em> happen at exactly 500ms, then run it from the timer routine, and deal with the fall-out from that. This is effectively what a pre-emptive RTOS would be doing anyway.</p>\n\n<p>If you want it to run from the 'program loop', then you will have to make sure than nothing else which runs from that loop ever takes more than the maximum delay you can tolerate - often that means breaking your other long-running work into state-machines which can do a little bit of work per pass through the loop.</p>\n" }, { "answer_id": 211893, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": true, "text": "<p>Would this do what you need?</p>\n\n<pre><code>#define FUDGE_MARGIN 2 //In 10ms increments\n\nvolatile unsigned int ticks = 0;\n\nvoid timer_10ms_interrupt( void ) { ticks++; }\n\nvoid mainloop( void )\n{\n unsigned int next_time = ticks+50;\n\n while( 1 )\n {\n do_mainloopy_stuff();\n\n if( ticks &gt;= next_time-FUDGE_MARGIN )\n {\n while( ticks &lt; next_time );\n do_500ms_thingy();\n next_time += 50;\n }\n }\n}\n</code></pre>\n\n<p>NB: If you got behind with servicing your every-500ms task then this would queue them up, which may not be what you want.</p>\n" }, { "answer_id": 211896, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "<p>I don't think there's a way to guarantee it but this solution may provide an acceptable alternative.</p>\n\n<p>Might I suggest <strong>not</strong> setting a flag but instead modifying a value?</p>\n\n<p>Here's how it could work.</p>\n\n<p>1/ Start a value at zero.</p>\n\n<p>2/ Every 10ms interrupt, increase this value by 10 in the ISR (interrupt service routine).</p>\n\n<p>3/ In the main loop, if the value is >= 500, subtract 500 from the value and do your 500ms activities.</p>\n\n<p>You will have to be careful to watch for race conditions between the timer and main program in modifying the value.</p>\n\n<p>This has the advantage that the function runs as close as possible to the 500ms boundaries regardless of latency or duration.</p>\n\n<p>If, for some reason, your function starts 20ms late in one iteration, the value will already be 520 so your function will then set it to 20, meaning it will only wait 480ms before the next iteration.</p>\n\n<p>That seems to me to be the best way to achieve what you want.</p>\n\n<p>I haven't touched the 8051 for many years (assuming that's what C51 is targeting which seems a safe bet given your description) but it may have an instruction which will subtract 50 without an interrupt being possible. However, I seem to remember the architecture was pretty simple so you may have to disable or delay interrupts while it does the load/modify/store operation.</p>\n\n<pre><code>volatile int xtime = 0;\nvoid isr_10ms(void) {\n xtime += 10;\n}\nvoid loop(void) {\n while (1) {\n /* Do all your regular main stuff here. */\n if (xtime &gt;= 500) {\n xtime -= 500;\n /* Do your 500ms activity here */\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 214486, "author": "Justin Tanner", "author_id": 609, "author_profile": "https://Stackoverflow.com/users/609", "pm_score": 1, "selected": false, "text": "<p>A good option is to use an RTOS or write your own simple RTOS.</p>\n\n<p>An RTOS to meet your needs will only need to do the following:</p>\n\n<ul>\n<li>schedule periodic tasks</li>\n<li>schedule round robin tasks</li>\n<li>preform context switching</li>\n</ul>\n\n<p>Your requirements are the following:</p>\n\n<ul>\n<li>execute a periodic task every 500ms</li>\n<li>in the extra time between execute round robin tasks ( doing non-time critical operations )</li>\n</ul>\n\n<p>An RTOS like this will guarantee a 99.9% chance that your code will execute on time. I can't say 100% because whatever operations your do in your ISR's may interfere with the RTOS. This is a problem with 8-bit micro-controllers that can only execute one instruction at a time.</p>\n\n<p>Writing an RTOS is tricky, but do-able. Here is an example of small ( 900 lines ) RTOS targeted at ATMEL's 8-bit AVR platform.</p>\n\n<p>The following is the <b><a href=\"http://www.jwtanner.com/csc460/Report2/\" rel=\"nofollow noreferrer\">Report and Code</a></b> created for the class CSC 460: Real Time Operating Systems ( at the University of Victoria ).</p>\n" }, { "answer_id": 223913, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 0, "selected": false, "text": "<p>One straightforward solution is to have a timer interrupt that fires off at 500ms...<br>\nIf you have some flexibility in your hardware design, you can cascade the output of one timer to a second stage counter to get you a long time base. I forget, but I vaguely recall being able to cascade timers on the x51.</p>\n" }, { "answer_id": 223930, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 0, "selected": false, "text": "<p>Why do you have a time-critical routine that takes so long to run? </p>\n\n<p>I agree with some of the others that there may be an architectural issue here. </p>\n\n<p>If the purpose of having precise 500ms (or whatever) intervals is to have signal changes occuring at specific time intervals, you may be better off with a fast ISR that ouputs the new signals based on a previous calculation, and then set a flag that would cause the new calculation to run outside of the ISR.</p>\n\n<p>Can you better describe what this long-running routine is doing, and what the need for the specific interval is for?</p>\n\n<hr>\n\n<p>Addition based on the comments:</p>\n\n<p>If you can insure that the time in the service routine is of a predictable duration, you might get away with missing the timer interrupt postings... </p>\n\n<p>To take your example, if your timer interrupt is set for 10 ms periods, and you know your service routine will take 89ms, just go ahead and count up 41 timer interrupts, then do your 89 ms activity and miss eight timer interrupts (42nd to 49th). </p>\n\n<p>Then, when your ISR exits (and clears the pending interrupt), the \"first\" interrupt of the next round of 500ms will occur about a ms later.</p>\n\n<p>Given that you're \"resource maxed\" suggests that you have your other timer and interrupt sources also in use -- which means that relying on the main loop to be timed accurately isn't going to work, because those other interrupt sources could fire at the wrong moment. </p>\n" }, { "answer_id": 223955, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 0, "selected": false, "text": "<p>Ah, one more alternative for consideration -- the x51 architecture allow two levels of interrupt priorities. If you have some hardware flexibility, you can cause one of the external interrupt pins to be raised by the timer ISR at 500ms intervals, and then let the lower-level interrupt processing of your every-500ms code to occur.</p>\n\n<p>Depending on your particular x51, you might be able to also generate a lower priority interrupt completely internal to your device.</p>\n\n<p>See part 11.2 in this document I found on the web: <a href=\"http://www.esacademy.com/automation/docs/c51primer/c11.htm\" rel=\"nofollow noreferrer\">http://www.esacademy.com/automation/docs/c51primer/c11.htm</a></p>\n" }, { "answer_id": 232631, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 0, "selected": false, "text": "<p>If I'm interpretting your question correctly, you have:</p>\n\n<ul>\n<li>a main loop</li>\n<li>some high priority operation that needs to be run every 500ms, for a duration of up to 89ms</li>\n<li>a 10ms timer that also performs a small number of operations.</li>\n</ul>\n\n<p>There are three options as I see it.\nThe first is to use a second timer of a lower priority for your 500ms operations. You can still process your 10ms interrupt, and once complete continue servicing your 500ms timer interrupt.</p>\n\n<p>Second option - doe you actually need to service your 10ms interrupt every 10ms? Is it doing anything other than time keeping? If not, and if your hardware will allow you to determine the number of 10ms ticks that have passed while processing your 500ms op's (ie. by not using the interrupts themselves), then can you start your 500ms op's within the 10ms interrupt and process the 10ms ticks that you missed when you're done.</p>\n\n<p>Third option: To follow on from Justin Tanner's answer, it sounds like you could produce your own preemptive multitasking kernel to fill your requirements without too much trouble.\nIt sounds like all you need is two tasks - one for the main super loop and one for your 500ms task.</p>\n\n<p>The code to swap between two contexts (ie. two copies of all of your registers, using different stack pointers) is very simple, and usually consists of a series of register pushes (to save the current context), a series of register pops (to restore your new context) and a return from interrupt instruction. Once your 500ms op's are complete, you restore the original context.</p>\n\n<p>(I guess that strictly this is a hybrid of preemptive and cooperative multitasking, but that's not important right now)</p>\n\n<hr>\n\n<p>edit:\nThere is a simple fourth option. Liberally pepper your main super loop with checks for whether the 500ms has elapsed, both before and after any lengthy operations.\nNot exactly 500ms, but you may be able to reduce the latency to a tolerable level.</p>\n" }, { "answer_id": 234402, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 1, "selected": false, "text": "<p>You can also use two flags - a \"pre-action\" flag, and a \"trigger\" flag (using Mike F's as a starting point):</p>\n\n<pre><code>#define PREACTION_HOLD_TICKS (2)\n#define TOTAL_WAIT_TICKS (10)\n\nvolatile unsigned char pre_action_flag;\nvolatile unsigned char trigger_flag;\n\nstatic isr_ticks;\ninterrupt void timer0_isr (void) {\n isr_ticks--;\n if (!isr_ticks) {\n isr_ticks=TOTAL_WAIT_TICKS;\n trigger_flag=1;\n } else {\n if (isr_ticks==PREACTION_HOLD_TICKS)\n preaction_flag=1;\n }\n}\n\n// ...\n\nint main(...) {\n\n\nisr_ticks = TOTAL_WAIT_TICKS;\npreaction_flag = 0;\ntigger_flag = 0;\n// ...\n\n while (1) {\n if (preaction_flag) {\n preaction_flag=0;\n while(!trigger_flag)\n ;\n trigger_flag=0;\n service_routine();\n } else {\n main_processing_routines();\n }\n }\n }\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27795/" ]
I am using a microcontroller with a C51 core. I have a fairly timeconsuming and large subroutine that needs to be called every 500ms. An RTOS is not being used. The way I am doing it right now is that I have an existing Timer interrupt of 10 ms. I set a flag after every 50 interrupts that is checked for being true in the main program loop. If the Flag is true the subroutine is called. The issue is that by the time the program loop comes round to servicing the flag, it is already more than 500ms,sometimes even >515 ms in case of certain code paths. The time taken is not accurately predictable. Obviously, the subroutine cannot be called from inside the timer interrupt due to that large time it takes to execute.The subroutine takes 50ms to 89ms depending upon various conditions. Is there a way to ensure that the subroutine is called in exactly 500ms each time?
Would this do what you need? ``` #define FUDGE_MARGIN 2 //In 10ms increments volatile unsigned int ticks = 0; void timer_10ms_interrupt( void ) { ticks++; } void mainloop( void ) { unsigned int next_time = ticks+50; while( 1 ) { do_mainloopy_stuff(); if( ticks >= next_time-FUDGE_MARGIN ) { while( ticks < next_time ); do_500ms_thingy(); next_time += 50; } } } ``` NB: If you got behind with servicing your every-500ms task then this would queue them up, which may not be what you want.
211,611
<p>I have a <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> <a href="http://www.google.com/search?hl=en&amp;q=TreeView%20msdn&amp;btnG=Search" rel="noreferrer">TreeView</a> (node, subnodes). Each node contains some additional information in its Tag. Also, each nodes maps a file on the disk. What's the easiest way copy/cut/paste nodes/files in C#?</p> <p>It would be nice to have some sample code.</p>
[ { "answer_id": 211619, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": false, "text": "<p>Consider using the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard_members.aspx\" rel=\"noreferrer\">Clipboard class</a>. It features all the methods necessary for putting data on the Windows clipboard and to retrieve data from the Windows clipboard.</p>\n<pre><code>StringCollection paths = new StringCollection();\npaths.Add(&quot;f:\\\\temp\\\\test.txt&quot;);\npaths.Add(&quot;f:\\\\temp\\\\test2.txt&quot;);\nClipboard.SetFileDropList(paths);\n</code></pre>\n<p>The code above will put the files test.txt and test2.txt for copy on the Windows Clipboard. After executing the code you can navigate to any folder and Paste (<kbd>Ctrl</kbd>+<kbd>V</kbd>) the files. This is equivalent to selecting both files in Windows Explorer and selecting copy (<kbd>Ctrl</kbd>+<kbd>C</kbd>).</p>\n" }, { "answer_id": 213294, "author": "AR.", "author_id": 1354, "author_profile": "https://Stackoverflow.com/users/1354", "pm_score": 3, "selected": false, "text": "<p>If you are only copying and pasting within your application, you can map the cut/copy operation of your treeview to a method that just clones your selected node. Ie:</p>\n\n<pre><code>TreeNode selectedNode;\nTreeNode copiedNode;\n\nselectedNode = yourTreeview.SelectedNode;\n\nif (selectedNode != null)\n{\n copiedNode = selectedNode.Clone;\n}\n\n// Then you can do whatever you like with copiedNode elsewhere in your app.\n</code></pre>\n\n<p>If you are wanting to be able to paste to other applications, then you'll have to use the clipboard. You can get a bit fancier than just plain text by learning more about the <strong>IDataObject</strong> interface. I can't remember the source but here's something I had in my own notes:</p>\n\n<blockquote>\n <p>When implemented in a class, the\n IDataObject methods allow the user to\n store data in multiple formats in an\n instance of the class. Storing data in\n more than one format increases the\n chance that a target application,\n whose format requirements you might\n not know, can retrieve the stored\n data. To store data in an instance of\n IDataObject, call the SetData method\n and specify the data format in the\n format parameter. Set the autoConvert\n parameter to false if you do not want\n stored data to be converted to another\n format when it is retrieved. Invoke\n SetData multiple times on one instance\n of IDataObject to store data in more\n than one format.</p>\n</blockquote>\n\n<p>Once you've populated an object that implements <strong>IDataObject</strong> (e.g. something called <strong>yourTreeNodeDataObject</strong>), then you can call:</p>\n\n<pre><code>Clipboard.SetDataObjecT(yourTreeNodeDataObject);\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) [TreeView](http://www.google.com/search?hl=en&q=TreeView%20msdn&btnG=Search) (node, subnodes). Each node contains some additional information in its Tag. Also, each nodes maps a file on the disk. What's the easiest way copy/cut/paste nodes/files in C#? It would be nice to have some sample code.
Consider using the [Clipboard class](http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard_members.aspx). It features all the methods necessary for putting data on the Windows clipboard and to retrieve data from the Windows clipboard. ``` StringCollection paths = new StringCollection(); paths.Add("f:\\temp\\test.txt"); paths.Add("f:\\temp\\test2.txt"); Clipboard.SetFileDropList(paths); ``` The code above will put the files test.txt and test2.txt for copy on the Windows Clipboard. After executing the code you can navigate to any folder and Paste (`Ctrl`+`V`) the files. This is equivalent to selecting both files in Windows Explorer and selecting copy (`Ctrl`+`C`).
211,612
<p>There are a dozen Rails plugins whose goal is to replace fixtures in testing. Here are a few I can think of:</p> <ul> <li>fixture replacement</li> <li>factory girl</li> <li>factories and workers</li> <li>rails scenarios</li> <li>fixture-scenarios</li> <li>object daddy</li> </ul> <p>There are probably others. Which of these plugins do you prefer and why?</p>
[ { "answer_id": 211649, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 3, "selected": false, "text": "<p>I personally use <a href=\"http://faker.rubyforge.org/\" rel=\"nofollow noreferrer\">Faker</a> with a custom Factory class. This allows me to create my factories, and populate the generated instances with non-static data.</p>\n\n<pre><code># spec/factory.rb\nmodule Factory\n def self.create_offer(options={})\n Offer.create({\n :code =&gt; Faker::Lorem.words(1),\n :expires_on =&gt; Time.now + (rand(30) + 1).day\n }.merge(options))\n end\nend\n\n\n# spec_helper.rb\nrequire 'faker'\nrequire 'spec/factory'\n\n\n# In the specs\n@offer = Factory.create_offer(:code =&gt; 'TESTING')\n</code></pre>\n" }, { "answer_id": 212040, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 2, "selected": false, "text": "<p>+1 factory girl</p>\n" }, { "answer_id": 213049, "author": "Jeff Waltzer", "author_id": 23513, "author_profile": "https://Stackoverflow.com/users/23513", "pm_score": 2, "selected": false, "text": "<p>We've just started using Factory Girl for our projects. Its way of doing things wasn't very different from our home grown solution so its working well for us.</p>\n" }, { "answer_id": 214227, "author": "James Baker", "author_id": 9365, "author_profile": "https://Stackoverflow.com/users/9365", "pm_score": 2, "selected": false, "text": "<p>I'll advocate for <a href=\"http://replacefixtures.rubyforge.org/\" rel=\"nofollow noreferrer\">Fixture Replacement 2</a>. Your default (don't care) model attributes are stored all in one place, db/example_data.rb, and provide quick valid objects. Any attributes you specify upon creation override the default attributes - meaning the data that you <strong>care</strong> about is <strong>in the test</strong>, and nothing else.</p>\n\n<p>Your example data can also refer to other default models, which are represented by procs with delayed evaluation, so you can override associations easily when desired.</p>\n\n<p>Version 2 provides a much cleaner definition format, while still providing the magic <code>new_*, create_*, and default_*</code> methods for every model.</p>\n\n<p>I would avoid any kind of \"scenarios\" scheme which encourages building more and more test data that's hard to read later. You can create named(custom) objects with FR2, but I've never found a need for it.</p>\n\n<p>P.S. Make sure you consider your <strong>unit</strong> testing strategy as well - Fixtures and all their analogues are real objects that hit the DB, making for functional or integration tests. I'm currently using RSpec's mocking along with <code>stub_model()</code> and the latest <a href=\"http://github.com/dan-manges/unit-record/tree/master\" rel=\"nofollow noreferrer\">unit_record</a> gem to disallow DB access.</p>\n" }, { "answer_id": 408961, "author": "Subbu", "author_id": 11107, "author_profile": "https://Stackoverflow.com/users/11107", "pm_score": 2, "selected": false, "text": "<p>I use Faker along with Populator gem by Ryan Bates. He even has a nice screencast at <a href=\"http://railscasts.com/episodes/126-populating-a-database\" rel=\"nofollow noreferrer\">http://railscasts.com/episodes/126-populating-a-database</a>.</p>\n" }, { "answer_id": 425316, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 2, "selected": false, "text": "<p>I've been playing around with <a href=\"http://github.com/notahat/machinist/tree/master\" rel=\"nofollow noreferrer\">machinist</a> lately and am digging it.</p>\n" }, { "answer_id": 432466, "author": "Abie", "author_id": 53166, "author_profile": "https://Stackoverflow.com/users/53166", "pm_score": 2, "selected": false, "text": "<p>I'm a big fan of the factory when you only need one or a few objects. You can either write your own or use Thoughtbot's <a href=\"http://www.thoughtbot.com/projects/factory_girl\" rel=\"nofollow noreferrer\">Factory Girl</a>.</p>\n\n<p>For situations where you need a curated set of interrelated objects, fixtures beat factory, and you should take a look at the excellent <a href=\"http://github.com/theIntuitionist/lite-fixtures/tree/master\" rel=\"nofollow noreferrer\">Lite Fixtures</a> which makes fixtures considerably more DRY and manageable.</p>\n" }, { "answer_id": 1061002, "author": "James Conroy-Finn", "author_id": 123142, "author_profile": "https://Stackoverflow.com/users/123142", "pm_score": 0, "selected": false, "text": "<p>Factory Girl is great. We use it in work loads.</p>\n\n<pre><code>Factory.define :usa, :class =&gt; Team do |f|\n f.country_name 'USA'\n f.rank 15.6\nend\n\nFactory.define :player do |f|\n f.first_name 'Stevie'\n f.last_name 'Wonder'\n f.team Factory.build(:usa)\nend\n</code></pre>\n\n<p>Then in your specs you can use <code>Factory.build(:usa)</code> or <code>Factory.create(:usa)</code> to build or create a USA team respectively.</p>\n" }, { "answer_id": 1523938, "author": "Kyle Daigle", "author_id": 184780, "author_profile": "https://Stackoverflow.com/users/184780", "pm_score": 2, "selected": false, "text": "<p>I can give Factory Girl a plus one as well. The way it can associate between multiple Factories is really helpful when you have a somewhat normal model set. A Project has one project manager, for example.</p>\n\n<pre><code>Factory.define :project_manager do |f|\n f.first_name \"John\"\n f.last_name \"Doe\"\nend\n\nFactory.define :project do |f|\n f.name \"Sample Project\"\n f.association :project_manager\nend\n</code></pre>\n\n<p>That way you don't need to worry about actually setting up the relationships in each test. It can also do some work like Faker where you can build sample data in factories using Factory.sequence. For all the information on Factory Girl, check out: <a href=\"http://dev.thoughtbot.com/factory_girl/\" rel=\"nofollow noreferrer\">http://dev.thoughtbot.com/factory_girl/</a>.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082/" ]
There are a dozen Rails plugins whose goal is to replace fixtures in testing. Here are a few I can think of: * fixture replacement * factory girl * factories and workers * rails scenarios * fixture-scenarios * object daddy There are probably others. Which of these plugins do you prefer and why?
I personally use [Faker](http://faker.rubyforge.org/) with a custom Factory class. This allows me to create my factories, and populate the generated instances with non-static data. ``` # spec/factory.rb module Factory def self.create_offer(options={}) Offer.create({ :code => Faker::Lorem.words(1), :expires_on => Time.now + (rand(30) + 1).day }.merge(options)) end end # spec_helper.rb require 'faker' require 'spec/factory' # In the specs @offer = Factory.create_offer(:code => 'TESTING') ```
211,616
<p>Objective-C is getting wider use due to its use by Apple for Mac OS X and iPhone development. What are some of your favourite "hidden" features of the Objective-C language?</p> <ul> <li>One feature per answer.</li> <li>Give an example and short description of the feature, not just a link to documentation.</li> <li>Label the feature using a title as the first line.</li> </ul>
[ { "answer_id": 211672, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 4, "selected": false, "text": "<h2>Posing</h2>\n\n<p>Objective-C permits a class to <strong>entirely replace another class</strong> within an application. The replacing class is said to \"pose as\" the target class. All messages sent to the target class are then instead received by the posing class. There are some restrictions on which classes can pose:</p>\n\n<ul>\n<li>A class may only pose as one of its direct or indirect superclasses</li>\n<li>The posing class must not define any new instance variables which are absent from the target class (though it may define or override methods).</li>\n<li>No messages must have been sent to the target class prior to the posing.</li>\n</ul>\n\n<p>Posing, similarly to categories, allows <strong>globally augmenting existing classes</strong>. Posing permits two features absent from categories:</p>\n\n<ul>\n<li>A posing class can call overridden methods through super, thus incorporating the implementation of the target class.</li>\n<li>A posing class can override methods defined in categories.</li>\n</ul>\n\n<p><strong>An example:</strong></p>\n\n<pre><code>@interface CustomNSApplication : NSApplication\n@end\n\n@implementation CustomNSApplication\n- (void) setMainMenu: (NSMenu*) menu\n{\n // do something with menu\n}\n@end\n\nclass_poseAs ([CustomNSApplication class], [NSApplication class]);\n</code></pre>\n\n<p>This intercepts every invocation of setMainMenu to NSApplication.</p>\n" }, { "answer_id": 212690, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 3, "selected": false, "text": "<pre><code>#include &lt;Foundation/Debug.h&gt;\n</code></pre>\n\n<p>Lots of tools for trying to track down memory leaks, premature deallocs, and more in that header file.</p>\n" }, { "answer_id": 214448, "author": "pfeilbr", "author_id": 29148, "author_profile": "https://Stackoverflow.com/users/29148", "pm_score": 4, "selected": false, "text": "<p><strong>Object Forwarding/Method Missing</strong></p>\n\n<p>When an object is sent a message for which it has no\nmethod, the runtime system gives it another chance to handle\nthe call before giving up. If the object supports a\n-forward:: method, the runtime calls this method, passing it\ninformation about the unhandled call. The return value from\nthe forwarded call is propagated back to the original caller of\nthe method.</p>\n\n<pre><code>-(retval_t)forward:(SEL)sel :(arglist_t)args {\n if ([myDelegate respondsTo:sel])\n return [myDelegate performv:sel :args]\n else\n return [super forward:sel :args];\n }\n</code></pre>\n\n<p>Content from <a href=\"http://oreilly.com/catalog/9780596004231/\" rel=\"nofollow noreferrer\">Objective-C Pocket Reference</a></p>\n\n<p>This is very powerful and is used heavily in the Ruby community for the various DSLs and rails, etc. Originated in Smalltalk which influenced both Objective-C and Ruby.</p>\n" }, { "answer_id": 214628, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 4, "selected": false, "text": "<h2>Method Swizzling</h2>\n\n<p>Basically, at runtime you can swap out one implementation of a method with another.</p>\n\n<p><a href=\"http://cocoadev.com/MethodSwizzling\" rel=\"nofollow noreferrer\">Here is a an explanation with code.</a></p>\n\n<p>One clever use case is for lazy loading of a shared resource: usually you would implement a <code>sharedFoo</code> method by acquiring a lock, creating the <code>foo</code> if needed, getting its address, releasing the lock, then returning the <code>foo</code>. This ensures that the <code>foo</code> is only created once, but every subsequent access wastes time with a lock that isn't needed any more.</p>\n\n<p>With method swizzling, you can do the same as before, except once the <code>foo</code> has been created, use swizzling to swap out the initial implementation of <code>sharedFoo</code> with a second one that does no checks and simply returns the <code>foo</code> that we now know has been created!</p>\n\n<p>Of course, method swizzling can get you into trouble, and there may be situations where the above example is a bad idea, but hey... that's why it's a <em>hidden</em> feature.</p>\n" }, { "answer_id": 214710, "author": "Michael Ledford", "author_id": 21834, "author_profile": "https://Stackoverflow.com/users/21834", "pm_score": 2, "selected": false, "text": "<p><strong>Objective-C Runtime Reference</strong></p>\n\n<p>It's easy to forget that the syntactic sugar of Objective-C is converted to normal C function calls that are the Object-C Runtime. It's likely that you will never need to actually delve into and use anything in the runtime. That is why I would consider this a 'hidden feature'.</p>\n\n<p>Let me give a way one might use the runtime system.</p>\n\n<p>Let's say that someone is designing an external framework API that will be used by third parties. And that someone designs a class in the framework that abstractly represents a packet of data, we'll call it <code>MLAbstractDataPacket</code>. Now it's up to the application who is linking in the framework to subclass <code>MLAbstractDataPacket</code> and define the subclass data packets. Every subclass must override the method <code>+(BOOL)isMyKindOfDataPacket:(NSData *)data</code>.</p>\n\n<p>With that information in mind...</p>\n\n<p>It would be nice if <code>MLAbstractDataPacket</code> provided a convenience method that returned the correct initialized class for a packet of data that comes in the form <code>+(id)initWithDataPacket:(NSData *)data</code>.</p>\n\n<p>There's only one problem here. The superclass doesn't know about any of its subclasses. So here you could use the runtime method <code>objc_getClassList()</code> along with <code>objc_getSuperclass()</code> to find the classes that are subclasses of MLAbstractDataPacket. Once you have a list of subclasses you can then try <code>+isMyKindOfDataPacket:</code> on each until one is found or not found.</p>\n\n<p>The reference information about this can be found at <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html</a>.</p>\n" }, { "answer_id": 227368, "author": "Marco", "author_id": 30480, "author_profile": "https://Stackoverflow.com/users/30480", "pm_score": 3, "selected": false, "text": "<p><strong>Categories</strong></p>\n\n<p>Using Categories, you can add methods to built-in classes without subclassing. <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_4_section_2.html#//apple_ref/doc/uid/TP30001163-CH20-TPXREF139\" rel=\"nofollow noreferrer\">Full reference</a>.</p>\n\n<p>It's nice to add convenience methods to commonly used classes, such as NSString or NSData.</p>\n" }, { "answer_id": 227402, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 0, "selected": false, "text": "<p>I like the verbose method naming like <code>[myArray writeToFile:myPath atomically:YES]</code>, where every argument has a label.</p>\n" }, { "answer_id": 679866, "author": "Becca Royal-Gordon", "author_id": 41222, "author_profile": "https://Stackoverflow.com/users/41222", "pm_score": 4, "selected": false, "text": "<h2>ISA Switching</h2>\n\n<p>Need to override all of an object's behaviors? You can actually change the class of an active object with a single line of code:</p>\n\n<pre><code>obj-&gt;isa = [NewClass class];\n</code></pre>\n\n<p>This only changes the class that receives method calls for that object; it doesn't change the object's layout in memory. Thus, this is only really useful when you have a set of classes with the same ivars (or one with a subset of the others') and you want to switch between them.</p>\n\n<p>One piece of code I've written uses this for lazy loading: it allocates an object of class <code>A</code>, fills a couple critical ivars (in this case, mainly a record number) and switches the <code>isa</code> pointer to point to <code>LazyA</code>. When any method other than a very small set like <code>release</code> and <code>retain</code> is called, <code>LazyA</code> loads all the data from disk, finishes filling in the ivars, switches the <code>isa</code> pointer back to <code>A</code>, and forwards the call to the real class.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2438/" ]
Objective-C is getting wider use due to its use by Apple for Mac OS X and iPhone development. What are some of your favourite "hidden" features of the Objective-C language? * One feature per answer. * Give an example and short description of the feature, not just a link to documentation. * Label the feature using a title as the first line.
Posing ------ Objective-C permits a class to **entirely replace another class** within an application. The replacing class is said to "pose as" the target class. All messages sent to the target class are then instead received by the posing class. There are some restrictions on which classes can pose: * A class may only pose as one of its direct or indirect superclasses * The posing class must not define any new instance variables which are absent from the target class (though it may define or override methods). * No messages must have been sent to the target class prior to the posing. Posing, similarly to categories, allows **globally augmenting existing classes**. Posing permits two features absent from categories: * A posing class can call overridden methods through super, thus incorporating the implementation of the target class. * A posing class can override methods defined in categories. **An example:** ``` @interface CustomNSApplication : NSApplication @end @implementation CustomNSApplication - (void) setMainMenu: (NSMenu*) menu { // do something with menu } @end class_poseAs ([CustomNSApplication class], [NSApplication class]); ``` This intercepts every invocation of setMainMenu to NSApplication.
211,622
<p>I would like to have some kind of catch-all exceptions mechanism in the root of my code, so when an app terminates unexpectedly I can still provide some useful logging.</p> <p>Something along the lines of</p> <pre><code>static void Main () { if (Debugger.IsAttached) RunApp(); else { try { RunApp(); } catch (Exception e) { LogException(e); throw; } } } </code></pre> <p>While this all works fine, my problem is when I want to attach the debugger after the exception has been raised.</p> <p>Since the exception escapes to the runtime, windows will prompt to attach visual studio, except, since it has been rethrown, all locals and parameters further up the stack have been lost.</p> <p>Is there anyway to log these exceptions, while still providing a way to attach the debugger and retain all useful information?</p>
[ { "answer_id": 211641, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 0, "selected": false, "text": "<p>Shouldn't simply do a</p>\n\n<pre><code>Exception e1 = e;\nLogException(e);\nthrow(e1);\n</code></pre>\n\n<p>inside the catch do the trick (at least you can examine the outer exception)?</p>\n" }, { "answer_id": 211870, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 0, "selected": false, "text": "<p>If you're strictly using Debug mode for developing and Release mode for deploying, you could try using the System.Diagnostics.Debugger class.</p>\n\n<pre><code>catch (Exception e) {\n#if DEBUG\n System.Diagnostics.Debugger.Launch()\n#endif\n LogException(e);\n throw;\n }\n</code></pre>\n" }, { "answer_id": 536210, "author": "Alexander", "author_id": 63231, "author_profile": "https://Stackoverflow.com/users/63231", "pm_score": 0, "selected": false, "text": "<p>You can get information of the exception by writing into the trace log:</p>\n\n<pre><code> private static void Main(string[] args)\n {\n try\n {\n // ...\n }\n catch (Exception exception)\n {\n System.Diagnostics.Trace.Write(exception);\n #if DEBUG\n System.Diagnostics.Trace.Write(\"Waiting 20 seconds for debuggers to attach to process.\");\n System.Threading.Thread.Sleep(20000);\n System.Diagnostics.Trace.Write(\"Continue with process...\");\n #endif\n throw;\n }\n }\n</code></pre>\n\n<p>Use <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx\" rel=\"nofollow noreferrer\">DebugView</a> to display the trace log. Stopping the Thread for a few seconds will give you some time to attach your debugger to process without loosing the original exception.</p>\n" }, { "answer_id": 539502, "author": "ShuggyCoUk", "author_id": 12748, "author_profile": "https://Stackoverflow.com/users/12748", "pm_score": 2, "selected": false, "text": "<p>Horribly hacky but without runtime hooks (I know of none) the only way to get to the stack frame where you are throwing from....</p>\n\n<p>All exceptions which are known to be terminal thrown would have to have the following in their constructor:</p>\n\n<pre><code>#if DEBUG\nSystem.Diagnostics.Debugger.Launch()\n#endif\n</code></pre>\n\n<p>This would present a dialogue allowing the user to either supply the relevant debugger or choose no and no debugging will occur (either way the exception will finish being constructed then be thrown. This obviously only works on exceptions whose source you control.</p>\n\n<p>I don't recommend this, in a debug build with debugger attached you can just choose to get 'First Chance' break on exception throwing which should normally be sufficient to your needs.</p>\n\n<p>Another option is to start generating mini dumps programmatically at the exception throw sites, such data could then be inspected later with a tool like windbg but not interfere too much with the desired behaviour of the exception unwinding the stack after.</p>\n\n<p>The act of the exception reaching your catch-all trap is precisely the stack unwind you don't want, sorry.\nIf you're comfortable with C++ and fancy it you could build a minor (but complex to get right) fork of mono which caused all exceptions to trigger the debugger. Alternatively just rebuild mono's BCL Exception class to do the same as detailed above..</p>\n" }, { "answer_id": 539895, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 1, "selected": false, "text": "<p>Why don't you just let it crash and then register to receive the Windows Error reports from Microsoft? Check out <a href=\"http://msdn.microsoft.com/en-us/isv/bb190483.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/isv/bb190483.aspx</a> for the details.</p>\n\n<p>If you don't want to do that, you can use the IsDebuggerPresent function (<a href=\"http://msdn.microsoft.com/en-us/library/ms680345.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms680345.aspx</a>), and if the result is False, instead of wrapping your code in a try-catch, add an event handler to the AppDomain.UnhandledException event (<a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx</a>)</p>\n" }, { "answer_id": 546068, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 0, "selected": false, "text": "<p>If none of the global events work out, then what you could try is putting the error catch in any events your software handles. The ease of these depends on the complexity of your applications. Many of application written with the .NET framework are written to handle events whether it is a traditional application or a web application. By putting the hooks in the events themselves you should be able to preserve the information in the stack you need.</p>\n" }, { "answer_id": 546922, "author": "Leaf Garland", "author_id": 30348, "author_profile": "https://Stackoverflow.com/users/30348", "pm_score": 5, "selected": true, "text": "<p>As Paul Betts already mentioned, you might be better off using the <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx\" rel=\"nofollow noreferrer\">AppDomain.UnhandledException</a> event instead of a try/catch block.</p>\n\n<p>In your UnhandledException event handler you can log/display the exception and then offer the option to debug e.g. show a form with the exception details and buttons to ignore, debug or quit.</p>\n\n<p>If the user selects the debug option, call <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break.aspx\" rel=\"nofollow noreferrer\">System.Diagnostics.Debugger.Break()</a> which allows the user to attach whatever debugger they want with the full call stack still available.</p>\n\n<p>Obviously, you could disable this option for any builds you know you're not ever going to be attaching the debugger to.</p>\n\n<pre><code>class Program\n{\n static void Main()\n {\n AppDomain.CurrentDomain.UnhandledException += ExceptionHandler;\n\n RunApp();\n }\n\n static void ExceptionHandler(object sender, UnhandledExceptionEventArgs e)\n {\n Console.WriteLine(e.ExceptionObject);\n Console.WriteLine(\"Do you want to Debug?\");\n if (Console.ReadLine().StartsWith(\"y\"))\n Debugger.Break();\n }\n\n static void RunApp()\n {\n throw new Exception();\n }\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28859/" ]
I would like to have some kind of catch-all exceptions mechanism in the root of my code, so when an app terminates unexpectedly I can still provide some useful logging. Something along the lines of ``` static void Main () { if (Debugger.IsAttached) RunApp(); else { try { RunApp(); } catch (Exception e) { LogException(e); throw; } } } ``` While this all works fine, my problem is when I want to attach the debugger after the exception has been raised. Since the exception escapes to the runtime, windows will prompt to attach visual studio, except, since it has been rethrown, all locals and parameters further up the stack have been lost. Is there anyway to log these exceptions, while still providing a way to attach the debugger and retain all useful information?
As Paul Betts already mentioned, you might be better off using the [AppDomain.UnhandledException](http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx) event instead of a try/catch block. In your UnhandledException event handler you can log/display the exception and then offer the option to debug e.g. show a form with the exception details and buttons to ignore, debug or quit. If the user selects the debug option, call [System.Diagnostics.Debugger.Break()](http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break.aspx) which allows the user to attach whatever debugger they want with the full call stack still available. Obviously, you could disable this option for any builds you know you're not ever going to be attaching the debugger to. ``` class Program { static void Main() { AppDomain.CurrentDomain.UnhandledException += ExceptionHandler; RunApp(); } static void ExceptionHandler(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine(e.ExceptionObject); Console.WriteLine("Do you want to Debug?"); if (Console.ReadLine().StartsWith("y")) Debugger.Break(); } static void RunApp() { throw new Exception(); } } ```
211,629
<p>How to remove the program icon from the Programs folder?</p>
[ { "answer_id": 211631, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 1, "selected": false, "text": "<p>You can use the standard file operations on shortcuts.</p>\n\n<p>I believe the file extension is lnk.</p>\n" }, { "answer_id": 211637, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<p>A shortcut file is a normal file that happens to redirect (on click) the call to another file, program or directory. To remove a shortcut you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx\" rel=\"nofollow noreferrer\">File.Delete</a> method.</p>\n\n<pre><code>File.Delete(path_to_lnk_file);\n</code></pre>\n" }, { "answer_id": 211657, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": false, "text": "<p>To get the start menu location, use the <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx\" rel=\"noreferrer\">SpecialFolder enumeration</a>. Something like the following should get you started:</p>\n\n<pre><code>string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);\nstring shortcut = Path.Combine(startMenuDir, @\"The Company\\MyShortcut.lnk\");\nif (File.Exists(shortcut))\n File.Delete(shortcut);\n</code></pre>\n\n<p>If you don't know the exact file name, you could enumerate over all the files in the start menu folder using <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles.aspx\" rel=\"noreferrer\">Directory.GetFiles</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectories.aspx\" rel=\"noreferrer\">Directory.GetDirectories</a>.\nYou could also remove the entire folder (\"The Company\"), using <a href=\"http://msdn.microsoft.com/en-us/library/fxeahc5f.aspx\" rel=\"noreferrer\">Directory.Delete</a></p>\n" }, { "answer_id": 211674, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "<p>In Windows explorer, the file extension for links (lnk) is never shown, even if you have disabled the <em>Hide extensions for known file types</em> feature.</p>\n\n<p>So if you want to delete the 'Shortcut to foobar.exe' shortcut, you have to do </p>\n\n<pre><code>File.Delete(\"Shortcut to foobar.exe.lnk\");\n</code></pre>\n" }, { "answer_id": 59829956, "author": "Mostafa Anssary", "author_id": 4119126, "author_profile": "https://Stackoverflow.com/users/4119126", "pm_score": 0, "selected": false, "text": "<p>1- Be sure to get actual file link use OpenFileDialog</p>\n\n<hr>\n\n<p>OpenFileDialog od = new OpenFileDialog();\n od.DereferenceLinks = false; </p>\n\n<p><a href=\"http://www.vbforums.com/showthread.php?549631-RESOLVED-Shortcut-path-in-VB-NET\" rel=\"nofollow noreferrer\">use DereferenceLinks</a></p>\n\n<p>2 use shell lib to get all information including the path</p>\n\n<hr>\n\n<p><a href=\"http://csharphelper.com/blog/2018/06/get-information-about-windows-shortcuts-in-c/\" rel=\"nofollow noreferrer\">GetShortcutInfo</a></p>\n\n<hr>\n\n<h2>finaly usse c# file.move or delete according to the path</h2>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How to remove the program icon from the Programs folder?
A shortcut file is a normal file that happens to redirect (on click) the call to another file, program or directory. To remove a shortcut you can use the [File.Delete](http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx) method. ``` File.Delete(path_to_lnk_file); ```
211,648
<p>I have a form, when I click on submit button, I want to communicate with the server and get something from the server to be displayed on the same page. Everything must be done in AJAX manner. How to do it in Google App Engine? If possible, I want to do it in JQuery.</p> <p>Edit: The example in <a href="http://groups.google.com.my/group/google-appengine/browse_thread/thread/36dc8759dab4cc28?hl=en#" rel="nofollow noreferrer">code.google.com/appengine/articles/rpc.html</a> doesn't work on form. </p> <hr> <p>Edit: The rpc procedure <a href="http://groups.google.com.my/group/google-appengine/browse_thread/thread/36dc8759dab4cc28?hl=en#" rel="nofollow noreferrer">doesn't work for form</a>. </p>
[ { "answer_id": 216929, "author": "JJ.", "author_id": 9106, "author_profile": "https://Stackoverflow.com/users/9106", "pm_score": 1, "selected": false, "text": "<p>I'd add that in Firebug, you should see your ajax call pop up in the console. If you're getting the exception when you open that address, there's something up with your Python code. Maybe you're not correctly mapping your urls?</p>\n" }, { "answer_id": 220197, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 1, "selected": false, "text": "<p>I've done it with something like this before in jQuery (not sure if it's the \"best\" way, but it works):</p>\n\n<pre><code>function jsonhandler(data) {\n // do stuff with the JSON data here\n}\n\nvar doajax = function () {\n arr = Object();\n $(\"#form_id\").children(\"input,select\").each(function() { arr[this.name] = this.value;});\n $.getJSON(\"&lt;page to call with AJAX&gt;\", arr, function (data) { jsonhandler(data);});\n}\n\n$(document).ready(function () {\n $(\"#submit_button_id\").replaceWith(\"&lt;input id=\\\"sub\\\" name=\\\"sub\\\" type=\\\"button\\\" value=\\\"Submit\\\"&gt;\");\n $(\"#sub\").click(doajax);\n}\n</code></pre>\n\n<p>You can replace the $.getJSON with <a href=\"http://docs.jquery.com/Ajax\" rel=\"nofollow noreferrer\">whichever jQuery AJAX function does what you want</a>. If you just want to display the output of the page you're calling, $.get is probably your best bet. If you have other input types besides input and select in your form, you'll need to add those to the children function as well.</p>\n" }, { "answer_id": 253067, "author": "Rik Heywood", "author_id": 4012, "author_profile": "https://Stackoverflow.com/users/4012", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://www.malsup.com/jquery/form/\" rel=\"noreferrer\">jquery Form plugin</a> to submit forms using ajax. Works very well.</p>\n\n<pre><code>$('#myFormId').submit(function() {\n // submit the form\n $(this).ajaxSubmit();\n return false;\n});\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
I have a form, when I click on submit button, I want to communicate with the server and get something from the server to be displayed on the same page. Everything must be done in AJAX manner. How to do it in Google App Engine? If possible, I want to do it in JQuery. Edit: The example in [code.google.com/appengine/articles/rpc.html](http://groups.google.com.my/group/google-appengine/browse_thread/thread/36dc8759dab4cc28?hl=en#) doesn't work on form. --- Edit: The rpc procedure [doesn't work for form](http://groups.google.com.my/group/google-appengine/browse_thread/thread/36dc8759dab4cc28?hl=en#).
You can use [jquery Form plugin](http://www.malsup.com/jquery/form/) to submit forms using ajax. Works very well. ``` $('#myFormId').submit(function() { // submit the form $(this).ajaxSubmit(); return false; }); ```
211,689
<p>I'm using xsd.exe to make the C# classes for our settings. I have a setting that is per-server and per-database, so I want the class to behave like Dictionary&lt;string, string[][]&gt;. So I want to be able to say</p> <pre><code>string serverName = "myServer"; int databaseId = 1; FieldSettings fieldSettings = getFieldSettings(); string[] fields = fieldSettings[serverName][databaseId]; </code></pre> <p>how do I represent that in XSD?</p>
[ { "answer_id": 211700, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>This not what <code>xsd</code> is used for. You can always just add your own indexer to a partial class, and mark it with <code>[XmlIgnore]</code></p>\n" }, { "answer_id": 211702, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>xsd defines the data structure, not really the access approach. I don't think you can express \"this is a lookup\" in xsd : everything is either values or set of values/entities.</p>\n\n<p>If you want specific handling, you might consider custom serialization - or alternatively consider your DTOs and your <em>working</em> classes as separate things, and simply translate between the two.</p>\n\n<p>[edit] As leppie notes - you can write your own indexer (typically in a partial class if generating cs from the xsd) that loops over the list to find the item: this will give you the caller usage, but not really the full dictionary experience (uniqueness, O(1) retrieval, etc)</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
I'm using xsd.exe to make the C# classes for our settings. I have a setting that is per-server and per-database, so I want the class to behave like Dictionary<string, string[][]>. So I want to be able to say ``` string serverName = "myServer"; int databaseId = 1; FieldSettings fieldSettings = getFieldSettings(); string[] fields = fieldSettings[serverName][databaseId]; ``` how do I represent that in XSD?
xsd defines the data structure, not really the access approach. I don't think you can express "this is a lookup" in xsd : everything is either values or set of values/entities. If you want specific handling, you might consider custom serialization - or alternatively consider your DTOs and your *working* classes as separate things, and simply translate between the two. [edit] As leppie notes - you can write your own indexer (typically in a partial class if generating cs from the xsd) that loops over the list to find the item: this will give you the caller usage, but not really the full dictionary experience (uniqueness, O(1) retrieval, etc)
211,693
<p>What steps do I need to take to get HTML documentation automatically building via the build step in Visual Studio? I have all the comments in place and the comments.xml file being generated, and Sandcastle installed. I just need to know what to add to the post-build step in order to generate the docs.</p>
[ { "answer_id": 211710, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p>I recommend you install Sandcastle Help File Builder from <a href=\"http://www.codeplex.com/SHFB\" rel=\"noreferrer\">Codeplex</a>.</p>\n\n<p>You can run this from the command line, e.g. from a Post-Build event. The simplest command line is:</p>\n\n<pre><code>&lt;install-path&gt;\\SandcastleBuilderConsole.exe ProjectName.shfb\n</code></pre>\n\n<p>Sandcastle is very slow, so I only run it for Release Builds. To do this, create a Post-Build event with a command something like the following, which passes the configuration name to a batch file:</p>\n\n<pre><code>CALL \"$(ProjectDir)PostBuild.cmd\" $(ConfigurationName)\n</code></pre>\n\n<p>Then inside the batch file you can test if the first argument is \"Release\" and if so run SandcastleBuilderConsole.exe.</p>\n" }, { "answer_id": 211716, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "<p>I must admit that I find the current version of Sandcastle a bit lacking; for large projects it is quite slow, and it isn't easy to integrate (since it is still early).</p>\n\n<p>For regular use, I actually find it easier just to point reflector at a folder with the dll and xml files - IIRC, it will load the xml file(s) as you navigate around.</p>\n\n<p>Plus I almost always have reflector open anyway...</p>\n\n<p>[edit] checked, and yes - xml comments show in the disassembler panel</p>\n" }, { "answer_id": 211754, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 0, "selected": false, "text": "<p>Install these:</p>\n\n<p>NDoc: <a href=\"http://prdownloads.sourceforge.net/ndoc/NDoc-v1.3.1.msi?download\" rel=\"nofollow noreferrer\">http://prdownloads.sourceforge.net/ndoc/NDoc-v1.3.1.msi?download</a></p>\n\n<p>HTML Help Workshop: <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=00535334-c8a6-452f-9aa0-d597d16580cc&amp;displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?FamilyID=00535334-c8a6-452f-9aa0-d597d16580cc&amp;displaylang=en</a></p>\n\n<p>Then use the NDocConsole.exe command line to generate documentation in either MSDN or CHM form:</p>\n\n<p>@c:\\progra~1\\NDoc\\NDocConsole.exe MyCode.dll,MyCode.xml -Documenter=MSDN-CHM</p>\n\n<p>I myself have made an External Tool for this and gave it a shortcut, but as the previous poster said you can hook it up to a postbuild event and there you go. </p>\n\n<p>(PS I have been using the setup above for a few years now and am very happy with it)</p>\n" }, { "answer_id": 4750130, "author": "Oliver Nina", "author_id": 527244, "author_profile": "https://Stackoverflow.com/users/527244", "pm_score": 1, "selected": false, "text": "<p>An easy way to do this as suggested above is using Sandcastle Help File Builder.\nThere have been some changes made to the build process from the command line and now these projects can be built with MSbuild instead of SandcastleBuilderConsole.exe. So all you have to do is:</p>\n\n<p>MSbuild.exe ProjectName.shfb</p>\n" }, { "answer_id": 5200822, "author": "Chev", "author_id": 498624, "author_profile": "https://Stackoverflow.com/users/498624", "pm_score": 6, "selected": true, "text": "<p>Some changes have been made since this question was asked. Sandcastle no longer includes <code>SandcastleBuilderConsole.exe</code>. Instead it uses plain old <code>MSBuild.exe</code>.</p>\n\n<p>To integrate this with visual studio here is what I did:</p>\n\n<p>Place this in your Post-build event:</p>\n\n<pre><code>IF \"$(ConfigurationName)\"==\"Release\" Goto Exit\n\n\"$(SystemRoot)\\microsoft.net\\framework64\\v4.0.30319\\msbuild.exe\" /p:CleanIntermediates=True /p:Configuration=Release \"$(SolutionDir)ProjectName\\doc\\DocumentationProjectName.shfbproj\"\n\n:Exit\n</code></pre>\n\n<p>This will cause visual studio to build your documentation, only when you build in \"Release\" mode. That way you aren't waiting forever when you build in \"Debug\" mode during development.</p>\n\n<p>A couple notes:</p>\n\n<ul>\n<li><p>My system is 64-bit, if yours is not then replace <code>framework64</code> with <code>framework</code> in the path to <code>msbuild.exe</code>.</p></li>\n<li><p>The way I have it setup is to document each project in my solution individually. If you have a \"Sandcastle Help File Builder\" project file which includes several projects together, then you probably want to get rid of <code>ProjectName\\</code> and move <code>doc</code> into the solution directory. In this case you will want to only put the Post-build event commands on the project that is built LAST in your solution. If you put it in the Post-build event for every project then you will be rebuilding your documentation for each project that is built. Needless to say, you'll be sitting there a while. Personally I prefer to document each project individually, but that's just me.</p></li>\n</ul>\n\n<p><strong>Installing Sandcastle and \"Sandcastle Help File Builder\".</strong></p>\n\n<p>If you don't know how to get Sandcastle and \"Sandcastle Help File Builder\" setup correctly, then follow these steps:</p>\n\n<ol>\n<li><p>Download and install Sandcastle from <a href=\"http://sandcastle.codeplex.com/\" rel=\"noreferrer\">http://sandcastle.codeplex.com/</a> (if you have a 64 bit system, you will need to add an environment variable. The instructions are <a href=\"http://sandcastle.codeplex.com/wikipage?title=How%20to:%20Install%20Sandcastle&amp;referringTitle=Introduction\" rel=\"noreferrer\">here</a>.</p></li>\n<li><p>Download and install \"Sandcastle Help File Builder\" from <a href=\"http://shfb.codeplex.com/\" rel=\"noreferrer\">http://shfb.codeplex.com/</a> (ignore warnings about MSHelp2 if you get any. You won't be needing it.)</p></li>\n<li><p>Once you have those installed then use \"Sandcastle Help File Builder\" to create a new documentation project. When it asks you where to save the file, save it in the documentation folder you have in your solution/project.\n<a href=\"http://www.chevtek.com/Temp/NewProject.jpg\" rel=\"noreferrer\">http://www.chevtek.com/Temp/NewProject.jpg</a></p></li>\n<li><p>After creating a new project you'll need to choose which kind of documentation you want to create. A compiled windows help file, a website, or both.\n<a href=\"http://www.chevtek.com/Temp/DocumentationType.jpg\" rel=\"noreferrer\">http://www.chevtek.com/Temp/DocumentationType.jpg</a></p></li>\n<li><p>If you saved the SHFB project file in the directory where you want your documentation to be generated then you can skip this step. But if you want the generated documentation to be placed elsewhere then you need to adjust the output path.\n<a href=\"http://www.chevtek.com/Temp/OutputPath.jpg\" rel=\"noreferrer\">http://www.chevtek.com/Temp/OutputPath.jpg</a>\nNOTE: One thing to keep in mind about the output path (which frustrated me for an hour) is that when you have website checked as the type of documentation you want, it will overwrite content in its output path. What they neglect to tell you is that SHFB purposely restricted certain folders from being included as part of the output path. Desktop is one such folder. Your output path cannot be on the desktop, not even a sub-folder of desktop. It can't by My Documents either, but it CAN be a subfolder of my documents. If you get errors when building your documentation, try changing the output path and see if that fixes it. See <a href=\"http://shfb.codeplex.com/discussions/226668?ProjectName=shfb\" rel=\"noreferrer\">http://shfb.codeplex.com/discussions/226668?ProjectName=shfb</a> for details on this.</p></li>\n<li><p>Finally, you will need to add a reference to the project you want to document. If you are doing individual projects like I do, then for each SHFB project file you create, you will reference the corresponding .CSPROJ file. If you have one SHFB project for your entire solution, then you would find the .SLN file for your solution. (sandcastle also works if you reference the compiled DLLs, but since you're integrating it with Visual Studio I find it makes more sense to reference the project/solution files instead. This may also mean that it really doesn't matter which project you do the post-build event on since it's referencing the code instead of the DLLs, but it's better to be safe and put it on the last project that's built)\n<a href=\"http://www.chevtek.com/Temp/AddSource.jpg\" rel=\"noreferrer\">http://www.chevtek.com/Temp/AddSource.jpg</a></p></li>\n<li><p>Save the project and you can close \"Sandcastle Help File Builder\". Now all is setup. Just be sure to put the documentation project file in the appropriate folder that the batch commands point to in the Post-build event.</p></li>\n</ol>\n\n<p>I hope my short tutorial helps you out! It was very hard for me to find any decent tutorials showing me how to use sandcastle, let alone how to integrate it with visual studio. Hopefully future google searches will turn up this question.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
What steps do I need to take to get HTML documentation automatically building via the build step in Visual Studio? I have all the comments in place and the comments.xml file being generated, and Sandcastle installed. I just need to know what to add to the post-build step in order to generate the docs.
Some changes have been made since this question was asked. Sandcastle no longer includes `SandcastleBuilderConsole.exe`. Instead it uses plain old `MSBuild.exe`. To integrate this with visual studio here is what I did: Place this in your Post-build event: ``` IF "$(ConfigurationName)"=="Release" Goto Exit "$(SystemRoot)\microsoft.net\framework64\v4.0.30319\msbuild.exe" /p:CleanIntermediates=True /p:Configuration=Release "$(SolutionDir)ProjectName\doc\DocumentationProjectName.shfbproj" :Exit ``` This will cause visual studio to build your documentation, only when you build in "Release" mode. That way you aren't waiting forever when you build in "Debug" mode during development. A couple notes: * My system is 64-bit, if yours is not then replace `framework64` with `framework` in the path to `msbuild.exe`. * The way I have it setup is to document each project in my solution individually. If you have a "Sandcastle Help File Builder" project file which includes several projects together, then you probably want to get rid of `ProjectName\` and move `doc` into the solution directory. In this case you will want to only put the Post-build event commands on the project that is built LAST in your solution. If you put it in the Post-build event for every project then you will be rebuilding your documentation for each project that is built. Needless to say, you'll be sitting there a while. Personally I prefer to document each project individually, but that's just me. **Installing Sandcastle and "Sandcastle Help File Builder".** If you don't know how to get Sandcastle and "Sandcastle Help File Builder" setup correctly, then follow these steps: 1. Download and install Sandcastle from <http://sandcastle.codeplex.com/> (if you have a 64 bit system, you will need to add an environment variable. The instructions are [here](http://sandcastle.codeplex.com/wikipage?title=How%20to:%20Install%20Sandcastle&referringTitle=Introduction). 2. Download and install "Sandcastle Help File Builder" from <http://shfb.codeplex.com/> (ignore warnings about MSHelp2 if you get any. You won't be needing it.) 3. Once you have those installed then use "Sandcastle Help File Builder" to create a new documentation project. When it asks you where to save the file, save it in the documentation folder you have in your solution/project. <http://www.chevtek.com/Temp/NewProject.jpg> 4. After creating a new project you'll need to choose which kind of documentation you want to create. A compiled windows help file, a website, or both. <http://www.chevtek.com/Temp/DocumentationType.jpg> 5. If you saved the SHFB project file in the directory where you want your documentation to be generated then you can skip this step. But if you want the generated documentation to be placed elsewhere then you need to adjust the output path. <http://www.chevtek.com/Temp/OutputPath.jpg> NOTE: One thing to keep in mind about the output path (which frustrated me for an hour) is that when you have website checked as the type of documentation you want, it will overwrite content in its output path. What they neglect to tell you is that SHFB purposely restricted certain folders from being included as part of the output path. Desktop is one such folder. Your output path cannot be on the desktop, not even a sub-folder of desktop. It can't by My Documents either, but it CAN be a subfolder of my documents. If you get errors when building your documentation, try changing the output path and see if that fixes it. See <http://shfb.codeplex.com/discussions/226668?ProjectName=shfb> for details on this. 6. Finally, you will need to add a reference to the project you want to document. If you are doing individual projects like I do, then for each SHFB project file you create, you will reference the corresponding .CSPROJ file. If you have one SHFB project for your entire solution, then you would find the .SLN file for your solution. (sandcastle also works if you reference the compiled DLLs, but since you're integrating it with Visual Studio I find it makes more sense to reference the project/solution files instead. This may also mean that it really doesn't matter which project you do the post-build event on since it's referencing the code instead of the DLLs, but it's better to be safe and put it on the last project that's built) <http://www.chevtek.com/Temp/AddSource.jpg> 7. Save the project and you can close "Sandcastle Help File Builder". Now all is setup. Just be sure to put the documentation project file in the appropriate folder that the batch commands point to in the Post-build event. I hope my short tutorial helps you out! It was very hard for me to find any decent tutorials showing me how to use sandcastle, let alone how to integrate it with visual studio. Hopefully future google searches will turn up this question.
211,694
<p>I am writing controls that work nice with JavaScript, but they have to work even without it. Now testing with selenium works fine for me. But all test with disabled JavaScript (in my browser) won't run with selenium. Is there a way to do automated test for this purpose?</p>
[ { "answer_id": 211726, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I don't know Selenium, but with the NoScript Firefox extension, you can disable scripts on a per-domain basis. So could you use that to allow Selenium but disable your page's scripts?</p>\n" }, { "answer_id": 211753, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 1, "selected": false, "text": "<p>Check out other automation packages such as <a href=\"http://www.automatedqa.com/products/testcomplete/\" rel=\"nofollow noreferrer\">TestComplete</a> or <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">AutoIt</a></p>\n" }, { "answer_id": 211777, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 0, "selected": false, "text": "<p>If it's just plain html with no javascript, you could just use normal screenscraping techniques to compare the html you downloaded from the server to what you expect, no need to test in a browser.</p>\n" }, { "answer_id": 214739, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 2, "selected": true, "text": "<p><a href=\"http://search.cpan.org/perldoc?WWW::Mechanize\" rel=\"nofollow noreferrer\">WWW::Mechanize</a> and <a href=\"http://search.cpan.org/perldoc?Test::WWW::Mechanize\" rel=\"nofollow noreferrer\">Test::WWW::Mechanize</a> are two Perl modules to do exactly that.</p>\n\n<pre><code>use Test::More tests =&gt; 5;\nuse Test::WWW::Mechanize;\n\nmy $mech = Test::WWW::Mechanize-&gt;new;\n\n# Test you can get http://petdance.com\n$mech-&gt;get_ok( \"http://petdance.com\" );\n\n# Test the &lt;BASE&gt; tag\n$mech-&gt;base_is( 'http://petdance.com/', 'Proper &lt;BASE HREF&gt;' );\n\n# Test the &lt;TITLE&gt;\n$mech-&gt;title_is( \"Invoice Status\", \"Make sure we're on the invoice page\" );\n\n# Test the text of the page contains \"Andy Lester\"\n$mech-&gt;content_contains( \"Andy Lester\", \"My name somewhere\" );\n\n# Test that all links on the page succeed.\n$mech-&gt;page_links_ok('Check all links');\n</code></pre>\n" }, { "answer_id": 215485, "author": "Željko Filipin", "author_id": 17469, "author_profile": "https://Stackoverflow.com/users/17469", "pm_score": 0, "selected": false, "text": "<p>You could use Watir to test your web application.</p>\n\n<p><a href=\"http://wtr.rubyforge.org/\" rel=\"nofollow noreferrer\">http://wtr.rubyforge.org/</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am writing controls that work nice with JavaScript, but they have to work even without it. Now testing with selenium works fine for me. But all test with disabled JavaScript (in my browser) won't run with selenium. Is there a way to do automated test for this purpose?
[WWW::Mechanize](http://search.cpan.org/perldoc?WWW::Mechanize) and [Test::WWW::Mechanize](http://search.cpan.org/perldoc?Test::WWW::Mechanize) are two Perl modules to do exactly that. ``` use Test::More tests => 5; use Test::WWW::Mechanize; my $mech = Test::WWW::Mechanize->new; # Test you can get http://petdance.com $mech->get_ok( "http://petdance.com" ); # Test the <BASE> tag $mech->base_is( 'http://petdance.com/', 'Proper <BASE HREF>' ); # Test the <TITLE> $mech->title_is( "Invoice Status", "Make sure we're on the invoice page" ); # Test the text of the page contains "Andy Lester" $mech->content_contains( "Andy Lester", "My name somewhere" ); # Test that all links on the page succeed. $mech->page_links_ok('Check all links'); ```
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p> <p>I <em>thought</em> that I should be able to do</p> <pre><code>options = object() </code></pre> <p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p> <pre><code>options.VERBOSE = True Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'object' object has no attribute 'VERBOSE' </code></pre> <p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
[ { "answer_id": 211774, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://docs.python.org/library/collections.html\" rel=\"noreferrer\">collections module</a> has grown a <em>namedtuple</em> function in 2.6:</p>\n\n<pre><code>import collections\nopt=collections.namedtuple('options','VERBOSE IGNORE_WARNINGS')\nmyoptions=opt(True, False)\n\n&gt;&gt;&gt; myoptions\noptions(VERBOSE=True, IGNORE_WARNINGS=False)\n&gt;&gt;&gt; myoptions.VERBOSE\nTrue\n</code></pre>\n\n<p>A <em>namedtuple</em> is immutable, so you can only assign field values when you create it.</p>\n\n<p>In earlier <em>Python</em> versions, you can create an empty class:</p>\n\n<pre><code>class options(object):\n pass\n\nmyoptions=options()\nmyoptions.VERBOSE=True\nmyoptions.IGNORE_WARNINGS=False\n&gt;&gt;&gt; myoptions.IGNORE_WARNINGS,myoptions.VERBOSE\n(False, True)\n</code></pre>\n" }, { "answer_id": 211918, "author": "davidavr", "author_id": 8247, "author_profile": "https://Stackoverflow.com/users/8247", "pm_score": 3, "selected": false, "text": "<p>I use <a href=\"http://code.activestate.com/recipes/361668/\" rel=\"noreferrer\">attrdict</a>:</p>\n\n<pre><code>class attrdict(dict):\n def __init__(self, *args, **kwargs):\n dict.__init__(self, *args, **kwargs)\n self.__dict__ = self\n</code></pre>\n\n<p>Depending on your point of view, you probably think it's either a big kludge or quite clever. But whatever you think, it does make for nice looking code, and is compatible with a dict:</p>\n\n<pre><code>&gt;&gt;&gt; ad = attrdict({'foo': 100, 'bar': 200})\n&gt;&gt;&gt; ad.foo\n100\n&gt;&gt;&gt; ad.bar\n200\n&gt;&gt;&gt; ad.baz = 'hello'\n&gt;&gt;&gt; ad.baz\n'hello'\n&gt;&gt;&gt; ad\n{'baz': 'hello', 'foo': 100, 'bar': 200}\n&gt;&gt;&gt; isinstance(ad, dict)\nTrue\n</code></pre>\n" }, { "answer_id": 211970, "author": "mhagger", "author_id": 24478, "author_profile": "https://Stackoverflow.com/users/24478", "pm_score": 2, "selected": false, "text": "<p>Simplifying <a href=\"https://stackoverflow.com/questions/211695/what-is-an-easy-way-to-create-a-trivial-one-off-python-object#211918\">davraamides's suggestion</a>, one could use the following:</p>\n\n<pre><code>class attrdict2(object):\n def __init__(self, *args, **kwargs):\n self.__dict__.update(*args, **kwargs)\n</code></pre>\n\n<p>which</p>\n\n<ol>\n<li><p>Isn't so kludgy.</p></li>\n<li><p>Doesn't contaminate the namespace of each object with the standard methods of <code>dict</code>; for example, <code>ad.has_key</code> is not defined for objects of type <code>attrdict2</code>.</p></li>\n</ol>\n\n<p>By the way, it is even easier to initialize instances of <code>attrdict</code> or <code>attrdict2</code>:</p>\n\n<pre><code>&gt;&gt;&gt; ad = attrdict2(foo = 100, bar = 200)\n</code></pre>\n\n<p>Granted, <code>attrdict2</code> is not compatible with a <code>dict</code>.</p>\n\n<p>If you don't need the magic initialization behavior, you can even use</p>\n\n<pre><code>class attrdict3(object):\n pass\n\nad = attrdict3()\nad.foo = 100\nad.bar = 200\n</code></pre>\n\n<p>But I was still hoping for a solution that doesn't require an auxiliary class.</p>\n" }, { "answer_id": 212010, "author": "mhagger", "author_id": 24478, "author_profile": "https://Stackoverflow.com/users/24478", "pm_score": 1, "selected": false, "text": "<p>One can use</p>\n\n<pre><code>class options(object):\n VERBOSE = True\n IGNORE_WARNINGS = False\n\noptions.VERBOSE = False\n\nif options.VERBOSE:\n ...\n</code></pre>\n\n<p>, using the class object itself (not an instance of the class!) as the place to store individual options. This is terse and satisfies all of the requirements, but it seems like a misuse of the class concept. It would also lead to confusion if a user instantiated the <code>options</code> class.</p>\n\n<p>(If multiple instances of the options-holding objects were needed, this would be a very nice solution--the class definition supplies default values, which can be overridden in individual instances.)</p>\n" }, { "answer_id": 212144, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 1, "selected": false, "text": "<p>The absolutely simplest class to do the job is:</p>\n\n<pre><code>class Struct:\n def __init__(self, **entries): \n self.__dict__.update(entries)\n</code></pre>\n\n<p>It can be later used as:</p>\n\n<pre><code>john = Struct(name='john doe', salary=34000)\nprint john.salary\n</code></pre>\n\n<p><code>namedtuple</code> (as another commented suggested) is a more advanced class that gives you more functionality. If you're still using Python 2.5, the implementation 2.6's <code>namedtuple</code> is based on can be found at <a href=\"http://code.activestate.com/recipes/500261/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/500261/</a></p>\n" }, { "answer_id": 212187, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 3, "selected": false, "text": "<p>If you insist on not having to define a class, you can abuse some existing classes. Most objects belong to \"new-style\" classes which don't have a dict, but functions can have arbitrary attributes:</p>\n\n<pre><code>&gt;&gt;&gt; x = lambda: 0 # any function will do\n&gt;&gt;&gt; x.foo = 'bar'\n&gt;&gt;&gt; x.bar = 0\n&gt;&gt;&gt; x.xyzzy = x\n&gt;&gt;&gt; x.foo\n'bar'\n&gt;&gt;&gt; x.bar\n0\n&gt;&gt;&gt; x.xyzzy\n&lt;function &lt;lambda&gt; at 0x6cf30&gt;\n</code></pre>\n\n<p>One problem is that functions already have some attributes, so dir(x) is a little messy:</p>\n\n<pre><code>&gt;&gt;&gt; dir(x)\n['__call__', '__class__', '__delattr__', '__dict__', '__doc__',\n'__get__', '__getattribute__', '__hash__', '__init__',\n'__module__', '__name__', '__new__', '__reduce__',\n'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'foo',\n'func_closure', 'func_code', 'func_defaults', 'func_dict',\n'func_doc', 'func_globals', 'func_name', 'xyzzy']\n</code></pre>\n" }, { "answer_id": 212299, "author": "David Eyk", "author_id": 18950, "author_profile": "https://Stackoverflow.com/users/18950", "pm_score": 4, "selected": true, "text": "<p>Given your requirements, I'd say the custom class is your best bet:</p>\n\n<pre><code>class options(object):\n VERBOSE = True\n IGNORE_WARNINGS = True\n\nif options.VERBOSE:\n # ...\n</code></pre>\n\n<p>To be complete, another approach would be using a separate module, i.e. <code>options.py</code> to encapsulate your option defaults.</p>\n\n<p><code>options.py</code>:</p>\n\n<pre><code>VERBOSE = True\nIGNORE_WARNINGS = True\n</code></pre>\n\n<p>Then, in <code>main.py</code>:</p>\n\n<pre><code>import options\n\nif options.VERBOSE:\n # ...\n</code></pre>\n\n<p>This has the feature of removing some clutter from your script. The default values are easy to find and change, as they are cordoned off in their own module. If later your application has grown, you can easily access the options from other modules.</p>\n\n<p>This is a pattern that I frequently use, and would heartily recommend if you don't mind your application growing larger than a single module. Or, start with a custom class, and expand to a module later if your app grows to multiple modules.</p>\n" }, { "answer_id": 212357, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p>Just make a module called Options.py, and import it. Put your default options values in there as global variables.</p>\n" }, { "answer_id": 212959, "author": "alif", "author_id": 12650, "author_profile": "https://Stackoverflow.com/users/12650", "pm_score": 3, "selected": false, "text": "<p>Why not just use <a href=\"http://docs.python.org/library/optparse.html#module-optparse\" rel=\"nofollow noreferrer\">optparse</a>:</p>\n\n<pre><code>from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nfile = options.filename\nif options.quiet == True:\n [...]\n</code></pre>\n" }, { "answer_id": 216453, "author": "itsadok", "author_id": 7581, "author_profile": "https://Stackoverflow.com/users/7581", "pm_score": 2, "selected": false, "text": "<p>As best practices go, you're really better off with one of the options in <a href=\"https://stackoverflow.com/questions/211695/what-is-an-easy-way-to-create-a-trivial-one-off-python-object#212299\">David Eyk's answer</a>. </p>\n\n<p>However, to answer your question, you can create a one-off class using the <code>type</code> function:</p>\n\n<pre><code>options = type('Options', (object,), { 'VERBOSE': True })()\noptions.IGNORE_WARNINGS = False\n</code></pre>\n\n<p>Note that you can provide an initial dictionary, or just leave it empty .</p>\n\n<pre><code>Options = type('Options', (object,), {})\noptions = Options()\noptions.VERBOSE = True\noptions.IGNORE_WARNINGS = False\n</code></pre>\n\n<p>Not very pythonic.</p>\n" }, { "answer_id": 6465039, "author": "Philippe Ombredanne", "author_id": 302521, "author_profile": "https://Stackoverflow.com/users/302521", "pm_score": -1, "selected": false, "text": "<p>simple object and named tuples are the way to go</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24478/" ]
I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this: ``` options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... ``` Of course I could use a dictionary, but `options.VERBOSE` is more readable and easier to type than `options['VERBOSE']`. I *thought* that I should be able to do ``` options = object() ``` , since `object` is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using `object()` doesn't have a `__dict__` member, and so one cannot add attributes to it: ``` options.VERBOSE = True Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'object' object has no attribute 'VERBOSE' ``` What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?
Given your requirements, I'd say the custom class is your best bet: ``` class options(object): VERBOSE = True IGNORE_WARNINGS = True if options.VERBOSE: # ... ``` To be complete, another approach would be using a separate module, i.e. `options.py` to encapsulate your option defaults. `options.py`: ``` VERBOSE = True IGNORE_WARNINGS = True ``` Then, in `main.py`: ``` import options if options.VERBOSE: # ... ``` This has the feature of removing some clutter from your script. The default values are easy to find and change, as they are cordoned off in their own module. If later your application has grown, you can easily access the options from other modules. This is a pattern that I frequently use, and would heartily recommend if you don't mind your application growing larger than a single module. Or, start with a custom class, and expand to a module later if your app grows to multiple modules.
211,703
<p>Is this doable in either IE7 or Firefox?</p>
[ { "answer_id": 211732, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 2, "selected": false, "text": "<p>Try <a href=\"http://plugins.jquery.com/project/dimensions\" rel=\"nofollow noreferrer\">the dimensions jQuery plugin</a>. See <a href=\"http://brandonaaron.net/docs/dimensions/#sample-4\" rel=\"nofollow noreferrer\">this demo</a>.</p>\n\n<pre><code>$('#myelement.').offset();\n</code></pre>\n" }, { "answer_id": 211734, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 0, "selected": false, "text": "<p>You could subtract the div's offsetTop from the document.body.scrollTop</p>\n\n<p>This seems to work on IE7 and FF3, but on a very simple page. I haven't checked with nested DIVs.</p>\n" }, { "answer_id": 211737, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 6, "selected": true, "text": "<p>You can do it in both - get the position relative to the document, then subtract the scroll position.</p>\n\n<pre><code>var e = document.getElementById('xxx');\nvar offset = {x:0,y:0};\nwhile (e)\n{\n offset.x += e.offsetLeft;\n offset.y += e.offsetTop;\n e = e.offsetParent;\n}\n\nif (document.documentElement &amp;&amp; (document.documentElement.scrollTop || document.documentElement.scrollLeft))\n{\n offset.x -= document.documentElement.scrollLeft;\n offset.y -= document.documentElement.scrollTop;\n}\nelse if (document.body &amp;&amp; (document.body.scrollTop || document.body.scrollLeft))\n{\n offset.x -= document.body.scrollLeft;\n offset.y -= document.body.scrollTop;\n}\nelse if (window.pageXOffset || window.pageYOffset)\n{\n offset.x -= window.pageXOffset;\n offset.y -= window.pageYOffset;\n}\n\nalert(offset.x + '\\n' + offset.y);\n</code></pre>\n" }, { "answer_id": 211935, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>Using Prototype it would be:</p>\n\n<pre><code>$('divname').viewportOffset.top\n$('divname').viewportOffset.left\n</code></pre>\n" }, { "answer_id": 213785, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 2, "selected": false, "text": "<p>In IE and Firefox 3, you can use <a href=\"http://ejohn.org/blog/getboundingclientrect-is-awesome\" rel=\"nofollow noreferrer\">getBoundingClientRect</a> for this; no framework necessary.</p>\n\n<p>But, yes, you should use a framework if you need to support other browsers as well.</p>\n" }, { "answer_id": 36233305, "author": "Himanshu P", "author_id": 1091378, "author_profile": "https://Stackoverflow.com/users/1091378", "pm_score": 4, "selected": false, "text": "<p>[Pasting from the answer I gave <a href=\"https://stackoverflow.com/questions/1350581/how-to-get-an-elements-top-position-relative-to-the-browsers-window/18794913#18794913\">here</a>]</p>\n\n<p>The native <code>getBoundingClientRect()</code> method has been around for quite a while now, and does exactly what the question asks for. Plus it is supported across all browsers (including IE 5, it seems!)</p>\n\n<p>From <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect\" rel=\"noreferrer\">this</a> MDN page:</p>\n\n<p><em>The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left <strong>relative to the top-left of the viewport</strong>.</em></p>\n\n<p>You use it like so:</p>\n\n<pre><code>var viewportOffset = el.getBoundingClientRect();\n// these are relative to the viewport, i.e. the window\nvar top = viewportOffset.top;\nvar left = viewportOffset.left;\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
Is this doable in either IE7 or Firefox?
You can do it in both - get the position relative to the document, then subtract the scroll position. ``` var e = document.getElementById('xxx'); var offset = {x:0,y:0}; while (e) { offset.x += e.offsetLeft; offset.y += e.offsetTop; e = e.offsetParent; } if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) { offset.x -= document.documentElement.scrollLeft; offset.y -= document.documentElement.scrollTop; } else if (document.body && (document.body.scrollTop || document.body.scrollLeft)) { offset.x -= document.body.scrollLeft; offset.y -= document.body.scrollTop; } else if (window.pageXOffset || window.pageYOffset) { offset.x -= window.pageXOffset; offset.y -= window.pageYOffset; } alert(offset.x + '\n' + offset.y); ```
211,714
<p>Morning all,</p> <p>Bit of a language theory question here... I've found some references online suggesting that exception handling and delegates in C# have some different behaviour in some cases but I cannot find any concrete documentation on the matter.</p> <p>We recently had some big problems with exceptions inside delegates for a Microsoft Excel addin causing a hard-crash in the MSVC runtime. Removing delegates solved this but I'm now curious to find out the gory details.</p> <p>As a terse example of the core code:</p> <pre><code>Delegate del; // initialized elsewhere try { del.DynamicInvoke(); } catch(Exception e) { /* Parsing of exception to generate user-friendly message here */ } </code></pre> <p>The above construct allowed a centralized form of error handling and from a pure code point of view was clean and concise. Each publicly exposed function was declared as a delegate and executed via the above fragment.</p> <p>In a simple console app, throwing an exception from the delegate or just a plain unexpected error (e.g. "accidentally" calling ToString() on a null pointer) works as expected and the error is handled as desired.</p> <p>Throw in MS Excel and you get hard-crashes. Stepping through the code will show where the error occurs but <em>no</em> stack unwinding appears to take place before everything comes down in a big fireball of destruction.</p> <p>My hypothesis is that COM, hosting the .NET runtime (and hence our code) is doing something different to normal .NET code execution. This kills the end-point and Excel doesn't know this, which in turn tries to access the end-point via COM only to find it has somehow disappeared and Excel craps out in return.</p> <p>This only happens with the combination of Excel+COM+delegates, but I don't honestly know which is the more influential in this behaviour... any thoughts?</p>
[ { "answer_id": 213569, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>Side note:\nThe whole idea of exception catching is not to \"swallow\" them and display the error message, but to recover, if possible from the situation, as well as to cleanup resources.</p>\n\n<p>Better use try/catch wherever you need (i.e. around the code which may throw), and then call a common function to display/log the problem.</p>\n\n<p>Also, if you use different threads to access Excel COM objects a lot of strange things can happen.</p>\n\n<p>For proper answer to your question more information is needed:</p>\n\n<ol>\n<li>Does it happen always?</li>\n<li>If not, when you see the problem is it a managed exception, or one thrown from an Excel object?</li>\n<li>Can you create a simple method, which just throws an exception( throw new ApplicationException();), and see if you still have the problem?</li>\n</ol>\n\n<p>Cheers</p>\n" }, { "answer_id": 216715, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "<p>I think what you might find here is that you are not releasing the MS Excel COM objects you are implicitly creating when an exception is thrown. In my experience MS Office apps are very sensitive to their resources not being released (though most of my experience is with Outlook). </p>\n\n<p>I would tend NOT to try to handle COM-based exceptions in this way if at all possible. If you want centalized logging, look at Application.ThreadException (for WinForms app) and AppDomain.CurrentDomain.UnhandledException instead.</p>\n\n<p>Inside of your functions, you may want to call Marshal.ReleaseComObject() in your methods' finally {} blocks in order to make sure Excel doesn't get hosed when your exceptions are thrown.</p>\n" }, { "answer_id": 221668, "author": "user25519", "author_id": 25519, "author_profile": "https://Stackoverflow.com/users/25519", "pm_score": 0, "selected": false, "text": "<p>Apologies for the late reply - busy week!</p>\n\n<blockquote>\n <p>The whole idea of exception catching is not to \"swallow\" them and display the error message, but to recover, if possible from the situation, as well as to cleanup resources.</p>\n</blockquote>\n\n<p>Yup, that's the idea but in practice it doesn't always work out that cleanly. The code in question here is essentially a middleman and often can't know if an error will occur and if one happens it can't know what the user was actually trying to do and thus automagically recover.</p>\n\n<blockquote>\n <p>Does it happen always?</p>\n</blockquote>\n\n<p>Yes, if it is an unexpected exception and it always appears as a .NET one originating within the C#/.NET code</p>\n\n<blockquote>\n <p>create a simple method, which just throws an exception( throw new ApplicationException();), and see if you still have the problem?</p>\n</blockquote>\n\n<p>No, throwing our own exceptions works fine every time. It's only if the runtime itself generates the exception that we get hard crashes.</p>\n\n<blockquote>\n <p>you are not releasing the MS Excel COM objects you are implicitly creating when an exception is thrown</p>\n</blockquote>\n\n<p>This sounds plausible. A VBA layer passes data from Excel over COM and into .NET, so it could well be doing something funky with resource ownership.</p>\n\n<blockquote>\n <p>If you want centalized logging, look at Application.ThreadException (for WinForms app) and AppDomain.CurrentDomain.UnhandledException instead.</p>\n</blockquote>\n\n<p>I didn't look into the former, but the latter would never get called. One of my first attempts was to catch it at the AppDomain level assuming that, for whatever reason, a delegate-based exception was slipping through the net.</p>\n\n<blockquote>\n <p>you may want to call Marshal.ReleaseComObject()</p>\n</blockquote>\n\n<p>Interesting, I wasn't aware of that function. We've mostly ignored any explicit COM code and gone with the bare minimum and hope (!) that the .NET CLR does its magic... </p>\n\n<p>I've worked around it now by removing the delegates and everything seems happy. Just have to remember to be careful (or outright avoid) delegates and exceptions in future Office+VBA+COM+CLR code :-)</p>\n" }, { "answer_id": 553343, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>One reason i feel is due to the fact that delegate is invoking the actual code which is throwing exception in another thread. so the exception in another thread which was called async would not be catch in the current thread as the current thread function would mostly exit before the async invoke executes.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25519/" ]
Morning all, Bit of a language theory question here... I've found some references online suggesting that exception handling and delegates in C# have some different behaviour in some cases but I cannot find any concrete documentation on the matter. We recently had some big problems with exceptions inside delegates for a Microsoft Excel addin causing a hard-crash in the MSVC runtime. Removing delegates solved this but I'm now curious to find out the gory details. As a terse example of the core code: ``` Delegate del; // initialized elsewhere try { del.DynamicInvoke(); } catch(Exception e) { /* Parsing of exception to generate user-friendly message here */ } ``` The above construct allowed a centralized form of error handling and from a pure code point of view was clean and concise. Each publicly exposed function was declared as a delegate and executed via the above fragment. In a simple console app, throwing an exception from the delegate or just a plain unexpected error (e.g. "accidentally" calling ToString() on a null pointer) works as expected and the error is handled as desired. Throw in MS Excel and you get hard-crashes. Stepping through the code will show where the error occurs but *no* stack unwinding appears to take place before everything comes down in a big fireball of destruction. My hypothesis is that COM, hosting the .NET runtime (and hence our code) is doing something different to normal .NET code execution. This kills the end-point and Excel doesn't know this, which in turn tries to access the end-point via COM only to find it has somehow disappeared and Excel craps out in return. This only happens with the combination of Excel+COM+delegates, but I don't honestly know which is the more influential in this behaviour... any thoughts?
I think what you might find here is that you are not releasing the MS Excel COM objects you are implicitly creating when an exception is thrown. In my experience MS Office apps are very sensitive to their resources not being released (though most of my experience is with Outlook). I would tend NOT to try to handle COM-based exceptions in this way if at all possible. If you want centalized logging, look at Application.ThreadException (for WinForms app) and AppDomain.CurrentDomain.UnhandledException instead. Inside of your functions, you may want to call Marshal.ReleaseComObject() in your methods' finally {} blocks in order to make sure Excel doesn't get hosed when your exceptions are thrown.
211,715
<p>How does one execute some VBA code periodically, completely automated?</p>
[ { "answer_id": 211742, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>There is an application method that can be used for timing events. If you want this to occur periodically you'll have to 'reload' the timer after each execution, but that should be pretty straightforward.</p>\n\n<pre><code>Sub MyTimer()\n Application.Wait Now + TimeValue(\"00:00:05\")\n MsgBox (\"5 seconds\")\nEnd Sub\n</code></pre>\n\n<p>-Adam</p>\n" }, { "answer_id": 211779, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 5, "selected": true, "text": "<p>You can use Application.OnTime to schedule a macro to be executed periodically. For example create a module with the code below. Call \"Enable\" to start the timer running. </p>\n\n<p>It is important to stop the timer running when you close your workbook: to do so handle Workbook_BeforeClose and call \"Disable\"</p>\n\n<pre><code>Option Explicit\n\nPrivate m_dtNextTime As Date\nPrivate m_dtInterval As Date\n\nPublic Sub Enable(Interval As Date)\n Disable\n m_dtInterval = Interval\n StartTimer\nEnd Sub\n\nPrivate Sub StartTimer()\n m_dtNextTime = Now + m_dtInterval\n Application.OnTime m_dtNextTime, \"MacroName\"\nEnd Sub\n\nPublic Sub MacroName()\n On Error GoTo ErrHandler:\n ' ... do your stuff here\n\n ' Start timer again\n StartTimer\n Exit Sub\nErrHandler:\n ' Handle errors, restart timer if desired\nEnd Sub\n\nPublic Sub Disable()\n On Error Resume Next ' Ignore errors\n Dim dtZero As Date\n If m_dtNextTime &lt;&gt; dtZero Then\n ' Stop timer if it is running\n Application.OnTime m_dtNextTime, \"MacroName\", , False\n m_dtNextTime = dtZero\n End If\n m_dtInterval = dtZero\nEnd Sub\n</code></pre>\n\n<p>Alternatively you can use the Win32 API SetTimer/KillTimer functions in a similar way.</p>\n" }, { "answer_id": 211874, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "<p>You could consider the Windows Task Scheduler and VBScript.</p>\n" }, { "answer_id": 389633, "author": "CABecker", "author_id": 32790, "author_profile": "https://Stackoverflow.com/users/32790", "pm_score": 0, "selected": false, "text": "<p>I do this all the time, I used to use the \"OnTime\" method as shown above but it renders the machine you are running the code on useless for other things, because Excel is running 100% of the time. Instead I use a modified hidden workbook and I execute with windows Task Scheduler and in the thisworkbook workbook_open function call the macro from your personal workbook, or open and run another workbook with the code in it. After the code has run you can call the application.quit function from the hidden workbook and close ecxel for the next run through. I use that for all my on 15 minute and daily unattended reporting functions.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9095/" ]
How does one execute some VBA code periodically, completely automated?
You can use Application.OnTime to schedule a macro to be executed periodically. For example create a module with the code below. Call "Enable" to start the timer running. It is important to stop the timer running when you close your workbook: to do so handle Workbook\_BeforeClose and call "Disable" ``` Option Explicit Private m_dtNextTime As Date Private m_dtInterval As Date Public Sub Enable(Interval As Date) Disable m_dtInterval = Interval StartTimer End Sub Private Sub StartTimer() m_dtNextTime = Now + m_dtInterval Application.OnTime m_dtNextTime, "MacroName" End Sub Public Sub MacroName() On Error GoTo ErrHandler: ' ... do your stuff here ' Start timer again StartTimer Exit Sub ErrHandler: ' Handle errors, restart timer if desired End Sub Public Sub Disable() On Error Resume Next ' Ignore errors Dim dtZero As Date If m_dtNextTime <> dtZero Then ' Stop timer if it is running Application.OnTime m_dtNextTime, "MacroName", , False m_dtNextTime = dtZero End If m_dtInterval = dtZero End Sub ``` Alternatively you can use the Win32 API SetTimer/KillTimer functions in a similar way.
211,717
<p>Is there a function in Common Lisp that takes a string as an argument and returns a keyword?</p> <p>Example: <code>(keyword "foo")</code> -> <code>:foo</code></p>
[ { "answer_id": 211786, "author": "Jonathan Wright", "author_id": 28840, "author_profile": "https://Stackoverflow.com/users/28840", "pm_score": -1, "selected": false, "text": "<pre><code>(intern \"foo\" \"KEYWORD\") -&gt; :foo\n</code></pre>\n\n<p>See the <a href=\"https://lispcookbook.github.io/cl-cookbook/strings.html#converting-between-symbols-and-strings\" rel=\"nofollow noreferrer\">Strings section</a> of the <a href=\"https://lispcookbook.github.io/cl-cookbook/\" rel=\"nofollow noreferrer\">Common Lisp Cookbook</a> for other string/symbol conversions and a detailed discussion of symbols and packages.</p>\n" }, { "answer_id": 211806, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": true, "text": "<p>Here's a <code>make-keyword</code> function which packages up keyword creation process (<code>intern</code>ing of a name into the <code>KEYWORD</code> package). :-)</p>\n\n<pre><code>(defun make-keyword (name) (values (intern name \"KEYWORD\")))\n</code></pre>\n" }, { "answer_id": 556001, "author": "Leslie P. Polzer", "author_id": 19619, "author_profile": "https://Stackoverflow.com/users/19619", "pm_score": 5, "selected": false, "text": "<p>The answers given while being roughly correct do not produce a correct solution to the question's example.</p>\n\n<p>Consider:</p>\n\n<pre><code>CL-USER(4): (intern \"foo\" :keyword)\n\n:|foo|\nNIL\nCL-USER(5): (eq * :foo)\n\nNIL\n</code></pre>\n\n<p>Usually you want to apply STRING-UPCASE to the string before interning it, thus:</p>\n\n<pre><code>(defun make-keyword (name) (values (intern (string-upcase name) \"KEYWORD\")))\n</code></pre>\n" }, { "answer_id": 12118364, "author": "Samuel Edwin Ward", "author_id": 894885, "author_profile": "https://Stackoverflow.com/users/894885", "pm_score": 2, "selected": false, "text": "<p>There is a <code>make-keyword</code> function in the <a href=\"http://common-lisp.net/project/alexandria/\" rel=\"nofollow\">Alexandria</a> library, although it does preserve case so to get exactly what you want you'll have to upcase the string first.</p>\n" }, { "answer_id": 15658042, "author": "Paulo Tomé", "author_id": 2152558, "author_profile": "https://Stackoverflow.com/users/2152558", "pm_score": 1, "selected": false, "text": "<p>In this example it also deals with strings with spaces (replacing them by dots):</p>\n\n<pre><code>(defun make-keyword (name) (values (intern (substitute #\\. #\\space (string-upcase name)) :keyword)))\n</code></pre>\n" }, { "answer_id": 55526783, "author": "I.Omar", "author_id": 5556374, "author_profile": "https://Stackoverflow.com/users/5556374", "pm_score": 1, "selected": false, "text": "<p>In case, you can change the string to start with colon sign <code>:</code></p>\n\n<p>use <code>read-from-string</code> directly.</p>\n\n<p>Here is another version of <code>make-keyword</code>:</p>\n\n<pre><code>(defun make-keyword (name)\n (read-from-string (concatenate 'string \":\" name)))\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18480/" ]
Is there a function in Common Lisp that takes a string as an argument and returns a keyword? Example: `(keyword "foo")` -> `:foo`
Here's a `make-keyword` function which packages up keyword creation process (`intern`ing of a name into the `KEYWORD` package). :-) ``` (defun make-keyword (name) (values (intern name "KEYWORD"))) ```
211,718
<p>Why doesn't the code below work? The idea is that the page checks to see if the dropdown variable has changes since you last refreshed the page.</p> <pre><code> &lt;logic:equal name="Result" value = "-1"&gt; &lt;bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope = "session" /&gt; &lt;/logic:equal&gt; &lt;logic:equal name="Result" value = "-1"&gt; &lt;bean:define id="DropDownValue" name="smlMoverDetailForm" property="moverChangeType" type="java.lang.String" toScope = "session" /&gt; &lt;/logic:equal&gt; &lt;-- when you fisrt access this page from the above are run --&gt; &lt;bean:define id="NewDropDownValue" name="smlMoverDetailForm" property="moverChangeType" type="java.lang.String" toScope = "sess &lt;-- this happens everytime the page is refreshed--&gt; &lt;logic:equal name= DropDownValue value = NewDropDownValue&gt; &lt;bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope = "session" /&gt; &lt;/logic:equal&gt; &lt;logic:notEqual name="DropDownValue" value = "NewDropDownValue"&gt; &lt;bean:define id="DropDownValue" name="smlMoverDetailForm" property="moverChangeType" type="java.lang.String" toScope = "session" /&gt; &lt;/logic:notEqual&gt; </code></pre>
[ { "answer_id": 211797, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;logic:equal name= DropDownValue value = NewDropDownValue&gt;\n</code></pre>\n\n<p>I'm not sure if this is your problem (describe <em>how</em> it doesn't work please), but the above is not valid xml: it needs quotes around the attribute values.</p>\n" }, { "answer_id": 211916, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The problem is as your describe i can't get the logic tags to evaluate the values held in the defined beans. </p>\n" }, { "answer_id": 216926, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 1, "selected": false, "text": "<p>You have realized, that your bean:define - at least in your question stated here - is flawed?</p>\n\n<pre><code>toScope=\"sess\n</code></pre>\n\n<p>is most likely not what you want - it doesn't even terminate the tag. But this may be formatting in StackOverflow... Also, the missing quotes have been mentioned in other answers. </p>\n\n<p>The error may be the use of the value property: According to <a href=\"http://struts.apache.org/1.2.x/userGuide/struts-logic.html#equal\" rel=\"nofollow noreferrer\">http://struts.apache.org/1.2.x/userGuide/struts-logic.html#equal</a> value is <em>The constant value to which the variable, specified by other attribute(s) of this tag, will be compared.</em></p>\n\n<p>Thus, given that you've defined a bean named NewDropDownValue you might want to evaluate </p>\n\n<pre><code>&lt;logic:equal name=\"DropDownValue\" value=\"&lt;%=NewDropDownValue/&gt;\"&gt;\n</code></pre>\n\n<p>Edit: Additionally I can't remember what happens when you only conditionally define a bean - your bean is defined inside a logic:equal block that might or might not be evaluated. It might be legal and have defined results, I just can't remember...</p>\n" }, { "answer_id": 269963, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 0, "selected": false, "text": "<p>Actually, I don't really get what you want, but here's some pseudocode (removing those dangerous pointy brackets) of your code in the question</p>\n\n<pre><code>if result == -1\n define JOININGDATE\nend\nif result == -1\n define DropDownValue\nend\n</code></pre>\n\n<p>This might be an error (you might want to check once for 'equals' and once for 'does not equal') or be written shorter and more clear</p>\n\n<pre><code>if result == -1\n define JOININGDATE\n define DropDownValue\nend\n// otherwise don't define both values\n</code></pre>\n\n<p>Your question might get better answers (or be answered by you yourself) if you placed some output inside of those logic tags and post both the output and a bit more of the context (e.g. actual parameter values -- what is 'Result'). But then - you've posted from an unregistered account and have not been seen for some time...</p>\n" }, { "answer_id": 271525, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>&lt;logic:equal name=\"Result\" value = \"-1\"&gt;\n &lt;bean:define id=\"JOININGDATE\" name=\"smlMoverDetailForm\" property=\"empFDJoiningDate\"\n type=\"java.lang.String\" toScope = \"session\" /&gt;\n &lt;/logic:equal&gt; \n\n\n&lt;logic:equal name=\"Result\" value = \"-1\"&gt;\n &lt;bean:define id=\"DropDownValue\" name=\"smlMoverDetailForm\" property=\"moverChangeType\" \n type=\"java.lang.String\" toScope = \"session\" /&gt; \n&lt;/logic:equal&gt;\n\n&lt;!-- when you fisrt access this page from the above are run --&gt;\n\n&lt;bean:define id=\"NewDropDownValue\" name=\"smlMoverDetailForm\"\n property=\"moverChangeType\" type=\"java.lang.String\" toScope = \"session\"/&gt;\n\n&lt;!-- this happens everytime the page is refreshed--&gt;\n\n&lt;logic:equal name=\"DropDownValue\" value=\"&lt;%=request.getSession().getAttribute(\"NewDropDownValue\").toString()%&gt;\"&gt;\n &lt;bean:define id=\"JOININGDATE\" name=\"smlMoverDetailForm\"\n property=\"empFDJoiningDate\" type=\"java.lang.String\" toScope =\"session\" /&gt;\n&lt;/logic:equal&gt;\n\n&lt;logic:notEqual name=\"DropDownValue\" value=\"NewDropDownValue\"&gt;\n &lt;bean:define id=\"DropDownValue\" name=\"smlMoverDetailForm\" \n property=\"moverChangeType\" type=\"java.lang.String\" toScope = \"session\"/&gt; \n&lt;/logic:notEqual&gt;\n</code></pre>\n\n<p>Errors corrected:</p>\n\n<ul>\n<li>Comments were not well formed</li>\n<li>Third was not correctly ended</li>\n<li>Change the way to get NewDropDownValue</li>\n</ul>\n\n<p>I think those changements will make it runs correctly.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Why doesn't the code below work? The idea is that the page checks to see if the dropdown variable has changes since you last refreshed the page. ``` <logic:equal name="Result" value = "-1"> <bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope = "session" /> </logic:equal> <logic:equal name="Result" value = "-1"> <bean:define id="DropDownValue" name="smlMoverDetailForm" property="moverChangeType" type="java.lang.String" toScope = "session" /> </logic:equal> <-- when you fisrt access this page from the above are run --> <bean:define id="NewDropDownValue" name="smlMoverDetailForm" property="moverChangeType" type="java.lang.String" toScope = "sess <-- this happens everytime the page is refreshed--> <logic:equal name= DropDownValue value = NewDropDownValue> <bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope = "session" /> </logic:equal> <logic:notEqual name="DropDownValue" value = "NewDropDownValue"> <bean:define id="DropDownValue" name="smlMoverDetailForm" property="moverChangeType" type="java.lang.String" toScope = "session" /> </logic:notEqual> ```
You have realized, that your bean:define - at least in your question stated here - is flawed? ``` toScope="sess ``` is most likely not what you want - it doesn't even terminate the tag. But this may be formatting in StackOverflow... Also, the missing quotes have been mentioned in other answers. The error may be the use of the value property: According to <http://struts.apache.org/1.2.x/userGuide/struts-logic.html#equal> value is *The constant value to which the variable, specified by other attribute(s) of this tag, will be compared.* Thus, given that you've defined a bean named NewDropDownValue you might want to evaluate ``` <logic:equal name="DropDownValue" value="<%=NewDropDownValue/>"> ``` Edit: Additionally I can't remember what happens when you only conditionally define a bean - your bean is defined inside a logic:equal block that might or might not be evaluated. It might be legal and have defined results, I just can't remember...
211,758
<p>I have a sproc that returns a single line and column with a text, I need to set this text to a variable, something like:</p> <pre><code>declare @bla varchar(100) select @bla = sp_Name 9999, 99989999, 'A', 'S', null </code></pre> <p>but of course, this code doesn't work...</p> <p>thanks!</p>
[ { "answer_id": 211778, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 4, "selected": false, "text": "<p>If the stored procedure is returning a single value you could define one of the parameters on the stored procedure to be an OUTPUT variable, and then the stored procedure would set the value of the parameter</p>\n\n<pre><code>CREATE PROCEDURE dbo.sp_Name\n @In INT,\n @Out VARCHAR(100) OUTPUT\n\nAS\nBEGIN\n SELECT @Out = 'Test'\nEND\nGO\n</code></pre>\n\n<p>And then, you get the output value as follows</p>\n\n<pre><code>DECLARE @OUT VARCHAR(100)\nEXEC sp_name 1, @Out OUTPUT\nPRINT @Out\n</code></pre>\n" }, { "answer_id": 211815, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 6, "selected": true, "text": "<p>If you are unable to change the stored procedure, another solution would be to define a temporary table, and insert the results into that</p>\n\n<pre><code>DECLARE @Output VARCHAR(100)\n\nCREATE TABLE #tmpTable\n(\n OutputValue VARCHAR(100)\n)\nINSERT INTO #tmpTable (OutputValue)\nEXEC dbo.sp_name 9999, 99989999, 'A', 'S', null\n\nSELECT\n @Output = OutputValue\nFROM \n #tmpTable\n\nDROP TABLE #tmpTable\n</code></pre>\n" }, { "answer_id": 211886, "author": "DiGi", "author_id": 12042, "author_profile": "https://Stackoverflow.com/users/12042", "pm_score": 4, "selected": false, "text": "<pre><code>DECLARE\n @out INT\n\nEXEC @out = sp_name 'param', 2, ...\n</code></pre>\n\n<p>More info in T-SQL \"EXECUTE\" <a href=\"http://msdn.microsoft.com/en-us/library/ms188332.aspx\" rel=\"noreferrer\">help</a> (Help is from MSSQL 2008 but this works in 2000 too)</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17648/" ]
I have a sproc that returns a single line and column with a text, I need to set this text to a variable, something like: ``` declare @bla varchar(100) select @bla = sp_Name 9999, 99989999, 'A', 'S', null ``` but of course, this code doesn't work... thanks!
If you are unable to change the stored procedure, another solution would be to define a temporary table, and insert the results into that ``` DECLARE @Output VARCHAR(100) CREATE TABLE #tmpTable ( OutputValue VARCHAR(100) ) INSERT INTO #tmpTable (OutputValue) EXEC dbo.sp_name 9999, 99989999, 'A', 'S', null SELECT @Output = OutputValue FROM #tmpTable DROP TABLE #tmpTable ```
211,800
<p>I have no idea. This causes seemingly random time-outs. These in turn break the flash that i am loading it into. Has anyone seen anything like this before?</p> <pre><code>&lt;?php require_once("../includes/class.database.php"); require_once("../includes/dbConnectInfo.inc"); require_once("../includes/functions.php"); include("../includes/conn.php"); $cat = $_GET['category']; $result = mysql_query("SELECT * FROM media WHERE related_page_id=4 &amp;&amp; type='copy' ORDER BY id ASC LIMIT 6"); $media = "&lt;?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?&gt;\n"; $media .= "&lt;content&gt;\n"; while($row = mysql_fetch_array($result)) { $media .="&lt;member&gt;\n"; $body = $row[copy]; if($row[title] == "") { $media .= "&lt;title&gt;&lt;![CDATA["; $media .= "Team"; $media .="]]&gt;&lt;/title&gt;\n"; } elseif ($row['path']=="") { $name = explode("/",$row[title],2); $media .= "&lt;name&gt;&lt;![CDATA["; $media .= $name[0]; $media .="]]&gt;&lt;/name&gt;\n"; $media .= "&lt;job&gt;&lt;![CDATA["; $media .= $name[1]; $media .="]]&gt;&lt;/job&gt;\n"; } if($body !="") { $media .="&lt;bio&gt;&lt;![CDATA["; $media .= $body; $media .= "]]&gt;&lt;/bio&gt;\n"; } $something = $row['id']; $result1 = mysql_query("SELECT * FROM media WHERE assets='$something'"); $media .= "&lt;images&gt;"; while($row1 = mysql_fetch_array($result1)) { $img = explode("/",$row1[path],2); $media .= "&lt;image url='$img[1]' /&gt;"; } $media .= "&lt;/images&gt;\n"; $media .="&lt;/member&gt;\n"; } $media .= "&lt;/content&gt;"; echo $media; ?&gt; </code></pre>
[ { "answer_id": 211807, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 3, "selected": true, "text": "<p>What happens if you add <code>set_time_limit(0);</code> to the code? I usually add that line to long-executing code below the include statements.</p>\n\n<p>Since this works, let me elaborate.</p>\n\n<p>By default, PHP scripts are set up to only execute for so long. I believe the limit is 30 seconds when PHP is installed, but this can be changed in the php.ini file. However, you might not want to allow all scripts to run for the same length of time - 30 seconds might be fine for most scripts. The <code>set_time_limit</code> function allows you to set the execution time for one script. It takes an integer value which represents the number of seconds to run the script, but a value of 0 means the script will run forever.</p>\n" }, { "answer_id": 211823, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>The default timeout for PHP is 30 seconds. If that code is taking 30 seconds then I think you have some problems! Do you have indices on the media table (one across <code>related_page_id</code> + <code>type</code> and one on <code>assets</code> should do it).</p>\n\n<p>Increasing the time limit is more like hiding the problem than fixing it, and I definitely wouldn't use <code>set_time_limit(0);</code>. You want some kind of sensible maximum in there, be it a minute, an hour, a day or whatever, depending on your needs.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have no idea. This causes seemingly random time-outs. These in turn break the flash that i am loading it into. Has anyone seen anything like this before? ``` <?php require_once("../includes/class.database.php"); require_once("../includes/dbConnectInfo.inc"); require_once("../includes/functions.php"); include("../includes/conn.php"); $cat = $_GET['category']; $result = mysql_query("SELECT * FROM media WHERE related_page_id=4 && type='copy' ORDER BY id ASC LIMIT 6"); $media = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n"; $media .= "<content>\n"; while($row = mysql_fetch_array($result)) { $media .="<member>\n"; $body = $row[copy]; if($row[title] == "") { $media .= "<title><![CDATA["; $media .= "Team"; $media .="]]></title>\n"; } elseif ($row['path']=="") { $name = explode("/",$row[title],2); $media .= "<name><![CDATA["; $media .= $name[0]; $media .="]]></name>\n"; $media .= "<job><![CDATA["; $media .= $name[1]; $media .="]]></job>\n"; } if($body !="") { $media .="<bio><![CDATA["; $media .= $body; $media .= "]]></bio>\n"; } $something = $row['id']; $result1 = mysql_query("SELECT * FROM media WHERE assets='$something'"); $media .= "<images>"; while($row1 = mysql_fetch_array($result1)) { $img = explode("/",$row1[path],2); $media .= "<image url='$img[1]' />"; } $media .= "</images>\n"; $media .="</member>\n"; } $media .= "</content>"; echo $media; ?> ```
What happens if you add `set_time_limit(0);` to the code? I usually add that line to long-executing code below the include statements. Since this works, let me elaborate. By default, PHP scripts are set up to only execute for so long. I believe the limit is 30 seconds when PHP is installed, but this can be changed in the php.ini file. However, you might not want to allow all scripts to run for the same length of time - 30 seconds might be fine for most scripts. The `set_time_limit` function allows you to set the execution time for one script. It takes an integer value which represents the number of seconds to run the script, but a value of 0 means the script will run forever.
211,819
<p>When doing a <code>cvs update</code>, you get a nice summary of the state of the repository, for example:</p> <pre><code>M src/file1.txt M src/file2.txt C src/file3.txt A src/file4.txt ? src/file5.txt </code></pre> <p>Is there a way to get this without actually updating? I know there is <code>cvs status</code>, but this is way to verbose:</p> <pre><code>=================================================================== File: file6.txt Status: Up-to-date Working revision: 1.2 Repository revision: 1.2 /var/cvs/cvsroot/file6.txt,v Sticky Tag: (none) Sticky Date: (none) Sticky Options: (none) </code></pre> <p>I could of course make a script to do the transformation from the latter to the former, but it seems a waste of time since cvs can obviously produce the former.</p>
[ { "answer_id": 211821, "author": "jmcnamara", "author_id": 10238, "author_profile": "https://Stackoverflow.com/users/10238", "pm_score": 6, "selected": true, "text": "<p>You can use the -n flag to get the update output without actually updating the files. You can also add -q (quiet) to suppress any server messages.</p>\n\n<pre><code>cvs -q -n update\n</code></pre>\n" }, { "answer_id": 211915, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 2, "selected": false, "text": "<p>@jmcnamara: Good tip!</p>\n\n<p>And all this time I've been using this bash script:</p>\n\n<pre><code>cvs -q status \"$@\" | grep '^[?F]' | grep -v 'Up-to-date'\n</code></pre>\n" }, { "answer_id": 270760, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 2, "selected": false, "text": "<p>If you're using CVSNT you can also just do <code>cvs status -q</code> which will also produce much briefer output than the regular status command (also just one line per file). With more recent versions you can even do <code>cvs status -qq</code> which will skip the up-to-date files.</p>\n" }, { "answer_id": 20122122, "author": "Kiril Kirov", "author_id": 435800, "author_profile": "https://Stackoverflow.com/users/435800", "pm_score": 2, "selected": false, "text": "<p>I have some aliases, that may be useful for somebody:</p>\n\n<pre><code>alias cvsstatus_command='cvs -q status | grep \"^[?F]\" | grep -v \"Up-to-date\" | \\\n grep -v \"\\.so\" | grep -v \"\\.[c]*project\"'\n\nalias cvsstatus_color='nawk '\"'\"'BEGIN \\\n { \\\n arr[\"Needs Merge\"] = \"0;31\"; \\\n arr[\"Needs Patch\"] = \"1;31\"; \\\n arr[\"conflicts\"] = \"1;33\"; \\\n arr[\"Locally Modified\"] = \"0;33\"; \\\n arr[\"Locally Added\"] = \"0;32\" \\\n } \\\n { \\\n l = $0; \\\n for (pattern in arr) { \\\n gsub(\".*\" pattern \".*\", \"\\033[\" arr[pattern] \"m&amp;\\033[0m\", l); \\\n } \\\n print l; \\\n }'\"'\"\n\nalias cvsstatus='cvsstatus_command | cvsstatus_color'\n</code></pre>\n\n<p>This will display only file names and their status, ignore all up-to-date files, remove all eclipse project files and shared objects and will also <strong>print the lines in different colors, depending on the status</strong> (for example, I have orange for locally modified; red for files, needing merge; green for locally added, etc)</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3102/" ]
When doing a `cvs update`, you get a nice summary of the state of the repository, for example: ``` M src/file1.txt M src/file2.txt C src/file3.txt A src/file4.txt ? src/file5.txt ``` Is there a way to get this without actually updating? I know there is `cvs status`, but this is way to verbose: ``` =================================================================== File: file6.txt Status: Up-to-date Working revision: 1.2 Repository revision: 1.2 /var/cvs/cvsroot/file6.txt,v Sticky Tag: (none) Sticky Date: (none) Sticky Options: (none) ``` I could of course make a script to do the transformation from the latter to the former, but it seems a waste of time since cvs can obviously produce the former.
You can use the -n flag to get the update output without actually updating the files. You can also add -q (quiet) to suppress any server messages. ``` cvs -q -n update ```
211,834
<p>OK... I'm a VB.NET WinForms guy trying to understand WPF and all of its awesomeness. I'm writing a basic app as a learning experience, and have been reading lots of information and watching tutorial videos, but I just can't get off the ground with simple DataBinding, and I know I'm missing some basic concept. As much as I'd love it, I haven't had that "Aha!" moment when reviewing source code yet.</p> <p>So... In my Window class I defined a custom string Property. When I go into Blend, I try to databind my TextBox's Text to this property, but my Property doesn't show up in Blend as something that available for Binding to.</p> <p>Can someone tell me what I need to add to my code/XAML below... and most importantly why?</p> <p>My XAML:</p> <pre><code>&lt;Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"&gt; &lt;Grid&gt; &lt;TextBox Text="How do I Bind my SomeText property here?"&gt;&lt;/TextBox&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>My Window Code:</p> <pre><code>Class Window1 Private _sometext As String = "Hello World" Public Property SomeText() As String Get Return _sometext End Get Set(ByVal value As String) _sometext = value End Set End Property End Class </code></pre>
[ { "answer_id": 211990, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 4, "selected": true, "text": "<p>Here's how you need to change your XAML (the code is fine). </p>\n\n<pre><code>&lt;Window x:Class=\"Window1\" \n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title=\"Window1\" Height=\"300\" Width=\"300\" \n DataContext=\"{Binding RelativeSource={RelativeSource Self}}\"&gt; \n &lt;Grid&gt; \n &lt;TextBox Text=\"{Binding SomeText}\"&gt;\n &lt;/TextBox&gt; \n &lt;/Grid&gt;\n &lt;/Window&gt;\n</code></pre>\n\n<p>To understand Bindings in WPF, you need to understand the DataContext. Every element has a DataContext property, and any object you put in that property becomes the data source of any bindings which do not have an explicit data source specified. The value of the DataContext is inherited from a parent object (so in this case the TextBox inherits the Grid's DataContext, which inherits the Window's DataContext). Since you want to refer to a property of the window, you need to set the DataContext to point to the Window instance, which is what I do in the DataContext attribute of the Window.</p>\n\n<p>You can also change the data source for individual bindings by using the Source= or RelativeSource= syntax in the {Binding } element.</p>\n" }, { "answer_id": 212015, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 3, "selected": false, "text": "<p>For data binding it is helpful to think about several things:</p>\n\n<ol>\n<li>Source Object</li>\n<li>Target Object (which must be a DependencyObject)</li>\n<li>Source Property (the property on the Source Object that is participating in the binding)</li>\n<li>Target Property (which must be a Dependency Property)</li>\n</ol>\n\n<p>In your sample code:</p>\n\n<ol>\n<li>Source Object = Window1</li>\n<li>Target Object = TextBox</li>\n<li>Source Property = SomeText Property</li>\n<li>Target Property = Text</li>\n</ol>\n\n<p>The Binding markup extension goes on the Target property of the Target object.</p>\n\n<p>Here is a picture which illustrates the above:</p>\n\n<p><img src=\"https://farm4.static.flickr.com/3193/2949579676_4a98851949_o.png\" alt=\"alt text\"></p>\n\n<p>Check out the following code (one way to solve this problem):</p>\n\n<pre><code>&lt;Window\n x:Class=\"WpfApplication2.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n x:Name=\"theWindow\"\n Title=\"Window1\"\n Height=\"300\"\n Width=\"300\"\n&gt;\n &lt;Grid&gt;\n &lt;StackPanel&gt;\n &lt;TextBox Text=\"{Binding ElementName=theWindow, Path=SomeText}\"/&gt;\n &lt;Button\n Width=\"100\"\n Height=\"25\"\n Content=\"Change Text\"\n Click=\"Button_Click\"\n /&gt;\n &lt;/StackPanel&gt;\n &lt;/Grid&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>In the Binding markup extension, I have defined the source using ElementName ... which allows you to use another element in your visual tree as the source. In doing so, I also had to give the window a name with the x:Name attribute.</p>\n\n<p>There are several ways to define a source with Binding (i.e. Source, ElementName, DataContext) ... ElementName is just one way.</p>\n\n<p>One thing to note is that the Source property doesn't have to be a Dependency Property, but if it isn't, then the Target property won't update ... without some special help.\nCheck out the following piece of code (my apologies it is C#, that was quicker for me). In it you will see me implement INotifyPropertyChanged. This allows a source object to say that something has changed ... and the data binding is smart enough to watch for it. Thus, if you click the button (from the example code here), it will update the TextBox. Without implementing this interface (and if you click the button), the TextBox would not update.</p>\n\n<p>I hope that helps.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Interaction logic for Window1.xaml\n/// &lt;/summary&gt;\npublic partial class Window1 : Window, INotifyPropertyChanged\n{\n public Window1()\n {\n InitializeComponent();\n }\n\n private string _someText = \"Hello World!\";\n public string SomeText\n {\n get { return _someText; }\n set\n {\n _someText = value;\n OnNotifyPropertyChanged(\"SomeText\");\n }\n }\n\n #region INotifyPropertyChanged Members\n\n public event PropertyChangedEventHandler PropertyChanged;\n private void OnNotifyPropertyChanged(string propertyName)\n {\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n\n #endregion\n\n private void Button_Click(object sender, RoutedEventArgs e)\n {\n this.SomeText = \"Goodbye World!\";\n }\n}\n</code></pre>\n" }, { "answer_id": 212017, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 1, "selected": false, "text": "<p>WPF DataBinding is a very powerful feature. I suggest to read some already existing articles on the web, such as</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/aa480224.aspx\" rel=\"nofollow noreferrer\">Windows Presentation Foundation Data Binding: Part 1</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/aa480226.aspx\" rel=\"nofollow noreferrer\">Windows Presentation Foundation Data Binding: Part 2</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms752347.aspx\" rel=\"nofollow noreferrer\">Data Binding Overview</a></li>\n</ul>\n\n<p>Very helpful to me was also <a href=\"http://www.beacosta.com/blog/\" rel=\"nofollow noreferrer\">Beatrix Costa's blog on Data Binding</a>.</p>\n" }, { "answer_id": 397814, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 0, "selected": false, "text": "<p>Data binding with a CLR property requires an extra step. You have to implement INotifyPropertyChanged and fire the PropertyChanged event whenever that CLR property changes. This won't make it appear in Blend, but you can bind to the property using Text=\"{Binding SomeText}\" and setting the window's DataContext to your object.</p>\n\n<p>There is an alternative. Instead of using .NET data binding, consider <a href=\"http://codeplex.com/updatecontrols\" rel=\"nofollow noreferrer\">Update Controls .NET</a>. It's an open source project that replaces data binding and does not require INotifyPropertyChanged. The great thing about Update Controls is that it can see through intermediate business logic. With INotifyPropertyChanged you have to catch and re-fire events.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/641985/" ]
OK... I'm a VB.NET WinForms guy trying to understand WPF and all of its awesomeness. I'm writing a basic app as a learning experience, and have been reading lots of information and watching tutorial videos, but I just can't get off the ground with simple DataBinding, and I know I'm missing some basic concept. As much as I'd love it, I haven't had that "Aha!" moment when reviewing source code yet. So... In my Window class I defined a custom string Property. When I go into Blend, I try to databind my TextBox's Text to this property, but my Property doesn't show up in Blend as something that available for Binding to. Can someone tell me what I need to add to my code/XAML below... and most importantly why? My XAML: ``` <Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <TextBox Text="How do I Bind my SomeText property here?"></TextBox> </Grid> </Window> ``` My Window Code: ``` Class Window1 Private _sometext As String = "Hello World" Public Property SomeText() As String Get Return _sometext End Get Set(ByVal value As String) _sometext = value End Set End Property End Class ```
Here's how you need to change your XAML (the code is fine). ``` <Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <Grid> <TextBox Text="{Binding SomeText}"> </TextBox> </Grid> </Window> ``` To understand Bindings in WPF, you need to understand the DataContext. Every element has a DataContext property, and any object you put in that property becomes the data source of any bindings which do not have an explicit data source specified. The value of the DataContext is inherited from a parent object (so in this case the TextBox inherits the Grid's DataContext, which inherits the Window's DataContext). Since you want to refer to a property of the window, you need to set the DataContext to point to the Window instance, which is what I do in the DataContext attribute of the Window. You can also change the data source for individual bindings by using the Source= or RelativeSource= syntax in the {Binding } element.
211,875
<p>I have a string column in a database table which maps to an Enum in code. In my dbml file when I set the "Type" to <code>MyTypes.EnumType</code> I get the following error:</p> <blockquote> <p>Error 1 DBML1005: Mapping between DbType 'VarChar(50) NOT NULL' and Type 'MyTypes.EnumType' in Column 'EnumCol' of Type 'Table1' is not supported.</p> </blockquote> <p>This question: <a href="https://stackoverflow.com/questions/4939/linq-to-sql-strings-to-enums">LINQ to SQL strings to enums</a> indicates that what I am trying to do is possible, but how is it done?</p>
[ { "answer_id": 211894, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>Curious - it should work IIRC; I'll see if I can do a quick example - however, you might want to check that you have the fully-qualified enum name (i.e. including the namespace).</p>\n\n<p>[update] From <a href=\"http://blog.rolpdog.com/2007/07/linq-to-sql-enum-mapping.html\" rel=\"noreferrer\">here</a> it seems that the RTM version shipped with a bug when resolving the enum. One workaround suggested (on that page) was to add the <code>global::</code> prefix. It works fine for me without this workaround, so maybe it is fixed in 3.5 SP1? It also allegedly works fine in 3.5 if you use the unqualified name if the enum is in the same namespace.</p>\n\n<p>[example] Yup, worked fine: with Northwind, I defined an enum for the shipping country:</p>\n\n<pre><code>namespace Foo.Bar\n{\n public enum MyEnum\n {\n France,\n Belgium,\n Brazil,\n Switzerland\n }\n}\n</code></pre>\n\n<p>I then edited the dbml to have:</p>\n\n<pre><code>&lt;Column Name=\"ShipCountry\" Type=\"Foo.Bar.MyEnum\" DbType=\"NVarChar(15)\" CanBeNull=\"true\" /&gt;\n</code></pre>\n\n<p>This generated:</p>\n\n<pre><code>private Foo.Bar.MyEnum _ShipCountry;\n//...\n[Column(Storage=\"_ShipCountry\", DbType=\"NVarChar(15)\", CanBeNull=true)]\npublic Foo.Bar.MyEnum ShipCountry\n{ get {...} set {...} }\n</code></pre>\n\n<p>And finally wrote a query:</p>\n\n<pre><code>using (DataClasses1DataContext ctx = new DataClasses1DataContext())\n{\n var qry = from order in ctx.Orders\n where order.ShipCountry == Foo.Bar.MyEnum.Brazil\n || order.ShipCountry == Foo.Bar.MyEnum.Belgium\n select order;\n foreach (var order in qry.Take(10))\n {\n Console.WriteLine(\"{0}, {1}\", order.OrderID, order.ShipCountry);\n }\n}\n</code></pre>\n\n<p>Worked fine; results:</p>\n\n<pre><code>10250, Brazil\n10252, Belgium\n10253, Brazil\n10256, Brazil\n10261, Brazil\n10287, Brazil\n10290, Brazil\n10291, Brazil\n10292, Brazil\n10299, Brazil\n</code></pre>\n" }, { "answer_id": 1583931, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 4, "selected": false, "text": "<p>I know this has been answered, but i'm still getting this error also. Very weird.</p>\n\n<p>Anyways, I found a solution. You need to <em>PREPEND</em> the full namespace of the enum with <code>global::</code></p>\n\n<p>like WTF? Exactly. I know it sounds very weird. Here's an example screenie =></p>\n\n<p><a href=\"http://img11.imageshack.us/img11/7517/lolzqg.png\" rel=\"noreferrer\">alt text http://img11.imageshack.us/img11/7517/lolzqg.png</a></p>\n\n<p>So lame :(</p>\n\n<p>Anyways, I didn't figure this out. Some dude called <a href=\"http://blog.rolpdog.com/2007/07/linq-to-sql-enum-mapping.html\" rel=\"noreferrer\">Matt</a>, did. And he posted a bug report on MS Connect and they can't repro it so it's not fixed, I guess.</p>\n\n<p>Anyways, HTH.</p>\n" }, { "answer_id": 3518015, "author": "Manuel Castro", "author_id": 288415, "author_profile": "https://Stackoverflow.com/users/288415", "pm_score": 1, "selected": false, "text": "<p>If you add the global:: qualyfier and press Control + space over the type in the designer.cs file it recognizes the type and you can remove it.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28889/" ]
I have a string column in a database table which maps to an Enum in code. In my dbml file when I set the "Type" to `MyTypes.EnumType` I get the following error: > > Error 1 DBML1005: Mapping between DbType 'VarChar(50) NOT NULL' and > Type 'MyTypes.EnumType' in Column 'EnumCol' of Type 'Table1' is not > supported. > > > This question: [LINQ to SQL strings to enums](https://stackoverflow.com/questions/4939/linq-to-sql-strings-to-enums) indicates that what I am trying to do is possible, but how is it done?
Curious - it should work IIRC; I'll see if I can do a quick example - however, you might want to check that you have the fully-qualified enum name (i.e. including the namespace). [update] From [here](http://blog.rolpdog.com/2007/07/linq-to-sql-enum-mapping.html) it seems that the RTM version shipped with a bug when resolving the enum. One workaround suggested (on that page) was to add the `global::` prefix. It works fine for me without this workaround, so maybe it is fixed in 3.5 SP1? It also allegedly works fine in 3.5 if you use the unqualified name if the enum is in the same namespace. [example] Yup, worked fine: with Northwind, I defined an enum for the shipping country: ``` namespace Foo.Bar { public enum MyEnum { France, Belgium, Brazil, Switzerland } } ``` I then edited the dbml to have: ``` <Column Name="ShipCountry" Type="Foo.Bar.MyEnum" DbType="NVarChar(15)" CanBeNull="true" /> ``` This generated: ``` private Foo.Bar.MyEnum _ShipCountry; //... [Column(Storage="_ShipCountry", DbType="NVarChar(15)", CanBeNull=true)] public Foo.Bar.MyEnum ShipCountry { get {...} set {...} } ``` And finally wrote a query: ``` using (DataClasses1DataContext ctx = new DataClasses1DataContext()) { var qry = from order in ctx.Orders where order.ShipCountry == Foo.Bar.MyEnum.Brazil || order.ShipCountry == Foo.Bar.MyEnum.Belgium select order; foreach (var order in qry.Take(10)) { Console.WriteLine("{0}, {1}", order.OrderID, order.ShipCountry); } } ``` Worked fine; results: ``` 10250, Brazil 10252, Belgium 10253, Brazil 10256, Brazil 10261, Brazil 10287, Brazil 10290, Brazil 10291, Brazil 10292, Brazil 10299, Brazil ```
211,941
<p>This is an extension of my <a href="https://stackoverflow.com/questions/205923">earlier XSS question</a>.</p> <p>Assuming that there isn't a Regex strong enough to guarantee XSS saftey for user entered URLs I'm looking at using a redirect.</p> <p>(Although if you do have one please add it under the other question)</p> <p>We have user input web addresses, so:</p> <blockquote> <p>stackoverflow.com</p> </blockquote> <p>They want a link to appear for other users, so:</p> <pre><code>&lt;a href="http://stackoverflow.com"&gt;stackoverflow.com&lt;/a&gt; </code></pre> <p>To reduce the risk of hacking I'm planning to use a warning page, so the link becomes:</p> <pre><code>&lt;a href="leavingSite.aspx?linkid=1234" target="_blank"&gt;stackoverflow.com&lt;/a&gt; </code></pre> <p>Then on that page there will be a warning message and a plain link to the original link:</p> <pre><code>&lt;a href="javascript:alert('oh noes! xss!');"&gt;Following this link at your own risk!&lt;/a&gt; </code></pre> <p>As we use a lot of Ajax I want to make that leaving-site page a walled garden of sorts, ideally by essentially logging the user out in that page only. I want them to stay logged in on the original page.</p> <p>Then if someone does get past the santisation Regex they can't access anything as the duped user.</p> <p>Anyone know how to do this? Is it possible to log out one window/tab without logging them all out? We support IE &amp; FX, but ideally a solution would work in Opera/Chrome/Safari too.</p>
[ { "answer_id": 211952, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "<p>It's not possible to log someone out in just one tab / window.</p>\n" }, { "answer_id": 212024, "author": "Erik Johansson", "author_id": 15307, "author_profile": "https://Stackoverflow.com/users/15307", "pm_score": 0, "selected": false, "text": "<p>restrict cookies to www.example.com and have the forwarding page at links.example.com</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
This is an extension of my [earlier XSS question](https://stackoverflow.com/questions/205923). Assuming that there isn't a Regex strong enough to guarantee XSS saftey for user entered URLs I'm looking at using a redirect. (Although if you do have one please add it under the other question) We have user input web addresses, so: > > stackoverflow.com > > > They want a link to appear for other users, so: ``` <a href="http://stackoverflow.com">stackoverflow.com</a> ``` To reduce the risk of hacking I'm planning to use a warning page, so the link becomes: ``` <a href="leavingSite.aspx?linkid=1234" target="_blank">stackoverflow.com</a> ``` Then on that page there will be a warning message and a plain link to the original link: ``` <a href="javascript:alert('oh noes! xss!');">Following this link at your own risk!</a> ``` As we use a lot of Ajax I want to make that leaving-site page a walled garden of sorts, ideally by essentially logging the user out in that page only. I want them to stay logged in on the original page. Then if someone does get past the santisation Regex they can't access anything as the duped user. Anyone know how to do this? Is it possible to log out one window/tab without logging them all out? We support IE & FX, but ideally a solution would work in Opera/Chrome/Safari too.
It's not possible to log someone out in just one tab / window.
211,958
<p><strong>EDIT: I missed a crucial point: .NET 2.0</strong></p> <p>Consider the case where I have a list of unsorted items, for the sake of simplicity of a type like this:</p> <pre><code>class TestClass { DateTime SomeTime; decimal SomePrice; // constructor } </code></pre> <p>I need to create a report-like output, where the total prices for each day are accumulated. There should be one line for each item, folled by the appropriate summary lines.</p> <p>Take this test data:</p> <pre><code>List&lt;TestClass&gt; testList = new List&lt;TestClass&gt; { new TestClass(new DateTime(2008,01,01), 12), new TestClass(new DateTime(2007,01,01), 20), new TestClass(new DateTime(2008,01,01), 18) }; </code></pre> <p>The desired output would be something like this:</p> <pre><code>2007-01-01: 20 Total: 20 2008-01-01: 12 18 Total: 30 </code></pre> <p>What's the best way to approach such scenarios? In the case of such a list, I would implement the IComparable interface for TestClass, so that the list can be sorted.</p> <p>To create the report itself, something like this could be used (let's assume that we have methods for tasks like accumulating the prices, keeping track of the current date etc):</p> <pre><code>for (int i=0;i&lt;testList.Count;i++) { if (IsNewDate(testList[i])) { CreateSummaryLine(); ResetValuesForNewDate(); } AddValues(testList[i]); } // a final summary line is needed to include the data for the last couple of items. CreateSummaryLine(); </code></pre> <p>This works alright, but I have a strange feeling as far as the second "CreateSummaryLines" is concerned.</p> <p>In what ways do you handle such situations (especially considering the fact, the we need to work with a List&lt;> of items rather than a pre-categorized Dictionary or something like that)?</p>
[ { "answer_id": 211977, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Crucial question: are you using .NET 3.5, thus allowing LINQ to be used? If so, you can group by SomeTime.Date and then process each date separately.</p>\n\n<p>If you have massive amounts of data, you may find my <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx\" rel=\"nofollow noreferrer\">Push LINQ</a> project useful - but otherwise straight LINQ to Objects is your best bet.</p>\n" }, { "answer_id": 211978, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>[edit] Since you are using .NET 2.0 with C# 3.0, you can use <a href=\"http://www.albahari.com/nutshell/linqbridge.aspx\" rel=\"nofollow noreferrer\">LINQBridge</a> to enable this.</p>\n\n<p>LINQ; something like:</p>\n\n<pre><code> var groups = from row in testList\n group row by row.SomeTime;\n foreach (var group in groups.OrderBy(group =&gt; group.Key))\n {\n Console.WriteLine(group.Key);\n foreach(var item in group.OrderBy(item =&gt; item.SomePrice))\n {\n Console.WriteLine(item.SomePrice);\n }\n Console.WriteLine(\"Total\" + group.Sum(x=&gt;x.SomePrice));\n }\n</code></pre>\n" }, { "answer_id": 211979, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>What version of C#/.NET are you using? If you're up to date, have a look at LINQ. This allows grouping your data. In your case, you could group by date:</p>\n\n<pre><code>var days = from test in testList group test by test.SomeTime;\nforeach (var day in days) {\n var sum = day.Sum(x =&gt; x.SomePrice);\n Report(day, sum);\n}\n</code></pre>\n\n<p>This way you could report a list of values for each <code>day</code>, along with the sum of money for that day.</p>\n" }, { "answer_id": 211983, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 0, "selected": false, "text": "<p>Your desired output feels like you want to make a data structure that represents your summary data. You want to pair a date with a list of TestClass objects, then have a collection of those. You could use a HashSet or a Dictionary for the collection.</p>\n\n<p>For the summary, pair data structure can implement ToString for you.</p>\n" }, { "answer_id": 212000, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Okay, so if you can't use LINQ:</p>\n\n<p>(I'm using var to save space, but it's easy to translate to C# 2.0 if necessary...)</p>\n\n<pre><code>var grouped = new SortedDictionary&lt;DateTime, List&lt;TestClass&gt;&gt;();\nforeach (TestClass entry in testList) {\n DateTime date = entry.SomeTime.Date;\n if (!grouped.ContainsKey(date)) {\n grouped[date] = new List&lt;TestClass&gt;();\n }\n grouped[date].Add(entry);\n}\n\nforeach (KeyValuePair&lt;DateTime, List&lt;TestClass&gt;&gt; pair in testList) {\n Console.WriteLine(\"{0}: \", pair.Key);\n Console.WriteLine(BuildSummaryLine(pair.Value));\n}\n</code></pre>\n" }, { "answer_id": 212218, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>Regardless of how you generate the report output, if you are going to be doing this regularly in your application consider putting together a report interface and implementing classes for this interface to localize the logic for creating the report in one place rather than scattering the code to create reports throughout your application. In my experience, applications typically have (or grow) requirements for multiple reports and, eventually, multiple formats.</p>\n\n<p><strong>If you've only got one report, don't worry about it until you write your second one,</strong> but then start working on a reporting architecture that makes it easier to extend and maintain.</p>\n\n<p>For example (and using @Marc Gravell's code):</p>\n\n<pre><code>public interface IReport\n{\n string GetTextReportDocument();\n byte[] GetPDFReportDocument(); // needing this triggers the development of interface\n}\n\npublic class SalesReport : IReport\n{\n public void AddSale( Sale newSale )\n {\n this.Sales.Add(newSale); // or however you implement it\n }\n\n public string GetTextReportDocument()\n {\n StringBuilder reportBuilder = new StringBuilder();\n var groups = from row in this.Sales\n group row by row.SomeTime.Date;\n foreach (var group in groups.OrderBy(group =&gt; group.Key))\n { \n reportBuilder.AppendLine(group.Key);\n foreach(var item in group.OrderBy(item =&gt; item.SomePrice)) \n {\n reportBuilder.AppendLine(item.SomePrice);\n }\n reportBuilder.AppendLine(\"Total\" + group.Sum(x=&gt;x.SomePrice));\n }\n\n return reportBuilder.ToString();\n }\n\n public byte[] GetPDFReportDocument()\n {\n return PDFReporter.GenerateDocumentFromXML( this.ConvertSalesToXML() );\n }\n</code></pre>\n\n<p>... the rest is left as an exercise for the reader ...</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17378/" ]
**EDIT: I missed a crucial point: .NET 2.0** Consider the case where I have a list of unsorted items, for the sake of simplicity of a type like this: ``` class TestClass { DateTime SomeTime; decimal SomePrice; // constructor } ``` I need to create a report-like output, where the total prices for each day are accumulated. There should be one line for each item, folled by the appropriate summary lines. Take this test data: ``` List<TestClass> testList = new List<TestClass> { new TestClass(new DateTime(2008,01,01), 12), new TestClass(new DateTime(2007,01,01), 20), new TestClass(new DateTime(2008,01,01), 18) }; ``` The desired output would be something like this: ``` 2007-01-01: 20 Total: 20 2008-01-01: 12 18 Total: 30 ``` What's the best way to approach such scenarios? In the case of such a list, I would implement the IComparable interface for TestClass, so that the list can be sorted. To create the report itself, something like this could be used (let's assume that we have methods for tasks like accumulating the prices, keeping track of the current date etc): ``` for (int i=0;i<testList.Count;i++) { if (IsNewDate(testList[i])) { CreateSummaryLine(); ResetValuesForNewDate(); } AddValues(testList[i]); } // a final summary line is needed to include the data for the last couple of items. CreateSummaryLine(); ``` This works alright, but I have a strange feeling as far as the second "CreateSummaryLines" is concerned. In what ways do you handle such situations (especially considering the fact, the we need to work with a List<> of items rather than a pre-categorized Dictionary or something like that)?
[edit] Since you are using .NET 2.0 with C# 3.0, you can use [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) to enable this. LINQ; something like: ``` var groups = from row in testList group row by row.SomeTime; foreach (var group in groups.OrderBy(group => group.Key)) { Console.WriteLine(group.Key); foreach(var item in group.OrderBy(item => item.SomePrice)) { Console.WriteLine(item.SomePrice); } Console.WriteLine("Total" + group.Sum(x=>x.SomePrice)); } ```
211,971
<p>WPF, Browserlike app.<br> I got one page containing a ListView. After calling a PageFunction I add a line to the ListView, and want to scroll the new line into view:</p> <pre><code> ListViewItem item = ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem; if (item != null) ScrollIntoView(item); </code></pre> <p>This works. As long as the new line is in view the line gets the focus like it should.</p> <p>Problem is, things don't work when the line is not visible.<br> If the line is not visible, there is no ListViewItem for the line generated, so ItemContainerGenerator.ContainerFromIndex returns null.</p> <p>But without the item, how do I scroll the line into view? Is there any way to scroll to the last line (or anywhere) without needing an ListViewItem?</p>
[ { "answer_id": 211984, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 5, "selected": true, "text": "<p>I think the problem here is that the ListViewItem is not created yet if the line is not visible. WPF creates the Visible on demand.</p>\n\n<p>So in this case you probably get <code>null</code> for the item, do you?\n(According to your comment, you do)</p>\n\n<p>I have found a <a href=\"http://social.msdn.microsoft.com/forums/en-US/wpf/thread/7c5812bd-482f-448c-bc67-02573e48d691\" rel=\"noreferrer\">link on MSDN forums that suggest accessing the Scrollviewer directly</a> in order to scroll. To me the solution presented there looks very much like a hack, but you can decide for yourself.</p>\n\n<p>Here is the code snippet from the <a href=\"http://social.msdn.microsoft.com/forums/en-US/wpf/thread/7c5812bd-482f-448c-bc67-02573e48d691\" rel=\"noreferrer\">link above</a>:</p>\n\n<pre><code>VirtualizingStackPanel vsp = \n (VirtualizingStackPanel)typeof(ItemsControl).InvokeMember(\"_itemsHost\",\n BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic, null, \n _listView, null);\n\ndouble scrollHeight = vsp.ScrollOwner.ScrollableHeight;\n\n// itemIndex_ is index of the item which we want to show in the middle of the view\ndouble offset = scrollHeight * itemIndex_ / _listView.Items.Count;\n\nvsp.SetVerticalOffset(offset);\n</code></pre>\n" }, { "answer_id": 213095, "author": "decasteljau", "author_id": 12082, "author_profile": "https://Stackoverflow.com/users/12082", "pm_score": 2, "selected": false, "text": "<p>One workaround to this is to change the ItemsPanel of the ListView. The default panel is the VirtualizingStackPanel which only creates the ListBoxItem the first time they become visible. If you don't have too many items in your list, it should not be a problem.</p>\n\n<pre><code>&lt;ListView&gt;\n ...\n &lt;ListView.ItemsPanel&gt;\n &lt;ItemsPanelTemplate&gt;\n &lt;StackPanel/&gt;\n &lt;/ItemsPanelTemplate&gt;\n &lt;/ListView.ItemsPanel&gt;\n&lt;/ListView&gt;\n</code></pre>\n" }, { "answer_id": 229259, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 5, "selected": false, "text": "<p>Someone told me an even better way to scroll to a specific line, which is easy and works like charm.<br>\nIn short:</p>\n\n<pre><code>public void ScrollToLastItem()\n{\n lv.SelectedItem = lv.Items.GetItemAt(rows.Count - 1);\n lv.ScrollIntoView(lv.SelectedItem);\n ListViewItem item = lv.ItemContainerGenerator.ContainerFromItem(lv.SelectedItem) as ListViewItem;\n item.Focus();\n}\n</code></pre>\n\n<p>The longer version in <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/2ce4fee4-fbf6-4c0e-9dc6-49c0ac0c3152/\" rel=\"noreferrer\">MSDN forums</a>:</p>\n" }, { "answer_id": 686940, "author": "Echilon", "author_id": 30512, "author_profile": "https://Stackoverflow.com/users/30512", "pm_score": 2, "selected": false, "text": "<p>Thanks for that last tip Sam. I had a dialog which opened, meaning my grid lost focus every time the dialog closed. I use this:</p>\n\n<pre><code>if(currentRow &gt;= 0 &amp;&amp; currentRow &lt; lstGrid.Items.Count) {\n lstGrid.SelectedIndex = currentRow;\n lstGrid.ScrollIntoView(lstGrid.SelectedItem);\n if(shouldFocusGrid) {\n ListViewItem item = lstGrid.ItemContainerGenerator.ContainerFromItem(lstGrid.SelectedItem) as ListViewItem;\n item.Focus();\n }\n} else if(shouldFocusGrid) {\n lstGrid.Focus();\n}\n</code></pre>\n" }, { "answer_id": 1305542, "author": "Joseph jun. Melettukunnel", "author_id": 123172, "author_profile": "https://Stackoverflow.com/users/123172", "pm_score": 3, "selected": false, "text": "<p>I made some changes to Sam's answer. Note that I wanted to scroll to the last line. Unfortunately the ListView sometiems just displayed the last line (even when there were e.g. 100 lines above it), so this is how I fixed that:</p>\n\n<pre><code> public void ScrollToLastItem()\n {\n if (_mainViewModel.DisplayedList.Count &gt; 0)\n {\n var listView = myListView;\n listView.SelectedItem = listView.Items.GetItemAt(_mainViewModel.DisplayedList.Count - 1);\n listView.ScrollIntoView(listView.Items[0]);\n listView.ScrollIntoView(listView.SelectedItem);\n //item.Focus();\n }\n }\n</code></pre>\n\n<p>Cheers</p>\n" }, { "answer_id": 2610968, "author": "Murali.S", "author_id": 313185, "author_profile": "https://Stackoverflow.com/users/313185", "pm_score": 2, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n ScrollViewer scrollViewer = GetScrollViewer(lstVw) as ScrollViewer;\n scrollViewer.ScrollToHorizontalOffset(dataRowToFocus.RowIndex);\n if (dataRowToFocus.RowIndex &lt; 2)\n lstVw.ScrollIntoView((Entity)lstVw.Items[0]);\n else\n lstVw.ScrollIntoView(e.AddedItems[0]);\n } \n\n public static DependencyObject GetScrollViewer(DependencyObject o)\n {\n if (o is ScrollViewer)\n { return o; }\n\n for (int i = 0; i &lt; VisualTreeHelper.GetChildrenCount(o); i++)\n {\n var child = VisualTreeHelper.GetChild(o, i);\n\n var result = GetScrollViewer(child);\n if (result == null)\n {\n continue;\n }\n else\n {\n return result;\n }\n }\n return null;\n } \n\nprivate void Focus()\n{\n lstVw.SelectedIndex = dataRowToFocus.RowIndex;\n lstVw.SelectedItem = (Entity)dataRowToFocus.Row;\n\n ListViewItem lvi = (ListViewItem)lstVw.ItemContainerGenerator.ContainerFromItem(lstVw.SelectedItem);\nContentPresenter contentPresenter = FindVisualChild&lt;ContentPresenter&gt;(lvi);\ncontentPresenter.Focus();\ncontentPresenter.BringIntoView();\n\n}\n</code></pre>\n" }, { "answer_id": 8410386, "author": "Ray Ackley", "author_id": 1084850, "author_profile": "https://Stackoverflow.com/users/1084850", "pm_score": 1, "selected": false, "text": "<p>I just had the same issue with ItemContainerGenerator.ContainerFromItem() and ItemContainerGenerator.ContainerFromIndex() returning null for items that clearly existed in the listbox. Decasteljau was right but I had to do some digging to figure out exactly what he meant. Here is the breakdown to save the next guy/gal some legwork.</p>\n\n<p>Long story short, ListBoxItems are destroyed if they are not within view. Consequently ContainerFromItem() and ContainerFromIndex() return null since the ListBoxItems do not exist. This is apparently a memory/performance saving feature detailed here: <a href=\"http://blogs.msdn.com/b/oren/archive/2010/11/08/wp7-silverlight-perf-demo-1-virtualizingstackpanel-vs-stackpanel-as-a-listbox-itemspanel.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/oren/archive/2010/11/08/wp7-silverlight-perf-demo-1-virtualizingstackpanel-vs-stackpanel-as-a-listbox-itemspanel.aspx</a></p>\n\n<p>The empty <code>&lt;ListBox.ItemsPanel&gt;</code> code is what turns off the virtualization. Sample code that fixed the issue for me:</p>\n\n<p>Data template:</p>\n\n<pre><code>&lt;phone:PhoneApplicationPage.Resources&gt;\n &lt;DataTemplate x:Key=\"StoryViewModelTemplate\"&gt;\n &lt;StackPanel&gt;\n &lt;your datatemplated stuff here/&gt;\n &lt;/StackPanel&gt;\n &lt;/DataTemplate&gt;\n&lt;/phone:PhoneApplicationPage.Resources&gt;\n</code></pre>\n\n<p>Main body:</p>\n\n<pre><code>&lt;Grid x:Name=\"ContentPanel\"&gt;\n &lt;ListBox Name=\"lbResults\" ItemsSource=\"{Binding SearchResults}\" ItemTemplate=\"{StaticResource StoryViewModelTemplate}\"&gt;\n &lt;ListBox.ItemsPanel&gt;\n &lt;ItemsPanelTemplate&gt;\n &lt;StackPanel&gt;\n &lt;/StackPanel&gt;\n &lt;/ItemsPanelTemplate&gt;\n &lt;/ListBox.ItemsPanel&gt;\n &lt;/ListBox&gt;\n&lt;/Grid&gt;\n</code></pre>\n" }, { "answer_id": 13362285, "author": "Willi", "author_id": 1746253, "author_profile": "https://Stackoverflow.com/users/1746253", "pm_score": 2, "selected": false, "text": "<p>If you just want to show and focus the last item after creating a new data item, this method is maybe better. Compare to ScrollIntoView, ScrollToEnd of ScrollViewer is in my tests more reliable.\nIn some tests using ScrollIntoView method of ListView like above failed and i don't know reason. But using ScrollViewer to scroll to last one can work.</p>\n\n<pre><code>void FocusLastOne(ListView lsv)\n{\n ObservableCollection&lt;object&gt; items= sender as ObservableCollection&lt;object&gt;;\n\n Decorator d = VisualTreeHelper.GetChild(lsv, 0) as Decorator;\n ScrollViewer v = d.Child as ScrollViewer;\n v.ScrollToEnd();\n\n lsv.SelectedItem = lsv.Items.GetItemAt(items.Count - 1);\n ListViewItem lvi = lsv.ItemContainerGenerator.ContainerFromIndex(items.Count - 1) as ListViewItem;\n lvi.Focus();\n}\n</code></pre>\n" }, { "answer_id": 15293188, "author": "ygoe", "author_id": 143684, "author_profile": "https://Stackoverflow.com/users/143684", "pm_score": 0, "selected": false, "text": "<p>To overcome the virtualisation issue but still use <code>ScrollIntoView</code> and not hacking around in the guts of the ListView, you could also use your ViewModel objects to determine what is selected. Assuming that you have ViewModel objects in your list that feature an <code>IsSelected</code> property. You'd link the items to the ListView in XAML like this:</p>\n\n<pre><code>&lt;ListView Name=\"PersonsListView\" ItemsSource=\"{Binding PersonVMs}\"&gt;\n &lt;ListView.ItemContainerStyle&gt;\n &lt;Style TargetType=\"{x:Type ListViewItem}\"&gt;\n &lt;Setter Property=\"IsSelected\" Value=\"{Binding IsSelected, Mode=TwoWay}\" /&gt;\n &lt;/Style&gt;\n &lt;/ListView.ItemContainerStyle&gt;\n&lt;/ListView&gt;\n</code></pre>\n\n<p>Then, the code-behind method can scroll to the first selected item with this:</p>\n\n<pre><code>var firstSelected = PersonsListView.Items\n .OfType&lt;TreeViewItemViewModel&gt;().FirstOrDefault(x =&gt; x.IsSelected);\nif (firstSelected != null)\n CoObjectsListView.ScrollIntoView(firstSelected);\n</code></pre>\n\n<p>This also works if the selected item is well out of view. In my experiment, the <code>PersonsListView.SelectedItem</code> property was <code>null</code>, but of course your ViewModel <code>IsSelected</code> property is always there. Be sure to call this method after all binding and loading has completed (with the right <code>DispatcherPriority</code>).</p>\n\n<p>Using the <a href=\"http://www.codeproject.com/Articles/554677/View-control-from-a-ViewModel-with-ViewCommands\" rel=\"nofollow\">ViewCommand</a> pattern, your ViewModel code could look like this:</p>\n\n<pre><code>PersonVMs.ForEach(vm =&gt; vm.IsSelected = false);\nPersonVMs.Add(newPersonVM);\nnewPersonVM.IsSelected = true;\nViewCommandManager.InvokeLoaded(\"ScrollToSelectedPerson\");\n</code></pre>\n" }, { "answer_id": 28068770, "author": "Jeyavel", "author_id": 212809, "author_profile": "https://Stackoverflow.com/users/212809", "pm_score": 0, "selected": false, "text": "<p>In my project i need to display the selected index line from the listview to the user so i assigned the selected item to ListView control. This code will scroll the scrollbar and display the selected item.</p>\n\n<p>BooleanListView.ScrollIntoView(BooleanListView.SelectedItem);</p>\n\n<p>OR</p>\n\n<p>var listView = BooleanListView;\n listView.SelectedItem = listView.Items.GetItemAt(BooleanListView.SelectedIndex);\n listView.ScrollIntoView(listView.Items[0]);\n listView.ScrollIntoView(listView.SelectedItem);</p>\n" }, { "answer_id": 29080015, "author": "Jayson Ragasa", "author_id": 1102895, "author_profile": "https://Stackoverflow.com/users/1102895", "pm_score": 0, "selected": false, "text": "<p>not sure if this is the way to go but this currently works for me using WPF, MVVM Light, and .NET 3.5</p>\n\n<p>I added the SelectionChanged event for ListBox called \"<strong>lbPossibleError_SelectionChanged</strong>\"\n<img src=\"https://i.stack.imgur.com/I4Lkl.png\" alt=\"I added the SelectionChanged event for ListBox\"></p>\n\n<p>then behind this \"<strong>lbPossibleError_SelectionChanged</strong>\" event, here's the code\n<img src=\"https://i.stack.imgur.com/4AAs1.png\" alt=\"enter image description here\"></p>\n\n<p>works as it should for me.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/211971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
WPF, Browserlike app. I got one page containing a ListView. After calling a PageFunction I add a line to the ListView, and want to scroll the new line into view: ``` ListViewItem item = ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem; if (item != null) ScrollIntoView(item); ``` This works. As long as the new line is in view the line gets the focus like it should. Problem is, things don't work when the line is not visible. If the line is not visible, there is no ListViewItem for the line generated, so ItemContainerGenerator.ContainerFromIndex returns null. But without the item, how do I scroll the line into view? Is there any way to scroll to the last line (or anywhere) without needing an ListViewItem?
I think the problem here is that the ListViewItem is not created yet if the line is not visible. WPF creates the Visible on demand. So in this case you probably get `null` for the item, do you? (According to your comment, you do) I have found a [link on MSDN forums that suggest accessing the Scrollviewer directly](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/7c5812bd-482f-448c-bc67-02573e48d691) in order to scroll. To me the solution presented there looks very much like a hack, but you can decide for yourself. Here is the code snippet from the [link above](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/7c5812bd-482f-448c-bc67-02573e48d691): ``` VirtualizingStackPanel vsp = (VirtualizingStackPanel)typeof(ItemsControl).InvokeMember("_itemsHost", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic, null, _listView, null); double scrollHeight = vsp.ScrollOwner.ScrollableHeight; // itemIndex_ is index of the item which we want to show in the middle of the view double offset = scrollHeight * itemIndex_ / _listView.Items.Count; vsp.SetVerticalOffset(offset); ```
212,006
<p>I have a c++ header file containing a class. I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file: </p> <pre><code>// example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{ class TestClass{ public: void testMethod(); }; void TestClass::testMethod(){ // some code here... } } // end namespace test_ns #endif </code></pre> <p>If inside the same project I include this header from more than one cpp file, I get an error saying "<code>multiple definition of test_ns::TestClass::testMethod()</code>", while if I put the method definition inside the class body this does not happen:</p> <pre><code>// example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{ class TestClass{ public: void testMethod(){ // some code here... } }; } // end namespace test_ns #endif </code></pre> <p>Since the class is defined inside a namespace, shouldn't the two forms be equivalent? Why is the method considered to be defined twice in the first case?</p>
[ { "answer_id": 212019, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 5, "selected": false, "text": "<p>Inside the class body is considered to be inline by the compiler.\nIf you implement outside of body, but still in header, you have to mark the method as 'inline' explicitly.</p>\n\n<pre><code>namespace test_ns{\n\nclass TestClass{\npublic:\n inline void testMethod();\n};\n\nvoid TestClass::testMethod(){\n // some code here...\n}\n\n} // end namespace test_ns\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>For myself it often helps to solve these kinds of compile problems by realizing that the compiler does not see anything like a header file. Header files are preprocessed and the compiler just sees one huge file containing every line from every (recursively) included file. Normally the starting point for these recursive includes is a cpp source file that is being compiled. \nIn our company, even a modest looking cpp file can be presented to the compiler as a 300000 line monster. </p>\n\n<p>So when a method, that is not declared inline, is implemented in a header file, the compiler could end up seeing void TestClass::testMethod() {...} dozens of times in the preprocessed file. Now you can see that this does not make sense, same effect as you'd get when copy/pasting it multiple times in one source file.\nAnd even if you succeeded by only having it once in every compilation unit, by some form of conditional compilation ( e.g. using inclusion brackets ) the linker would still find this method's symbol to be in multiple compiled units ( object files ).</p>\n" }, { "answer_id": 212022, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 6, "selected": true, "text": "<p>These are not equivalent. The second example given has an implicit 'inline' modifier on the method and so the compiler will reconcile multiple definitions itself (most likely with internal linkage of the method if it isn't inlineable).</p>\n\n<p>The first example isn't inline and so if this header is included in multiple translation units then you will have multiple definitions and linker errors.</p>\n\n<p>Also, headers should really always be guarded to prevent multiple definition errors in the same translation unit. That should convert your header to:</p>\n\n<pre><code>#ifndef EXAMPLE_H\n#define EXAMPLE_H\n\n//define your class here\n\n#endif\n</code></pre>\n" }, { "answer_id": 212037, "author": "PW.", "author_id": 927, "author_profile": "https://Stackoverflow.com/users/927", "pm_score": 2, "selected": false, "text": "<p>Don't put a function/method definition in an header file unless they are inlined (by defining them directly in a class declaration or explicity specified by the inline keyword)</p>\n\n<p>header files are (mostly) for declaration (whatever you need to declare). Definitions allowed are the ones for constants and inlined functions/methods (and templates too). </p>\n" }, { "answer_id": 213107, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Your first code snippet is falling foul of C++'s \"One Definition Rule\" <a href=\"http://en.wikipedia.org/wiki/One_Definition_Rule\" rel=\"nofollow noreferrer\">- see here for a link to a Wikipedia article describing ODR.</a> You're actually falling foul of point #2 because every time the compiler includes the header file into a source file, you run into the risk of the compiler generating a globally visible definition of <code>test_ns::TestClass::testMethod()</code>. And of course by the time you get to link the code, the linker will have kittens because it will find the same symbol in multiple object files.</p>\n\n<p>The second snippet works because you've inlined the definition of the function, which means that even if the compiler doesn't generate any inline code for the function (say, you've got inlining turned off or the compiler decides the function is too big to inline), the code generated for the function definition will be visible in the translation unit only, as if you'd stuck it in an anonymous namespace. Hence you get multiple copies of the function in the generated object code that the linker may or may not optimize away depending on how smart it is.</p>\n\n<p>You could achieve a similar effect in your first code snippet by prefixing <code>TestClass::testMethod()</code> with <code>inline</code>.</p>\n" }, { "answer_id": 11502363, "author": "Mahendra", "author_id": 1528591, "author_profile": "https://Stackoverflow.com/users/1528591", "pm_score": -1, "selected": false, "text": "<pre><code>//Baseclass.h or .cpp\n\n#ifndef CDerivedclass\n#include \"Derivedclass.h\"\n#endif\n\nor\n//COthercls.h or .cpp\n\n#ifndef CCommonheadercls\n#include \"Commonheadercls.h\"\n#endif\n\nI think this suffice all instances.\n</code></pre>\n" }, { "answer_id": 30744937, "author": "sastanin", "author_id": 25450, "author_profile": "https://Stackoverflow.com/users/25450", "pm_score": 2, "selected": false, "text": "<p>Actually it is possible to have definitions in a single header file (without a separate .c/.cpp file) and still be able to use it from multiple source files.</p>\n\n<p>Consider this <code>foobar.h</code> header:</p>\n\n<pre><code>#ifndef FOOBAR_H\n#define FOOBAR_H\n\n/* write declarations normally */\nvoid foo();\nvoid bar();\n\n/* use conditional compilation to disable definitions when necessary */\n#ifndef ONLY_DECLARATIONS\nvoid foo() {\n /* your code goes here */\n}\nvoid bar() {\n /* your code goes here */\n}\n#endif /* ONLY_DECLARATIONS */\n#endif /* FOOBAR_H */\n</code></pre>\n\n<p>If you use this header in only one source file, include and use it normally.\nLike in <code>main.c</code>:</p>\n\n<pre><code>#include \"foobar.h\"\n\nint main(int argc, char *argv[]) {\n foo();\n}\n</code></pre>\n\n<p>If there're other source files in your project which require <code>foobar.h</code>, then <code>#define ONLY_DECLARATIONS</code> macro before including it.\nIn <code>use_bar.c</code> you may write:</p>\n\n<pre><code>#define ONLY_DECLARATIONS\n#include \"foobar.h\"\n\nvoid use_bar() {\n bar();\n}\n</code></pre>\n\n<p>After compilation use_bar.o and main.o can be linked together without errors, because only one of them (main.o) will have implementation of foo() and bar().</p>\n\n<p>That's slightly non-idiomatic, but it allows to keep definitions and declarations together in one file. I feel like it's a poor man's substitute for true <a href=\"http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2015/n4465.pdf\" rel=\"nofollow\">modules</a>.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15622/" ]
I have a c++ header file containing a class. I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file: ``` // example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{ class TestClass{ public: void testMethod(); }; void TestClass::testMethod(){ // some code here... } } // end namespace test_ns #endif ``` If inside the same project I include this header from more than one cpp file, I get an error saying "`multiple definition of test_ns::TestClass::testMethod()`", while if I put the method definition inside the class body this does not happen: ``` // example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{ class TestClass{ public: void testMethod(){ // some code here... } }; } // end namespace test_ns #endif ``` Since the class is defined inside a namespace, shouldn't the two forms be equivalent? Why is the method considered to be defined twice in the first case?
These are not equivalent. The second example given has an implicit 'inline' modifier on the method and so the compiler will reconcile multiple definitions itself (most likely with internal linkage of the method if it isn't inlineable). The first example isn't inline and so if this header is included in multiple translation units then you will have multiple definitions and linker errors. Also, headers should really always be guarded to prevent multiple definition errors in the same translation unit. That should convert your header to: ``` #ifndef EXAMPLE_H #define EXAMPLE_H //define your class here #endif ```
212,028
<p>I have a C# method which accepts a Predicate&lt;Foo&gt; and returns a list of matching items...</p> <pre><code>public static List&lt;Foo&gt; FindAll( Predicate&lt;Foo&gt; filter ) { ... } </code></pre> <p>The filter will often be one of a common set...</p> <pre><code>public static class FooPredicates { public static readonly Predicate&lt;Foo&gt; IsEligible = ( foo =&gt; ...) ... } </code></pre> <p>...but may be an anonymous delegate.</p> <p>I'd now like to have this method cache its results in the ASP.NET cache, so repeated calls with the same delegate just return the cached result. For this, I need to create a cache key from the delegate. Will Delegate.GetHashCode() produce sensible results for this purpose? Is there some other member of Delegate that I should look at? Would you do this another way entirely?</p>
[ { "answer_id": 212090, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Delegate equality looks at each invocation in the invocation list, testing for equality of method to be invoked, and target of method.</p>\n\n<p>The method is a simple piece of the cache key, but the target of the method (the instance to call it on - assuming an instance method) could be impossible to cache in a serializable way. In particular, for anonymous functions which capture state, it will be an instance of a nested class created to capture that state.</p>\n\n<p>If this is all in memory, just keeping the delegate itself as the hash key will be okay - although it may mean that some objects which clients would expect to be garbage collected hang around. If you need to serialize this to a database, it gets hairier.</p>\n\n<p>Could you make your method accept a cache key (e.g. a string) as well? (That's assuming an in memory cache is inadequate.)</p>\n" }, { "answer_id": 212098, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Unless you're sure Delegate's implementation of GetHashCode is deterministic and doesn't result in any collisions I wouldn't trust it.</p>\n\n<p>Here's two ideas. First, store the results of the delegates within a Predicate/List dictionary, using the predicate as the key, and then store the entire dictionary of results under a single key in the cache. Bad thing is that you lose all your cached results if the cache item is lost.</p>\n\n<p>An alternative would be to create an extension method for Predicate, GetKey(), that uses an object/string dictionary to store and retrieve all keys for all Predicates. You index into the dictionary with the delegate and return its key, creating one if you don't find it. This way you're assured that you are getting the correct key per delegate and there aren't any collisions. A naiive one would be type name + Guid.</p>\n" }, { "answer_id": 212154, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 3, "selected": true, "text": "<p>To perform your caching task, you can follow the other suggestions and create a Dictionary&lt;Predicate&lt;Foo>,List&lt;Foo>> (static for global, or member field otherwise) that caches the results. Before actually executing the Predicate&lt;Foo>, you would need to check if the result already exists in the dictionary.</p>\n\n<p>The general name for this deterministic function caching is called Memoization - and its awesome :)</p>\n\n<p>Ever since C# 3.0 added lambda's and the swag of Func/Action delegates, adding Memoization to C# is quite easy.</p>\n\n<p>Wes Dyer has a <a href=\"http://blogs.msdn.com/wesdyer/archive/2007/01/26/function-memoization.aspx\" rel=\"nofollow noreferrer\">great post</a> that brings the concept to C# with some great examples.</p>\n\n<p>If you want me to show you how to do this, let me know...otherwise, Wes' post should be adequate.</p>\n\n<p>In answer to your query about delegate hash codes. If two delegates are the same, d1.GetHashCode() should equal d2.GetHashCode(), but I'm not 100% about this. You can check this quickly by giving Memoization a go, and adding a WriteLine into your FindAll method. If this ends up not being true, another option is to use Linq.Expression&lt;Predicate&lt;Foo>> as a parameter. If the expressions are not closures, then expressions that do the same thing should be equal.</p>\n\n<p>Let me know how this goes, I'm interested to know the answer about delegate.Equals.</p>\n" }, { "answer_id": 214607, "author": "Samuel Kim", "author_id": 437435, "author_profile": "https://Stackoverflow.com/users/437435", "pm_score": 0, "selected": false, "text": "<p>The same instance of an object will always return the same hashcode (requirement of GetHashCode() in .Net). If your predicates are inside a static list and you are not redefining them each time, I can't see a problem in using them as keys.</p>\n" }, { "answer_id": 215035, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 2, "selected": false, "text": "<p>Keeping the cached results in a Dictionary&lt;Predicate&lt;Foo>,List&lt;Foo>> is awkward for me because I want the ASP.NET cache to handle expiry for me rather than caching all results forever, but it's otherwise a good solution. I think I'll end up going with Will's Dictionary&lt;Predicate&lt;Foo>,string> to cache a string that I can use in the ASP.NET cache key.</p>\n\n<p>Some initial tests suggest that delegate equality does the \"right thing\" as others have said, but Delegate.GetHashCode is pathologically unhelpful. Reflector reveals </p>\n\n<pre><code>public override int GetHashCode()\n{\n return base.GetType().GetHashCode();\n}\n</code></pre>\n\n<p>So any Predicate&lt;Foo> returns the same result.</p>\n\n<p>My remaining issue was how equality works for anonymous delegates. What does \"same method called on the same target\" mean then? It seems that as long as the delegate was defined in the same place, references are equal. Delegates with the same body defined in different places are not.</p>\n\n<pre><code>static Predicate&lt;int&gt; Test()\n{\n Predicate&lt;int&gt; test = delegate(int i) { return false; };\n return test;\n}\n\nstatic void Main()\n{\n Predicate&lt;int&gt; test1 = Test();\n Predicate&lt;int&gt; test2 = Test();\n Console.WriteLine(test1.Equals( test2 )); // True\n\n test1 = delegate(int i) { return false; };\n test2 = delegate(int i) { return false; };\n Console.WriteLine(test1.Equals( test2 )); // False\n}\n</code></pre>\n\n<p>This should be OK for my needs. Calls with the predefined predicates will be cached. Multiple calls to one method that calls FindAll with an anonymous method should get cached results. Two methods calling FindAll with apparently the same anonymous method won't share cached results, but this should be fairly rare.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25028/" ]
I have a C# method which accepts a Predicate<Foo> and returns a list of matching items... ``` public static List<Foo> FindAll( Predicate<Foo> filter ) { ... } ``` The filter will often be one of a common set... ``` public static class FooPredicates { public static readonly Predicate<Foo> IsEligible = ( foo => ...) ... } ``` ...but may be an anonymous delegate. I'd now like to have this method cache its results in the ASP.NET cache, so repeated calls with the same delegate just return the cached result. For this, I need to create a cache key from the delegate. Will Delegate.GetHashCode() produce sensible results for this purpose? Is there some other member of Delegate that I should look at? Would you do this another way entirely?
To perform your caching task, you can follow the other suggestions and create a Dictionary<Predicate<Foo>,List<Foo>> (static for global, or member field otherwise) that caches the results. Before actually executing the Predicate<Foo>, you would need to check if the result already exists in the dictionary. The general name for this deterministic function caching is called Memoization - and its awesome :) Ever since C# 3.0 added lambda's and the swag of Func/Action delegates, adding Memoization to C# is quite easy. Wes Dyer has a [great post](http://blogs.msdn.com/wesdyer/archive/2007/01/26/function-memoization.aspx) that brings the concept to C# with some great examples. If you want me to show you how to do this, let me know...otherwise, Wes' post should be adequate. In answer to your query about delegate hash codes. If two delegates are the same, d1.GetHashCode() should equal d2.GetHashCode(), but I'm not 100% about this. You can check this quickly by giving Memoization a go, and adding a WriteLine into your FindAll method. If this ends up not being true, another option is to use Linq.Expression<Predicate<Foo>> as a parameter. If the expressions are not closures, then expressions that do the same thing should be equal. Let me know how this goes, I'm interested to know the answer about delegate.Equals.
212,031
<p>I would like to break a long line of text assigned to the standard Label widget in GWT. I was experimenting with inline <code>&lt;br /&gt;</code> elements but with no success.</p> <p>Something like this: </p> <pre><code>label = "My very very very long&lt;br /&gt;long long text" </code></pre>
[ { "answer_id": 212571, "author": "jgindin", "author_id": 17941, "author_profile": "https://Stackoverflow.com/users/17941", "pm_score": 5, "selected": true, "text": "<p>You need to use the HTML widget, which extends the standard Label widget, and adds support for interpreting HTML tags.</p>\n\n<p>See the <a href=\"http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/client/ui/HTML.html\" rel=\"noreferrer\">JavaDoc</a>.</p>\n" }, { "answer_id": 286593, "author": "smerten", "author_id": 37288, "author_profile": "https://Stackoverflow.com/users/37288", "pm_score": 2, "selected": false, "text": "<p>I would use CSS to style the label to fit a given with and drop the <code>&lt;br/&gt;</code> all together.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6482/" ]
I would like to break a long line of text assigned to the standard Label widget in GWT. I was experimenting with inline `<br />` elements but with no success. Something like this: ``` label = "My very very very long<br />long long text" ```
You need to use the HTML widget, which extends the standard Label widget, and adds support for interpreting HTML tags. See the [JavaDoc](http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/client/ui/HTML.html).
212,048
<p>I'm using the ListView control (ASP.NET 2008) to show a bunch of lines of data, and at the bottom I want some totals. I was initially going to define the header and footer in the LayoutTemplate and get the totals with some local function, i.e. &lt;%#GetTheSum()%>, but it appears that the LayoutTemplate does not process the &lt;%#...%> syntax.</p> <p>Another thought would be to put a Label in the LayoutTemplate and use FindControl to update it. Not sure if that's possible (will try shortly).</p> <p>What's the best way to show totals using a ListView?</p> <p>UPDATE: Solution <a href="https://stackoverflow.com/questions/212048/displaying-totals-in-the-listview-layouttemplate#212308">here</a>.</p>
[ { "answer_id": 212126, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 1, "selected": false, "text": "<p>Use a literal and set the variable in the code-behind.</p>\n\n<pre><code>&lt;asp:Literal ID=\"litTotal\" runat=\"server\" /&gt;\n</code></pre>\n\n<p>code-behind:</p>\n\n<pre><code>litTotal.Text = GetTheSum();\n</code></pre>\n" }, { "answer_id": 212244, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 0, "selected": false, "text": "<p>You can't reference the control in the code-behind because it's in the LayoutTemplate. Maybe with FindControl, but I haven't tried that yet.</p>\n" }, { "answer_id": 212308, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 4, "selected": true, "text": "<p>It turns out that FindControl does work: </p>\n\n<pre><code>CType(MyListView.FindControl(\"litTotal\"), Literal).Text = GetTheSum()\n</code></pre>\n\n<p>I'd still like to know if there might be a better way though.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23935/" ]
I'm using the ListView control (ASP.NET 2008) to show a bunch of lines of data, and at the bottom I want some totals. I was initially going to define the header and footer in the LayoutTemplate and get the totals with some local function, i.e. <%#GetTheSum()%>, but it appears that the LayoutTemplate does not process the <%#...%> syntax. Another thought would be to put a Label in the LayoutTemplate and use FindControl to update it. Not sure if that's possible (will try shortly). What's the best way to show totals using a ListView? UPDATE: Solution [here](https://stackoverflow.com/questions/212048/displaying-totals-in-the-listview-layouttemplate#212308).
It turns out that FindControl does work: ``` CType(MyListView.FindControl("litTotal"), Literal).Text = GetTheSum() ``` I'd still like to know if there might be a better way though.
212,050
<p>In a spring configuration, what is the difference between using name vs id? I'm aware that XML restricts the "id" attribute to be unique in a document and limits the characters for using in the id. But otherwise when declaring a bean, what is the difference between using the "name" attribute vs the "id" attribute?</p>
[ { "answer_id": 212126, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 1, "selected": false, "text": "<p>Use a literal and set the variable in the code-behind.</p>\n\n<pre><code>&lt;asp:Literal ID=\"litTotal\" runat=\"server\" /&gt;\n</code></pre>\n\n<p>code-behind:</p>\n\n<pre><code>litTotal.Text = GetTheSum();\n</code></pre>\n" }, { "answer_id": 212244, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 0, "selected": false, "text": "<p>You can't reference the control in the code-behind because it's in the LayoutTemplate. Maybe with FindControl, but I haven't tried that yet.</p>\n" }, { "answer_id": 212308, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 4, "selected": true, "text": "<p>It turns out that FindControl does work: </p>\n\n<pre><code>CType(MyListView.FindControl(\"litTotal\"), Literal).Text = GetTheSum()\n</code></pre>\n\n<p>I'd still like to know if there might be a better way though.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580/" ]
In a spring configuration, what is the difference between using name vs id? I'm aware that XML restricts the "id" attribute to be unique in a document and limits the characters for using in the id. But otherwise when declaring a bean, what is the difference between using the "name" attribute vs the "id" attribute?
It turns out that FindControl does work: ``` CType(MyListView.FindControl("litTotal"), Literal).Text = GetTheSum() ``` I'd still like to know if there might be a better way though.
212,089
<p>This is the way I read file:</p> <pre><code> public static string readFile(string path) { StringBuilder stringFromFile = new StringBuilder(); StreamReader SR; string S; SR = File.OpenText(path); S = SR.ReadLine(); while (S != null) { stringFromFile.Append(SR.ReadLine()); } SR.Close(); return stringFromFile.ToString(); } </code></pre> <p>The problem is it so long (the .txt file is about 2.5 megs). Took over 5 minutes. Is there a better way?</p> <p><strong>Solution taken</strong></p> <pre><code> public static string readFile(string path) { return File.ReadAllText(path); } </code></pre> <p>Took less than 1 second... :)</p>
[ { "answer_id": 212094, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>Leaving aside the horrible variable names and the lack of a using statement (you won't close the file if there are any exceptions) that should be okay, and <em>certainly</em> shouldn't take 5 minutes to read 2.5 megs.</p>\n\n<p>Where does the file live? Is it on a flaky network share?</p>\n\n<p>By the way, the only difference between what you're doing and using File.ReadAllText is that you're losing line breaks. Is this deliberate? How long does ReadAllText take?</p>\n" }, { "answer_id": 212097, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 2, "selected": false, "text": "<p>Do you need the entire 2.5 Mb in memory at once?</p>\n\n<p>If not, I would try to work with what you need.</p>\n" }, { "answer_id": 212101, "author": "C. Broadbent", "author_id": 28859, "author_profile": "https://Stackoverflow.com/users/28859", "pm_score": 1, "selected": false, "text": "<p>Use System.IO.File.RealAllLines instead.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx</a></p>\n\n<p>Alternatively, estimating the character count and passing that to StringBuilder's constructor as the capacity should speed it up.</p>\n" }, { "answer_id": 212102, "author": "pian0", "author_id": 5692, "author_profile": "https://Stackoverflow.com/users/5692", "pm_score": 3, "selected": false, "text": "<pre><code>return System.IO.File.ReadAllText(path);\n</code></pre>\n" }, { "answer_id": 212104, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>Try this, should be much faster:</p>\n\n<pre><code>var str = System.IO.File.ReadAllText(path);\nreturn str.Replace(Environment.NewLine, \"\");\n</code></pre>\n" }, { "answer_id": 212105, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "<p>The loop and <code>StringBuilder</code> may be redundant; Try using \n<a href=\"http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx\" rel=\"nofollow noreferrer\">ReadToEnd</a>.</p>\n" }, { "answer_id": 212128, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 3, "selected": false, "text": "<pre><code>S = SR.ReadLine();\nwhile (S != null)\n{\n stringFromFile.Append(SR.ReadLine());\n}\n</code></pre>\n\n<p>Of note here, <code>S</code> is never set after that initial <code>ReadLine()</code>, so the <code>S != null</code> condition never triggers if you enter the while loop. Try:</p>\n\n<pre><code>S = SR.ReadLine();\nwhile (S != null)\n{\n stringFromFile.Append(S = SR.ReadLine());\n}\n</code></pre>\n\n<p>or use one of the other comments.</p>\n\n<p>If you need to remove newlines, use string.Replace(Environment.NewLine, \"\")</p>\n" }, { "answer_id": 212150, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": 2, "selected": false, "text": "<p>Marcus Griep has it right. IT's taking so long because YOU HAVE AN INFINITE LOOP. copied your code and made his changes and it read a 2.4 M text file in less than a second.</p>\n\n<p>but I think you might miss the first line of the file. Try this.</p>\n\n<pre><code>\nS = SR.ReadLine();\nwhile (S != null){\n stringFromFile.Append(S);\n S = SR.ReadLine();\n}\n</code>\n</pre>\n" }, { "answer_id": 212179, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>By the way: Next time you're in a similar situation, try pre-allocating memory. This improves runtime drastically, regardless of the exact data structures you use. Most containers (<code>StringBuilder</code> as well) have a constructor that allow you to reserve memory. This way, less time-consuming reallocations are necessary during the read process.</p>\n\n<p>For example, you could write the following if you want to read data from a file into a <code>StringBuilder</code>:</p>\n\n<pre><code>var info = new FileInfo(path);\nvar sb = new StringBuilder((int)info.Length);\n</code></pre>\n\n<p>(Cast necessary because <code>System.IO.FileInfo.Length</code> is <code>long</code>.)</p>\n" }, { "answer_id": 13722128, "author": "Salim", "author_id": 1306836, "author_profile": "https://Stackoverflow.com/users/1306836", "pm_score": 1, "selected": false, "text": "<p>ReadAllText was a very good solution for me. I used following code for 3.000.000 row text file and it took 4-5 seconds to read all rows.</p>\n\n<pre><code>string fileContent = System.IO.File.ReadAllText(txtFilePath.Text)\nstring[] arr = fileContent.Split('\\n');\n</code></pre>\n" }, { "answer_id": 37985301, "author": "Amit Kumawat", "author_id": 4140166, "author_profile": "https://Stackoverflow.com/users/4140166", "pm_score": -1, "selected": false, "text": "<p>To read a text file fastest you can use something like this</p>\n\n<pre><code>public static string ReadFileAndFetchStringInSingleLine(string file)\n {\n StringBuilder sb;\n try\n {\n sb = new StringBuilder();\n using (FileStream fs = File.Open(file, FileMode.Open))\n {\n using (BufferedStream bs = new BufferedStream(fs))\n {\n using (StreamReader sr = new StreamReader(bs))\n {\n string str;\n while ((str = sr.ReadLine()) != null)\n {\n sb.Append(str);\n }\n }\n }\n }\n return sb.ToString();\n }\n catch (Exception ex)\n {\n return \"\";\n }\n }\n</code></pre>\n\n<p>Hope this will help you. and for more info, please visit to the following link-\n<a href=\"http://cc.davelozinski.com/c-sharp/fastest-way-to-read-text-files\" rel=\"nofollow\">Fastest Way to Read Text Files</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
This is the way I read file: ``` public static string readFile(string path) { StringBuilder stringFromFile = new StringBuilder(); StreamReader SR; string S; SR = File.OpenText(path); S = SR.ReadLine(); while (S != null) { stringFromFile.Append(SR.ReadLine()); } SR.Close(); return stringFromFile.ToString(); } ``` The problem is it so long (the .txt file is about 2.5 megs). Took over 5 minutes. Is there a better way? **Solution taken** ``` public static string readFile(string path) { return File.ReadAllText(path); } ``` Took less than 1 second... :)
Leaving aside the horrible variable names and the lack of a using statement (you won't close the file if there are any exceptions) that should be okay, and *certainly* shouldn't take 5 minutes to read 2.5 megs. Where does the file live? Is it on a flaky network share? By the way, the only difference between what you're doing and using File.ReadAllText is that you're losing line breaks. Is this deliberate? How long does ReadAllText take?
212,115
<p>What is the best method for displaying major/minor versions in a C# console application?</p> <p>The <code>System.Windows.Forms</code> namespace includes a <code>ProductVersion</code> class that can be used to display the name/version information set via the Visual Studio project properties (Assembly Information). As such, here is my current mechanism:</p> <pre class="lang-cs prettyprint-override"><code>Console.WriteLine("{0} ({1})", System.Windows.Forms.Application.ProductName, System.Windows.Forms.Application.ProductVersion); </code></pre> <p>Why is this part of <code>Forms</code>? Is this appropriate for a Console application?</p>
[ { "answer_id": 212135, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<pre><code>Assembly.GetExecutingAssembly().GetName().Version\n</code></pre>\n\n<p>Also, you can still use the class, you just have to reference the containing assembly. It's no biggie.</p>\n" }, { "answer_id": 213083, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p><code>Assembly.GetExecutingAssembly().GetName().Version</code> is not the same as <code>Application.ProductVersion</code> (but may be good enough depending on your environment.</p>\n\n<p>As can be seen with Lutz Reflector, <code>Application.ProductVersion</code> first attempts to use the <strong>AssemblyInformationalVersion</strong> attribute from <code>Assembly.GetEntryAssembly()</code> if it's present, and if <code>GetEntryAssembly()</code> is not null.</p>\n\n<p>Otherwise it uses the file version of the executable file.</p>\n\n<p>I don't see any reason not to use <code>Application.ProductVersion</code> in a console application.</p>\n" }, { "answer_id": 68620594, "author": "tilli", "author_id": 2965054, "author_profile": "https://Stackoverflow.com/users/2965054", "pm_score": 0, "selected": false, "text": "<p>what about the following line</p>\n<pre><code>Console.WriteLine(&quot;FileVersionInfo::ProductVersion : {0}&quot;,\n System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.ProductVersion);\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644/" ]
What is the best method for displaying major/minor versions in a C# console application? The `System.Windows.Forms` namespace includes a `ProductVersion` class that can be used to display the name/version information set via the Visual Studio project properties (Assembly Information). As such, here is my current mechanism: ```cs Console.WriteLine("{0} ({1})", System.Windows.Forms.Application.ProductName, System.Windows.Forms.Application.ProductVersion); ``` Why is this part of `Forms`? Is this appropriate for a Console application?
``` Assembly.GetExecutingAssembly().GetName().Version ``` Also, you can still use the class, you just have to reference the containing assembly. It's no biggie.
212,124
<p>Some friends and colleagues of mine have a little running contest to find or write the longest class/variable/property/method names possible. Keep in mind, we try to be good boys and girls and keep the naming intelligible and concise, while still explaining what the thing does via its name.</p> <p>Sometimes it just doesn't happen though. Have you run in to this? I'd just like to see what's out there. (Maybe my friends and I aren't as crazy as we think)</p> <p>Note: I'm not looking for <strong>bad</strong> naming. That's already <a href="https://stackoverflow.com/questions/143701/what-is-the-worst-classvariablefunction-name-you-have-ever-encountered">here</a>. I'm looking for <strong>good</strong> naming that just got a little long.</p>
[ { "answer_id": 212132, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "<p>Check out Apple's documentation. They're kings at that. Very descriptive, but sometimes miles long. A couple of examples from the NSString class:</p>\n\n<pre><code>NSString.completePathInfoString:caseSensitive:matchesToArray:filterType\nNSString.stringByAddingPercentEscapesUsingEncoding\n</code></pre>\n\n<p>My favourite in the Microsoft world: <code>SetProcessWorkingSetSize</code></p>\n" }, { "answer_id": 212136, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>I find it's nice to have long test names which describe the test. For instance:</p>\n\n<pre><code>testMapWithOneEntryAllowsDifferentEntryPreservingFirst\ntestMapWithOneEntryAllowsDuplicateEntryOverwritingFirst\n</code></pre>\n\n<p>(These are just examples off the top of my head... you get the idea though.)</p>\n" }, { "answer_id": 212140, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 1, "selected": false, "text": "<p>In the apple mail app: </p>\n\n<pre><code>_synchronouslyTellServicesToRegisterAndSync()\n</code></pre>\n\n<p>In a app I wrote:</p>\n\n<pre><code>User.CanViewRestrictedItems()\n</code></pre>\n\n<p>I an app a colleague wrote:</p>\n\n<pre><code>Profile.DisplayMyDraftOrPendingProfile()\nProfile.DisplayMyApprovedProfile()\n</code></pre>\n\n<p>Just to get started.</p>\n\n<p><strong>new:</strong></p>\n\n<p>A foreign key constraint name: </p>\n\n<pre><code>constraint ReportCompanyReportTemplateIDVersionID_ReportTemplateVersionReportTemplateIDVersionIDFk foreign key (ReportTemplateID, VersionID) references customer_ReportTemplateVersion (ReportTemplateID, VersionID)\n</code></pre>\n" }, { "answer_id": 212178, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<pre><code>protected virtual OcrBarcodeSymbologies GetSupportedBarcodeSymbologies() { }\n</code></pre>\n" }, { "answer_id": 212241, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "<p>The excellent <a href=\"http://www.gtk.org/\" rel=\"nofollow noreferrer\">GTK+</a> library \"suffers\" from this. It has very neatly named functions, but since the main API is C, and GTK+ is very object-oriented, it must encode class names in the functions name. The constructor for class X is X_new(), and so on. This leads to beaties such as <a href=\"http://library.gnome.org/devel/gtk/stable/GtkRecentChooserWidget.html#gtk-recent-chooser-widget-new-for-manager\" rel=\"nofollow noreferrer\">gtk_recent_chooser_widget_new_for_manager()</a>.</p>\n\n<p>I'm sure there are even longer function names in there, this was just one that I found quickly. :)</p>\n" }, { "answer_id": 212584, "author": "denny", "author_id": 27, "author_profile": "https://Stackoverflow.com/users/27", "pm_score": 4, "selected": false, "text": "<p>It isn't really long but my favorite variable name ever was to indicate that a user had opted in to receive email.</p>\n\n<blockquote>\n <p>User.IsSpammable</p>\n</blockquote>\n" }, { "answer_id": 212619, "author": "Romain Linsolas", "author_id": 26457, "author_profile": "https://Stackoverflow.com/users/26457", "pm_score": 2, "selected": false, "text": "<p>Some times ago, I had a problem with Hibernate.\nI got a NullPointerException in the method called findIntendedAliasedFromElementBasedOnCrazyJPARequirements !</p>\n" }, { "answer_id": 238599, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "<p>Long variable names don't bother me as long as there's not an obvious more concise name and the naming is sane. For instance, in Kamaelia, there's a class type named this:</p>\n\n<pre><code>threadedadaptivecommscomponent\n</code></pre>\n" }, { "answer_id": 1194341, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 1, "selected": false, "text": "<p>A naming convention I've seen, years before fluent became en vogue</p>\n\n<pre><code>public DataSet SelectAllUsersWhereDobIsGreaterThan1980AndIsMaleOrderByNameAndAge()\n</code></pre>\n" }, { "answer_id": 2162485, "author": "Albert", "author_id": 261870, "author_profile": "https://Stackoverflow.com/users/261870", "pm_score": 3, "selected": false, "text": "<pre><code>org.aspectj.weaver.patterns;\n\npublic class HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor {\n boolean ohYesItHas = false;\n\n public boolean wellHasItThen/*?*/() {\n return ohYesItHas;\n }\n\n ... more methods...\n}\n</code></pre>\n" }, { "answer_id": 3670922, "author": "wsd", "author_id": 118096, "author_profile": "https://Stackoverflow.com/users/118096", "pm_score": 5, "selected": true, "text": "<p>This isn't a class name but an enum, but it's a lot longer:</p>\n\n<pre><code>VirtualMachineDeviceRuntimeInfoVirtualEthernetCardRuntimeStateVmDirectPathGen2InactiveReasonOther\n</code></pre>\n\n<p>from the VMware vSphere API. Google for it and you'll find the online documentation.</p>\n" }, { "answer_id": 9917455, "author": "Karel", "author_id": 1299512, "author_profile": "https://Stackoverflow.com/users/1299512", "pm_score": 1, "selected": false, "text": "<pre><code>bool instrumentAreaDockWidgetVisibilityFollowsChildPresence;\n</code></pre>\n" }, { "answer_id": 10245748, "author": "Kostas", "author_id": 1346461, "author_profile": "https://Stackoverflow.com/users/1346461", "pm_score": 0, "selected": false, "text": "<p>get the <code>js</code> items that will be retrieved and if page should display recommendations.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8360/" ]
Some friends and colleagues of mine have a little running contest to find or write the longest class/variable/property/method names possible. Keep in mind, we try to be good boys and girls and keep the naming intelligible and concise, while still explaining what the thing does via its name. Sometimes it just doesn't happen though. Have you run in to this? I'd just like to see what's out there. (Maybe my friends and I aren't as crazy as we think) Note: I'm not looking for **bad** naming. That's already [here](https://stackoverflow.com/questions/143701/what-is-the-worst-classvariablefunction-name-you-have-ever-encountered). I'm looking for **good** naming that just got a little long.
This isn't a class name but an enum, but it's a lot longer: ``` VirtualMachineDeviceRuntimeInfoVirtualEthernetCardRuntimeStateVmDirectPathGen2InactiveReasonOther ``` from the VMware vSphere API. Google for it and you'll find the online documentation.
212,125
<p>Let's say I have a model like this</p> <pre><code>class Foo(db.Model): id = db.StringProperty() bar = db.StringProperty() baz = db.StringProperty() </code></pre> <p>And I'm going a GqlQuery like this</p> <pre><code>foos = db.GqlQuery("SELECT * FROM Foo") </code></pre> <p><strong>I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages.</strong></p> <hr> <p>Here's how I'm doing it now</p> <ol> <li><p>Add a method to the <strong>Foo</strong> class that converts it into a dictionary</p> <pre><code>def toDict(self): return { 'id': self.id, 'bar': self.bar, 'baz': self'baz } </code></pre></li> <li><p>Loop through the GqlQuery results and manually add each Foo instance to a dictionary</p> <pre><code>fooDict = {} for foo in foos: fooDict[foo.id] = foo.toDict() return simplejson.dumps(fooDict) </code></pre></li> </ol> <hr> <p>My approach above works but it feels kind of gross.</p> <p>Is there a cleaner, more "Pythonic" way to handle this?</p> <p><strong>The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever.</strong></p>
[ { "answer_id": 212351, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": "<p>I can't do too much better than that, but here are a couple of ideas:</p>\n\n<pre><code>class Foo:\n id = db.StringProperty() # etc.\n json_attrs = 'id bar baz'.split()\n\n# Depending on how easy it is to identify string properties, there\n# might also be a way to assign json_attrs programmatically after the\n# definition of Foo, like this\nFoo.json_attrs = [attr for attr in dir(Foo)\n if isStringProperty(getattr(Foo, attr))]\n\nfooDict=dict((foo.id,dict(getattr(foo, attr)\n for attr in Foo.json_attrs))\n for foo in foos)\n</code></pre>\n" }, { "answer_id": 212682, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 3, "selected": true, "text": "<p>Take a look at <a href=\"http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/api/datastore.py\" rel=\"nofollow noreferrer\">google.appengine.api.datastore</a>. It's the lower level datastore API that google.appengine.ext.db builds on, and it returns Entity objects, which subclass dict. You can query it using GQL with <a href=\"http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/ext/gql/__init__.py\" rel=\"nofollow noreferrer\">google.appengine.ext.gql</a>, or (my personal preference) use the Query class, which avoids the need for you to construct text strings for the GQL parser to parse. The Query class in api.datastore behaves exactly like the one <a href=\"http://code.google.com/appengine/docs/datastore/queryclass.html\" rel=\"nofollow noreferrer\">documented here</a> (but returns the lower level Entity objects instead of Model instances).</p>\n\n<p>As an example, your query above can be reformulated as \"datastore.Query(\"Foo\").all()\".</p>\n" }, { "answer_id": 214766, "author": "JJ.", "author_id": 9106, "author_profile": "https://Stackoverflow.com/users/9106", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55\" rel=\"nofollow noreferrer\">http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55</a></p>\n\n<p>The encoder method will solve your GQL-to-JSON needs nicely. I'd recommend getting rid of some of the excessive datetime options....out time as an epoch? really?</p>\n" }, { "answer_id": 259334, "author": "massimo", "author_id": 24489, "author_profile": "https://Stackoverflow.com/users/24489", "pm_score": -1, "selected": false, "text": "<p>You can use web2py on GAE and do:</p>\n\n<pre><code>db.define_table('foo',SQLField('bar'),SQLField('baz'))\nrows=db(db.foo.id&gt;0).select()\n### rows is a list, rows.response is a list of tuples\nfor row in rows: print dict(row)\n</code></pre>\n\n<p>Runs on Oracle, Postgresql, Mssql, mysql, etc... too.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
Let's say I have a model like this ``` class Foo(db.Model): id = db.StringProperty() bar = db.StringProperty() baz = db.StringProperty() ``` And I'm going a GqlQuery like this ``` foos = db.GqlQuery("SELECT * FROM Foo") ``` **I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages.** --- Here's how I'm doing it now 1. Add a method to the **Foo** class that converts it into a dictionary ``` def toDict(self): return { 'id': self.id, 'bar': self.bar, 'baz': self'baz } ``` 2. Loop through the GqlQuery results and manually add each Foo instance to a dictionary ``` fooDict = {} for foo in foos: fooDict[foo.id] = foo.toDict() return simplejson.dumps(fooDict) ``` --- My approach above works but it feels kind of gross. Is there a cleaner, more "Pythonic" way to handle this? **The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever.**
Take a look at [google.appengine.api.datastore](http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/api/datastore.py). It's the lower level datastore API that google.appengine.ext.db builds on, and it returns Entity objects, which subclass dict. You can query it using GQL with [google.appengine.ext.gql](http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/ext/gql/__init__.py), or (my personal preference) use the Query class, which avoids the need for you to construct text strings for the GQL parser to parse. The Query class in api.datastore behaves exactly like the one [documented here](http://code.google.com/appengine/docs/datastore/queryclass.html) (but returns the lower level Entity objects instead of Model instances). As an example, your query above can be reformulated as "datastore.Query("Foo").all()".
212,155
<p>I'm encountering a strange memory read/write error while calling a compiled DLL from C#. I use DllImport to get a handle to the function we need, which writes a return value to a parametric pointer to an int (i.e., int* out). This function is called multiple times within a thread, and runs successfully over the execution life of the first thread. However, if one launches another thread after the first has completed, the call to the external dll throws an AccessViolationException. Since the multiple calls from the first thread execute successfully, I'm thinking this is somehow related to the first thread not releasing the pointers to the relevant integer parameters(?). If so, how can I explicitly release that memory? Or, perhaps someone has a different insight into what might be going on here? Thank you very much.</p> <p>EDIT: Danny has requested more specifics, and I'm happy to oblige. Here is where the external routine is invoked:</p> <pre><code> int success = -1; unsafe { int res = 0; int* res_ptr = &amp;res; int len = cmd.ToCharArray().Length; int* len_ptr = &amp;len; CmdInterpreter(ref cmd, len_ptr, res_ptr); success = *res_ptr; } </code></pre> <p>Where CmdInterpreter is defined as:</p> <pre><code> [DllImport("brugs.dll", EntryPoint="CmdInterpreter", ExactSpelling=false, CallingConvention = CallingConvention.StdCall)] public static unsafe extern void CmdInterpreter(ref string cmd, int *len, int *res); </code></pre> <p>Please let me know if there is any additional info that would be helpful. Thank you!</p>
[ { "answer_id": 212200, "author": "GregUzelac", "author_id": 27068, "author_profile": "https://Stackoverflow.com/users/27068", "pm_score": 0, "selected": false, "text": "<p>It may be the [DllImport]. If you post the [DllImport] signature, and the DLL's ptototype, maybe we can spot a problem.</p>\n\n<p>I read that the Managed, Native, and COM Interop Team released the PInvoke Interop Assistant on CodePlex. <a href=\"http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120\" rel=\"nofollow noreferrer\">http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120</a></p>\n" }, { "answer_id": 214312, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 1, "selected": false, "text": "<p>Given that the problem only occurs when multiple threads are involved, it may be that the command interpreter DLL is using some sort of thread-local storage and doing it incorrectly. It could also have to do with the COM initialization state of the second thread (the one that generates the error).</p>\n\n<p>It would be interesting to know what happens if you launch your new thread and have it call into the DLL <em>before</em> making any calls into the DLL on your first/main thread. If it works, that might support the thread-local storage theory. If it fails, that would support the COM state theory.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm encountering a strange memory read/write error while calling a compiled DLL from C#. I use DllImport to get a handle to the function we need, which writes a return value to a parametric pointer to an int (i.e., int\* out). This function is called multiple times within a thread, and runs successfully over the execution life of the first thread. However, if one launches another thread after the first has completed, the call to the external dll throws an AccessViolationException. Since the multiple calls from the first thread execute successfully, I'm thinking this is somehow related to the first thread not releasing the pointers to the relevant integer parameters(?). If so, how can I explicitly release that memory? Or, perhaps someone has a different insight into what might be going on here? Thank you very much. EDIT: Danny has requested more specifics, and I'm happy to oblige. Here is where the external routine is invoked: ``` int success = -1; unsafe { int res = 0; int* res_ptr = &res; int len = cmd.ToCharArray().Length; int* len_ptr = &len; CmdInterpreter(ref cmd, len_ptr, res_ptr); success = *res_ptr; } ``` Where CmdInterpreter is defined as: ``` [DllImport("brugs.dll", EntryPoint="CmdInterpreter", ExactSpelling=false, CallingConvention = CallingConvention.StdCall)] public static unsafe extern void CmdInterpreter(ref string cmd, int *len, int *res); ``` Please let me know if there is any additional info that would be helpful. Thank you!
Given that the problem only occurs when multiple threads are involved, it may be that the command interpreter DLL is using some sort of thread-local storage and doing it incorrectly. It could also have to do with the COM initialization state of the second thread (the one that generates the error). It would be interesting to know what happens if you launch your new thread and have it call into the DLL *before* making any calls into the DLL on your first/main thread. If it works, that might support the thread-local storage theory. If it fails, that would support the COM state theory.
212,198
<p>What is the purpose of the <code>Using</code> block in C#? How is it different from a local variable?</p>
[ { "answer_id": 212204, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 7, "selected": false, "text": "<p><code>Using</code> calls <code>Dispose()</code> after the <code>using</code>-block is left, even if the code throws an exception.</p>\n\n<p>So you usually use <code>using</code> for classes that require cleaning up after them, like IO.</p>\n\n<p>So, this using block:</p>\n\n<pre><code>using (MyClass mine = new MyClass())\n{\n mine.Action();\n}\n</code></pre>\n\n<p>would do the same as:</p>\n\n<pre><code>MyClass mine = new MyClass();\ntry\n{\n mine.Action();\n}\nfinally\n{\n if (mine != null)\n mine.Dispose();\n}\n</code></pre>\n\n<p>Using <code>using</code> is way shorter and easier to read.</p>\n" }, { "answer_id": 212206, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": false, "text": "<p>Placing code in a using block ensures that the objects are disposed (though not necessarily collected) as soon as control leaves the block.</p>\n" }, { "answer_id": 212210, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 10, "selected": true, "text": "<p>If the type implements IDisposable, it automatically disposes that type.</p>\n<p>Given:</p>\n<pre><code>public class SomeDisposableType : IDisposable\n{\n ...implmentation details...\n}\n</code></pre>\n<p>These are equivalent:</p>\n<pre><code>SomeDisposableType t = new SomeDisposableType();\ntry {\n OperateOnType(t);\n}\nfinally {\n if (t != null) {\n ((IDisposable)t).Dispose();\n }\n}\n</code></pre>\n \n<pre><code>using (SomeDisposableType u = new SomeDisposableType()) {\n OperateOnType(u);\n}\n</code></pre>\n<p>The second is easier to read and maintain.</p>\n<hr />\n<p>Since C# 8 there is a <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations\" rel=\"noreferrer\">new syntax for <code>using</code></a> that may make for more readable code:</p>\n<pre><code>using var x = new SomeDisposableType();\n</code></pre>\n<p>It doesn't have a <code>{ }</code> block of its own and the scope of the using is from the point of declaration to the end of the block it is declared in. It means you can avoid stuff like:</p>\n<pre><code>string x = null;\nusing(var someReader = ...)\n{\n x = someReader.Read();\n}\n</code></pre>\n<p>And have this:</p>\n<pre><code>using var someReader = ...;\nstring x = someReader.Read();\n</code></pre>\n" }, { "answer_id": 212222, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 6, "selected": false, "text": "<p>From MSDN:</p>\n\n<blockquote>\n <p>C#, through the .NET Framework common\n language runtime (CLR), automatically\n releases the memory used to store\n objects that are no longer required.\n The release of memory is\n non-deterministic; memory is released\n whenever the CLR decides to perform\n garbage collection. However, it is\n usually best to release limited\n resources such as file handles and\n network connections as quickly as\n possible. </p>\n \n <p>The using statement allows the\n programmer to specify when objects\n that use resources should release\n them. The object provided to the using\n statement must implement the\n IDisposable interface. This interface\n provides the Dispose method, which\n should release the object's resources.</p>\n</blockquote>\n\n<p>In other words, the <code>using</code> statement tells .NET to release the object specified in the <code>using</code> block once it is no longer needed.</p>\n" }, { "answer_id": 212223, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 2, "selected": false, "text": "<p>It is really just some syntatic sugar that does not require you to explicity call Dispose on members that implement IDisposable.</p>\n" }, { "answer_id": 212227, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 3, "selected": false, "text": "<pre><code>using (B a = new B())\n{\n DoSomethingWith(a);\n}\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>B a = new B();\ntry\n{\n DoSomethingWith(a);\n}\nfinally\n{\n ((IDisposable)a).Dispose();\n}\n</code></pre>\n" }, { "answer_id": 1518541, "author": "Meera Tolia", "author_id": 184185, "author_profile": "https://Stackoverflow.com/users/184185", "pm_score": 2, "selected": false, "text": "<p>The using statement obtains one or more resources, executes a statement, and then disposes of the resource. </p>\n" }, { "answer_id": 8844163, "author": "Sunquick", "author_id": 1120346, "author_profile": "https://Stackoverflow.com/users/1120346", "pm_score": 5, "selected": false, "text": "<p>The using statement is used to work with an object in C# that implements the <code>IDisposable</code> interface. </p>\n\n<p>The <code>IDisposable</code> interface has one public method called <code>Dispose</code> that is used to dispose of the object. When we use the using statement, we don't need to explicitly dispose of the object in the code, the using statement takes care of it.</p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection())\n{\n\n}\n</code></pre>\n\n<p>When we use the above block, internally the code is generated like this:</p>\n\n<pre><code>SqlConnection conn = new SqlConnection() \ntry\n{\n\n}\nfinally\n{\n // calls the dispose method of the conn object\n}\n</code></pre>\n\n<p>For more details read: <a href=\"http://www.codeproject.com/KB/cs/tinguusingstatement.aspx\" rel=\"noreferrer\">Understanding the 'using' statement in C#</a>.</p>\n" }, { "answer_id": 23912032, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Also take note that the object instantiated via <code>using</code> is read-only within the using block. Refer to the official C# reference <a href=\"http://msdn.microsoft.com/en-us//library/yh598w02.aspx\" rel=\"noreferrer\">here</a>.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17715/" ]
What is the purpose of the `Using` block in C#? How is it different from a local variable?
If the type implements IDisposable, it automatically disposes that type. Given: ``` public class SomeDisposableType : IDisposable { ...implmentation details... } ``` These are equivalent: ``` SomeDisposableType t = new SomeDisposableType(); try { OperateOnType(t); } finally { if (t != null) { ((IDisposable)t).Dispose(); } } ``` ``` using (SomeDisposableType u = new SomeDisposableType()) { OperateOnType(u); } ``` The second is easier to read and maintain. --- Since C# 8 there is a [new syntax for `using`](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations) that may make for more readable code: ``` using var x = new SomeDisposableType(); ``` It doesn't have a `{ }` block of its own and the scope of the using is from the point of declaration to the end of the block it is declared in. It means you can avoid stuff like: ``` string x = null; using(var someReader = ...) { x = someReader.Read(); } ``` And have this: ``` using var someReader = ...; string x = someReader.Read(); ```
212,201
<p>A little benchmark with ASP.NET MVC. Viewpage code:</p> <pre><code> public string Bechmark(Func&lt;string&gt; url) { var s = new Stopwatch(); var n = 1000; s.Reset(); s.Start(); for (int i = 0; i &lt; n; i++) { var u = url(); } s.Stop(); return s.ElapsedMilliseconds + &quot; ms, &quot; + ((s.ElapsedMilliseconds) / (float)n) + &quot; ms per link&lt;br/&gt;&quot;; } </code></pre> <p>View code:</p> <pre><code>&lt;%= Bechmark(() =&gt; Url.Action(&quot;Login&quot;, &quot;Account&quot;)) %&gt; &lt;%= Bechmark(() =&gt; Url.Action(&quot;Login&quot;, &quot;Account&quot;, new {username=&quot;bla&quot;, password=&quot;bla2&quot;, returnurl=&quot;blabla32&quot;, rememberme=false} )) %&gt; &lt;%= Bechmark(() =&gt; Html.BuildUrlFromExpression&lt;AccountController&gt;(a=&gt;a.ChangePassword(&quot;bla&quot;, &quot;bla&quot;, &quot;ya&quot;)) ) %&gt; </code></pre> <p>Running this on a typical Core2 notebook on the default new project template with ASP.NET MVC Beta yields these results:</p> <blockquote> <p>38 ms, 0,038 ms per link</p> <p>120 ms, 0,12 ms per link</p> <p>54 ms, 0,054 ms per link</p> </blockquote> <p>Running the same benchmark on a production project with about 10 controllers that have all in all around 100 methods and 30 routing table entries, the performance degrades greatly for the expression-based method:</p> <blockquote> <p>31 ms, 0,031 ms per link</p> <p>112 ms, 0,112 ms per link</p> <p>450 ms, 0,45 ms per link</p> </blockquote> <p>We use this method quite a lot (maintainability) and doing some performance benchmarking, this degrades the performance of the site greatly - pages quickly contain around 30 or more of such links, that means 10ms of additional overhead on a single page. Even 0.112ms per an URL is around 4ms of pure CPU overhead.</p> <p>It should be noted that performance of all the three URL generation calls between MVC Preview 3 and Beta (released yesterday) got improved by a factor of 5.</p> <p>Stack Overflow is supposedly powered by the same framework, how have you guys tackled this scaling problem? Liberal caching of the front page (lots of links) and pre-rendered controls?</p> <p>Any other production websites in ASP.NET MVC with performance issues or some good tips?</p>
[ { "answer_id": 212243, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>Caching links would probably be a good suggestion for the team, as they won't change for the life of the process (for most apps anyway).</p>\n\n<p>Until you start defining your routes in a configurable form (such as web.config or in a database) then you'd have to scale back a bit.</p>\n\n<p>I suspect that a big portion of the delay on the middle example is the anonymous type that gets automatically converted to a dictionary. Caching the URL wouldn't help here b/c you'd still need to reflect that type.</p>\n\n<p>In the meantime, you can create your own helper methods for some of those dictionary-based links that take the exact input you require. Then you can handle the caching yourself.</p>\n" }, { "answer_id": 212327, "author": "rudib", "author_id": 28917, "author_profile": "https://Stackoverflow.com/users/28917", "pm_score": 1, "selected": false, "text": "<p>Ok, two additional metrics on the blank template project:</p>\n\n<pre><code>&lt;%= Bechmark(() =&gt; Url.Action(\"Login\", \"Account\", new Dictionary&lt;string, object&gt; {{\"username\", \"bla\"}, {\"password\", \"bla2\"}, {\"returnurl\", \"blabla32\"}, {\"rememberme\", \"false\"}})) %&gt;\n\n&lt;%= Bechmark(() =&gt; Url.Action(\"Login\", \"Account\", new RouteValueDictionary(new Dictionary&lt;string, object&gt; {{\"username\", \"bla\"}, {\"password\", \"bla2\"}, {\"returnurl\", \"blabla32\"}, {\"rememberme\", \"false\"}}))) %&gt;\n</code></pre>\n\n<p>Results:</p>\n\n<blockquote>\n <p>71 ms, 0,071 ms per link</p>\n \n <p>35 ms, 0,035 ms per link</p>\n</blockquote>\n\n<p>Much better performance with way nastier code. Too bad.</p>\n" }, { "answer_id": 213120, "author": "bashmohandes", "author_id": 28120, "author_profile": "https://Stackoverflow.com/users/28120", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Caching links would probably be a good\n suggestion for the team, as they won't\n change for the life of the process\n (for most apps anyway).</p>\n</blockquote>\n\n<p>How can you cache links, you can't do that as far as I know, because you need to cache the method that gets executed, which happens after the route gets resolved, which is the slow part.</p>\n" }, { "answer_id": 216456, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 2, "selected": false, "text": "<p>I asked this question on the MS forums, which got an answer from an MS MVC developer.</p>\n<p><a href=\"http://forums.asp.net/t/1335585.aspx\" rel=\"nofollow noreferrer\">The post</a></p>\n<p><strong>The answer</strong></p>\n<blockquote>\n<p>From MVC Preview 2 to the recently released MVC Beta from yesterday there have been a lot of changes to Routing. Some of those changes include performance improvements. Here are some tricks to make URL generation more performant in your application:</p>\n<ol>\n<li><p>Use named routes. Named routes are an optional feature of routing. The names only apply to URL generation - they are never used for matching incoming URLs. When you specify a name when generating a URL we will only try to match that one route. This means that even if the named route you specified is the 100th route in the route table we'll jump straight to it and try to match.</p>\n</li>\n<li><p>Put your most common routes at the beginning of the route table. This will improve performance of both URL generation as well as processing incoming URLs. Routing works based on the rule that the first match wins. If the first match is the 100th route in your route table, then that means it had to try 99 other routes and none of them matched.</p>\n</li>\n<li><p>Don't use URL generation. Some people like it, some people don't. It's a bit tricky to master. It's nice to use if your URLs are very dynamic but it can be a bit of a hassle when you have very few URLs to begin with and perhaps you don't care about exactly what they look like.</p>\n</li>\n</ol>\n<p>My favorite option is #1 since it's super easy to use and it also makes URL generation more deterministic from the app developer's perspective (that's you!).</p>\n</blockquote>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28917/" ]
A little benchmark with ASP.NET MVC. Viewpage code: ``` public string Bechmark(Func<string> url) { var s = new Stopwatch(); var n = 1000; s.Reset(); s.Start(); for (int i = 0; i < n; i++) { var u = url(); } s.Stop(); return s.ElapsedMilliseconds + " ms, " + ((s.ElapsedMilliseconds) / (float)n) + " ms per link<br/>"; } ``` View code: ``` <%= Bechmark(() => Url.Action("Login", "Account")) %> <%= Bechmark(() => Url.Action("Login", "Account", new {username="bla", password="bla2", returnurl="blabla32", rememberme=false} )) %> <%= Bechmark(() => Html.BuildUrlFromExpression<AccountController>(a=>a.ChangePassword("bla", "bla", "ya")) ) %> ``` Running this on a typical Core2 notebook on the default new project template with ASP.NET MVC Beta yields these results: > > 38 ms, 0,038 ms per link > > > 120 ms, 0,12 ms per link > > > 54 ms, 0,054 ms per link > > > Running the same benchmark on a production project with about 10 controllers that have all in all around 100 methods and 30 routing table entries, the performance degrades greatly for the expression-based method: > > 31 ms, 0,031 ms per link > > > 112 ms, 0,112 ms per link > > > 450 ms, 0,45 ms per link > > > We use this method quite a lot (maintainability) and doing some performance benchmarking, this degrades the performance of the site greatly - pages quickly contain around 30 or more of such links, that means 10ms of additional overhead on a single page. Even 0.112ms per an URL is around 4ms of pure CPU overhead. It should be noted that performance of all the three URL generation calls between MVC Preview 3 and Beta (released yesterday) got improved by a factor of 5. Stack Overflow is supposedly powered by the same framework, how have you guys tackled this scaling problem? Liberal caching of the front page (lots of links) and pre-rendered controls? Any other production websites in ASP.NET MVC with performance issues or some good tips?
I asked this question on the MS forums, which got an answer from an MS MVC developer. [The post](http://forums.asp.net/t/1335585.aspx) **The answer** > > From MVC Preview 2 to the recently released MVC Beta from yesterday there have been a lot of changes to Routing. Some of those changes include performance improvements. Here are some tricks to make URL generation more performant in your application: > > > 1. Use named routes. Named routes are an optional feature of routing. The names only apply to URL generation - they are never used for matching incoming URLs. When you specify a name when generating a URL we will only try to match that one route. This means that even if the named route you specified is the 100th route in the route table we'll jump straight to it and try to match. > 2. Put your most common routes at the beginning of the route table. This will improve performance of both URL generation as well as processing incoming URLs. Routing works based on the rule that the first match wins. If the first match is the 100th route in your route table, then that means it had to try 99 other routes and none of them matched. > 3. Don't use URL generation. Some people like it, some people don't. It's a bit tricky to master. It's nice to use if your URLs are very dynamic but it can be a bit of a hassle when you have very few URLs to begin with and perhaps you don't care about exactly what they look like. > > > My favorite option is #1 since it's super easy to use and it also makes URL generation more deterministic from the app developer's perspective (that's you!). > > >
212,215
<p>I'm trying to display a loading icon while my iPhone app downloads a network resource, but I can't figure out how to make it show up correctly.</p> <p>I searched around and found some details on the <code>UIActivityView</code> class, but the available example source code didn't work, and the documentation is kind of terse.</p> <p>Could someone provide a simple example on how to use this class?</p>
[ { "answer_id": 212564, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 5, "selected": true, "text": "<p>Assuming you've got a view controller set up, and would like to add a <code>UIActivityIndicator</code> to it, here's how you could do it:</p>\n\n<p>(assume you've got a member variable called <code>indicator</code>, which you can use later to clean up)</p>\n\n<p><strong>For your interface (.h file):</strong></p>\n\n<pre><code>UIActivityIndicator *indicator;\n</code></pre>\n\n<p><strong>For your implementation (.m file):</strong></p>\n\n<p><strong>Start the Animation</strong></p>\n\n<pre><code>CGRect b = self.view.bounds;\nindicator = [[UIActivityIndicator alloc] initWithActivityIndicatorStyle: \n UIActivityIndicatorStyleWhite];\n//center the indicator in the view\nindicator.frame = CGRectMake((b.size.width - 20) / 2, (b.size.height - 20) / 2, 20, 20); \n[self.view addSubview: indicator];\n[indicator release];\n[indicator startAnimating];\n</code></pre>\n\n<p><strong>Stop the Animation</strong></p>\n\n<pre><code>[indicator removeFromSuperview];\nindicator = nil;\n</code></pre>\n" }, { "answer_id": 213243, "author": "Jablair", "author_id": 24168, "author_profile": "https://Stackoverflow.com/users/24168", "pm_score": 0, "selected": false, "text": "<p>Ben answer looks pretty similar to what I'm doing - your guess about the thread is probably accurate. Are you using <code>NSURLConnection</code> to handle your downloading? If so, are you using the synchronous or asynchronous version? If it's the synchronous version and you're simply starting and stopping the animation around the synchronous call, then the UI isn't updating until after the you've stopped the animation.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to display a loading icon while my iPhone app downloads a network resource, but I can't figure out how to make it show up correctly. I searched around and found some details on the `UIActivityView` class, but the available example source code didn't work, and the documentation is kind of terse. Could someone provide a simple example on how to use this class?
Assuming you've got a view controller set up, and would like to add a `UIActivityIndicator` to it, here's how you could do it: (assume you've got a member variable called `indicator`, which you can use later to clean up) **For your interface (.h file):** ``` UIActivityIndicator *indicator; ``` **For your implementation (.m file):** **Start the Animation** ``` CGRect b = self.view.bounds; indicator = [[UIActivityIndicator alloc] initWithActivityIndicatorStyle: UIActivityIndicatorStyleWhite]; //center the indicator in the view indicator.frame = CGRectMake((b.size.width - 20) / 2, (b.size.height - 20) / 2, 20, 20); [self.view addSubview: indicator]; [indicator release]; [indicator startAnimating]; ``` **Stop the Animation** ``` [indicator removeFromSuperview]; indicator = nil; ```
212,228
<p>I have read the GOLD Homepage ( <a href="http://www.devincook.com/goldparser/" rel="nofollow noreferrer">http://www.devincook.com/goldparser/</a> ) docs, FAQ and Wikipedia to find out what practical application there could possibly be for GOLD. I was thinking along the lines of having a programming language (easily) available to my systems such as ABAP on SAP or X++ on Axapta - but it doesn't look feasible to me, at least not easily - even if you use GOLD.</p> <p>The final use of the parsed result produced by GOLD escapes me - what do you do with the result of the parse?</p> <p>EDIT: A practical example (description) would be great.</p>
[ { "answer_id": 212251, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 1, "selected": false, "text": "<p>GOLD can be used for any kind of application where you have to apply context-free grammars to input.</p>\n\n<p>elaboration:</p>\n\n<p>Essentially, CFGs apply to all programming languages. So if you wanted to develop a scripting language for your company, you'd need to write a parser- or get a parsing program. Alternatively, if you wanted to have a semi-natural language for input for non-programmers in the company, you could use a parser to read that input and spit out more \"machine-readable\" data. Essentially, a context-free grammar allows you to describe far more inputs than a regular expression. The GOLD system apparently makes the parsing problem somewhat easier than lex/yacc(the UNIX standard programs for parsing).</p>\n" }, { "answer_id": 212314, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "<p>I would recommend antlr.org for information and the 'free' tool I would use for any parser use. </p>\n" }, { "answer_id": 212529, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 4, "selected": true, "text": "<p>Parsing really consists of two phases. The first is \"lexing\", which convert the raw strings of character in to something that the program can more readily understand (commonly called tokens).</p>\n\n<p>Simple example, lex would convert:</p>\n\n<p>if (a + b > 2) then</p>\n\n<p>In to: </p>\n\n<pre>\nIF_TOKEN LEFT_PAREN IDENTIFIER(a) PLUS_SIGN IDENTIFIER(b) GREATER_THAN NUMBER(2) RIGHT_PAREN THEN_TOKEN\n</pre>\n\n<p>The parse takes that stream of tokens, and attempts to make yet more sense out of them. In this case, it would try and match up those tokens to an IF_STATEMENT. To the parse, the IF _STATEMENT may well look like this:</p>\n\n<pre> IF ( BOOLEAN_EXPRESSION ) THEN </pre>\n\n<p>Where the result of the lexing phase is a token stream, the result of the parsing phase is a Parse Tree.</p>\n\n<p>So, a parser could convert the above in to:</p>\n\n<pre>\n if_statement\n |\n v\n boolean_expression.operator = GREATER_THAN\n | |\n | v\n V numeric_constant.string=\"2\" \n expression.operator = PLUS_SIGN\n | |\n | v\n v identifier.string = \"b\"\n identifier.string = \"a\"\n</pre>\n\n<p>Here you see we have an IF_STATEMENT. An IF_STATEMENT has a single argument, which is a BOOLEAN_EXPRESSION. This was explained in some manner to the parser. When the parser is converting the token stream, it \"knows\" what a IF looks like, and know what a BOOLEAN_EXPRESSION looks like, so it can make the proper assignments when it sees the code.</p>\n\n<p>For example, if you have just:</p>\n\n<p>if (a + b) then</p>\n\n<p>The parser could know that it's not a boolean expression (because the + is arithmetic, not a boolean operator) and the parse could throw an error at this point.</p>\n\n<p>Next, we see that a BOOLEAN_EXPRESSION has 3 components, the operator (GREATER_THAN), and two sides, the left side and the right side.</p>\n\n<p>On the left side, it points to yet another expression, the \"a + b\", while on the right is points to a NUMERIC_CONSTANT, in this case the string \"2\". Again, the parser \"knows\" this is a NUMERIC constant because we told it about strings of numbers. If it wasn't numbers, it would be an IDENTIFIER (like \"a\" and \"b\" are).</p>\n\n<p>Note, that if we had something like:</p>\n\n<p>if (a + b > \"XYZ\") then</p>\n\n<p>That \"parses\" just fine (expression on the left, string constant on the right). We don't know from looking at this whether this is a valid expression or not. We don't know if \"a\" or \"b\" reference Strings or Numbers at this point. So, this is something the parser can't decided for us, can't flag as an error, as it simply doesn't know. That will happen when we evaluate (either execute or try to compile in to code) the IF statement.</p>\n\n<p>If we did:</p>\n\n<p>if [a > b ) then</p>\n\n<p>The parser can readily see that syntax error as a problem, and will throw an error. That string of tokens doesn't look like anything it knows about.</p>\n\n<p>So, the point being that when you get a complete parse tree, you have some assurance that at first cut the \"code looks good\". Now during execution, other errors may well come up.</p>\n\n<p>To evaluate the parse tree, you just walk the tree. You'll have some code associated with the major nodes of the parse tree during the compile or evaluation part. Let's assuming that we have an interpreter.</p>\n\n<pre><code>public void execute_if_statment(ParseTreeNode node) {\n // We already know we have a IF_STATEMENT node\n Value value = evaluate_expression(node.getBooleanExpression());\n if (value.getBooleanResult() == true) {\n // we do the \"then\" part of the code\n }\n}\n\npublic Value evaluate_expression(ParseTreeNode node) {\n Value result = null;\n if (node.isConstant()) {\n result = evaluate_constant(node);\n return result;\n }\n if (node.isIdentifier()) {\n result = lookupIdentifier(node);\n return result;\n }\n Value leftSide = evaluate_expression(node.getLeftSide());\n Value rightSide = evaluate_expression(node.getRightSide());\n if (node.getOperator() == '+') {\n if (!leftSide.isNumber() || !rightSide.isNumber()) {\n throw new RuntimeError(\"Must have numbers for adding\");\n }\n int l = leftSide.getIntValue();\n int r = rightSide.getIntValue();\n int sum = l + r;\n return new Value(sum);\n }\n if (node.getOperator() == '&gt;') {\n if (leftSide.getType() != rightSide.getType()) {\n throw new RuntimeError(\"You can only compare values of the same type\");\n }\n if (leftSide.isNumber()) {\n int l = leftSide.getIntValue();\n int r = rightSide.getIntValue();\n boolean greater = l &gt; r;\n return new Value(greater);\n } else {\n // do string compare instead\n }\n }\n}\n</code></pre>\n\n<p>So, you can see that we have a recursive evaluator here. You see how we're checking the run time types, and performing the basic evaluations.</p>\n\n<p>What will happen is the execute_if_statement will evaluate it's main expression. Even tho we wanted only BOOLEAN_EXPRESION in the parse, all expressions are mostly the same for our purposes. So, execute_if_statement calls evaluate_expression.</p>\n\n<p>In our system, all expressions have an operator and a left and right side. Each side of an expression is ALSO an expression, so you can see how we immediately try and evaluate those as well to get their real value. The one note is that if the expression consists of a CONSTANT, then we simply return the constants value, if it's an identifier, we look it up as a variable (and that would be a good place to throw a \"I can't find the variable 'a'\" message), otherwise we're back to the left side/right side thing.</p>\n\n<p>I hope you can see how a simple evaluator can work once you have a token stream from a parser. Note how during evaluation, the major elements of the language are in place, otherwise we'd have got a syntax error and never got to this phase. We can simply expect to \"know\" that when we have a, for example, PLUS operator, we're going to have 2 expressions, the left and right side. Or when we execute an IF statement, that we already have a boolean expression to evaluate. The parse is what does that heavy lifting for us.</p>\n\n<p>Getting started with a new language can be a challenge, but you'll find once you get rolling, the rest become pretty straightforward and it's almost \"magic\" that it all works in the end.</p>\n\n<p>Note, pardon the formatting, but underscores are messing things up -- I hope it's still clear.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535708/" ]
I have read the GOLD Homepage ( <http://www.devincook.com/goldparser/> ) docs, FAQ and Wikipedia to find out what practical application there could possibly be for GOLD. I was thinking along the lines of having a programming language (easily) available to my systems such as ABAP on SAP or X++ on Axapta - but it doesn't look feasible to me, at least not easily - even if you use GOLD. The final use of the parsed result produced by GOLD escapes me - what do you do with the result of the parse? EDIT: A practical example (description) would be great.
Parsing really consists of two phases. The first is "lexing", which convert the raw strings of character in to something that the program can more readily understand (commonly called tokens). Simple example, lex would convert: if (a + b > 2) then In to: ``` IF_TOKEN LEFT_PAREN IDENTIFIER(a) PLUS_SIGN IDENTIFIER(b) GREATER_THAN NUMBER(2) RIGHT_PAREN THEN_TOKEN ``` The parse takes that stream of tokens, and attempts to make yet more sense out of them. In this case, it would try and match up those tokens to an IF\_STATEMENT. To the parse, the IF \_STATEMENT may well look like this: ``` IF ( BOOLEAN_EXPRESSION ) THEN ``` Where the result of the lexing phase is a token stream, the result of the parsing phase is a Parse Tree. So, a parser could convert the above in to: ``` if_statement | v boolean_expression.operator = GREATER_THAN | | | v V numeric_constant.string="2" expression.operator = PLUS_SIGN | | | v v identifier.string = "b" identifier.string = "a" ``` Here you see we have an IF\_STATEMENT. An IF\_STATEMENT has a single argument, which is a BOOLEAN\_EXPRESSION. This was explained in some manner to the parser. When the parser is converting the token stream, it "knows" what a IF looks like, and know what a BOOLEAN\_EXPRESSION looks like, so it can make the proper assignments when it sees the code. For example, if you have just: if (a + b) then The parser could know that it's not a boolean expression (because the + is arithmetic, not a boolean operator) and the parse could throw an error at this point. Next, we see that a BOOLEAN\_EXPRESSION has 3 components, the operator (GREATER\_THAN), and two sides, the left side and the right side. On the left side, it points to yet another expression, the "a + b", while on the right is points to a NUMERIC\_CONSTANT, in this case the string "2". Again, the parser "knows" this is a NUMERIC constant because we told it about strings of numbers. If it wasn't numbers, it would be an IDENTIFIER (like "a" and "b" are). Note, that if we had something like: if (a + b > "XYZ") then That "parses" just fine (expression on the left, string constant on the right). We don't know from looking at this whether this is a valid expression or not. We don't know if "a" or "b" reference Strings or Numbers at this point. So, this is something the parser can't decided for us, can't flag as an error, as it simply doesn't know. That will happen when we evaluate (either execute or try to compile in to code) the IF statement. If we did: if [a > b ) then The parser can readily see that syntax error as a problem, and will throw an error. That string of tokens doesn't look like anything it knows about. So, the point being that when you get a complete parse tree, you have some assurance that at first cut the "code looks good". Now during execution, other errors may well come up. To evaluate the parse tree, you just walk the tree. You'll have some code associated with the major nodes of the parse tree during the compile or evaluation part. Let's assuming that we have an interpreter. ``` public void execute_if_statment(ParseTreeNode node) { // We already know we have a IF_STATEMENT node Value value = evaluate_expression(node.getBooleanExpression()); if (value.getBooleanResult() == true) { // we do the "then" part of the code } } public Value evaluate_expression(ParseTreeNode node) { Value result = null; if (node.isConstant()) { result = evaluate_constant(node); return result; } if (node.isIdentifier()) { result = lookupIdentifier(node); return result; } Value leftSide = evaluate_expression(node.getLeftSide()); Value rightSide = evaluate_expression(node.getRightSide()); if (node.getOperator() == '+') { if (!leftSide.isNumber() || !rightSide.isNumber()) { throw new RuntimeError("Must have numbers for adding"); } int l = leftSide.getIntValue(); int r = rightSide.getIntValue(); int sum = l + r; return new Value(sum); } if (node.getOperator() == '>') { if (leftSide.getType() != rightSide.getType()) { throw new RuntimeError("You can only compare values of the same type"); } if (leftSide.isNumber()) { int l = leftSide.getIntValue(); int r = rightSide.getIntValue(); boolean greater = l > r; return new Value(greater); } else { // do string compare instead } } } ``` So, you can see that we have a recursive evaluator here. You see how we're checking the run time types, and performing the basic evaluations. What will happen is the execute\_if\_statement will evaluate it's main expression. Even tho we wanted only BOOLEAN\_EXPRESION in the parse, all expressions are mostly the same for our purposes. So, execute\_if\_statement calls evaluate\_expression. In our system, all expressions have an operator and a left and right side. Each side of an expression is ALSO an expression, so you can see how we immediately try and evaluate those as well to get their real value. The one note is that if the expression consists of a CONSTANT, then we simply return the constants value, if it's an identifier, we look it up as a variable (and that would be a good place to throw a "I can't find the variable 'a'" message), otherwise we're back to the left side/right side thing. I hope you can see how a simple evaluator can work once you have a token stream from a parser. Note how during evaluation, the major elements of the language are in place, otherwise we'd have got a syntax error and never got to this phase. We can simply expect to "know" that when we have a, for example, PLUS operator, we're going to have 2 expressions, the left and right side. Or when we execute an IF statement, that we already have a boolean expression to evaluate. The parse is what does that heavy lifting for us. Getting started with a new language can be a challenge, but you'll find once you get rolling, the rest become pretty straightforward and it's almost "magic" that it all works in the end. Note, pardon the formatting, but underscores are messing things up -- I hope it's still clear.
212,234
<p>I am building an MS Access application in which all the forms are modal. However, after data change in a form, I want to refresh the parent form of this form with newer data. Is there any way to do it. To elaborate further :</p> <p>Consider there are two forms, Form A and Form B. Both are modal form. From Form A, I initiate Form B, and now Form B has the user attention. But at the close of form B, I want to refresh the Form A. Is there a way to do it?</p>
[ { "answer_id": 212303, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": false, "text": "<p>You can repaint and / or requery:</p>\n\n<p>On the close event of form B:</p>\n\n<pre><code>Forms!FormA.Requery\n</code></pre>\n\n<p>Is this what you mean?</p>\n" }, { "answer_id": 212482, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>No, it is like I want to run Form_Load\n of Form A,if it is possible</p>\n</blockquote>\n\n<p>-- Varun Mahajan</p>\n\n<p>The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:</p>\n\n<p>Form B:</p>\n\n<pre><code>Sub RunFormALoad()\n Forms!FormA.ToDoOnLoad\nEnd Sub\n</code></pre>\n\n<p>Form A:</p>\n\n<pre><code>Public Sub Form_Load()\n ToDoOnLoad\nEnd Sub \n\nSub ToDoOnLoad()\n txtText = \"Hi\"\nEnd Sub\n</code></pre>\n" }, { "answer_id": 212505, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 1, "selected": false, "text": "<p>\"Requery\" is indeed what you what you want to run, but you could do that in Form A's \"On Got Focus\" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.</p>\n" }, { "answer_id": 15571032, "author": "tony gil", "author_id": 1166727, "author_profile": "https://Stackoverflow.com/users/1166727", "pm_score": 1, "selected": false, "text": "<p>I recommend that you use <code>REQUERY</code> the specific combo box whose data you have changed AND that you do it after the <code>Cmd.Close</code> statement. that way, if you were inputing data, that data is also requeried. </p>\n\n<pre><code>DoCmd.Close\nForms![Form_Name]![Combo_Box_Name].Requery\n</code></pre>\n\n<p>you might also want to point to the recently changed value</p>\n\n<pre><code>Dim id As Integer\nid = Me.[Index_Field]\nDoCmd.Close\nForms![Form_Name]![Combo_Box_Name].Requery\nForms![Form_Name]![Combo_Box_Name] = id\n</code></pre>\n\n<p>this example supposes that you opened a form to input data into a secondary table. </p>\n\n<p>let us say you save School_Index and School_Name in a School table and refer to it in a Student table (which contains only the School_Index field). while you are editing a student, you need to associate him with a school that is not in your School table, etc etc</p>\n" }, { "answer_id": 39350825, "author": "dinesh", "author_id": 6800626, "author_profile": "https://Stackoverflow.com/users/6800626", "pm_score": -1, "selected": false, "text": "<p><strong>to refresh the form you need to type -</strong>\nme.refresh\nin the button event on click</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6613/" ]
I am building an MS Access application in which all the forms are modal. However, after data change in a form, I want to refresh the parent form of this form with newer data. Is there any way to do it. To elaborate further : Consider there are two forms, Form A and Form B. Both are modal form. From Form A, I initiate Form B, and now Form B has the user attention. But at the close of form B, I want to refresh the Form A. Is there a way to do it?
> > No, it is like I want to run Form\_Load > of Form A,if it is possible > > > -- Varun Mahajan The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a: Form B: ``` Sub RunFormALoad() Forms!FormA.ToDoOnLoad End Sub ``` Form A: ``` Public Sub Form_Load() ToDoOnLoad End Sub Sub ToDoOnLoad() txtText = "Hi" End Sub ```
212,257
<p>It seems like this should be straightforward but I'm boggling. I've got my listview all setup and bound to my LINQ datasource. The source is dependent on a dropdown list which decides which branch information to show in the listview. My edit template works fine but my insert template won't work because it wants the branch ID which I want to get from the dropdownlist outside the listview but I don't know how to both bind that value and set it in my template. It looks like this:</p> <pre><code>&lt;InsertItemTemplate&gt; &lt;tr style=""&gt; &lt;td&gt; &lt;asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" /&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:TextBox ID="RechargeRateTextBox" runat="server" Text='&lt;%# Bind("RechargeRate") %&gt;' /&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Calendar SelectedDate='&lt;%# Bind("StartDate") %&gt;' ID="Calendar1" runat="server"&gt;&lt;/asp:Calendar&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/InsertItemTemplate&gt; </code></pre> <p>I need to get a label in there that binds to the value of a databound asp dropdownlist outside of the listview so that the insert will work.</p>
[ { "answer_id": 212341, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>Use the OnSelectedIndexChanged (with AutoPostBack=True) callback for the DropDownList to manually set the values in the ListView to the defaults for that branch when the value of the DropDownList changes.</p>\n\n<pre><code>protected void BranchDropDownList_OnSelectedIndexChanged( object sender, EventArgs e )\n{\n DropDownList ddl = (DropDownList)sender;\n RechargeRateTextBox.Text = BranchManager.GetRechargeRate( ddl.SelectedValue );\n}\n</code></pre>\n\n<p>Wrap the whole thing up in an UpdatePanel and it can all happen via AJAX.</p>\n" }, { "answer_id": 212436, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": 2, "selected": true, "text": "<p>I ended up going with this, thanks twanfosson.</p>\n\n<pre><code>protected void ListView1_ItemInserting(object sender, System.Web.UI.WebControls.ListViewInsertEventArgs e)\n {\n e.Values[\"BranchID\"] = DropDownList1.SelectedValue;\n }\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12862/" ]
It seems like this should be straightforward but I'm boggling. I've got my listview all setup and bound to my LINQ datasource. The source is dependent on a dropdown list which decides which branch information to show in the listview. My edit template works fine but my insert template won't work because it wants the branch ID which I want to get from the dropdownlist outside the listview but I don't know how to both bind that value and set it in my template. It looks like this: ``` <InsertItemTemplate> <tr style=""> <td> <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" /> </td> <td> <asp:TextBox ID="RechargeRateTextBox" runat="server" Text='<%# Bind("RechargeRate") %>' /> </td> <td> <asp:Calendar SelectedDate='<%# Bind("StartDate") %>' ID="Calendar1" runat="server"></asp:Calendar> </td> </tr> </InsertItemTemplate> ``` I need to get a label in there that binds to the value of a databound asp dropdownlist outside of the listview so that the insert will work.
I ended up going with this, thanks twanfosson. ``` protected void ListView1_ItemInserting(object sender, System.Web.UI.WebControls.ListViewInsertEventArgs e) { e.Values["BranchID"] = DropDownList1.SelectedValue; } ```
212,271
<p>A person uses their cell phone multiple times per day, and the length of their calls vary. I am tracking the length of the calls in a table:</p> <pre><code>Calls [callID, memberID, startTime, duration] </code></pre> <p>I need to a query to return the average call length for users <strong>per day</strong>. Per day means, if a user used the phone 3 times, first time for 5 minutes, second for 10 minutes and the last time for 7 minutes, the calculation is: <code>5 + 10 + 7 / 3 = ...</code></p> <p>Note:</p> <ol> <li><p>People don't use the phone everyday, so we have to get the latest day's average per person and use this to get the overall average call duration.</p></li> <li><p>we don't want to count anyone twice in the average, so only 1 row per user will go into calculating the average daily call duration.</p></li> </ol> <p>Some clarifications...</p> <p>I need a overall per day average, based on the per-user per-day average, using the users latest days numbers (since we are only counting a given user ONCE in the query), so it will mean we will be using different days avg. since people might not use the phone each day or on the same day even.</p>
[ { "answer_id": 212284, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "<pre><code>select average(duration) from calls group by date(startTime);\n</code></pre>\n" }, { "answer_id": 212285, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>You need to convert the DATETIME to something you can make \"per day\" groups on, so this would produce \"yy/mm/dd\".</p>\n\n<pre><code>SELECT\n memberId,\n CONVERT(VARCHAR, startTime, 102) Day,\n AVG(Duration) AvgDuration\nFROM\n Calls\nWHERE\n CONVERT(VARCHAR, startTime, 102) = \n (\n SELECT \n CONVERT(VARCHAR, MAX(startTime), 102) \n FROM \n Calls i WHERE i.memberId = Calls.memberId\n )\nGROUP BY\n memberId,\n CONVERT(VARCHAR, startTime, 102)\n</code></pre>\n\n<p>Use <code>LEFT(CONVERT(VARCHAR, startTime, 120), 10)</code> to produce \"yyyy-mm-dd\".</p>\n\n<p>For these kind of queries it would be helpful to have a dedicated \"day only\" column to avoid the whole conversion business and as a side effect make the query more readable.</p>\n" }, { "answer_id": 212500, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>The following query will get you the desired end results.</p>\n\n<pre><code>SELECT AVG(rt.UserDuration) AS AveragePerDay\nFROM\n(\n SELECT\n c1.MemberId,\n AVG(c1.Duration) AS \"UserDuration\"\n FROM Calls c1\n WHERE CONVERT(VARCHAR, c1.StartTime, 102) =\n (SELECT CONVERT(VARCHAR, MAX(c2.StartTime), 102)\n FROM Calls c2\n WHERE c2.MemberId = c1.MemberId)\n GROUP By MemberId\n) AS rt\n</code></pre>\n\n<p>THis accomplishes it by first creating a table with 1 record for each member and the average duration of their calls for the most recent day. Then it simply averages all of those values to get the end \"average call duration. If you want to see a specific user, you can run just the innser SELECT section to get the member list</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A person uses their cell phone multiple times per day, and the length of their calls vary. I am tracking the length of the calls in a table: ``` Calls [callID, memberID, startTime, duration] ``` I need to a query to return the average call length for users **per day**. Per day means, if a user used the phone 3 times, first time for 5 minutes, second for 10 minutes and the last time for 7 minutes, the calculation is: `5 + 10 + 7 / 3 = ...` Note: 1. People don't use the phone everyday, so we have to get the latest day's average per person and use this to get the overall average call duration. 2. we don't want to count anyone twice in the average, so only 1 row per user will go into calculating the average daily call duration. Some clarifications... I need a overall per day average, based on the per-user per-day average, using the users latest days numbers (since we are only counting a given user ONCE in the query), so it will mean we will be using different days avg. since people might not use the phone each day or on the same day even.
You need to convert the DATETIME to something you can make "per day" groups on, so this would produce "yy/mm/dd". ``` SELECT memberId, CONVERT(VARCHAR, startTime, 102) Day, AVG(Duration) AvgDuration FROM Calls WHERE CONVERT(VARCHAR, startTime, 102) = ( SELECT CONVERT(VARCHAR, MAX(startTime), 102) FROM Calls i WHERE i.memberId = Calls.memberId ) GROUP BY memberId, CONVERT(VARCHAR, startTime, 102) ``` Use `LEFT(CONVERT(VARCHAR, startTime, 120), 10)` to produce "yyyy-mm-dd". For these kind of queries it would be helpful to have a dedicated "day only" column to avoid the whole conversion business and as a side effect make the query more readable.
212,321
<p>Anyone know a simple way using Java calendar to subtract X days from a date?</p> <p>I have not been able to find any function which allows me to directly subtract X days from a date in Java. Can someone point me to the right direction?</p>
[ { "answer_id": 212334, "author": "Anson Smith", "author_id": 28685, "author_profile": "https://Stackoverflow.com/users/28685", "pm_score": 9, "selected": true, "text": "<p>Taken from <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add%28int,%20int%29\" rel=\"noreferrer\">the docs here</a>: </p>\n\n<blockquote>\n <p>Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:</p>\n\n<pre><code>Calendar calendar = Calendar.getInstance(); // this would default to now\ncalendar.add(Calendar.DAY_OF_MONTH, -5).\n</code></pre>\n</blockquote>\n" }, { "answer_id": 212337, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "<pre><code>int x = -1;\nCalendar cal = ...;\ncal.add(Calendar.DATE, x);\n</code></pre>\n<p>See <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html#add(int,int)\" rel=\"nofollow noreferrer\"><code>java.util.Calendar#add(int,int)</code></a></p>\n" }, { "answer_id": 212353, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 5, "selected": false, "text": "<p>You could use the <code>add</code> method and pass it a negative number. However, you could also write a simpler method that doesn't use the <code>Calendar</code> class such as the following</p>\n\n<pre><code>public static void addDays(Date d, int days)\n{\n d.setTime( d.getTime() + (long)days*1000*60*60*24 );\n}\n</code></pre>\n\n<p>This gets the timestamp value of the date (milliseconds since the epoch) and adds the proper number of milliseconds. You could pass a negative integer for the days parameter to do subtraction. This would be simpler than the \"proper\" calendar solution:</p>\n\n<pre><code>public static void addDays(Date d, int days)\n{\n Calendar c = Calendar.getInstance();\n c.setTime(d);\n c.add(Calendar.DATE, days);\n d.setTime( c.getTime().getTime() );\n}\n</code></pre>\n\n<p>Note that both of these solutions change the <code>Date</code> object passed as a parameter rather than returning a completely new <code>Date</code>. Either function could be easily changed to do it the other way if desired.</p>\n" }, { "answer_id": 212363, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/212321/anyone-know-a-simple-way-using-java-calendar-to-subtract-x-days-to-a-date#212334\">Anson's answer</a> will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out <a href=\"http://joda-time.sourceforge.net/\" rel=\"nofollow noreferrer\">Joda Time</a>. It will make your life much easier.</p>\n\n<p>FYI in Joda Time you could do</p>\n\n<pre><code>DateTime dt = new DateTime();\nDateTime fiveDaysEarlier = dt.minusDays(5);\n</code></pre>\n" }, { "answer_id": 1476346, "author": "user178973", "author_id": 178973, "author_profile": "https://Stackoverflow.com/users/178973", "pm_score": 0, "selected": false, "text": "<p>Eli Courtwright second solution is wrong, it should be:</p>\n\n<pre><code>Calendar c = Calendar.getInstance();\nc.setTime(date);\nc.add(Calendar.DATE, -days);\ndate.setTime(c.getTime().getTime());\n</code></pre>\n" }, { "answer_id": 7922011, "author": "Michael K", "author_id": 620054, "author_profile": "https://Stackoverflow.com/users/620054", "pm_score": 1, "selected": false, "text": "<p>Someone recommended Joda Time so - I have been using this <strong>CalendarDate</strong> class <a href=\"http://calendardate.sourceforge.net\" rel=\"nofollow\">http://calendardate.sourceforge.net</a> </p>\n\n<p>It's a somewhat competing project to Joda Time, but much more basic at only 2 classes. It's very handy and worked great for what I needed since I didn't want to use a package bigger than my project. Unlike the Java counterparts, its smallest unit is the day so it is really a date (not having it down to milliseconds or something). Once you create the date, all you do to subtract is something like myDay.addDays(-5) to go back 5 days. You can use it to find the day of the week and things like that.\nAnother example:</p>\n\n<pre><code>CalendarDate someDay = new CalendarDate(2011, 10, 27);\nCalendarDate someLaterDay = today.addDays(77);\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>//print 4 previous days of the week and today\nString dayLabel = \"\";\nCalendarDate today = new CalendarDate(TimeZone.getDefault());\nCalendarDateFormat cdf = new CalendarDateFormat(\"EEE\");//day of the week like \"Mon\"\nCalendarDate currDay = today.addDays(-4);\nwhile(!currDay.isAfter(today)) {\n dayLabel = cdf.format(currDay);\n if (currDay.equals(today))\n dayLabel = \"Today\";//print \"Today\" instead of the weekday name\n System.out.println(dayLabel);\n currDay = currDay.addDays(1);//go to next day\n}\n</code></pre>\n" }, { "answer_id": 11934301, "author": "Risav Karna", "author_id": 1187246, "author_profile": "https://Stackoverflow.com/users/1187246", "pm_score": 3, "selected": false, "text": "<p>Instead of writing my own <code>addDays</code> as suggested by Eli, I would prefer to use <code>DateUtils</code> from <strong>Apache</strong>. It is handy especially when you have to use it multiple places in your project.</p>\n\n<p>The API says: </p>\n\n<p><code>addDays(Date date, int amount)</code> </p>\n\n<p>Adds a number of days to a date returning a new object.</p>\n\n<p>Note that it returns a new <code>Date</code> object and does not make changes to the previous one itself. </p>\n" }, { "answer_id": 33530885, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 5, "selected": false, "text": "<h1>tl;dr</h1>\n\n<pre><code>LocalDate.now().minusDays( 10 )\n</code></pre>\n\n<p>Better to specify time zone.</p>\n\n<pre><code>LocalDate.now( ZoneId.of( \"America/Montreal\" ) ).minusDays( 10 )\n</code></pre>\n\n<h1>Details</h1>\n\n<p>The old date-time classes bundled with early versions of Java, such as <code>java.util.Date</code>/<code>.Calendar</code>, have proven to be troublesome, confusing, and flawed. Avoid them.</p>\n\n<h1>java.time</h1>\n\n<p>Java 8 and later supplants those old classes with the new java.time framework. See <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"noreferrer\">Tutorial</a>. Defined by <a href=\"http://jcp.org/en/jsr/detail?id=310\" rel=\"noreferrer\">JSR 310</a>, inspired by <a href=\"http://www.joda.org/joda-time/\" rel=\"noreferrer\">Joda-Time</a>, and extended by the<a href=\"http://www.threeten.org/threeten-extra/\" rel=\"noreferrer\">ThreeTen-Extra</a> project. The ThreeTen-Backport project back-ports the classes to Java 6 &amp; 7; the ThreeTenABP project to Android.</p>\n\n<p>The Question is vague, not clear if it asks for a date-only or a date-time.</p>\n\n<h2><code>LocalDate</code></h2>\n\n<p>For a date-only, without time-of-day, use the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"noreferrer\"><code>LocalDate</code></a> class. Note that a time zone in crucial in determining a date such as \"today\".</p>\n\n<pre><code>LocalDate today = LocalDate.now( ZoneId.of( \"America/Montreal\" ) );\nLocalDate tenDaysAgo = today.minusDays( 10 );\n</code></pre>\n\n<h2><code>ZonedDateTime</code></h2>\n\n<p>If you meant a date-time, then use the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/Instant.html\" rel=\"noreferrer\"><code>Instant</code></a> class to get a moment on the timeline in <a href=\"https://en.wikipedia.org/wiki/Coordinated_Universal_Time\" rel=\"noreferrer\">UTC</a>. From there, adjust to a time zone to get a <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html\" rel=\"noreferrer\"><code>ZonedDateTime</code></a> object.</p>\n\n<pre><code>Instant now = Instant.now(); // UTC.\nZoneId zoneId = ZoneId.of( \"America/Montreal\" );\nZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );\nZonedDateTime tenDaysAgo = zdt.minusDays( 10 );\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/kmXfI.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/kmXfI.png\" alt=\"Table of date-time types in Java, both modern and legacy.\"></a></p>\n\n<hr>\n\n<h1>About <em>java.time</em></h1>\n\n<p>The <a href=\"http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html\" rel=\"noreferrer\"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href=\"https://en.wikipedia.org/wiki/Legacy_system\" rel=\"noreferrer\">legacy</a> date-time classes such as <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Date.html\" rel=\"noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html\" rel=\"noreferrer\"><code>Calendar</code></a>, &amp; <a href=\"http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html\" rel=\"noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<p>The <a href=\"http://www.joda.org/joda-time/\" rel=\"noreferrer\"><em>Joda-Time</em></a> project, now in <a href=\"https://en.wikipedia.org/wiki/Maintenance_mode\" rel=\"noreferrer\">maintenance mode</a>, advises migration to the <a href=\"http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html\" rel=\"noreferrer\">java.time</a> classes.</p>\n\n<p>To learn more, see the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"noreferrer\"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href=\"https://jcp.org/en/jsr/detail?id=310\" rel=\"noreferrer\">JSR 310</a>.</p>\n\n<p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href=\"https://en.wikipedia.org/wiki/JDBC_driver\" rel=\"noreferrer\">JDBC driver</a> compliant with <a href=\"http://openjdk.java.net/jeps/170\" rel=\"noreferrer\">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes.</p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"noreferrer\"><strong>Java SE 8</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"noreferrer\"><strong>Java SE 9</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10\" rel=\"noreferrer\"><strong>Java SE 10</strong></a>, and later\n\n<ul>\n<li>Built-in. </li>\n<li>Part of the standard Java API with a bundled implementation.</li>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6\" rel=\"noreferrer\"><strong>Java SE 6</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"noreferrer\"><strong>Java SE 7</strong></a>\n\n<ul>\n<li>Much of the java.time functionality is back-ported to Java 6 &amp; 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the java.time classes.</li>\n<li>For earlier Android (&lt;26), the <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"noreferrer\"><strong><em>ThreeTenABP</em></strong></a> project adapts <em>ThreeTen-Backport</em> (mentioned above). See <a href=\"http://stackoverflow.com/q/38922754/642706\"><em>How to use ThreeTenABP…</em></a>.</li>\n</ul></li>\n</ul>\n\n<p>The <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"noreferrer\"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html\" rel=\"noreferrer\"><code>Interval</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"noreferrer\"><code>YearWeek</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html\" rel=\"noreferrer\"><code>YearQuarter</code></a>, and <a href=\"http://www.threeten.org/threeten-extra/apidocs/index.html\" rel=\"noreferrer\">more</a>.</p>\n" }, { "answer_id": 47881277, "author": "rab", "author_id": 2564329, "author_profile": "https://Stackoverflow.com/users/2564329", "pm_score": 2, "selected": false, "text": "<p>It can be done easily by the following</p>\n\n<pre><code>Calendar calendar = Calendar.getInstance();\n // from current time\n long curTimeInMills = new Date().getTime();\n long timeInMills = curTimeInMills - 5 * (24*60*60*1000); // `enter code here`subtract like 5 days\n calendar.setTimeInMillis(timeInMills);\n System.out.println(calendar.getTime());\n\n // from specific time like (08 05 2015)\n calendar.set(Calendar.DAY_OF_MONTH, 8);\n calendar.set(Calendar.MONTH, (5-1));\n calendar.set(Calendar.YEAR, 2015);\n timeInMills = calendar.getTimeInMillis() - 5 * (24*60*60*1000);\n calendar.setTimeInMillis(timeInMills);\n System.out.println(calendar.getTime());\n</code></pre>\n" }, { "answer_id": 59249667, "author": "Yordan Boev", "author_id": 2715285, "author_profile": "https://Stackoverflow.com/users/2715285", "pm_score": 2, "selected": false, "text": "<p>I believe a clean and nice way to perform subtraction or addition of any time unit (months, days, hours, minutes, seconds, ...) can be achieved using the <strong>java.time.Instant</strong> class.</p>\n<p>Example for subtracting 5 days from the current time and getting the result as Date:</p>\n<pre><code>new Date(Instant.now().minus(5, ChronoUnit.DAYS).toEpochMilli());\n</code></pre>\n<p>Another example for subtracting 1 hour and adding 15 minutes:</p>\n<pre><code>Date.from(Instant.now().minus(Duration.ofHours(1)).plus(Duration.ofMinutes(15)));\n</code></pre>\n<p>If you need more accuracy, Instance measures up to nanoseconds. Methods manipulating nanosecond part:</p>\n<pre><code>minusNano()\nplusNano()\ngetNano()\n</code></pre>\n<p>Also, keep in mind, that Date is not as accurate as Instant. My advice is to <strong>stay within the Instant class</strong>, when possible.</p>\n" }, { "answer_id": 69708511, "author": "shashi ranjan", "author_id": 8132714, "author_profile": "https://Stackoverflow.com/users/8132714", "pm_score": 2, "selected": false, "text": "<p>I faced the same challenge where I needed to go back by 1 day (should be able to roll back by one even if previous day falls into previous year or months).</p>\n<p>I did following, basically subtracted by 24 hours for 1 day.\nsomeDateInGregorianCalendar.add(Calendar.HOUR, -24);</p>\n<p>Alternatively, I could also do</p>\n<pre><code>GregorianCalendar cal = new GregorianCalendar();\n cal.set(Calendar.YEAR, 2021);\n cal.set(Calendar.MONTH, 0);\n cal.set(Calendar.DATE, 1);\n System.out.println(&quot;Original: &quot; + cal.getTime());\n cal.add(Calendar.DATE, -1);\n System.out.println(&quot;After adding DATE: &quot; + cal.getTime());\n</code></pre>\n<p>OUTPUT:</p>\n<pre><code>Original: Fri Jan 01 15:08:33 CET 2021\nAfter adding DATE: Thu Dec 31 15:08:33 CET 2020\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
Anyone know a simple way using Java calendar to subtract X days from a date? I have not been able to find any function which allows me to directly subtract X days from a date in Java. Can someone point me to the right direction?
Taken from [the docs here](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add%28int,%20int%29): > > Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling: > > > > ``` > Calendar calendar = Calendar.getInstance(); // this would default to now > calendar.add(Calendar.DAY_OF_MONTH, -5). > > ``` > >
212,350
<p>The <code>JPA</code> (Java Persistence API) specification has 2 different ways to specify entity composite keys: <code>@IdClass</code> and <code>@EmbeddedId</code>. </p> <p>I'm using both annotations on my mapped entities, but it turns out to be a big mess to people who aren't very familiar with <code>JPA</code>. </p> <p>I want to adopt only one way to specify composite keys. Which one is really the best? Why?</p>
[ { "answer_id": 212371, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 8, "selected": true, "text": "<p>I consider that <code>@EmbeddedId</code> is probably more verbose because with <code>@IdClass</code> you cannot access the entire primary key object using any field access operator. Using the <code>@EmbeddedId</code> you can do like this:</p>\n\n<pre><code>@Embeddable class EmployeeId { name, dataOfBirth }\n@Entity class Employee {\n @EmbeddedId EmployeeId employeeId;\n ...\n}\n</code></pre>\n\n<p>This gives a clear notion of the fields that make the composite key because they are all aggregated in a class that is accessed trough a field access operator.</p>\n\n<p>Another difference with <code>@IdClass</code> and <code>@EmbeddedId</code> is when it comes to write HQL :</p>\n\n<p>With <code>@IdClass</code> you write:</p>\n\n<pre>select e.name from Employee e</pre>\n\n<p>and with <code>@EmbeddedId</code> you have to write:</p>\n\n<pre>select e.employeeId.name from Employee e</pre>\n\n<p>You have to write more text for the same query. Some may argue that this differs from a more natural language like the one promoted by <code>IdClass</code>. But most of the times understanding right from the query that a given field is part of the composite key is of invaluable help.</p>\n" }, { "answer_id": 213454, "author": "laz", "author_id": 8753, "author_profile": "https://Stackoverflow.com/users/8753", "pm_score": 4, "selected": false, "text": "<p>I discovered an instance where I had to use EmbeddedId instead of IdClass. In this scenario there is a join table that has additional columns defined. I attempted to solve this problem using IdClass to represent the key of an entity that explicitly represents rows in the join table. I couldn't get it working this way. Thankfully \"Java Persistence With Hibernate\" has a section dedicated to this topic. One proposed solution was very similar to mine but it used EmbeddedId instead. I modeled my objects after those in the book it now behaves correctly.</p>\n" }, { "answer_id": 4672983, "author": "Bertie", "author_id": 500451, "author_profile": "https://Stackoverflow.com/users/500451", "pm_score": 3, "selected": false, "text": "<p>I think the main advantage is that we could use <code>@GeneratedValue</code> for the id when using the <code>@IdClass</code>? I'm sure we can't use <code>@GeneratedValue</code> for <code>@EmbeddedId</code>.</p>\n" }, { "answer_id": 18890592, "author": "Ondrej Bozek", "author_id": 668417, "author_profile": "https://Stackoverflow.com/users/668417", "pm_score": 4, "selected": false, "text": "<p>As far as I know, if your composite PK contains FK it's easier and more straightforward to use <code>@IdClass</code></p>\n<p>With <code>@EmbeddedId</code> you have to define a mapping for your FK column twice, once in <code>@Embeddedable</code> and once for as i.e. <code>@ManyToOne</code> where <code>@ManyToOne</code> has to be read-only(<code>@PrimaryKeyJoinColumn</code>) because you can't have one column set in two variables (possible conflicts).<br />\nSo you have to set your FK using a simple type in <code>@Embeddedable</code>.</p>\n<p>On the other site using <code>@IdClass</code> this situation can be handled much easier as shown in <a href=\"http://web.archive.org/web/20150508144430/http://blog.theapplicationbox.com/2012/07/primary-keys-through-onetoone-and.html\" rel=\"nofollow noreferrer\">Primary Keys through OneToOne and ManyToOne Relationships</a>:</p>\n<p>Example JPA 2.0 ManyToOne id annotation</p>\n<pre><code>...\n@Entity\n@IdClass(PhonePK.class)\npublic class Phone {\n \n @Id\n private String type;\n \n @ManyToOne\n @Id\n @JoinColumn(name=&quot;OWNER_ID&quot;, referencedColumnName=&quot;EMP_ID&quot;)\n private Employee owner;\n ...\n}\n</code></pre>\n<p>Example JPA 2.0 id class</p>\n<pre><code>...\npublic class PhonePK {\n private String type;\n private long owner;\n \n public PhonePK() {}\n \n public PhonePK(String type, long owner) {\n this.type = type;\n this.owner = owner;\n }\n \n public boolean equals(Object object) {\n if (object instanceof PhonePK) {\n PhonePK pk = (PhonePK)object;\n return type.equals(pk.type) &amp;&amp; owner == pk.owner;\n } else {\n return false;\n }\n }\n \n public int hashCode() {\n return type.hashCode() + owner;\n }\n}\n</code></pre>\n" }, { "answer_id": 25579661, "author": "bkuriach", "author_id": 3972704, "author_profile": "https://Stackoverflow.com/users/3972704", "pm_score": 3, "selected": false, "text": "<p>Composite Key must not have an <code>@Id</code> property when <code>@EmbeddedId</code> is used. </p>\n" }, { "answer_id": 42214032, "author": "Adelin", "author_id": 1170677, "author_profile": "https://Stackoverflow.com/users/1170677", "pm_score": 5, "selected": false, "text": "<p>There are three strategies to use a compound primary key:</p>\n<ul>\n<li>Mark it as <code>@Embeddable</code> and add to your entity class a normal property for it, marked with <code>@Id</code>.</li>\n<li>Add to your entity class a normal property for it, marked with <code>@EmbeddedId</code>.</li>\n<li>Add properties to your entity class for all of its fields, mark them with <code>@Id</code>,and mark your entity class with <code>@IdClass</code>, supplying the class of your primary key class.</li>\n</ul>\n<p>The use of <code>@Id</code> with a class marked as <code>@Embeddable</code> is the most natural approach. The <code>@Embeddable</code> tag can be used for non-primary key embeddable values anyway. It allows you to treat the compound primary key as a single property, and it permits the reuse of the <code>@Embeddable</code> class in other tables.</p>\n<p>The next most natural approach is the use of the <code>@EmbeddedId</code> tag. Here, the primary key class cannot be used in other tables since it is not an <code>@Embeddable</code> entity, but it does allow us to treat the key as a\nsingle attribute of some class.</p>\n<p>Finally, the use of the <code>@IdClass</code> and <code>@Id</code> annotations allows us to map the compound primary key class using properties of the entity itself corresponding to the names of the properties in the primary key class. <strong>The names must correspond</strong> (there is no mechanism for overriding this), and the primary key class must honor the same obligations as with the other two techniques. The only advantage to this approach is its ability to “hide” the use of the primary key class from the interface of the enclosing entity. The <code>@IdClass</code> annotation takes a value parameter of Class type, which must be the class to be used as the compound primary key. <strong>The fields that correspond to the properties of the primary key class to be used must all be annotated with <code>@Id</code>.</strong></p>\n<p>Reference: <a href=\"http://www.apress.com/us/book/9781430228509\" rel=\"nofollow noreferrer\">http://www.apress.com/us/book/9781430228509</a></p>\n" }, { "answer_id": 49615687, "author": "Aleks Ben Maza", "author_id": 6626501, "author_profile": "https://Stackoverflow.com/users/6626501", "pm_score": 2, "selected": false, "text": "<p>With EmbeddedId you can use the IN clause in HQL, for example : <code>FROM Entity WHERE id IN :ids</code> where id is an EmbeddedId whereas it's pain to achieve the same result with IdClass you will want to do something like <code>FROM Entity WHERE idPartA = :idPartA0 AND idPartB = :idPartB0 .... OR idPartA = :idPartAN AND idPartB = :idPartBN</code></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28921/" ]
The `JPA` (Java Persistence API) specification has 2 different ways to specify entity composite keys: `@IdClass` and `@EmbeddedId`. I'm using both annotations on my mapped entities, but it turns out to be a big mess to people who aren't very familiar with `JPA`. I want to adopt only one way to specify composite keys. Which one is really the best? Why?
I consider that `@EmbeddedId` is probably more verbose because with `@IdClass` you cannot access the entire primary key object using any field access operator. Using the `@EmbeddedId` you can do like this: ``` @Embeddable class EmployeeId { name, dataOfBirth } @Entity class Employee { @EmbeddedId EmployeeId employeeId; ... } ``` This gives a clear notion of the fields that make the composite key because they are all aggregated in a class that is accessed trough a field access operator. Another difference with `@IdClass` and `@EmbeddedId` is when it comes to write HQL : With `@IdClass` you write: ``` select e.name from Employee e ``` and with `@EmbeddedId` you have to write: ``` select e.employeeId.name from Employee e ``` You have to write more text for the same query. Some may argue that this differs from a more natural language like the one promoted by `IdClass`. But most of the times understanding right from the query that a given field is part of the composite key is of invaluable help.
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html" rel="noreferrer">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p> <p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p> <p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p> <p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p> <p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
[ { "answer_id": 212413, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 6, "selected": false, "text": "<p>Why not look at the code for bisect_left/right and adapt it to suit your purpose.</p>\n\n<p>like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def binary_search(a, x, lo=0, hi=None):\n if hi is None:\n hi = len(a)\n while lo &lt; hi:\n mid = (lo+hi)//2\n midval = a[mid]\n if midval &lt; x:\n lo = mid+1\n elif midval &gt; x: \n hi = mid\n else:\n return mid\n return -1\n</code></pre>\n" }, { "answer_id": 212541, "author": "jrb", "author_id": 27437, "author_profile": "https://Stackoverflow.com/users/27437", "pm_score": 2, "selected": false, "text": "<p>If you just want to see if it's present, try turning the list into a dict:</p>\n\n<pre><code># Generate a list\nl = [n*n for n in range(1000)]\n\n# Convert to dict - doesn't matter what you map values to\nd = dict((x, 1) for x in l)\n\ncount = 0\nfor n in range(1000000):\n # Compare with \"if n in l\"\n if n in d:\n count += 1\n</code></pre>\n\n<p>On my machine, \"if n in l\" took 37 seconds, while \"if n in d\" took 0.4 seconds.</p>\n" }, { "answer_id": 212971, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 5, "selected": false, "text": "<p>This is a little off-topic (since Moe's answer seems complete to the OP's question), but it might be worth looking at the complexity for your whole procedure from end to end. If you're storing thing in a sorted lists (which is where a binary search would help), and then just checking for existence, you're incurring (worst-case, unless specified):</p>\n\n<p><strong>Sorted Lists</strong></p>\n\n<ul>\n<li>O( n log n) to initially create the list (if it's unsorted data. O(n), if it's sorted )</li>\n<li>O( log n) lookups (this is the binary search part)</li>\n<li>O( n ) insert / delete (might be O(1) or O(log n) average case, depending on your pattern)</li>\n</ul>\n\n<p>Whereas with a <a href=\"http://docs.python.org/library/stdtypes.html#set\" rel=\"noreferrer\"><code>set()</code></a>, you're incurring</p>\n\n<ul>\n<li>O(n) to create</li>\n<li>O(1) lookup</li>\n<li>O(1) insert / delete</li>\n</ul>\n\n<p>The thing a sorted list really gets you are \"next\", \"previous\", and \"ranges\" (including inserting or deleting ranges), which are O(1) or O(|range|), given a starting index. If you aren't using those sorts of operations often, then storing as sets, and sorting for display might be a better deal overall. <a href=\"http://docs.python.org/library/stdtypes.html#set\" rel=\"noreferrer\"><code>set()</code></a> incurs very little additional overhead in python. </p>\n" }, { "answer_id": 213834, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 1, "selected": false, "text": "<p>Using a dict wouldn't like double your memory usage unless the objects you're storing are really tiny, since the values are only pointers to the actual objects:</p>\n\n<pre><code>&gt;&gt;&gt; a = 'foo'\n&gt;&gt;&gt; b = [a]\n&gt;&gt;&gt; c = [a]\n&gt;&gt;&gt; b[0] is c[0]\nTrue\n</code></pre>\n\n<p>In that example, 'foo' is only stored once. Does that make a difference for you? And exactly how many items are we talking about anyway?</p>\n" }, { "answer_id": 530397, "author": "Imran", "author_id": 58866, "author_profile": "https://Stackoverflow.com/users/58866", "pm_score": 4, "selected": false, "text": "<p>Simplest is to use <a href=\"http://docs.python.org/library/bisect.html\" rel=\"noreferrer\">bisect</a> and check one position back to see if the item is there:</p>\n\n<pre><code>def binary_search(a,x,lo=0,hi=-1):\n i = bisect(a,x,lo,hi)\n if i == 0:\n return -1\n elif a[i-1] == x:\n return i-1\n else:\n return -1\n</code></pre>\n" }, { "answer_id": 2233940, "author": "Dave Abrahams", "author_id": 125349, "author_profile": "https://Stackoverflow.com/users/125349", "pm_score": 9, "selected": true, "text": "<p><code>bisect_left</code> finds the first position <code>p</code> at which an element could be inserted in a given sorted range while maintaining the sorted order. That will be the position of <code>x</code> if <code>x</code> exists in the range. If <code>p</code> is the past-the-end position, <code>x</code> wasn't found. Otherwise, we can test to see if <code>x</code> is there to see if <code>x</code> was found.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from bisect import bisect_left\n\ndef binary_search(a, x, lo=0, hi=None):\n if hi is None: hi = len(a)\n pos = bisect_left(a, x, lo, hi) # find insertion position\n return pos if pos != hi and a[pos] == x else -1 # don't walk off the end\n</code></pre>\n" }, { "answer_id": 5763198, "author": "Petr Viktorin", "author_id": 99057, "author_profile": "https://Stackoverflow.com/users/99057", "pm_score": 4, "selected": false, "text": "<p>It might be worth mentioning that the bisect docs now provide searching examples:\n<a href=\"http://docs.python.org/library/bisect.html#searching-sorted-lists\" rel=\"noreferrer\">http://docs.python.org/library/bisect.html#searching-sorted-lists</a></p>\n\n<p>(Raising ValueError instead of returning -1 or None is more pythonic – list.index() does it, for example. But of course you can adapt the examples to your needs.)</p>\n" }, { "answer_id": 10390802, "author": "rct", "author_id": 1366727, "author_profile": "https://Stackoverflow.com/users/1366727", "pm_score": 1, "selected": false, "text": "<p><p>This code works with integer lists in a recursive way. Looks for the simplest case scenario, which is: list length less than 2. It means the answer is already there and a test is performed to check for the correct answer.\nIf not, a middle value is set and tested to be the correct, if not bisection is performed by calling again the function, but setting middle value as the upper or lower limit, by shifting it to the left or right</p></p>\n\n<pre>\ndef binary_search(intList, intValue, lowValue, highValue):\n if(highValue - lowValue) &lt 2:\n return intList[lowValue] == intValue or intList[highValue] == intValue\n middleValue = lowValue + ((highValue - lowValue)/2)\n if intList[middleValue] == intValue:\n return True\n if intList[middleValue] > intValue:\n return binary_search(intList, intValue, lowValue, middleValue - 1)\n return binary_search(intList, intValue, middleValue + 1, highValue)\n</pre>\n" }, { "answer_id": 10555553, "author": "iraycd", "author_id": 1097972, "author_profile": "https://Stackoverflow.com/users/1097972", "pm_score": 0, "selected": false, "text": "<pre><code>'''\nOnly used if set your position as global\n'''\nposition #set global \n\ndef bst(array,taget): # just pass the array and target\n global position\n low = 0\n high = len(array)\n while low &lt;= high:\n mid = (lo+hi)//2\n if a[mid] == target:\n position = mid\n return -1\n elif a[mid] &lt; target: \n high = mid+1\n else:\n low = mid-1\n return -1\n</code></pre>\n\n<p>I guess this is much better and effective. please correct me :) . Thank you</p>\n" }, { "answer_id": 10578346, "author": "jdsantiagojr", "author_id": 817423, "author_profile": "https://Stackoverflow.com/users/817423", "pm_score": 2, "selected": false, "text": "<p>Check out the examples on Wikipedia <a href=\"http://en.wikipedia.org/wiki/Binary_search_algorithm\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Binary_search_algorithm</a></p>\n\n<pre><code>def binary_search(a, key, imin=0, imax=None):\n if imax is None:\n # if max amount not set, get the total\n imax = len(a) - 1\n\n while imin &lt;= imax:\n # calculate the midpoint\n mid = (imin + imax)//2\n midval = a[mid]\n\n # determine which subarray to search\n if midval &lt; key:\n # change min index to search upper subarray\n imin = mid + 1\n elif midval &gt; key:\n # change max index to search lower subarray\n imax = mid - 1\n else:\n # return index number \n return mid\n raise ValueError\n</code></pre>\n" }, { "answer_id": 18678361, "author": "Florent", "author_id": 1908102, "author_profile": "https://Stackoverflow.com/users/1908102", "pm_score": 2, "selected": false, "text": "<p>Dave Abrahams' solution is good. Although I have would have done it minimalistic:</p>\n\n<pre><code>def binary_search(L, x):\n i = bisect.bisect_left(L, x)\n if i == len(L) or L[i] != x:\n return -1\n return i\n</code></pre>\n" }, { "answer_id": 18681876, "author": "paulluap", "author_id": 2484194, "author_profile": "https://Stackoverflow.com/users/2484194", "pm_score": 3, "selected": false, "text": "<p>I agree that <a href=\"https://stackoverflow.com/a/2233940/2484194\">@DaveAbrahams's answer</a> using the bisect module is the correct approach. He did not mention one important detail in his answer.</p>\n\n<p>From the <a href=\"http://docs.python.org/2/library/bisect.html#searching-sorted-lists\" rel=\"nofollow noreferrer\">docs</a> <code>bisect.bisect_left(a, x, lo=0, hi=len(a))</code></p>\n\n<p>The bisection module does not require the search array to be precomputed ahead of time. You can just present the endpoints to the <code>bisect.bisect_left</code> instead of it using the defaults of <code>0</code> and <code>len(a)</code>.</p>\n\n<p>Even more important for my use, looking for a value X such that the error of a given function is minimized. To do that, I needed a way to have the bisect_left's algorithm call my computation instead. This is really simple.</p>\n\n<p>Just provide an object that defines <code>__getitem__</code> as <code>a</code></p>\n\n<p>For example, we could use the bisect algorithm to find a square root with arbitrary precision!</p>\n\n<pre><code>import bisect\n\nclass sqrt_array(object):\n def __init__(self, digits):\n self.precision = float(10**(digits))\n def __getitem__(self, key):\n return (key/self.precision)**2.0\n\nsa = sqrt_array(4)\n\n# \"search\" in the range of 0 to 10 with a \"precision\" of 0.0001\nindex = bisect.bisect_left(sa, 7, 0, 10*10**4)\nprint 7**0.5\nprint index/(10**4.0)\n</code></pre>\n" }, { "answer_id": 20007672, "author": "stephenfin", "author_id": 613428, "author_profile": "https://Stackoverflow.com/users/613428", "pm_score": 2, "selected": false, "text": "<p>While there's no explicit binary search algorithm in Python, there is a module - <code>bisect</code> - designed to find the insertion point for an element in a sorted list using a binary search. This can be \"tricked\" into performing a binary search. The biggest advantage of this is the same advantage most library code has - it's high-performing, well-tested and just works (binary searches in particular can be <a href=\"http://en.wikipedia.org/wiki/Binary_search_algorithm#Implementation_issues\" rel=\"nofollow\">quite difficult to implement successfully</a> - particularly if edge cases aren't carefully considered).</p>\n\n<h1>Basic Types</h1>\n\n<p>For basic types like Strings or ints it's pretty easy - all you need is the <code>bisect</code> module and a sorted list:</p>\n\n<pre><code>&gt;&gt;&gt; import bisect\n&gt;&gt;&gt; names = ['bender', 'fry', 'leela', 'nibbler', 'zoidberg']\n&gt;&gt;&gt; bisect.bisect_left(names, 'fry')\n1\n&gt;&gt;&gt; keyword = 'fry'\n&gt;&gt;&gt; x = bisect.bisect_left(names, keyword)\n&gt;&gt;&gt; names[x] == keyword\nTrue\n&gt;&gt;&gt; keyword = 'arnie'\n&gt;&gt;&gt; x = bisect.bisect_left(names, keyword)\n&gt;&gt;&gt; names[x] == keyword\nFalse\n</code></pre>\n\n<p>You can also use this to find duplicates:</p>\n\n<pre><code>...\n&gt;&gt;&gt; names = ['bender', 'fry', 'fry', 'fry', 'leela', 'nibbler', 'zoidberg']\n&gt;&gt;&gt; keyword = 'fry'\n&gt;&gt;&gt; leftIndex = bisect.bisect_left(names, keyword)\n&gt;&gt;&gt; rightIndex = bisect.bisect_right(names, keyword)\n&gt;&gt;&gt; names[leftIndex:rightIndex]\n['fry', 'fry', 'fry']\n</code></pre>\n\n<p>Obviously you could just return the index rather than the value at that index if desired.</p>\n\n<h1>Objects</h1>\n\n<p>For custom types or objects, things are a little bit trickier: you have to make sure to implement rich comparison methods to get bisect to compare correctly.</p>\n\n<pre><code>&gt;&gt;&gt; import bisect\n&gt;&gt;&gt; class Tag(object): # a simple wrapper around strings\n... def __init__(self, tag):\n... self.tag = tag\n... def __lt__(self, other):\n... return self.tag &lt; other.tag\n... def __gt__(self, other):\n... return self.tag &gt; other.tag\n...\n&gt;&gt;&gt; tags = [Tag('bender'), Tag('fry'), Tag('leela'), Tag('nibbler'), Tag('zoidbe\nrg')]\n&gt;&gt;&gt; key = Tag('fry')\n&gt;&gt;&gt; leftIndex = bisect.bisect_left(tags, key)\n&gt;&gt;&gt; rightIndex = bisect.bisect_right(tags, key)\n&gt;&gt;&gt; print([tag.tag for tag in tags[leftIndex:rightIndex]])\n['fry']\n</code></pre>\n\n<p>This should work in at least Python 2.7 -> 3.3</p>\n" }, { "answer_id": 20827948, "author": "arainchi", "author_id": 1730644, "author_profile": "https://Stackoverflow.com/users/1730644", "pm_score": 3, "selected": false, "text": "<p>This is right from the manual:</p>\n\n<p><a href=\"http://docs.python.org/2/library/bisect.html\">http://docs.python.org/2/library/bisect.html</a></p>\n\n<p>8.5.1. Searching Sorted Lists</p>\n\n<p>The above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists:</p>\n\n<pre><code>def index(a, x):\n 'Locate the leftmost value exactly equal to x'\n i = bisect_left(a, x)\n if i != len(a) and a[i] == x:\n return i\n raise ValueError\n</code></pre>\n\n<p>So with the slight modification your code should be:</p>\n\n<pre><code>def index(a, x):\n 'Locate the leftmost value exactly equal to x'\n i = bisect_left(a, x)\n if i != len(a) and a[i] == x:\n return i\n return -1\n</code></pre>\n" }, { "answer_id": 27843077, "author": "AV94", "author_id": 3721259, "author_profile": "https://Stackoverflow.com/users/3721259", "pm_score": 1, "selected": false, "text": "<ul>\n<li><code>s</code> is a list. </li>\n<li><code>binary(s, 0, len(s) - 1, find)</code> is the initial call.</li>\n<li><p>Function returns an index of the queried item. If there is no such item it returns <code>-1</code>.</p>\n\n<pre><code>def binary(s,p,q,find):\n if find==s[(p+q)/2]:\n return (p+q)/2\n elif p==q-1 or p==q:\n if find==s[q]:\n return q\n else:\n return -1\n elif find &lt; s[(p+q)/2]:\n return binary(s,p,(p+q)/2,find)\n elif find &gt; s[(p+q)/2]:\n return binary(s,(p+q)/2+1,q,find)\n</code></pre></li>\n</ul>\n" }, { "answer_id": 30385777, "author": "Mateusz Piotrowski", "author_id": 4694621, "author_profile": "https://Stackoverflow.com/users/4694621", "pm_score": 3, "selected": false, "text": "<p>This one is <strong>based on a mathematical assertion</strong> that <em>the floor of (low + high)/2</em> is always smaller than <em>high</em> where <em>low</em> is the lower limit and <em>high</em> is the upper limit.</p>\n<hr />\n<pre><code>def binsearch(t, key, low = 0, high = len(t) - 1):\n # bisecting the range\n while low &lt; high:\n mid = (low + high)//2\n if t[mid] &lt; key:\n low = mid + 1\n else:\n high = mid\n # at this point 'low' should point at the place\n # where the value of 'key' is possibly stored.\n return low if t[low] == key else -1\n</code></pre>\n" }, { "answer_id": 42416906, "author": "sonus21", "author_id": 4255107, "author_profile": "https://Stackoverflow.com/users/4255107", "pm_score": 0, "selected": false, "text": "<p>I needed binary search in python and generic for Django models. In Django models, one model can have foreign key to another model and I wanted to perform some search on the retrieved models objects. I wrote following function you can use this.</p>\n\n<pre><code>def binary_search(values, key, lo=0, hi=None, length=None, cmp=None):\n \"\"\"\n This is a binary search function which search for given key in values.\n This is very generic since values and key can be of different type.\n If they are of different type then caller must specify `cmp` function to\n perform a comparison between key and values' item.\n :param values: List of items in which key has to be search\n :param key: search key\n :param lo: start index to begin search\n :param hi: end index where search will be performed\n :param length: length of values\n :param cmp: a comparator function which can be used to compare key and values\n :return: -1 if key is not found else index\n \"\"\"\n assert type(values[0]) == type(key) or cmp, \"can't be compared\"\n assert not (hi and length), \"`hi`, `length` both can't be specified at the same time\"\n\n lo = lo\n if not lo:\n lo = 0\n if hi:\n hi = hi\n elif length:\n hi = length - 1\n else:\n hi = len(values) - 1\n\n while lo &lt;= hi:\n mid = lo + (hi - lo) // 2\n if not cmp:\n if values[mid] == key:\n return mid\n if values[mid] &lt; key:\n lo = mid + 1\n else:\n hi = mid - 1\n else:\n val = cmp(values[mid], key)\n # 0 -&gt; a == b\n # &gt; 0 -&gt; a &gt; b\n # &lt; 0 -&gt; a &lt; b\n if val == 0:\n return mid\n if val &lt; 0:\n lo = mid + 1\n else:\n hi = mid - 1\n return -1\n</code></pre>\n" }, { "answer_id": 44033742, "author": "user3412550", "author_id": 3412550, "author_profile": "https://Stackoverflow.com/users/3412550", "pm_score": 0, "selected": false, "text": "<pre><code>def binary_search_length_of_a_list(single_method_list):\n index = 0\n first = 0\n last = 1\n\n while True:\n mid = ((first + last) // 2)\n if not single_method_list.get(index):\n break\n index = mid + 1\n first = index\n last = index + 1\n return mid\n</code></pre>\n" }, { "answer_id": 44761213, "author": "Jitesh Mohite", "author_id": 5106574, "author_profile": "https://Stackoverflow.com/users/5106574", "pm_score": 0, "selected": false, "text": "<p><strong>Binary Search :</strong> </p>\n\n<pre><code>// List - values inside list\n// searchItem - Item to search\n// size - Size of list\n// upperBound - higher index of list\n// lowerBound - lower index of list\ndef binarySearch(list, searchItem, size, upperBound, lowerBound):\n print(list)\n print(upperBound)\n print(lowerBound)\n mid = ((upperBound + lowerBound)) // 2\n print(mid)\n if int(list[int(mid)]) == value:\n return \"value exist\"\n elif int(list[int(mid)]) &lt; value:\n return searchItem(list, value, size, upperBound, mid + 1)\n elif int(list[int(mid)]) &gt; value:\n return searchItem(list, value, size, mid - 1, lowerBound)\n</code></pre>\n\n<p>// To call above function use :</p>\n\n<pre><code>list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nsearchItem = 1 \nprint(searchItem(list[0], item, len(list[0]) -1, len(list[0]) - 1, 0))\n</code></pre>\n" }, { "answer_id": 49907291, "author": "Bob", "author_id": 9666157, "author_profile": "https://Stackoverflow.com/users/9666157", "pm_score": 0, "selected": false, "text": "<p>Many good solutions above but I haven't seen a simple (KISS keep it simple (cause I'm) stupid use of the Python built in/generic bisect function to do a binary search. With a bit of code around the bisect function, I think I have an example below where I have tested all cases for a small string array of names. Some of the above solutions allude to/say this, but hopefully the simple code below will help anyone confused like I was. </p>\n\n<p>Python bisect is used to indicate where to insert an a new value/search item into a sorted list. The below code which uses bisect_left which will return the index of the hit if the search item in the list/array is found (Note bisect and bisect_right will return the index of the element after the hit or match as the insertion point) If not found, bisect_left will return an index to the next item in the sorted list which will not == the search value. The only other case is where the search item would go at the end of the list where the index returned would be beyond the end of the list/array, and which in the code below the early exit by Python with \"and\" logic handles. (first condition False Python does not check subsequent conditions)</p>\n\n<pre><code>#Code\nfrom bisect import bisect_left\nnames=[\"Adam\",\"Donny\",\"Jalan\",\"Zach\",\"Zayed\"]\nsearch=\"\"\nlenNames = len(names)\nwhile search !=\"none\":\n search =input(\"Enter name to search for or 'none' to terminate program:\")\n if search == \"none\":\n break\n i = bisect_left(names,search)\n print(i) # show index returned by Python bisect_left\n if i &lt; (lenNames) and names[i] == search:\n print(names[i],\"found\") #return True - if function\n else:\n print(search,\"not found\") #return False – if function\n##Exhaustive test cases:\n##Enter name to search for or 'none' to terminate program:Zayed\n##4\n##Zayed found\n##Enter name to search for or 'none' to terminate program:Zach\n##3\n##Zach found\n##Enter name to search for or 'none' to terminate program:Jalan\n##2\n##Jalan found\n##Enter name to search for or 'none' to terminate program:Donny\n##1\n##Donny found\n##Enter name to search for or 'none' to terminate program:Adam\n##0\n##Adam found\n##Enter name to search for or 'none' to terminate program:Abie\n##0\n##Abie not found\n##Enter name to search for or 'none' to terminate program:Carla\n##1\n##Carla not found\n##Enter name to search for or 'none' to terminate program:Ed\n##2\n##Ed not found\n##Enter name to search for or 'none' to terminate program:Roger\n##3\n##Roger not found\n##Enter name to search for or 'none' to terminate program:Zap\n##4\n##Zap not found\n##Enter name to search for or 'none' to terminate program:Zyss\n##5\n##Zyss not found\n</code></pre>\n" }, { "answer_id": 66909852, "author": "me6", "author_id": 6150460, "author_profile": "https://Stackoverflow.com/users/6150460", "pm_score": 0, "selected": false, "text": "<p>Hello here is my python implementation without bisect. let me know if it can be improved.</p>\n<pre><code>def bisectLeft(a, t):\n lo = 0\n hi = len(a) - 1\n ans = None\n # print(&quot;------lower------&quot;)\n # print(a, t)\n while lo &lt;= hi:\n mid = (lo + hi) // 2\n # print(a[lo:mid], [a[mid]], a[mid:hi])\n if a[mid] &lt; t:\n lo = mid + 1\n elif a[mid] &gt; t:\n hi = mid - 1\n elif a[mid] == t:\n if mid == 0: return 0\n if a[mid-1] != t: return mid\n hi = mid - 1\n \n return ans\n\ndef bisectRight(a, t):\n lo = 0\n hi = len(a) - 1\n ans = None\n # print(&quot;------upper------&quot;)\n # print(a, t)\n while lo &lt;= hi:\n mid = (lo + hi) // 2\n # print(a[lo:mid], [a[mid]], a[mid:hi])\n if a[mid] == t:\n ans = mid\n if a[mid] &lt;= t:\n lo = mid + 1\n else:\n hi = mid - 1\n return ans\n\n</code></pre>\n" }, { "answer_id": 72413103, "author": "Raymond Hettinger", "author_id": 424499, "author_profile": "https://Stackoverflow.com/users/424499", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>I thought of using bisect_left and then checking if the item at that\nposition is equal to what I'm searching, but that seems cumbersome\n(and I also need to do bounds checking if the number can be larger\nthan the largest number in my list). If there is a nicer method I'd\nlike to know about it.</p>\n</blockquote>\n<p>One way to avoid bounds checks or the checking the item for equality is to run both <em>bisect_left()</em> and <em>bisect_right()</em>:</p>\n<pre><code>def find(data, target):\n start = bisect_left(data, target)\n end = bisect_right(data, target)\n return -1 if start == end else start\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15682/" ]
Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not? I found the functions bisect\_left/right in the [bisect module](http://docs.python.org/library/bisect.html), but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything). I thought of using `bisect_left` and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it. **Edit** To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list. Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements. I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.
`bisect_left` finds the first position `p` at which an element could be inserted in a given sorted range while maintaining the sorted order. That will be the position of `x` if `x` exists in the range. If `p` is the past-the-end position, `x` wasn't found. Otherwise, we can test to see if `x` is there to see if `x` was found. ```python from bisect import bisect_left def binary_search(a, x, lo=0, hi=None): if hi is None: hi = len(a) pos = bisect_left(a, x, lo, hi) # find insertion position return pos if pos != hi and a[pos] == x else -1 # don't walk off the end ```
212,378
<p>I have an embedded webserver that has a total of 2 Megs of space on it. Normally you gzip files for the clients benefit, but this would save us space on the server. I read that you can just gzip the js file and save it on the server. I tested that on IIS and I didn't have any luck at all. What exactly do I need to do on every step of the process to make this work?</p> <p>This is what I imagine it will be like:</p> <ol> <li>gzip foo.js</li> <li>change link in html to point to foo.js.gz instead of just .js</li> <li>Add some kind of header to the response?</li> </ol> <p>Thanks for any help at all.</p> <p>-fREW</p> <p><strong>EDIT</strong>: My webserver can't do anything on the fly. It's not Apache or IIS; it's a binary on a ZiLog processor. I know that you can compress streams; I just heard that you can also compress the files once and leave them compressed.</p>
[ { "answer_id": 212402, "author": "Dave R", "author_id": 6969, "author_profile": "https://Stackoverflow.com/users/6969", "pm_score": 1, "selected": false, "text": "<p>Using gzip compression on a webserver usually means compressing the output from it to conserve your bandwidth - not quite what you have in mind.</p>\n\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/25d2170b-09c0-45fd-8da4-898cf9a7d568.mspx?mfr=true\" rel=\"nofollow noreferrer\">Look at this description</a>\nor\n<a href=\"http://www.keylimetie.com/Blog/2008/5/20/How-to-enable-HTTP-Compression-on-Windows-Server-2003/\" rel=\"nofollow noreferrer\">This example</a></p>\n" }, { "answer_id": 212555, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 1, "selected": false, "text": "<p>If you're using Apache, you use <a href=\"http://httpd.apache.org/docs/2.0/mod/mod_deflate.html\" rel=\"nofollow noreferrer\">mod_deflate</a>, and it compresses on the fly.</p>\n\n<p>I think you're getting confused by thinking that if you gzip something it has to be a file. Instead, think about how a file is just a stream of data, and that stream of data can get compressed here, transmitted, and uncompressed there without the client having to even think about it.</p>\n" }, { "answer_id": 212684, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 4, "selected": true, "text": "<p>As others have mentioned mod_deflate does that for you, but I guess you need to do it manually since it is an embedded environment.</p>\n\n<p>First of all you should leave the name of the file foo.js after you gzip it. </p>\n\n<p>You should not change anything in your html files. Since the file is still foo.js </p>\n\n<p>In the response header of (the gzipped) foo.js you send the header</p>\n\n<pre><code>Content-Encoding: gzip\n</code></pre>\n\n<p>This should do the trick. The client asks for foo.js and receives Content-Encoding: gzip followed by the gzipped file, which it automatically ungzips before parsing.</p>\n\n<p>Of course this assumes your are sure the client understands gzip encoding, if you are not sure, you should only send gzipped data when the request header contains</p>\n\n<pre><code>Accept-Encoding: gzip\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
I have an embedded webserver that has a total of 2 Megs of space on it. Normally you gzip files for the clients benefit, but this would save us space on the server. I read that you can just gzip the js file and save it on the server. I tested that on IIS and I didn't have any luck at all. What exactly do I need to do on every step of the process to make this work? This is what I imagine it will be like: 1. gzip foo.js 2. change link in html to point to foo.js.gz instead of just .js 3. Add some kind of header to the response? Thanks for any help at all. -fREW **EDIT**: My webserver can't do anything on the fly. It's not Apache or IIS; it's a binary on a ZiLog processor. I know that you can compress streams; I just heard that you can also compress the files once and leave them compressed.
As others have mentioned mod\_deflate does that for you, but I guess you need to do it manually since it is an embedded environment. First of all you should leave the name of the file foo.js after you gzip it. You should not change anything in your html files. Since the file is still foo.js In the response header of (the gzipped) foo.js you send the header ``` Content-Encoding: gzip ``` This should do the trick. The client asks for foo.js and receives Content-Encoding: gzip followed by the gzipped file, which it automatically ungzips before parsing. Of course this assumes your are sure the client understands gzip encoding, if you are not sure, you should only send gzipped data when the request header contains ``` Accept-Encoding: gzip ```
212,381
<p>I am trying to create a multi dimensional array using this syntax:</p> <pre><code>$x[1] = 'parent'; $x[1][] = 'child'; </code></pre> <p>I get the error: <code>[] operator not supported for strings</code> because it is evaluating the <code>$x[1]</code> as a string as opposed to returning the array so I can append to it.</p> <p>What is the correct syntax for doing it this way? The overall goal is to create this multidimensional array in an iteration that will append elements to a known index.</p> <p>The syntax <code>${$x[1]}[]</code> does not work either.</p>
[ { "answer_id": 212396, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 3, "selected": false, "text": "<pre><code>$x = array();\n$x[1] = array();\n$x[1][] = 'child';\n</code></pre>\n" }, { "answer_id": 212399, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 6, "selected": true, "text": "<p>The parent has to be an array!</p>\n\n<pre><code>$x[1] = array();\n$x[1][] = 'child';\n</code></pre>\n" }, { "answer_id": 216358, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 1, "selected": false, "text": "<p>I think what you want to do is to use $x['parent'] in the end, isn't it ?</p>\n\n<p>So it's not exactly $x = array() but more something like :</p>\n\n<pre><code>$x = array('parent' =&gt; array());\n$x['parent'][] = 'child';\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to create a multi dimensional array using this syntax: ``` $x[1] = 'parent'; $x[1][] = 'child'; ``` I get the error: `[] operator not supported for strings` because it is evaluating the `$x[1]` as a string as opposed to returning the array so I can append to it. What is the correct syntax for doing it this way? The overall goal is to create this multidimensional array in an iteration that will append elements to a known index. The syntax `${$x[1]}[]` does not work either.
The parent has to be an array! ``` $x[1] = array(); $x[1][] = 'child'; ```
212,401
<p>From Wikipedia, the free encyclopedia: <strong>Closure (computer science)</strong></p> <blockquote> <p>In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables. The explicit use of closures is associated with functional programming and with languages such as ML and Lisp. Constructs such as objects in other languages can also be modeled with closures.</p> </blockquote> <p>To use this inside of JavaScript, can someone point me to an example of how this applies?</p>
[ { "answer_id": 212417, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>Searching for \"javascript closures\" gave plenty of encouraging-looking links. The top three were these two (the third link was a reformatted version of the second):</p>\n\n<ul>\n<li><a href=\"http://www.jibbering.com/faq/faq_notes/closures.html\" rel=\"nofollow noreferrer\">Javascript closures</a></li>\n<li><a href=\"http://web.archive.org/web/20101113013100/http://blog.morrisjohns.com/javascript_closures_for_dummies.html\" rel=\"nofollow noreferrer\">JavaScript closures for dummies</a></li>\n</ul>\n\n<p>If these didn't help you, please explain why so we're in a better position to actually help. If you didn't search before asking the question, well - please do so next time :)</p>\n" }, { "answer_id": 212431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>(using an example from jQuery)</p>\n\n<pre><code>function SetClassOnHover(className){\n $(\"td\").hover(\n function () {\n $(this).addClass(className);\n },\n function () {\n $(this).removeClass(className);\n }\n );\n}\n</code></pre>\n\n<p>The closure comes into play when the variable className is used inside the scope of each function. When SetClassOnHover exits, both functions must retain a handle on className in order to access its value when the functions are called. That's what the closure enables.</p>\n" }, { "answer_id": 5084991, "author": "invisible bob", "author_id": 462266, "author_profile": "https://Stackoverflow.com/users/462266", "pm_score": 1, "selected": false, "text": "<p>A practical example of closures is when they are used to create \"Private\" variables, like</p>\n\n<pre><code>function incrementer(){\n var i=0;\n this.increment=function(){\n i++;\n }\n this.get=function(){\n return i;\n }\n}\n</code></pre>\n\n<p>The only way to access i is to use the method get, and the only way to change it is to use the method increment. In classes, you can do this to emulate private variables.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From Wikipedia, the free encyclopedia: **Closure (computer science)** > > In computer science, a closure is a > function that is evaluated in an > environment containing one or more > bound variables. When called, the > function can access these variables. > The explicit use of closures is > associated with functional programming > and with languages such as ML and > Lisp. Constructs such as objects in > other languages can also be modeled > with closures. > > > To use this inside of JavaScript, can someone point me to an example of how this applies?
(using an example from jQuery) ``` function SetClassOnHover(className){ $("td").hover( function () { $(this).addClass(className); }, function () { $(this).removeClass(className); } ); } ``` The closure comes into play when the variable className is used inside the scope of each function. When SetClassOnHover exits, both functions must retain a handle on className in order to access its value when the functions are called. That's what the closure enables.
212,407
<p>Is the singleton class in Ruby a class in and of itself? Is it the reason why all objects belong to "class?" The concept is <strong>fuzzy</strong>, but I believe it has something to do with why I can define a class method at all (<code>class foo; def foo.bar ...</code>).</p> <p>What is the singleton class in Ruby?</p>
[ { "answer_id": 212924, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 2, "selected": false, "text": "<p>The most pragmatic/action-oreinted way to think of it (IMHO) is: as an inheritance chain, or method lookup/resolution order. This picture might help</p>\n\n<p><a href=\"http://www.klankboomklang.com/2007/11/25/modules-part-i-enter-the-include-class/\" rel=\"nofollow noreferrer\">http://www.klankboomklang.com/2007/11/25/modules-part-i-enter-the-include-class/</a></p>\n\n<p>This is r 1.9, contrasting builtin and user-defined classes: i'm still digesting this one.</p>\n\n<p><a href=\"http://d.hatena.ne.jp/sumim/20080111/p1\" rel=\"nofollow noreferrer\">http://d.hatena.ne.jp/sumim/20080111/p1</a></p>\n\n<p>Also, i htink a confusing use of the term is \"Singleton object\", which is different concept. A singleton object comes from a class which has its constructor/instantiator method overridden so that you can allocate only one of that class.</p>\n" }, { "answer_id": 213177, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 8, "selected": true, "text": "<p>First, a little definition: a <strong>singleton method</strong> is a method that is defined only for a single object. Example:</p>\n\n<pre><code>irb(main):001:0&gt; class Foo; def method1; puts 1; end; end\n=&gt; nil\nirb(main):002:0&gt; foo = Foo.new\n=&gt; #&lt;Foo:0xb79fa724&gt;\nirb(main):003:0&gt; def foo.method2; puts 2; end\n=&gt; nil\nirb(main):004:0&gt; foo.method1\n1\n=&gt; nil\nirb(main):005:0&gt; foo.method2\n2\n=&gt; nil\nirb(main):006:0&gt; other_foo = Foo.new\n=&gt; #&lt;Foo:0xb79f0ef4&gt;\nirb(main):007:0&gt; other_foo.method1\n1\n=&gt; nil\nirb(main):008:0&gt; other_foo.method2\nNoMethodError: undefined method `method2' for #&lt;Foo:0xb79f0ef4&gt;\n from (irb):8\n</code></pre>\n\n<p>Instance methods are methods of a class (i.e. defined in the class's definition). Class methods are singleton methods on the <code>Class</code> instance of a class -- they are not defined in the class's definition. Instead, they are defined on the <strong>singleton class</strong> of the object.</p>\n\n<pre><code>irb(main):009:0&gt; Foo.method_defined? :method1\n=&gt; true\nirb(main):010:0&gt; Foo.method_defined? :method2\n=&gt; false\n</code></pre>\n\n<p>You open the singleton class of an object with the syntax <code>class &lt;&lt; obj</code>. Here, we see that this singleton class is where the singleton methods are defined:</p>\n\n<pre><code>irb(main):012:0&gt; singleton_class = ( class &lt;&lt; foo; self; end )\n=&gt; #&lt;Class:#&lt;Foo:0xb79fa724&gt;&gt;\nirb(main):013:0&gt; singleton_class.method_defined? :method1\n=&gt; true\nirb(main):014:0&gt; singleton_class.method_defined? :method2\n=&gt; true\nirb(main):015:0&gt; other_singleton_class = ( class &lt;&lt; other_foo; self; end )\n=&gt; #&lt;Class:#&lt;Foo:0xb79f0ef4&gt;&gt;\nirb(main):016:0&gt; other_singleton_class.method_defined? :method1\n=&gt; true\nirb(main):017:0&gt; other_singleton_class.method_defined? :method2\n=&gt; false\n</code></pre>\n\n<p>So an alternative means of adding singleton methods to an object would be to define them with the object's singleton class open:</p>\n\n<pre><code>irb(main):018:0&gt; class &lt;&lt; foo; def method3; puts 3; end; end\n=&gt; nil\nirb(main):019:0&gt; foo.method3\n3\n=&gt; nil\nirb(main):022:0&gt; Foo.method_defined? :method3\n=&gt; false\n</code></pre>\n\n<p>In summary:</p>\n\n<ul>\n<li>methods must always belong to a class (or: be instance methods of some class)</li>\n<li>normal methods belong to the class they're defined in (i.e. are instance methods of the class)</li>\n<li>class methods are just singleton methods of a <code>Class</code></li>\n<li>singleton methods of an object are not instance methods of the class of the object; rather, they are instance methods of the singleton class of the object.</li>\n</ul>\n" }, { "answer_id": 8932711, "author": "Bedasso", "author_id": 325589, "author_profile": "https://Stackoverflow.com/users/325589", "pm_score": 5, "selected": false, "text": "<p>Ruby provides a way to define methods that are specific to a particular object and such methods are known as Singleton Methods. When one declares a singleton method on an object, Ruby automatically creates a class to hold just the singleton methods. The newly created class is called Singleton Class. \n<pre><code>\n foo = Array.new\n def foo.size\n \"Hello World!\"\n end\n foo.size # => \"Hello World!\"\n foo.class # => Array\n #Create another instance of Array Class and call size method on it\n bar = Array.new\n bar.size # => 0\n</pre></code>\nSingleton class is object specific anonymous class that is automatically created and inserted into the inheritance hierarchy. </p>\n\n<p><code>singleton_methods</code> can be called on an object to get the list of of names for all of the singleton methods on an object.</p>\n\n<pre><code> foo.singleton_methods # =&gt; [:size]\n bar.singleton_methods # =&gt; []\n</code></pre>\n\n<p>This <a href=\"http://www.devalot.com/articles/2008/09/ruby-singleton\">article</a> really helped me to understand Singleton Classes in Ruby and it has a good code example. </p>\n" }, { "answer_id": 46916846, "author": "Piotr Galas", "author_id": 2482094, "author_profile": "https://Stackoverflow.com/users/2482094", "pm_score": 3, "selected": false, "text": "<p>As just update to @Pistos answer, from version 1.9.2 ruby add new syntax to getting singleton class </p>\n\n<pre><code> singleton_class = ( class &lt;&lt; foo; self; end )\n</code></pre>\n\n<p>can be replaced with:</p>\n\n<pre><code>singleton_class = foo.singleton_class\n</code></pre>\n\n<p><a href=\"https://apidock.com/ruby/Object/singleton_class\" rel=\"noreferrer\">https://apidock.com/ruby/Object/singleton_class</a></p>\n" }, { "answer_id": 60468299, "author": "Paa Yaw", "author_id": 5552374, "author_profile": "https://Stackoverflow.com/users/5552374", "pm_score": 2, "selected": false, "text": "<p>A singleton class in the simplest terms is a special class ruby whips up to host methods defined on individual objects. In ruby, it is possible to define methods on individual objects that are unique to that object alone. For instance consider the following below</p>\n\n<pre><code>class User; end\nuser = User.new\ndef user.age\n \"i'm a unique method\"\nend\nuser1 = User.new \nuser.age #\"i'm a unique method\"\nuser1.age # NoMethodError (undefined method `age' for #&lt;User:0x0000559c66ab7338&gt;)\n</code></pre>\n\n<p>As you can see above, user1 object does not respond to the 'age' method because it is a singleton method, a method uniquely defined on user object. For this to happen, ruby creates a special class, called singleton class, or eigenclass, to host this unique method. You can verify this by doing the following:</p>\n\n<pre><code>user.singleton_class # #&lt;Class:#&lt;User:0x0000559c66b47c58&gt;&gt;\n</code></pre>\n\n<p>You can also ask ruby whether the 'age' method is found here by using the method object to find out where the method 'age' is defined. When you do this you will see that singleton class has that method.</p>\n\n<pre><code>user_singleton_class = user.method(:age).owner # #&lt;Class:#&lt;User:0x0000559c66b47c58&gt;&gt;\nuser.method(:age).owner == user.singleton_class # true\nuser_singleton_class.instance_methods(false) # [:age]\n</code></pre>\n\n<p>Also note that, as far a singleton class goes, singleton methods are actually it's instance methods.</p>\n\n<pre><code>user.singleton_methods == user_singleton_class.instance_methods(false) # true\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28914/" ]
Is the singleton class in Ruby a class in and of itself? Is it the reason why all objects belong to "class?" The concept is **fuzzy**, but I believe it has something to do with why I can define a class method at all (`class foo; def foo.bar ...`). What is the singleton class in Ruby?
First, a little definition: a **singleton method** is a method that is defined only for a single object. Example: ``` irb(main):001:0> class Foo; def method1; puts 1; end; end => nil irb(main):002:0> foo = Foo.new => #<Foo:0xb79fa724> irb(main):003:0> def foo.method2; puts 2; end => nil irb(main):004:0> foo.method1 1 => nil irb(main):005:0> foo.method2 2 => nil irb(main):006:0> other_foo = Foo.new => #<Foo:0xb79f0ef4> irb(main):007:0> other_foo.method1 1 => nil irb(main):008:0> other_foo.method2 NoMethodError: undefined method `method2' for #<Foo:0xb79f0ef4> from (irb):8 ``` Instance methods are methods of a class (i.e. defined in the class's definition). Class methods are singleton methods on the `Class` instance of a class -- they are not defined in the class's definition. Instead, they are defined on the **singleton class** of the object. ``` irb(main):009:0> Foo.method_defined? :method1 => true irb(main):010:0> Foo.method_defined? :method2 => false ``` You open the singleton class of an object with the syntax `class << obj`. Here, we see that this singleton class is where the singleton methods are defined: ``` irb(main):012:0> singleton_class = ( class << foo; self; end ) => #<Class:#<Foo:0xb79fa724>> irb(main):013:0> singleton_class.method_defined? :method1 => true irb(main):014:0> singleton_class.method_defined? :method2 => true irb(main):015:0> other_singleton_class = ( class << other_foo; self; end ) => #<Class:#<Foo:0xb79f0ef4>> irb(main):016:0> other_singleton_class.method_defined? :method1 => true irb(main):017:0> other_singleton_class.method_defined? :method2 => false ``` So an alternative means of adding singleton methods to an object would be to define them with the object's singleton class open: ``` irb(main):018:0> class << foo; def method3; puts 3; end; end => nil irb(main):019:0> foo.method3 3 => nil irb(main):022:0> Foo.method_defined? :method3 => false ``` In summary: * methods must always belong to a class (or: be instance methods of some class) * normal methods belong to the class they're defined in (i.e. are instance methods of the class) * class methods are just singleton methods of a `Class` * singleton methods of an object are not instance methods of the class of the object; rather, they are instance methods of the singleton class of the object.
212,425
<p>How can I go about making my routes recognise an optional prefix parameter as follows:</p> <pre><code>/*lang/controller/id </code></pre> <p>In that the lang part is optional, and has a default value if it's not specified in the URL:</p> <pre><code>/en/posts/1 =&gt; lang = en /fr/posts/1 =&gt; lang = fr /posts/1 =&gt; lang = en </code></pre> <p><em>EDIT</em></p> <p>Ideally, I'm looking to do this across many controllers and actions by mapping a namespace:</p> <pre><code>map.namespace "*lang" do |lang| lang.resources :posts lang.resources :stories end </code></pre>
[ { "answer_id": 212895, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 1, "selected": false, "text": "<p>I'm guessing (no time to test right now) that this might work:</p>\n\n<pre><code>map.connect ':language/posts/:id', :controller =&gt; 'posts', :action =&gt; 'show'\nmap.connect 'posts/:id', :controller =&gt; 'posts', :action =&gt; 'show'\n</code></pre>\n\n<p>OK, tried it - it works, on Rails 2.1.1 at least. So that's good. Can't get the :defaults idea to work, though, which is a shame, because it's DRYer.</p>\n" }, { "answer_id": 213111, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": "<p>You can define defaults in a route using the <code>:defaults</code> key. Try this:</p>\n\n<pre><code>map.connect ':lang/posts/:id', :controller =&gt; 'posts', :action =&gt; 'show',\n :defaults =&gt; { :lang =&gt; 'en' }\n</code></pre>\n" }, { "answer_id": 213865, "author": "Collin", "author_id": 29104, "author_profile": "https://Stackoverflow.com/users/29104", "pm_score": 1, "selected": false, "text": "<p>Thought you could at one time use a [key] => nil to specify an optional parameter. Something like:</p>\n\n<pre><code>map.connect ':lang/posts/:id', :controller =&gt; 'posts', :action =&gt; 'show', :lang =&gt; nil\n</code></pre>\n" }, { "answer_id": 221125, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 5, "selected": true, "text": "<p>OK, I've managed to sort out this problem:</p>\n\n<p>THere is no way of doing this in Rails by default (at least, not yet). Instead of using namespaces and default values, I needed to install <a href=\"http://github.com/svenfuchs/routing-filter/tree/master\" rel=\"noreferrer\">Sven Fuchs' routing filter</a>.</p>\n\n<p>Once the plugin is installed, I added the following file to my lib directory:</p>\n\n<pre><code>require 'routing_filter/base'\n\nmodule RoutingFilter\n class Locale &lt; Base\n\n # remove the locale from the beginning of the path, pass the path\n # to the given block and set it to the resulting params hash\n def around_recognize(path, env, &amp;block)\n locale = nil\n path.sub! %r(^/([a-zA-Z]{2})(?=/|$)) do locale = $1; '' end\n returning yield do |params|\n params[:locale] = locale || 'en'\n end\n end\n\n def around_generate(*args, &amp;block)\n locale = args.extract_options!.delete(:locale) || 'en'\n returning yield do |result|\n if locale != 'en'\n result.sub!(%r(^(http.?://[^/]*)?(.*))){ \"#{$1}/#{locale}#{$2}\" }\n end \n end\n end\n\n end\nend\n</code></pre>\n\n<p>I added this line to routes.rb:</p>\n\n<pre><code>map.filter 'locale'\n</code></pre>\n\n<p>This basically fills out a before and after hook, generated by the plugin, that wraps the rails routing. </p>\n\n<p>When a url is recognised, and before Rails gets to do anything with it, the around_recognize method is called. This will extract a two-letter code representing the locale, and pass it through in the params, defaulting to 'en' if no locale is specified.</p>\n\n<p>Likewise, when a url is generated, the locale parameter will be pushed into the URL on the left side.</p>\n\n<p>This gives me the following urls and mappings:</p>\n\n<pre><code>/ =&gt; :locale =&gt; 'en'\n/en =&gt; :locale =&gt; 'en'\n/fr =&gt; :locale =&gt; 'fr'\n</code></pre>\n\n<p>All existing url helpers work as before, with the only difference being that unless the locale is specified, it is preserved:</p>\n\n<pre><code>home_path =&gt; /\nhome_path(:locale =&gt; 'en') =&gt; /\nhome_path(:locale =&gt; 'fr') =&gt; /fr\n</code></pre>\n" }, { "answer_id": 2167394, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I understand that this old question, but it may be useful.</p>\n\n<pre><code> map.with_options(:path_prefix =&gt; \":locale\") do |m|\n m.resources :posts\n m.resources :stories \n end\n</code></pre>\n\n<p>And you have to add before filter to application controller to define locale, such as </p>\n\n<pre><code>before_filter :define_locale\n\ndef define_locale\n if params[:locale] == nil\n I18n.locale = 'en'\n else\n I18n.locale = params[:locale]\n end\nend\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12037/" ]
How can I go about making my routes recognise an optional prefix parameter as follows: ``` /*lang/controller/id ``` In that the lang part is optional, and has a default value if it's not specified in the URL: ``` /en/posts/1 => lang = en /fr/posts/1 => lang = fr /posts/1 => lang = en ``` *EDIT* Ideally, I'm looking to do this across many controllers and actions by mapping a namespace: ``` map.namespace "*lang" do |lang| lang.resources :posts lang.resources :stories end ```
OK, I've managed to sort out this problem: THere is no way of doing this in Rails by default (at least, not yet). Instead of using namespaces and default values, I needed to install [Sven Fuchs' routing filter](http://github.com/svenfuchs/routing-filter/tree/master). Once the plugin is installed, I added the following file to my lib directory: ``` require 'routing_filter/base' module RoutingFilter class Locale < Base # remove the locale from the beginning of the path, pass the path # to the given block and set it to the resulting params hash def around_recognize(path, env, &block) locale = nil path.sub! %r(^/([a-zA-Z]{2})(?=/|$)) do locale = $1; '' end returning yield do |params| params[:locale] = locale || 'en' end end def around_generate(*args, &block) locale = args.extract_options!.delete(:locale) || 'en' returning yield do |result| if locale != 'en' result.sub!(%r(^(http.?://[^/]*)?(.*))){ "#{$1}/#{locale}#{$2}" } end end end end end ``` I added this line to routes.rb: ``` map.filter 'locale' ``` This basically fills out a before and after hook, generated by the plugin, that wraps the rails routing. When a url is recognised, and before Rails gets to do anything with it, the around\_recognize method is called. This will extract a two-letter code representing the locale, and pass it through in the params, defaulting to 'en' if no locale is specified. Likewise, when a url is generated, the locale parameter will be pushed into the URL on the left side. This gives me the following urls and mappings: ``` / => :locale => 'en' /en => :locale => 'en' /fr => :locale => 'fr' ``` All existing url helpers work as before, with the only difference being that unless the locale is specified, it is preserved: ``` home_path => / home_path(:locale => 'en') => / home_path(:locale => 'fr') => /fr ```
212,429
<p>Scenario:</p> <p>I'm currently writing a layer to abstract 3 similar webservices into one useable class. Each webservice exposes a set of objects that share commonality. I have created a set of intermediary objects which exploit the commonality. However in my layer I need to convert between the web service objects and my objects.</p> <p>I've used reflection to create the appropriate type at run time before I make the call to the web service like so:</p> <pre><code> public static object[] CreateProperties(Type type, IProperty[] properties) { //Empty so return null if (properties==null || properties.Length == 0) return null; //Check the type is allowed CheckPropertyTypes("CreateProperties(Type,IProperty[])",type); //Convert the array of intermediary IProperty objects into // the passed service type e.g. Service1.Property object[] result = new object[properties.Length]; for (int i = 0; i &lt; properties.Length; i++) { IProperty fromProp = properties[i]; object toProp = ReflectionUtility.CreateInstance(type, null); ServiceUtils.CopyProperties(fromProp, toProp); result[i] = toProp; } return result; } </code></pre> <p>Here's my calling code, from one of my service implementations:</p> <pre><code>Property[] props = (Property[])ObjectFactory.CreateProperties(typeof(Property), properties); _service.SetProperties(folderItem.Path, props); </code></pre> <p>So each service exposes a different "Property" object which I hide behind my own implementation of my IProperty interface.</p> <p>The reflection code works in unit tests producing an array of objects whose elements are of the appropriate type. But the calling code fails:</p> <blockquote> <p>System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'MyProject.Property[]</p> </blockquote> <p>Any ideas?</p> <p>I was under the impression that any cast from Object will work as long as the contained object is convertable?</p>
[ { "answer_id": 212437, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>You can't convert an array like that - it's returning an array of objects, which is different from an object. Try <a href=\"http://msdn.microsoft.com/en-us/library/exc45z53.aspx\" rel=\"nofollow noreferrer\">Array.ConvertAll</a></p>\n" }, { "answer_id": 212439, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "<p>That's correct, but that doesn't mean that you can cast containers of type Object to containers of other types. An Object[] is not the same thing as an Object (though you, strangely, could cast Object[] to Object).</p>\n" }, { "answer_id": 212443, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>Basically, no. There are a few, limited, uses of array covariance, but it is better to simply know which type of array you want. There is a generic Array.ConvertAll that is easy enough (at least, it is easier with C# 3.0):</p>\n\n<pre><code>Property[] props = Array.ConvertAll(source, prop =&gt; (Property)prop);\n</code></pre>\n\n<p>The C# 2.0 version (identical in meaning) is much less eyeball-friendly:</p>\n\n<pre><code> Property[] props = Array.ConvertAll&lt;object,Property&gt;(\n source, delegate(object prop) { return (Property)prop; });\n</code></pre>\n\n<p>Or just create a new Property[] of the right size and copy manually (or via <code>Array.Copy</code>).</p>\n\n<p>As an example of the things you <em>can</em> do with array covariance:</p>\n\n<pre><code>Property[] props = new Property[2];\nprops[0] = new Property();\nprops[1] = new Property();\n\nobject[] asObj = (object[])props;\n</code></pre>\n\n<p>Here, \"asObj\" is <em>still</em> a <code>Property[]</code> - it it simply accessible as <code>object[]</code>. In C# 2.0 and above, generics usually make a better option than array covariance.</p>\n" }, { "answer_id": 212447, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>As others have said, the array has to be of the right type to start with. The other answers have shown how to convert a genuine object[] after the fact, but you can create the right kind of array to start with using <a href=\"http://msdn.microsoft.com/en-us/library/system.array.createinstance.aspx\" rel=\"noreferrer\">Array.CreateInstance</a>:</p>\n\n<pre><code>object[] result = (object[]) Array.CreateInstance(type, properties.Length);\n</code></pre>\n\n<p>Assuming <code>type</code> is a reference type, this should work - the array will be of the correct type, but you'll use it as an <code>object[]</code> just to populate it.</p>\n" }, { "answer_id": 212512, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>Alternative answer: generics.</p>\n\n<pre><code>public static T[] CreateProperties&lt;T&gt;(IProperty[] properties)\n where T : class, new()\n{\n //Empty so return null\n if (properties==null || properties.Length == 0)\n return null;\n\n //Check the type is allowed\n CheckPropertyTypes(\"CreateProperties(Type,IProperty[])\",typeof(T));\n\n //Convert the array of intermediary IProperty objects into\n // the passed service type e.g. Service1.Property\n T[] result = new T[properties.Length];\n for (int i = 0; i &lt; properties.Length; i++)\n {\n T[i] = new T();\n ServiceUtils.CopyProperties(properties[i], t[i]);\n }\n return result;\n}\n</code></pre>\n\n<p>Then your calling code becomes:</p>\n\n<pre><code>Property[] props = ObjectFactory.CreateProperties&lt;Property&gt;(properties);\n_service.SetProperties(folderItem.Path, props);\n</code></pre>\n\n<p>Much cleaner :)</p>\n" }, { "answer_id": 3291110, "author": "Mr. Graves", "author_id": 171518, "author_profile": "https://Stackoverflow.com/users/171518", "pm_score": 1, "selected": false, "text": "<p>in C# 2.0 you <em>can</em> do this using reflection, without using generics and without knowing the desired type at compile time. </p>\n\n<pre><code>//get the data from the object factory\nobject[] newDataArray = AppObjectFactory.BuildInstances(Type.GetType(\"OutputData\"));\nif (newDataArray != null)\n{\n SomeComplexObject result = new SomeComplexObject();\n //find the source\n Type resultTypeRef = result.GetType();\n //get a reference to the property\n PropertyInfo pi = resultTypeRef.GetProperty(\"TargetPropertyName\");\n if (pi != null)\n {\n //create an array of the correct type with the correct number of items\n pi.SetValue(result, Array.CreateInstance(Type.GetType(\"OutputData\"), newDataArray.Length), null);\n //copy the data and leverage Array.Copy's built in type casting\n Array.Copy(newDataArray, pi.GetValue(result, null) as Array, newDataArray.Length);\n }\n}\n</code></pre>\n\n<p>You would want to replace all the Type.GetType(\"OutputData\") calls and the GetProperty(\"PropertyName\") with some code that reads from a config file. </p>\n\n<p>I would also use a generic to dictate the creation of SomeComplexObject </p>\n\n<pre><code>T result = new T();\nType resultTypeRef = result.GetType();\n</code></pre>\n\n<p>But I said you didn't need to use generics.</p>\n\n<p>No guarantees on performance/efficiency, but it does work.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950/" ]
Scenario: I'm currently writing a layer to abstract 3 similar webservices into one useable class. Each webservice exposes a set of objects that share commonality. I have created a set of intermediary objects which exploit the commonality. However in my layer I need to convert between the web service objects and my objects. I've used reflection to create the appropriate type at run time before I make the call to the web service like so: ``` public static object[] CreateProperties(Type type, IProperty[] properties) { //Empty so return null if (properties==null || properties.Length == 0) return null; //Check the type is allowed CheckPropertyTypes("CreateProperties(Type,IProperty[])",type); //Convert the array of intermediary IProperty objects into // the passed service type e.g. Service1.Property object[] result = new object[properties.Length]; for (int i = 0; i < properties.Length; i++) { IProperty fromProp = properties[i]; object toProp = ReflectionUtility.CreateInstance(type, null); ServiceUtils.CopyProperties(fromProp, toProp); result[i] = toProp; } return result; } ``` Here's my calling code, from one of my service implementations: ``` Property[] props = (Property[])ObjectFactory.CreateProperties(typeof(Property), properties); _service.SetProperties(folderItem.Path, props); ``` So each service exposes a different "Property" object which I hide behind my own implementation of my IProperty interface. The reflection code works in unit tests producing an array of objects whose elements are of the appropriate type. But the calling code fails: > > System.InvalidCastException: Unable to > cast object of type 'System.Object[]' > to type > 'MyProject.Property[] > > > Any ideas? I was under the impression that any cast from Object will work as long as the contained object is convertable?
Alternative answer: generics. ``` public static T[] CreateProperties<T>(IProperty[] properties) where T : class, new() { //Empty so return null if (properties==null || properties.Length == 0) return null; //Check the type is allowed CheckPropertyTypes("CreateProperties(Type,IProperty[])",typeof(T)); //Convert the array of intermediary IProperty objects into // the passed service type e.g. Service1.Property T[] result = new T[properties.Length]; for (int i = 0; i < properties.Length; i++) { T[i] = new T(); ServiceUtils.CopyProperties(properties[i], t[i]); } return result; } ``` Then your calling code becomes: ``` Property[] props = ObjectFactory.CreateProperties<Property>(properties); _service.SetProperties(folderItem.Path, props); ``` Much cleaner :)
212,434
<p>As the title states, is there a way to prevent extra elements from showing up in VBA dynamic arrays when they are non-zero based? </p> <p>For example, when using code similar to the following:</p> <pre><code>While Cells(ndx, 1).Value &lt;&gt; vbNullString ReDim Preserve data(1 To (UBound(data) + 1)) ndx = ndx + 1 Wend </code></pre> <p>You have an extra empty array element at the end of processing. While this can be eliminated with the following:</p> <pre><code>ReDim Preserve data(1 To (UBound(data) - 1)) </code></pre> <p>This doesn't seem like the best way of resolving this problem. </p> <p>As such, is there a way to prevent that extra element from being created in the first place? Preferably something that doesn't require additional logic inside of the loop.</p>
[ { "answer_id": 212497, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>Visual Basic arrays are zero-based. This can be changed with the <code>Option Base</code> statement, though. </p>\n\n<p>With your arrays, the extra elements are because you do a <code>UBound() + 1</code>, UBound will give you the correct number already. If the array has 5 Elements, UBound will be 5. But the last index will be 4, so ReDim to UBound will give you an array sized +1.</p>\n\n<p>As arrays are a pain to use anyway (in VBA, that is) and <code>ReDim Preserve</code> acually is an array copy operation to a new fixed size array, I would recommend you to use Collections wherever you can. They are a lot easier to iterate (<code>For Each ... In ...</code>) and much more efficient at adding, finding and removing elements.</p>\n\n<pre><code>' creation ' \nDim anyValue as Variant\nDim c as New Collection\n\n' and adding values '\nc.Add anyValue, strKey\n\n' iteration '\nFor Each anyValue in c\n Debug.Print anyValue\nNext c\n\n' count values '\nDebug.Print c.Count\n\n' element deletion '\nc.Delete strKey\n</code></pre>\n\n<p><em>(You can use Scripting.Dictionary from VBScript for added comfort, but you need to reference that first.)</em></p>\n\n<p>You can also have multiple dimensions of Collections by simply placing them inside each other.</p>\n" }, { "answer_id": 212615, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "<p><code>ReDim Preserve</code> is a relative expensive operation and probably not something to do on every iteration. Better to <code>ReDim</code> the array to an upper bounds larger than you need (perhaps in chunks) then reducing the array to the required upper bounds when you are done.</p>\n\n<p>Also, you may want to investigate other ways of reading an Excel Range into an array e.g. </p>\n\n<pre><code> Dim a()\n With Sheet1\n a = .Range(.Range(\"A1\"), .Range(\"A1\").End(xlDown)).Value\n End With\n Debug.Print a(1, 1)\n</code></pre>\n\n<p>Looping is often very slow :)</p>\n" }, { "answer_id": 213115, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "<p>VB6 and COM use a mixture of 0- and 1-based indexing (arrays are 0-based except when you change this with Option Base or declare them otherwise explicitly).</p>\n\n<p>COM collections are usually 1-based in earlier COM object models, but sometimes 0-based...</p>\n\n<p>Dim/Redim data(1 To N) is an array of N elements indexed from 1 to N</p>\n\n<p>Dim/Redim data(0 to N-1) is an array of N elements indexed from 0 to N-1</p>\n\n<p>Dim/Redim data(N) is an array of N+1 elements indexed from 0 to N (if Option Base is 0)</p>\n\n<p>The last case is the one that sometimes confuses, data(N) usually means data(0 To N) which is an array of N+1 elements.</p>\n\n<p>Personally I always declare arrays explicitly as (0 To N-1) and don't rely on Option Base, which is more familiar for developers who use more than one language.</p>\n\n<p>There is one edge case: VBA does not support zero-length arrays, you must always have at least one element (for each dimension in multidimensional arrays). So the smallest array you can declare is data(0 To 0) or data(1 To 1) with one element. </p>\n\n<p>In your case, I suspect you are creating an array with one element, then adding an element each time through the loop:</p>\n\n<pre><code>ReDim data(1 To 1) \nWhile Cells(ndx, 1).Value &lt;&gt; vbNullString \n ReDim Preserve data(1 To (UBound(data) + 1)) \n ndx = ndx + 1\nWend\n</code></pre>\n\n<p>Instead (and leaving aside for the moment considerations of the efficiency of calling ReDim Preserve in a loop), you should be using:</p>\n\n<pre><code>ReDim data(1 To 1) \nnStartIndex = ndx\nWhile Cells(ndx, 1).Value &lt;&gt; vbNullString \n ' On the first iteration this does nothing because\n ' the array already has one element\n ReDim Preserve data(1 To ndx - nStartIndex + 1) \n ndx = ndx + 1\nWend\n</code></pre>\n" }, { "answer_id": 213157, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 0, "selected": false, "text": "<p>Granted, its been a while since I've done classic VB6, and my VBA experience is even rustier... if memeory serves, the array syntax is different for VB in more than just the base being 1 instead of 0. The syntax also says that the \"size\" that you specify doesn't denote the total number of elements in the array, but rather the last index to be addressable.</p>\n" }, { "answer_id": 213570, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 2, "selected": true, "text": "<p>So this has turned out to be an annoying little problem as it looks like there really isn't a way to prevent the issue from coming up. Based upon the answers provided by the other users, I tired the following approaches to solving the problem.</p>\n\n<p><strong><a href=\"https://stackoverflow.com/questions/212434/is-there-a-way-to-prevent-extra-elements-in-vba-dynamic-arrays#212497\">Using a Collection</a></strong> - While this approach works quite will in situations where you need to read and store data, you can't use user-defined types with a Collection. Being able to define the item key is useful as you can use it to cross-reference two Collections; however, in VBA there is <a href=\"http://www.issociate.de/board/post/302889/VBA_collections_question.html\" rel=\"nofollow noreferrer\">no way to get the list of keys in the Collection</a> which can be limiting.</p>\n\n<p><strong><a href=\"https://stackoverflow.com/questions/212434/is-there-a-way-to-prevent-extra-elements-in-vba-dynamic-arrays#212615\">Reading an Excel Range into an Array</a></strong> - Another extremely nice approach, but it seems to work best when you know what the ranges are going to be ahead of time. If you have to figure out the ranges on the fly then you might find yourself in a situation where using a Collection or a smaller ReDim array easier to work with.</p>\n\n<p><strong>Building the Array on the fly with ReDim Preserve</strong> - While this can be a fairly straightforward operation, there are two issues involved with it. One is that <a href=\"http://msdn.microsoft.com/en-us/library/w8k3cys2.aspx\" rel=\"nofollow noreferrer\">ReDim</a> can be an expensive operation as Visual Basic actually creates a new array with the given size, copies the old array, and then deletes the old array (or releases it for the Garbage Collector in Visual Basic .NET). So you would want to minimize the calls to ReDim if you are going to be working with extremely large arrays. </p>\n\n<p>Additionally, you are likely going to run into a situation similar to the one in the question where you have an extra element at the start of the array or at the end of the array that is empty. The only way around this seems to be to either check to see if you need to resize before doing the operation, or to delete the empty element before returning the results.</p>\n" }, { "answer_id": 9774185, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 1, "selected": false, "text": "<p>There is quite a while since this question has been asked; however, I had the same problem today and solved it like this:</p>\n\n<p>There is a way to do it, by defining a first element that will never be used. If you need a zero based array you would define an empty array like this</p>\n\n<pre><code>Dim data()\nDim i as Long\n\nReDim data(-1 To -1) ' Empty array. We never use data(-1).\n\nFor i = 0 To UBound(data)\n ...\nNext i\n</code></pre>\n\n<p>If you need a 1-based array you would do this</p>\n\n<pre><code>ReDim data(0 To 0) ' Empty array. We never use data(0).\n\nFor i = 1 To UBound(data)\n ...\nNext i\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
As the title states, is there a way to prevent extra elements from showing up in VBA dynamic arrays when they are non-zero based? For example, when using code similar to the following: ``` While Cells(ndx, 1).Value <> vbNullString ReDim Preserve data(1 To (UBound(data) + 1)) ndx = ndx + 1 Wend ``` You have an extra empty array element at the end of processing. While this can be eliminated with the following: ``` ReDim Preserve data(1 To (UBound(data) - 1)) ``` This doesn't seem like the best way of resolving this problem. As such, is there a way to prevent that extra element from being created in the first place? Preferably something that doesn't require additional logic inside of the loop.
So this has turned out to be an annoying little problem as it looks like there really isn't a way to prevent the issue from coming up. Based upon the answers provided by the other users, I tired the following approaches to solving the problem. **[Using a Collection](https://stackoverflow.com/questions/212434/is-there-a-way-to-prevent-extra-elements-in-vba-dynamic-arrays#212497)** - While this approach works quite will in situations where you need to read and store data, you can't use user-defined types with a Collection. Being able to define the item key is useful as you can use it to cross-reference two Collections; however, in VBA there is [no way to get the list of keys in the Collection](http://www.issociate.de/board/post/302889/VBA_collections_question.html) which can be limiting. **[Reading an Excel Range into an Array](https://stackoverflow.com/questions/212434/is-there-a-way-to-prevent-extra-elements-in-vba-dynamic-arrays#212615)** - Another extremely nice approach, but it seems to work best when you know what the ranges are going to be ahead of time. If you have to figure out the ranges on the fly then you might find yourself in a situation where using a Collection or a smaller ReDim array easier to work with. **Building the Array on the fly with ReDim Preserve** - While this can be a fairly straightforward operation, there are two issues involved with it. One is that [ReDim](http://msdn.microsoft.com/en-us/library/w8k3cys2.aspx) can be an expensive operation as Visual Basic actually creates a new array with the given size, copies the old array, and then deletes the old array (or releases it for the Garbage Collector in Visual Basic .NET). So you would want to minimize the calls to ReDim if you are going to be working with extremely large arrays. Additionally, you are likely going to run into a situation similar to the one in the question where you have an extra element at the start of the array or at the end of the array that is empty. The only way around this seems to be to either check to see if you need to resize before doing the operation, or to delete the empty element before returning the results.
212,442
<p>I want to do something very simple in C++ but i can't find how. I want to create a function like a for loop where i will ideally enter a variable for the times the iteration should happen and some functions inside brackets my function will execute. I hope i was clear enough. Thanks...</p> <p>Example</p> <pre><code>superFor (1) { //commands to be executed here add(1+2); } </code></pre>
[ { "answer_id": 212460, "author": "FOR", "author_id": 27826, "author_profile": "https://Stackoverflow.com/users/27826", "pm_score": 0, "selected": false, "text": "<pre><code>void DoSomethingRepeatedly(int numTimesTo Loop)\n{\n for(int i=0; i&lt;numTimesToLoop; i++)\n { \n //do whatever; \n }\n}\n</code></pre>\n\n<p>That it ? That can't be.. too simple.. I must be misunderstanding your question :(\nOf course you'd have to check that the value of numTimesToLoop is >= 0.</p>\n\n<p>Edit: I made it a method, just in case.</p>\n" }, { "answer_id": 212462, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "<p>What you want isn't possible in C++ because the (current version of the) language lacks some features that are required here: namely, creating function blocks “on the fly”.</p>\n\n<p>The best you can do is pass a function pointer or function object to your function. The STL offers many examples of this. Consider:</p>\n\n<pre><code>void out(int x) {\n cout &lt;&lt; x &lt;&lt; ' ';\n}\n\nvector&lt;int&gt; xs;\nxs.push_back(42);\nxs.push_back(23);\n\nfor_each(xs.begin(), xs.end(), out);\n</code></pre>\n\n<p>This passes a pointer to function <code>out</code> to the function <a href=\"http://cppreference.com/wiki/stl/algorithm/for_each\" rel=\"noreferrer\"><code>for_each</code></a>.</p>\n" }, { "answer_id": 212464, "author": "user9282", "author_id": 9282, "author_profile": "https://Stackoverflow.com/users/9282", "pm_score": 3, "selected": false, "text": "<pre><code>#define superFor(n) for(int i = 0; i &lt; (n); i++)\n</code></pre>\n\n<p>Edit: Be careful to not use another variable called i in the loop.</p>\n" }, { "answer_id": 212471, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 0, "selected": false, "text": "<p>Maybe BOOST_FOREACH will do what you want:</p>\n\n<p><a href=\"http://engineering.meta-comm.com/resources/cs-win32_metacomm/doc/html/foreach.html\" rel=\"nofollow noreferrer\">http://engineering.meta-comm.com/resources/cs-win32_metacomm/doc/html/foreach.html</a></p>\n" }, { "answer_id": 212480, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 1, "selected": false, "text": "<p>You could use a macro.</p>\n\n<pre><code>#define superFor(v,i) for(int v=0; v&lt;(i); v++)\n</code></pre>\n\n<p>and use it like this:</p>\n\n<pre><code>superFor(i,10) {\n printf(\"Doing something ten times\");\n}\n</code></pre>\n" }, { "answer_id": 212487, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 2, "selected": false, "text": "<p>It's crazy, but it might just work...</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html</a>.</p>\n" }, { "answer_id": 212491, "author": "Keith Twombley", "author_id": 23866, "author_profile": "https://Stackoverflow.com/users/23866", "pm_score": 2, "selected": false, "text": "<p>in C++ you do that with a regular for-loop.</p>\n\n<pre><code> for(variable; condition; increment) {\n //stuff goes here\n }\n</code></pre>\n\n<p>In your for-loop:\nvariable is a counting variable like i. You can define the variable right here and initialize it. You often see something like \"int i = 0\"</p>\n\n<p>condition is some sort of test. In your case you want to check if your counting variable is less than how many times you want the loop to execute. You'd put something like \"i &lt; how_many_times_to_loop\"</p>\n\n<p>increment is a command to increment the counting variable. In your case you want \"i++\" which is a short hand way of saying \"i = i + 1\"</p>\n\n<p>So that gives us:</p>\n\n<pre><code> for(int i = 0; i &lt; how_many_times_to_loop; i++) {\n //stuff goes here\n }\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28954/" ]
I want to do something very simple in C++ but i can't find how. I want to create a function like a for loop where i will ideally enter a variable for the times the iteration should happen and some functions inside brackets my function will execute. I hope i was clear enough. Thanks... Example ``` superFor (1) { //commands to be executed here add(1+2); } ```
What you want isn't possible in C++ because the (current version of the) language lacks some features that are required here: namely, creating function blocks “on the fly”. The best you can do is pass a function pointer or function object to your function. The STL offers many examples of this. Consider: ``` void out(int x) { cout << x << ' '; } vector<int> xs; xs.push_back(42); xs.push_back(23); for_each(xs.begin(), xs.end(), out); ``` This passes a pointer to function `out` to the function [`for_each`](http://cppreference.com/wiki/stl/algorithm/for_each).
212,481
<p>I have a header file like this:</p> <pre><code>#ifndef __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__ #define __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__ #ifdef _DEBUG // macros for turning a number into a string #define STRING2(x) #x #define STRING(x) STRING2(x) #ifdef TRIAGE_MESG_AS_WARNING #define TRIAGE_TODO_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : warning : TRIAGE TO-DO: " STRING(description) )) #define TRIAGE_FIXTHIS_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : warning : TRIAGE FIXTHIS: " STRING(description) )) #else #define TRIAGE_TODO_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : message : TRIAGE TO-DO: " STRING(description) )) #define TRIAGE_FIXTHIS_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : message : TRIAGE FIXTHIS: " STRING(description) )) #endif #else #define TRIAGE_TODO_TAG(description) #define TRIAGE_FIXTHIS_TAG(description) #endif #endif // __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__ </code></pre> <p>Which outputs notes to the output pane in Visual Studio 2005. When 'TRIAGE_MESG_AS_WARNING' is defined, Visual Studio will harvest these messages and list them as warnings in the Error List. It does this because the text format matches a warning. However, I don't want them to show up as warnings all the time, I would rather they show up in the Messages pane of the Error List.</p> <blockquote> <p>How do you format lines you put in the "Output Window" so that Visual Studio will auto-magically show them in the "Messages" tab of the "Error List" window?</p> </blockquote> <p>The format I have setup for messages in the above code looks like a message from other output, but does not get harvested in the same way.</p> <p>A co-worker suggested to me that I might need to write a 'custom automation object' to write to the Messages pane. That seems like a pain, especially since it is trivial to end-up with entries in the Error pane and Warning pane simply by proper formating. Is this a possible avenue?</p> <p>We're using unmanaged C++, so we can't rely on managed (.NET) only tooling. We do not want to extend VS with hooks.</p>
[ { "answer_id": 212686, "author": "scootdawg", "author_id": 25512, "author_profile": "https://Stackoverflow.com/users/25512", "pm_score": 0, "selected": false, "text": "<p>I may not be understanding your question correctly but I'll give it a shot anyway.</p>\n\n<p>Have you looked at the TraceSwitch implentation? You can implement different listeners and output the info to various sources like text, console, etc.</p>\n\n<p>It might be what you need.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 847391, "author": "ChrisBD", "author_id": 102238, "author_profile": "https://Stackoverflow.com/users/102238", "pm_score": -1, "selected": false, "text": "<p>Could you not use \"Trace\" command within your code? This will just place whatever text that you tell it within the Output window. So for placing of error messages you'll need to format them first probably.</p>\n" }, { "answer_id": 888396, "author": "ChrisBD", "author_id": 102238, "author_profile": "https://Stackoverflow.com/users/102238", "pm_score": 2, "selected": false, "text": "<p>Okay I've had a hunt around and it looks as if you can do this if you have the Visual Studio SDK installed.</p>\n\n<p>I found this link <a href=\"http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/b1c37c03-f92b-46b1-83f5-7d54a1bbf5e6\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>You'll need to be using the Microsoft.VisualStudio.Shell namespace I believe.</p>\n\n<p>Snippets of code from the above link are as follows:</p>\n\n<pre><code>//Get the \"Error List Window\"\n\nErrorListProvider errorProvider = new ErrorListProvider(this);\nTask newError = new Task();\nnewError.ErrorCategory = TaskErrorCategory.Error; // or TaskErrorCategory.Warning for warnings\nnewError.Category = TaskCategory.BuildCompile;\nnewError.Text = \"Some Error Text\";\nerrorProvider.Tasks.Add(newError);\n</code></pre>\n\n<p>I haven't tried this yet, so if you're successful could you post back here for future reference please.</p>\n" }, { "answer_id": 908096, "author": "Andrey", "author_id": 106688, "author_profile": "https://Stackoverflow.com/users/106688", "pm_score": 4, "selected": true, "text": "<p>I believe they just <strong><em>forgot</em></strong> about adding additional category: info.\nAt least it is not specified in output format for external tools.</p>\n\n<p>Citation: \"Category must be either '<em>error</em>' or '<em>warning</em>'. Case does not matter. Like origin, category must not be localized.\"</p>\n\n<p>Link: <a href=\"http://blogs.msdn.com/msbuild/archive/2006/11/03/msbuild-visual-studio-aware-error-messages-and-message-formats.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/msbuild/archive/2006/11/03/msbuild-visual-studio-aware-error-messages-and-message-formats.aspx</a></p>\n" }, { "answer_id": 915623, "author": "Grant Peters", "author_id": 68241, "author_profile": "https://Stackoverflow.com/users/68241", "pm_score": 1, "selected": false, "text": "<p>I've attempted to get this to work as well, and as far as i can tell, its impossible unless you actually write your own plug-in for VS that parses output and generates tasks. This would be a really handy feature to have, and i just hope they add it at some point in the future (can't be bothered writing a plug-in myself, too many other little projects going on to spare the time :L)</p>\n\n<p>In the end, i've just opted to output it as a warning, which isn't too bad, seeing how i try to fix all warnings (or if they are intentional, turn the warning off for that little bit of code and comment if its not obvious why the warning is being ignored)</p>\n" }, { "answer_id": 941970, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 0, "selected": false, "text": "<p>Have you tried customizing the Task List keywords?</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ekwz6akh.aspx\" rel=\"nofollow noreferrer\">This page</a> suggests it's possible to do so. I suggest you read on from there, in case you haven't already.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28950/" ]
I have a header file like this: ``` #ifndef __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__ #define __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__ #ifdef _DEBUG // macros for turning a number into a string #define STRING2(x) #x #define STRING(x) STRING2(x) #ifdef TRIAGE_MESG_AS_WARNING #define TRIAGE_TODO_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : warning : TRIAGE TO-DO: " STRING(description) )) #define TRIAGE_FIXTHIS_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : warning : TRIAGE FIXTHIS: " STRING(description) )) #else #define TRIAGE_TODO_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : message : TRIAGE TO-DO: " STRING(description) )) #define TRIAGE_FIXTHIS_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : message : TRIAGE FIXTHIS: " STRING(description) )) #endif #else #define TRIAGE_TODO_TAG(description) #define TRIAGE_FIXTHIS_TAG(description) #endif #endif // __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__ ``` Which outputs notes to the output pane in Visual Studio 2005. When 'TRIAGE\_MESG\_AS\_WARNING' is defined, Visual Studio will harvest these messages and list them as warnings in the Error List. It does this because the text format matches a warning. However, I don't want them to show up as warnings all the time, I would rather they show up in the Messages pane of the Error List. > > How do you format lines you put in the > "Output Window" so that Visual Studio > will auto-magically show them in the > "Messages" tab of the "Error List" > window? > > > The format I have setup for messages in the above code looks like a message from other output, but does not get harvested in the same way. A co-worker suggested to me that I might need to write a 'custom automation object' to write to the Messages pane. That seems like a pain, especially since it is trivial to end-up with entries in the Error pane and Warning pane simply by proper formating. Is this a possible avenue? We're using unmanaged C++, so we can't rely on managed (.NET) only tooling. We do not want to extend VS with hooks.
I believe they just ***forgot*** about adding additional category: info. At least it is not specified in output format for external tools. Citation: "Category must be either '*error*' or '*warning*'. Case does not matter. Like origin, category must not be localized." Link: <http://blogs.msdn.com/msbuild/archive/2006/11/03/msbuild-visual-studio-aware-error-messages-and-message-formats.aspx>
212,510
<p>Currently I'm writing it in clear text <em>oops!</em>, it's an in house program so it's not that bad but I'd like to do it right. How should I go about encrypting this when writing to the registry and how do I decrypt it?</p> <pre><code>OurKey.SetValue("Password", textBoxPassword.Text); </code></pre>
[ { "answer_id": 212524, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 3, "selected": false, "text": "<p>One option would be to store the hash (SHA1, MD5) of the password instead of the clear-text password, and whenever you want to see if the password is good, just compare it to that hash.</p>\n\n<p>If you need secure storage (for example for a password that you will use to connect to a service), then the problem is more complicated.</p>\n\n<p>If it is just for authentication, then it would be enough to use the hash.</p>\n" }, { "answer_id": 212526, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 7, "selected": false, "text": "<h1>You don't decrypt authentication passwords!</h1>\n<p>Hash them using something like the SHA256 provider and when you have to challenge, hash the input from the user and see if the two hashes match.</p>\n<pre><code>byte[] data = System.Text.Encoding.ASCII.GetBytes(inputString);\ndata = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);\nString hash = System.Text.Encoding.ASCII.GetString(data);\n</code></pre>\n<p>Leaving passwords reversible is a <em>really</em> horrible model.</p>\n<p>Edit2: I thought we were just talking about front-line authentication. Sure there are cases where you want to encrypt passwords for other things that need to be reversible but there should be a 1-way lock on top of it all (with a very few exceptions).</p>\n<p>I've upgraded the hashing algorithm but for the best possible strength you want to keep <a href=\"https://stackoverflow.com/q/2138429/12870\">a private salt and add that to your input <em>before</em> hashing it</a>. You would do this again when you compare. This adds another layer making it even harder for somebody to reverse.</p>\n" }, { "answer_id": 212530, "author": "Jeremy B.", "author_id": 28567, "author_profile": "https://Stackoverflow.com/users/28567", "pm_score": -1, "selected": false, "text": "<p>Rather than encrypt/decrypt, you should be passing the password through a hashing algorithm, md5/sha512, or similar. What you would ideally do is hash the password and store the hash, then when the password is needed, you hash the entry and compare the entries. A password will then never be \"decrypted\", simply hashed and then compared.</p>\n" }, { "answer_id": 212535, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 3, "selected": false, "text": "<p>If you want to be able to decrypt the password, I think the easiest way would be to use DPAPI (user store mode) to encrypt/decrypt. This way you don't have to fiddle with encryption keys, store them somewhere or hard-code them in your code - in both cases somebody can discover them by looking into registry, user settings or using Reflector.</p>\n\n<p>Otherwise use hashes SHA1 or MD5 like others have said here.</p>\n" }, { "answer_id": 212536, "author": "osp70", "author_id": 2357, "author_profile": "https://Stackoverflow.com/users/2357", "pm_score": 1, "selected": false, "text": "<p>..NET provides cryptographics services in class contained in the\nSystem.Security.Cryptography namespace.</p>\n" }, { "answer_id": 212560, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 1, "selected": false, "text": "<p>If you need more than this, for example securing a connection string (for connection to a database), check this <a href=\"http://msdn.microsoft.com/en-us/library/89211k9b(VS.80).aspx\" rel=\"nofollow noreferrer\">article</a>, as it provides the best \"option\" for this.</p>\n\n<p>Oli's answer is also good, as it shows how you can create a hash for a string.</p>\n" }, { "answer_id": 212589, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 5, "selected": false, "text": "<p>Please also consider \"salting\" your hash (not a culinary concept!). Basically, that means appending some random text to the password before you hash it.</p>\n\n<p>\"<a href=\"http://msdn.microsoft.com/en-us/library/ms998372.aspx\" rel=\"noreferrer\">The salt value helps to slow an attacker perform a dictionary attack should your credential store be compromised, giving you additional time to detect and react to the compromise.</a>\"</p>\n\n<p>To store password hashes:</p>\n\n<p>a) Generate a random salt value:</p>\n\n<pre><code>byte[] salt = new byte[32];\nSystem.Security.Cryptography.RNGCryptoServiceProvider.Create().GetBytes(salt);\n</code></pre>\n\n<p>b) Append the salt to the password.</p>\n\n<pre><code>// Convert the plain string pwd into bytes\nbyte[] plainTextBytes = System.Text UnicodeEncoding.Unicode.GetBytes(plainText);\n// Append salt to pwd before hashing\nbyte[] combinedBytes = new byte[plainTextBytes.Length + salt.Length];\nSystem.Buffer.BlockCopy(plainTextBytes, 0, combinedBytes, 0, plainTextBytes.Length);\nSystem.Buffer.BlockCopy(salt, 0, combinedBytes, plainTextBytes.Length, salt.Length);\n</code></pre>\n\n<p>c) Hash the combined password &amp; salt:</p>\n\n<pre><code>// Create hash for the pwd+salt\nSystem.Security.Cryptography.HashAlgorithm hashAlgo = new System.Security.Cryptography.SHA256Managed();\nbyte[] hash = hashAlgo.ComputeHash(combinedBytes);\n</code></pre>\n\n<p>d) Append the salt to the resultant hash.</p>\n\n<pre><code>// Append the salt to the hash\nbyte[] hashPlusSalt = new byte[hash.Length + salt.Length];\nSystem.Buffer.BlockCopy(hash, 0, hashPlusSalt, 0, hash.Length);\nSystem.Buffer.BlockCopy(salt, 0, hashPlusSalt, hash.Length, salt.Length);\n</code></pre>\n\n<p>e) Store the result in your user store database.</p>\n\n<p>This approach means you don't need to store the salt separately and then recompute the hash using the salt value and the plaintext password value obtained from the user.</p>\n\n<p><strong>Edit</strong>: As raw computing power becomes cheaper and faster, the value of hashing -- or salting hashes -- has declined. <a href=\"http://www.codinghorror.com/blog/2012/04/speed-hashing.html\" rel=\"noreferrer\">Jeff Atwood has an excellent 2012 update</a> too lengthy to repeat in its entirety here which states:</p>\n\n<blockquote>\n <p>This (using salted hashes) will provide the illusion of security more than any actual security. Since you need both the salt and the choice of hash algorithm to generate the hash, and to check the hash, it's unlikely an attacker would have one but not the other. If you've been compromised to the point that an attacker has your password database, it's reasonable to assume they either have or can get your secret, hidden salt.</p>\n \n <p>The first rule of security is to always assume and plan for the worst.\n Should you use a salt, ideally a random salt for each user? Sure, it's\n definitely a good practice, and at the very least it lets you\n disambiguate two users who have the same password. But these days,\n salts alone can no longer save you from a person willing to spend a\n few thousand dollars on video card hardware, and if you think they\n can, you're in trouble.</p>\n</blockquote>\n" }, { "answer_id": 213037, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p>If it's a password used for authentication by your application, then hash the password as others suggest.</p>\n\n<p>If you're storing passwords for an external resource, you'll often want to be able to prompt the user for these credentials and give him the opportunity to save them securely. Windows provides the Credentials UI (CredUI) for this purpose - there are a number of samples showing how to use this in .NET, including <a href=\"http://msdn.microsoft.com/en-us/library/aa302353.aspx\" rel=\"noreferrer\">this one on MSDN</a>.</p>\n" }, { "answer_id": 272235, "author": "Jamie Wright", "author_id": 2779, "author_profile": "https://Stackoverflow.com/users/2779", "pm_score": 4, "selected": false, "text": "<p>This is what you would like to do:</p>\n\n<pre><code>OurKey.SetValue(\"Password\", StringEncryptor.EncryptString(textBoxPassword.Text));\nOurKey.GetValue(\"Password\", StringEncryptor.DecryptString(textBoxPassword.Text));\n</code></pre>\n\n<p>You can do that with this the following classes.\nThis class is a generic class is the client endpoint. It enables IOC of various encryption algorithms using <a href=\"http://ninject.org\" rel=\"noreferrer\">Ninject</a>.</p>\n\n<pre><code>public class StringEncryptor\n{\n private static IKernel _kernel;\n\n static StringEncryptor()\n {\n _kernel = new StandardKernel(new EncryptionModule());\n }\n\n public static string EncryptString(string plainText)\n {\n return _kernel.Get&lt;IStringEncryptor&gt;().EncryptString(plainText);\n }\n\n public static string DecryptString(string encryptedText)\n {\n return _kernel.Get&lt;IStringEncryptor&gt;().DecryptString(encryptedText);\n }\n}\n</code></pre>\n\n<p>This next class is the ninject class that allows you to inject the various algorithms:</p>\n\n<pre><code>public class EncryptionModule : StandardModule\n{\n public override void Load()\n {\n Bind&lt;IStringEncryptor&gt;().To&lt;TripleDESStringEncryptor&gt;();\n }\n}\n</code></pre>\n\n<p>This is the interface that any algorithm needs to implement to encrypt/decrypt strings:</p>\n\n<pre><code>public interface IStringEncryptor\n{\n string EncryptString(string plainText);\n string DecryptString(string encryptedText);\n}\n</code></pre>\n\n<p>This is a implementation using the TripleDES algorithm:</p>\n\n<pre><code>public class TripleDESStringEncryptor : IStringEncryptor\n{\n private byte[] _key;\n private byte[] _iv;\n private TripleDESCryptoServiceProvider _provider;\n\n public TripleDESStringEncryptor()\n {\n _key = System.Text.ASCIIEncoding.ASCII.GetBytes(\"GSYAHAGCBDUUADIADKOPAAAW\");\n _iv = System.Text.ASCIIEncoding.ASCII.GetBytes(\"USAZBGAW\");\n _provider = new TripleDESCryptoServiceProvider();\n }\n\n #region IStringEncryptor Members\n\n public string EncryptString(string plainText)\n {\n return Transform(plainText, _provider.CreateEncryptor(_key, _iv));\n }\n\n public string DecryptString(string encryptedText)\n {\n return Transform(encryptedText, _provider.CreateDecryptor(_key, _iv));\n }\n\n #endregion\n\n private string Transform(string text, ICryptoTransform transform)\n {\n if (text == null)\n {\n return null;\n }\n using (MemoryStream stream = new MemoryStream())\n {\n using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write))\n {\n byte[] input = Encoding.Default.GetBytes(text);\n cryptoStream.Write(input, 0, input.Length);\n cryptoStream.FlushFinalBlock();\n\n return Encoding.Default.GetString(stream.ToArray());\n }\n }\n }\n}\n</code></pre>\n\n<p>You can watch my video and download the code for this at : <a href=\"http://www.wrightin.gs/2008/11/how-to-encryptdecrypt-sensitive-column-contents-in-nhibernateactive-record-video.html\" rel=\"noreferrer\">http://www.wrightin.gs/2008/11/how-to-encryptdecrypt-sensitive-column-contents-in-nhibernateactive-record-video.html</a></p>\n" }, { "answer_id": 674267, "author": "Beau", "author_id": 60371, "author_profile": "https://Stackoverflow.com/users/60371", "pm_score": 3, "selected": false, "text": "<p>Like ligget78 said, DPAPI would be a good way to go for storing passwords. <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx\" rel=\"nofollow noreferrer\">Check out the ProtectedData class on MSDN</a> for example usage.</p>\n" }, { "answer_id": 6157302, "author": "Deathstalker", "author_id": 773704, "author_profile": "https://Stackoverflow.com/users/773704", "pm_score": 3, "selected": false, "text": "<p>I have looked all over for a good example of encryption and decryption process but most were overly complex. </p>\n\n<p>Anyhow there are many reasons someone may want to decrypt some text values including passwords. The reason I need to decrypt the password on the site I am working on currently is because they want to make sure when someone is forced to change their password when it expires that we do not let them change it with a close variant of the same password they used in the last x months. </p>\n\n<p>So I wrote up a process that will do this in a simplified manner. I hope this code is beneficial to someone. For all I know I may end up using this at another time for a different company/site.</p>\n\n<pre><code>public string GenerateAPassKey(string passphrase)\n {\n // Pass Phrase can be any string\n string passPhrase = passphrase;\n // Salt Value can be any string(for simplicity use the same value as used for the pass phrase)\n string saltValue = passphrase;\n // Hash Algorithm can be \"SHA1 or MD5\"\n string hashAlgorithm = \"SHA1\";\n // Password Iterations can be any number\n int passwordIterations = 2;\n // Key Size can be 128,192 or 256\n int keySize = 256;\n // Convert Salt passphrase string to a Byte Array\n byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);\n // Using System.Security.Cryptography.PasswordDeriveBytes to create the Key\n PasswordDeriveBytes pdb = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);\n //When creating a Key Byte array from the base64 string the Key must have 32 dimensions.\n byte[] Key = pdb.GetBytes(keySize / 11);\n String KeyString = Convert.ToBase64String(Key);\n\n return KeyString;\n }\n\n //Save the keystring some place like your database and use it to decrypt and encrypt\n//any text string or text file etc. Make sure you dont lose it though.\n\n private static string Encrypt(string plainStr, string KeyString) \n { \n RijndaelManaged aesEncryption = new RijndaelManaged();\n aesEncryption.KeySize = 256;\n aesEncryption.BlockSize = 128;\n aesEncryption.Mode = CipherMode.ECB;\n aesEncryption.Padding = PaddingMode.ISO10126;\n byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);\n aesEncryption.Key = KeyInBytes;\n byte[] plainText = ASCIIEncoding.UTF8.GetBytes(plainStr);\n ICryptoTransform crypto = aesEncryption.CreateEncryptor();\n byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);\n return Convert.ToBase64String(cipherText);\n }\n\n private static string Decrypt(string encryptedText, string KeyString) \n {\n RijndaelManaged aesEncryption = new RijndaelManaged(); \n aesEncryption.KeySize = 256;\n aesEncryption.BlockSize = 128; \n aesEncryption.Mode = CipherMode.ECB;\n aesEncryption.Padding = PaddingMode.ISO10126;\n byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);\n aesEncryption.Key = KeyInBytes;\n ICryptoTransform decrypto = aesEncryption.CreateDecryptor(); \n byte[] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(), 0, encryptedText.Length); \n return ASCIIEncoding.UTF8.GetString(decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length)); \n }\n\n String KeyString = GenerateAPassKey(\"PassKey\");\n String EncryptedPassword = Encrypt(\"25Characterlengthpassword!\", KeyString);\n String DecryptedPassword = Decrypt(EncryptedPassword, KeyString);\n</code></pre>\n" }, { "answer_id": 33311774, "author": "Iszi", "author_id": 477682, "author_profile": "https://Stackoverflow.com/users/477682", "pm_score": 4, "selected": false, "text": "<p>Tom Scott got it right in his coverage of how (not) to store passwords, on Computerphile.</p>\n\n<p><a href=\"https://www.youtube.com/watch?v=8ZtInClXe1Q\" rel=\"noreferrer\">https://www.youtube.com/watch?v=8ZtInClXe1Q</a></p>\n\n<ol>\n<li><p><strong>If you can at all avoid it, do not try to store passwords yourself.</strong> Use a separate, pre-established, trustworthy user authentication platform (e.g.: OAuth providers, you company's Active Directory domain, etc.) instead.</p></li>\n<li><p><strong>If you must store passwords, don't follow any of the guidance here.</strong> At least, not without also consulting more recent and reputable publications applicable to your language of choice.</p></li>\n</ol>\n\n<p>There's certainly a lot of smart people here, and probably even some good guidance given. But the odds are strong that, by the time you read this, all of the answers here (including this one) will already be outdated.</p>\n\n<hr>\n\n<h2>The right way to store passwords changes over time.</h2>\n\n<h2><strong><em>Probably more frequently than some people change their underwear.</em></strong></h2>\n\n<hr>\n\n<p>All that said, here's some general guidance that will hopefully remain useful for awhile.</p>\n\n<ol>\n<li><strong><em>Don't encrypt passwords.</em></strong> Any storage method that allows recovery of the stored data is inherently insecure for the purpose of holding passwords - all forms of encryption included.</li>\n<li><p><strong><em>Process the passwords exactly as entered by the user during the creation process.</em></strong> Anything you do to the password before sending it to the cryptography module will probably just weaken it. Doing any of the following also just adds complexity to the password storage &amp; verification process, which could cause other problems (perhaps even introduce vulnerabilities) down the road.</p>\n\n<ul>\n<li>Don't convert to all-uppercase/all-lowercase.</li>\n<li>Don't remove whitespace.</li>\n<li>Don't strip unacceptable characters or strings.</li>\n<li>Don't change the text encoding.</li>\n<li>Don't do any character or string substitutions.</li>\n<li>Don't truncate passwords of any length.</li>\n</ul></li>\n<li><p><strong><em>Reject creation of any passwords that can't be stored without modification.</em></strong> Reinforcing the above. If there's some reason your password storage mechanism can't appropriately handle certain characters, whitespaces, strings, or password lengths, then return an error and let the user know about the system's limitations so they can retry with a password that fits within them. For a better user experience, make a list of those limitations accessible to the user up-front. Don't even worry about, let alone bother, hiding the list from attackers - they'll figure it out easily enough on their own anyway.</p></li>\n<li><strong><em>Use a long, random, and unique salt for each account.</em></strong> No two accounts' passwords should ever look the same in storage, even if the passwords are actually identical.</li>\n<li><strong><em>Use slow and cryptographically strong hashing algorithms that are designed for use with passwords.</em></strong> MD5 is certainly out. SHA-1/SHA-2 are no-go. But I'm not going to tell you what you <em>should</em> use here either. (See the first #2 bullet in this post.)</li>\n<li><strong><em>Iterate as much as you can tolerate.</em></strong> While your system might have better things to do with its processor cycles than hash passwords all day, the people who will be cracking your passwords have systems that don't. Make it as hard on them as you can, without quite making it \"too hard\" on you.</li>\n</ol>\n\n<hr>\n\n<p>Most importantly...</p>\n\n<h2>Don't just listen to anyone here.</h2>\n\n<p>Go look up a reputable and very recent publication on the proper methods of password storage for your language of choice. Actually, you should find multiple recent publications from multiple separate sources that are in agreement before you settle on one method.</p>\n\n<p>It's extremely possible that everything that everyone here (myself included) has said has already been superseded by better technologies or rendered insecure by newly developed attack methods. Go find something that's more probably not.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Currently I'm writing it in clear text *oops!*, it's an in house program so it's not that bad but I'd like to do it right. How should I go about encrypting this when writing to the registry and how do I decrypt it? ``` OurKey.SetValue("Password", textBoxPassword.Text); ```
You don't decrypt authentication passwords! =========================================== Hash them using something like the SHA256 provider and when you have to challenge, hash the input from the user and see if the two hashes match. ``` byte[] data = System.Text.Encoding.ASCII.GetBytes(inputString); data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data); String hash = System.Text.Encoding.ASCII.GetString(data); ``` Leaving passwords reversible is a *really* horrible model. Edit2: I thought we were just talking about front-line authentication. Sure there are cases where you want to encrypt passwords for other things that need to be reversible but there should be a 1-way lock on top of it all (with a very few exceptions). I've upgraded the hashing algorithm but for the best possible strength you want to keep [a private salt and add that to your input *before* hashing it](https://stackoverflow.com/q/2138429/12870). You would do this again when you compare. This adds another layer making it even harder for somebody to reverse.
212,528
<p>This Question is almost the same as the previously asked <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer">How can I get the IP Address of a local computer?</a> -Question. However I need to find the IP address(es) of a <strong>Linux Machine</strong>.</p> <p>So: How do I - programmatically in <strong>C++</strong> - detect the IP addresses of the linux server my application is running on. The servers will have at least two IP addresses and I need a specific one (the one in a given network (the public one)).</p> <p>I'm sure there is a simple function to do that - but where?</p> <hr /> <p>To make things a bit clearer:</p> <ul> <li>The server will obviously have the &quot;localhost&quot;: 127.0.0.1</li> <li>The server will have an internal (management) IP address: 172.16.x.x</li> <li>The server will have an external (public) IP address: 80.190.x.x</li> </ul> <p>I need to find the external IP address to bind my application to it. Obviously I can also bind to INADDR_ANY (and actually that's what I do at the moment). I would prefer to detect the public address, though.</p>
[ { "answer_id": 212688, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 5, "selected": false, "text": "<ol>\n<li>Create a socket.</li>\n<li>Perform <code>ioctl(&lt;socketfd&gt;, SIOCGIFCONF, (struct ifconf)&amp;buffer);</code></li>\n</ol>\n\n<p>Read <code>/usr/include/linux/if.h</code> for information on the <code>ifconf</code> and <code>ifreq</code> structures. This should give you the IP address of each interface on the system. Also read <code>/usr/include/linux/sockios.h</code> for additional ioctls.</p>\n" }, { "answer_id": 213223, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can do some integration with curl as something as easy as: <code>curl www.whatismyip.org</code> from the shell will get you your global ip. You're kind of reliant on some external server, but you will always be if you're behind a NAT.</p>\n" }, { "answer_id": 214808, "author": "camh", "author_id": 23744, "author_profile": "https://Stackoverflow.com/users/23744", "pm_score": 3, "selected": false, "text": "<p>Further to what Steve Baker has said, you can find a description of the SIOCGIFCONF ioctl in the <a href=\"http://linux.die.net/man/7/netdevice\" rel=\"noreferrer\">netdevice(7) man page</a>.</p>\n\n<p>Once you have the list of all the IP addresses on the host, you will have to use application specific logic to filter out the addresses you do not want and hope you have one IP address left.</p>\n" }, { "answer_id": 215333, "author": "jjvainio", "author_id": 29264, "author_profile": "https://Stackoverflow.com/users/29264", "pm_score": 4, "selected": false, "text": "<p>As you have found out there is no such thing as a single \"local IP address\". Here's how to find out the local address that can be sent out to a specific host.</p>\n\n<ol>\n<li>Create a UDP socket</li>\n<li>Connect the socket to an outside address (the host that will eventually receive the local address)</li>\n<li>Use getsockname to get the local address</li>\n</ol>\n" }, { "answer_id": 265978, "author": "Twelve47", "author_id": 26961, "author_profile": "https://Stackoverflow.com/users/26961", "pm_score": 7, "selected": false, "text": "<p>I found the ioctl solution problematic on os x (which is POSIX compliant so should be similiar to linux). However getifaddress() will let you do the same thing easily, it works fine for me on os x 10.5 and should be the same below.</p>\n\n<p>I've done a quick example below which will print all of the machine's IPv4 address, (you should also check the getifaddrs was successful ie returns 0).</p>\n\n<p>I've updated it show IPv6 addresses too.</p>\n\n<pre><code>#include &lt;stdio.h&gt; \n#include &lt;sys/types.h&gt;\n#include &lt;ifaddrs.h&gt;\n#include &lt;netinet/in.h&gt; \n#include &lt;string.h&gt; \n#include &lt;arpa/inet.h&gt;\n\nint main (int argc, const char * argv[]) {\n struct ifaddrs * ifAddrStruct=NULL;\n struct ifaddrs * ifa=NULL;\n void * tmpAddrPtr=NULL;\n\n getifaddrs(&amp;ifAddrStruct);\n\n for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa-&gt;ifa_next) {\n if (!ifa-&gt;ifa_addr) {\n continue;\n }\n if (ifa-&gt;ifa_addr-&gt;sa_family == AF_INET) { // check it is IP4\n // is a valid IP4 Address\n tmpAddrPtr=&amp;((struct sockaddr_in *)ifa-&gt;ifa_addr)-&gt;sin_addr;\n char addressBuffer[INET_ADDRSTRLEN];\n inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n printf(\"%s IP Address %s\\n\", ifa-&gt;ifa_name, addressBuffer); \n } else if (ifa-&gt;ifa_addr-&gt;sa_family == AF_INET6) { // check it is IP6\n // is a valid IP6 Address\n tmpAddrPtr=&amp;((struct sockaddr_in6 *)ifa-&gt;ifa_addr)-&gt;sin6_addr;\n char addressBuffer[INET6_ADDRSTRLEN];\n inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);\n printf(\"%s IP Address %s\\n\", ifa-&gt;ifa_name, addressBuffer); \n } \n }\n if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 3120382, "author": "4dan", "author_id": 376518, "author_profile": "https://Stackoverflow.com/users/376518", "pm_score": 5, "selected": false, "text": "<p>I like <a href=\"https://stackoverflow.com/questions/212528/linux-c-get-the-ip-address-of-local-computer/215333#215333\">jjvainio's answer</a>. As Zan Lnyx says, it uses the local routing table to find the IP address of the ethernet interface that would be used for a connection to a specific external host. By using a connected UDP socket, you can get the information without actually sending any packets. The approach requires that you choose a specific external host. Most of the time, any well-known public IP should do the trick. I like Google's public DNS server address 8.8.8.8 for this purpose, but there may be times you'd want to choose a different external host IP. Here is some code that illustrates the full approach.</p>\n\n<pre><code>void GetPrimaryIp(char* buffer, size_t buflen) \n{\n assert(buflen &gt;= 16);\n\n int sock = socket(AF_INET, SOCK_DGRAM, 0);\n assert(sock != -1);\n\n const char* kGoogleDnsIp = \"8.8.8.8\";\n uint16_t kDnsPort = 53;\n struct sockaddr_in serv;\n memset(&amp;serv, 0, sizeof(serv));\n serv.sin_family = AF_INET;\n serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp);\n serv.sin_port = htons(kDnsPort);\n\n int err = connect(sock, (const sockaddr*) &amp;serv, sizeof(serv));\n assert(err != -1);\n\n sockaddr_in name;\n socklen_t namelen = sizeof(name);\n err = getsockname(sock, (sockaddr*) &amp;name, &amp;namelen);\n assert(err != -1);\n\n const char* p = inet_ntop(AF_INET, &amp;name.sin_addr, buffer, buflen);\n assert(p);\n\n close(sock);\n}\n</code></pre>\n" }, { "answer_id": 3225928, "author": "Thanatos", "author_id": 101999, "author_profile": "https://Stackoverflow.com/users/101999", "pm_score": 2, "selected": false, "text": "<p>Don't hard code it: this is the sort of thing that can change. Many programs figure out what to bind to by reading in a config file, and doing whatever that says. This way, should your program sometime in the future need to bind to something that's not a public IP, it can do so.</p>\n" }, { "answer_id": 5452793, "author": "Chaza", "author_id": 679398, "author_profile": "https://Stackoverflow.com/users/679398", "pm_score": -1, "selected": false, "text": "<pre><code>// Use a HTTP request to a well known server that echo's back the public IP address\nvoid GetPublicIP(CString &amp; csIP)\n{\n // Initialize COM\n bool bInit = false;\n if (SUCCEEDED(CoInitialize(NULL)))\n {\n // COM was initialized\n bInit = true;\n\n // Create a HTTP request object\n MSXML2::IXMLHTTPRequestPtr HTTPRequest;\n HRESULT hr = HTTPRequest.CreateInstance(&quot;MSXML2.XMLHTTP&quot;);\n if (SUCCEEDED(hr))\n {\n // Build a request to a web site that returns the public IP address\n VARIANT Async;\n Async.vt = VT_BOOL;\n Async.boolVal = VARIANT_FALSE;\n CComBSTR ccbRequest = L&quot;http://whatismyipaddress.com/&quot;;\n\n // Open the request\n if (SUCCEEDED(HTTPRequest-&gt;raw_open(L&quot;GET&quot;,ccbRequest,Async)))\n {\n // Send the request\n if (SUCCEEDED(HTTPRequest-&gt;raw_send()))\n {\n // Get the response\n CString csRequest = HTTPRequest-&gt;GetresponseText();\n\n // Parse the IP address\n CString csMarker = &quot;&lt;!-- contact us before using a script to get your IP address --&gt;&quot;;\n int iPos = csRequest.Find(csMarker);\n if (iPos == -1)\n return;\n iPos += csMarker.GetLength();\n int iPos2 = csRequest.Find(csMarker,iPos);\n if (iPos2 == -1)\n return;\n\n // Build the IP address\n int nCount = iPos2 - iPos;\n csIP = csRequest.Mid(iPos,nCount);\n }\n }\n }\n }\n\n // Unitialize COM\n if (bInit)\n CoUninitialize();\n}\n\n</code></pre>\n" }, { "answer_id": 6045426, "author": "Erik Aronesty", "author_id": 627042, "author_profile": "https://Stackoverflow.com/users/627042", "pm_score": 3, "selected": false, "text": "<p>This has the advantage of working on many flavors of unix ...and you can modify it trivially to work on any o/s. All of the solutions above give me compiler errors depending on the phase of the moon. The moment there's a good POSIX way to do it... don't use this (at the time this was written, that wasn't the case).</p>\n\n<pre><code>// ifconfig | perl -ne 'print \"$1\\n\" if /inet addr:([\\d.]+)/'\n\n#include &lt;stdlib.h&gt;\n\nint main() {\n setenv(\"LANG\",\"C\",1);\n FILE * fp = popen(\"ifconfig\", \"r\");\n if (fp) {\n char *p=NULL, *e; size_t n;\n while ((getline(&amp;p, &amp;n, fp) &gt; 0) &amp;&amp; p) {\n if (p = strstr(p, \"inet \")) {\n p+=5;\n if (p = strchr(p, ':')) {\n ++p;\n if (e = strchr(p, ' ')) {\n *e='\\0';\n printf(\"%s\\n\", p);\n }\n }\n }\n }\n }\n pclose(fp);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 17353962, "author": "Kristian Evensen", "author_id": 1024197, "author_profile": "https://Stackoverflow.com/users/1024197", "pm_score": 2, "selected": false, "text": "<p>As the question specifies Linux, my favourite technique for discovering the IP-addresses of a machine is to use netlink. By creating a netlink socket of the protocol NETLINK_ROUTE, and sending an RTM_GETADDR, your application will received a message(s) containing all available IP addresses. An example is provided <a href=\"http://linux-hacks.blogspot.no/2009/01/sample-code-to-learn-netlink.html\" rel=\"nofollow\">here</a>. </p>\n\n<p>In order to simply parts of the message handling, libmnl is convenient. If you are curios in figuring out more about the different options of NETLINK_ROUTE (and how they are parsed), the best source is the <a href=\"http://www.linuxfoundation.org/collaborate/workgroups/networking/iproute2\" rel=\"nofollow\">source code</a> of iproute2 (especially the monitor application) as well as the receive functions in the kernel. The man page of <a href=\"http://linux.die.net/man/7/rtnetlink\" rel=\"nofollow\">rtnetlink</a> also contains useful information.</p>\n" }, { "answer_id": 33872296, "author": "Tino", "author_id": 490291, "author_profile": "https://Stackoverflow.com/users/490291", "pm_score": 3, "selected": false, "text": "<p>I do not think there is a definitive right answer to your question. Instead there is a big bundle of ways how to get close to what you wish. Hence I will provide some hints how to get it done.</p>\n\n<p>If a machine has more than 2 interfaces (<code>lo</code> counts as one) you will have problems to autodetect the right interface easily. Here are some recipes on how to do it.</p>\n\n<p>The problem, for example, is if hosts are in a DMZ behind a NAT firewall which changes the public IP into some private IP and forwards the requests. Your machine may have 10 interfaces, but only one corresponds to the public one.</p>\n\n<p>Even autodetection does not work in case you are on double-NAT, where your firewall even translates the source-IP into something completely different. So you cannot even be sure, that the default route leads to your interface with a public interface.</p>\n\n<h1>Detect it via the default route</h1>\n\n<blockquote>\n <p>This is my recommended way to autodetect things</p>\n</blockquote>\n\n<p>Something like <code>ip r get 1.1.1.1</code> usually tells you the interface which has the default route.</p>\n\n<p>If you want to recreate this in your favourite scripting/programming language, use <code>strace ip r get 1.1.1.1</code> and follow the yellow brick road.</p>\n\n<h1>Set it with <code>/etc/hosts</code></h1>\n\n<blockquote>\n <p>This is my recommendation if you want to stay in control</p>\n</blockquote>\n\n<p>You can create an entry in <code>/etc/hosts</code> like</p>\n\n<pre><code>80.190.1.3 publicinterfaceip\n</code></pre>\n\n<p>Then you can use this alias <code>publicinterfaceip</code> to refer to your public interface.</p>\n\n<blockquote>\n <p>Sadly <code>haproxy</code> does not grok this trick with IPv6</p>\n</blockquote>\n\n<h1>Use the environment</h1>\n\n<blockquote>\n <p>This is a good workaround for <code>/etc/hosts</code> in case you are not <code>root</code></p>\n</blockquote>\n\n<p>Same as <code>/etc/hosts</code>. but use the environment for this. You can try <code>/etc/profile</code> or <code>~/.profile</code> for this.</p>\n\n<p>Hence if your program needs a variable <code>MYPUBLICIP</code> then you can include code like (this is C, feel free to create C++ from it):</p>\n\n<pre><code>#define MYPUBLICIPENVVAR \"MYPUBLICIP\"\n\nconst char *mypublicip = getenv(MYPUBLICIPENVVAR);\n\nif (!mypublicip) { fprintf(stderr, \"please set environment variable %s\\n\", MYPUBLICIPENVVAR); exit(3); }\n</code></pre>\n\n<p>So you can call your script/program <code>/path/to/your/script</code> like this</p>\n\n<p><code>MYPUBLICIP=80.190.1.3 /path/to/your/script</code></p>\n\n<p>this even works in <code>crontab</code>.</p>\n\n<h1>Enumerate all interfaces and eliminate those you do not want</h1>\n\n<blockquote>\n <p>The desperate way if you cannot use <code>ip</code></p>\n</blockquote>\n\n<p>If you do know what you do not want, you can enumerate all interfaces and ignore all the false ones.</p>\n\n<p>Here already seems to be an answer <a href=\"https://stackoverflow.com/a/265978/490291\">https://stackoverflow.com/a/265978/490291</a> for this approach.</p>\n\n<h1>Do it like DLNA</h1>\n\n<blockquote>\n <p>The way of the drunken man who tries to drown himself in alcohol</p>\n</blockquote>\n\n<p>You can try to enumerate all the UPnP gateways on your network and this way find out a proper route for some \"external\" thing. This even might be on a route where your default route does not point to.</p>\n\n<p>For more on this perhaps see <a href=\"https://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol</a></p>\n\n<p>This gives you a good impression which one is your real public interface, even if your default route points elsewhere.</p>\n\n<h1>There are even more</h1>\n\n<blockquote>\n <p>Where the mountain meets the prophet</p>\n</blockquote>\n\n<p>IPv6 routers advertise themselves to give you the right IPv6 prefix. Looking at the prefix gives you a hint about if it has some internal IP or a global one.</p>\n\n<p>You can listen for IGMP or IBGP frames to find out some suitable gateway.</p>\n\n<p>There are less than 2^32 IP addresses. Hence it does not take long on a LAN to just ping them all. This gives you a statistical hint on where the majority of the Internet is located from your point of view. However you should be a bit more sensible than the famous <a href=\"https://de.wikipedia.org/wiki/SQL_Slammer\" rel=\"nofollow noreferrer\">https://de.wikipedia.org/wiki/SQL_Slammer</a></p>\n\n<p>ICMP and even ARP are good sources for network sideband information. It might help you out as well.</p>\n\n<p>You can use Ethernet Broadcast address to contact to all your network infrastructure devices which often will help out, like DHCP (even DHCPv6) and so on.</p>\n\n<p>This additional list is probably endless and always incomplete, because every manufacturer of network devices is busily inventing new security holes on how to auto-detect their own devices. Which often helps a lot on how to detect some public interface where there shouln't be one.</p>\n\n<p>'Nuff said. Out.</p>\n" }, { "answer_id": 66467436, "author": "PYK", "author_id": 3233722, "author_profile": "https://Stackoverflow.com/users/3233722", "pm_score": 1, "selected": false, "text": "<p>How about you play with the <code>stdio.h</code> header only? (no network headers involved)</p>\n<p>Here is the full C++ code for that:</p>\n<p>(this is for the local IP; if you're over a home modem for example)</p>\n<pre><code>#include &lt;stdio.h&gt;\nint main()\n{\n static char ip[32];\n FILE *f = popen(&quot;ip a | grep 'scope global' | grep -v ':' | awk '{print $2}' | cut -d '/' -f1&quot;, &quot;r&quot;);\n int c, i = 0;\n while ((c = getc(f)) != EOF) i += sprintf(ip+i, &quot;%c&quot;, c);\n pclose(f);\n printf(ip);\n}\n</code></pre>\n<ul>\n<li><p>BONUS: you can cross-compile this for Android too over it's NDK C++ compiler</p>\n</li>\n<li><p>JUST SAYING: I have a VPS where I ran this and it gets the <strong>external IP</strong></p>\n</li>\n</ul>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999/" ]
This Question is almost the same as the previously asked [How can I get the IP Address of a local computer?](https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer) -Question. However I need to find the IP address(es) of a **Linux Machine**. So: How do I - programmatically in **C++** - detect the IP addresses of the linux server my application is running on. The servers will have at least two IP addresses and I need a specific one (the one in a given network (the public one)). I'm sure there is a simple function to do that - but where? --- To make things a bit clearer: * The server will obviously have the "localhost": 127.0.0.1 * The server will have an internal (management) IP address: 172.16.x.x * The server will have an external (public) IP address: 80.190.x.x I need to find the external IP address to bind my application to it. Obviously I can also bind to INADDR\_ANY (and actually that's what I do at the moment). I would prefer to detect the public address, though.
I found the ioctl solution problematic on os x (which is POSIX compliant so should be similiar to linux). However getifaddress() will let you do the same thing easily, it works fine for me on os x 10.5 and should be the same below. I've done a quick example below which will print all of the machine's IPv4 address, (you should also check the getifaddrs was successful ie returns 0). I've updated it show IPv6 addresses too. ``` #include <stdio.h> #include <sys/types.h> #include <ifaddrs.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> int main (int argc, const char * argv[]) { struct ifaddrs * ifAddrStruct=NULL; struct ifaddrs * ifa=NULL; void * tmpAddrPtr=NULL; getifaddrs(&ifAddrStruct); for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) { continue; } if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4 // is a valid IP4 Address tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); } else if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6 // is a valid IP6 Address tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr; char addressBuffer[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); } } if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct); return 0; } ```
212,562
<p>Is there a good way to have a <code>Map&lt;String, ?&gt;</code> get and put ignoring case?</p>
[ { "answer_id": 212583, "author": "John M", "author_id": 20734, "author_profile": "https://Stackoverflow.com/users/20734", "pm_score": 4, "selected": false, "text": "<p>You need a wrapper class for your String key with a case-insensitive equals() and hashCode() implementation. Use that instead of the String for the Map's key.</p>\n\n<p>See an example implementation at <a href=\"http://www.java.happycodings.com/Java_Util_Package/code3.html\" rel=\"nofollow noreferrer\">http://www.java.happycodings.com/Java_Util_Package/code3.html</a> I found it in 2 minutes of googling. Looks sensible to me, though I've never used it.</p>\n" }, { "answer_id": 212607, "author": "Eric Weilnau", "author_id": 13342, "author_profile": "https://Stackoverflow.com/users/13342", "pm_score": 5, "selected": false, "text": "<p>You could use <a href=\"http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/map/CaseInsensitiveMap.html\" rel=\"noreferrer\">CaseInsensitiveMap</a> from Apache's Commons Collections.</p>\n" }, { "answer_id": 212629, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 5, "selected": false, "text": "<p>Would it be possible to implement your own Map overriding put/get methods ?</p>\n\n<pre><code>public class CaseInsensitiveMap extends HashMap&lt;String, String&gt; {\n ...\n put(String key, String value) {\n super.put(key.toLowerCase(), value);\n }\n\n get(String key) {\n super.get(key.toLowercase());\n }\n}\n</code></pre>\n\n<p>This approach does not force you to change your \"key\" type but your Map implementation.</p>\n" }, { "answer_id": 212708, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>The three obvious solutions that spring to mind:</p>\n\n<ul>\n<li><p>Normalise the case before using a String as a key (not Turkish locale works differently from the rest of the world).</p></li>\n<li><p>Use a special object type designed to be used as key. This is a common idiom for dealing with composite keys.</p></li>\n<li><p>Use a TreeMap with a Comparator that is case insensitive (possibly a PRIMARY or SECONDARY strength java.text.Collator). Unfortunately the Java library doesn't have a Comparator equivalent for hashCode/equals.</p></li>\n</ul>\n" }, { "answer_id": 807172, "author": "glyn", "author_id": 98605, "author_profile": "https://Stackoverflow.com/users/98605", "pm_score": 2, "selected": false, "text": "<p>You could use my Apache licensed <a href=\"https://src.springsource.org/svn/dm-server-util/main-branches/jersey/com.springsource.util.common/src/main/java/com/springsource/util/common/CaseInsensitiveMap.java\" rel=\"nofollow noreferrer\">CaseInsensitiveMap</a> discussed <a href=\"http://underlap.blogspot.com/2009/04/caseinsensitivemapv.html\" rel=\"nofollow noreferrer\">here</a>. Unlike the Apache Commons version, it preserves the case of keys. It implements the map contract more strictly than TreeMap (plus has better concurrent semantics) (see the blog comments for details).</p>\n" }, { "answer_id": 1876814, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://trove4j.sourceforge.net/html/overview.html\" rel=\"nofollow noreferrer\">Trove4j</a> can use custom hashing for a HashMap. This may however have performance implications given that hashcodes cannot be cached (although Trove4j may have found a way around this?). Wrapper objects (as described by John M) do not have this caching deficiency. Also see my other answer regarding TreeMap.</p>\n" }, { "answer_id": 1876820, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 7, "selected": true, "text": "<p>TreeMap extends Map and supports custom comparators.</p>\n\n<p>String provides a default case insensitive comparator.</p>\n\n<p>So:</p>\n\n<pre><code>final Map&lt;String, ...&gt; map = new TreeMap&lt;&gt;(String.CASE_INSENSITIVE_ORDER);\n</code></pre>\n\n<p>The comparator does not take locale into account. Read more about it in its JavaDoc.</p>\n" }, { "answer_id": 15699340, "author": "Kunjan", "author_id": 2021027, "author_profile": "https://Stackoverflow.com/users/2021027", "pm_score": 0, "selected": false, "text": "<p>Check the accepted answer at the link below.\n<a href=\"https://stackoverflow.com/questions/3092710/how-to-check-for-key-in-a-map-irrespective-of-the-case\">How to check for key in a Map irrespective of the case?</a></p>\n\n<p>Bottom line is \"The simplest solution is to simply convert all inputs to uppercase (or lowercase) before inserting/checking. You could even write your own Map wrapper that would do this to ensure consistency.\"</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013/" ]
Is there a good way to have a `Map<String, ?>` get and put ignoring case?
TreeMap extends Map and supports custom comparators. String provides a default case insensitive comparator. So: ``` final Map<String, ...> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); ``` The comparator does not take locale into account. Read more about it in its JavaDoc.
212,569
<p>I'm using Spring's support for JDBC. I'd like to use <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html" rel="noreferrer">JdbcTemplate</a> (or SimpleJdbcTemplate) to execute a query and obtain the result as an instance of ResultSet.</p> <p>The only way that I can see of achieving this is using:</p> <pre><code>String sql = "select * from...."; SqlRowSet results = jdbcTemplate.queryForRowSet(sql); ((ResultSetWrappingSqlRowSet) results).getResultSet(); </code></pre> <p>An obvious shortcoming of this approach is that it requires me to make an assumption (by casting) about the implementation type of SqlRowSet, but is there a better way?</p> <p><strong>Background info...</strong></p> <p>The reason I want to obtain the results as a ResultSet, rather than a collection of beans, is because the results will be passed straight to a Jasper report for display. In other words, the Java bean would be used for nothing other than temporarily storing each row in the ResultSet, and I'd like to avoid creating such a bean for every Jasper report if possible.</p> <p>Cheers, Don</p>
[ { "answer_id": 212632, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 3, "selected": true, "text": "<p>If you want to just perform a query and get the results, why don't you use plain jdbc and grab the resultset? Notice that you don't need spring to do just this.</p>\n\n<pre><code> Connection c = ...\n c.prepareCall(\"select ...\").getResultSet();\n</code></pre>\n\n<p>Besides, you get an advantage by using an object as a DTO. You don't need to change your DTO class even if your data acess or your report tool changes (let's say you start using xquery instead of jdbc or you use apache-poi instead of jasper.</p>\n" }, { "answer_id": 7911154, "author": "Bill Poitras", "author_id": 994605, "author_profile": "https://Stackoverflow.com/users/994605", "pm_score": 1, "selected": false, "text": "<p>You can either invoke Jasper inside a JdbcTemplate callback (like a ResultSetExtractor) or use straight JDBC to pass the ResultSet to Jasper. Either way when you call Jasper your connection to the database is still active until your report is finished.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I'm using Spring's support for JDBC. I'd like to use [JdbcTemplate](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html) (or SimpleJdbcTemplate) to execute a query and obtain the result as an instance of ResultSet. The only way that I can see of achieving this is using: ``` String sql = "select * from...."; SqlRowSet results = jdbcTemplate.queryForRowSet(sql); ((ResultSetWrappingSqlRowSet) results).getResultSet(); ``` An obvious shortcoming of this approach is that it requires me to make an assumption (by casting) about the implementation type of SqlRowSet, but is there a better way? **Background info...** The reason I want to obtain the results as a ResultSet, rather than a collection of beans, is because the results will be passed straight to a Jasper report for display. In other words, the Java bean would be used for nothing other than temporarily storing each row in the ResultSet, and I'd like to avoid creating such a bean for every Jasper report if possible. Cheers, Don
If you want to just perform a query and get the results, why don't you use plain jdbc and grab the resultset? Notice that you don't need spring to do just this. ``` Connection c = ... c.prepareCall("select ...").getResultSet(); ``` Besides, you get an advantage by using an object as a DTO. You don't need to change your DTO class even if your data acess or your report tool changes (let's say you start using xquery instead of jdbc or you use apache-poi instead of jasper.
212,603
<p>I'm trying to write some SQL that will delete files of type '.7z' that are older than 7 days.</p> <p>Here's what I've got that's not working:</p> <pre><code>DECLARE @DateString CHAR(8) SET @DateString = CONVERT(CHAR(8), DATEADD(d, -7, GETDATE()), 1) EXECUTE master.dbo.xp_delete_file 0, N'e:\Database Backups',N'7z', @DateString, 1 </code></pre> <p>I've also tried changing the '1' at the end to a '0'.</p> <p>This returns 'success', but the files aren't getting deleted.</p> <p>I'm using SQL Server 2005, Standard, w/SP2.</p>
[ { "answer_id": 212757, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>Try changing the first parameter from 0 to 1.</p>\n\n<p>Here is a small <a href=\"http://nikeshikari.blogspot.com/2008/05/tech-mssql-xpdeletefile.html\" rel=\"nofollow noreferrer\">summary on <code>xp_delete_file</code></a> I just found. Sounds a bit like you'd be out of luck with this procedure.</p>\n" }, { "answer_id": 212834, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<p>AFAIK <code>xp_delete_file</code> only delete files recognized by SQL Server 2005 (backup files, transaction logs, ...). Perhaps you can try something like this:</p>\n\n<pre>xp_cmdshell 'del &lt;filename&gt;'</pre>\n" }, { "answer_id": 212931, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 2, "selected": false, "text": "<p>This sp will only delete native sql server backup files or native maintenance report files (for security purposes)</p>\n\n<p>As Smink suggested you can use</p>\n\n<pre><code>xp_cmdshell 'del &lt;filename&gt;'\n</code></pre>\n\n<p>With the proper permissions on the folder. </p>\n" }, { "answer_id": 529770, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>Had a similar problem, found various answers. Here's what I found.</p>\n\n<p>You can't delete 7z files with xp_delete_file. This is an undocumented extended stored procedure that's a holdover from SQL 2000. It checks the first line of the file to be deleted to verify that it is either a SQL backup file or a SQL report file. It doesn't check based on the file extension. From what I gather its intended use is in maintenance plans to cleanup old backups and plan reports. </p>\n\n<p>Here's a sample based on Tomalak's link to delete backup files older than 7 days. What trips people up is the 'sys' schema, the trailing slash in the folder path, and no dot in the file extension to look for. The user that SQL Server runs as also needs to have delete permissions on the folder.</p>\n\n<pre><code>DECLARE @DeleteDate datetime\nSET @DeleteDate = DateAdd(day, -7, GetDate())\n\nEXECUTE master.sys.xp_delete_file\n0, -- FileTypeSelected (0 = FileBackup, 1 = FileReport)\nN'D:\\SQLbackups\\', -- folder path (trailing slash)\nN'bak', -- file extension which needs to be deleted (no dot)\n@DeleteDate, -- date prior which to delete\n1 -- subfolder flag (1 = include files in first subfolder level, 0 = not)\n</code></pre>\n\n<p>Note that xp_delete_file is broken in SP2 and won't work on report files; there's a hotfix for it at [<a href=\"http://support.microsoft.com/kb/938085]\" rel=\"noreferrer\">http://support.microsoft.com/kb/938085]</a>. I have not tested it with SP3. </p>\n\n<p>Since it's undocumented, xp_delete_file may go away or change in future versions of SQL Server. Many sites recommend a shell script to do the deletions instead.</p>\n" }, { "answer_id": 8790057, "author": "Holger", "author_id": 317431, "author_profile": "https://Stackoverflow.com/users/317431", "pm_score": 2, "selected": false, "text": "<p>I found this question, but the solution didn't apply to me (as it was .bak files, SQL Server itself had made, as part of a Maintenance Plan).</p>\n\n<p>The issue in my case was security. The script was being run as the user which starts SQL Server (MSSQL) (in my case and probably most cases \"network service\") didn't have access to the folder it was trying to delete files in.</p>\n\n<p>So adding \"network service\" and granting it \"modify\" helped.</p>\n" }, { "answer_id": 14978735, "author": "dwjv", "author_id": 1453224, "author_profile": "https://Stackoverflow.com/users/1453224", "pm_score": 0, "selected": false, "text": "<p>I know this is a little old but I wanted to share my frustrations with you all. I was having the same problem as a lot of these posts but nothing seemed to work. I then remembered that we have an encryption layer on the database called NetLib. This means that the backups are encrypted and as such, xp_delete_file cannot read the headers. I now use a batch file in the OS and call it from an agent job. Hope this helps someone.</p>\n" }, { "answer_id": 26486818, "author": "Jivomir Yovkov", "author_id": 4165882, "author_profile": "https://Stackoverflow.com/users/4165882", "pm_score": 0, "selected": false, "text": "<p>We usually end up in such situations when you have the database moved to another server or when a SQL instance is reinstalled on the same one but the backup is left in the old directory.\nFor example:\nYou move the database from server1 to server2, but you have a server with a maintenance plan which performs a periodic backup or you reinstall the SQL instance on server1 and\nyou restore the database.</p>\n\n<p>In the backup case the sets which are kept as information in msdb are no longer there, therefore all older backups which have been created will not be deleted as no information\nis checked from the fails derived from the tables with backup sets.</p>\n\n<pre><code>EXECUTE master.sys.xp_delete_file 0, -- FileTypeSelected (0 = FileBackup, 1 = FileReport)\n</code></pre>\n\n<p>The first argument shows that the tables from msdb are being used.</p>\n\n<p>Hope this helps someone.</p>\n" }, { "answer_id": 35384431, "author": "user5923365", "author_id": 5923365, "author_profile": "https://Stackoverflow.com/users/5923365", "pm_score": 2, "selected": false, "text": "<p>I had read many different approaches and solutions multiple individuals pursued when attempting to resolve the issue with the extended stored procedure xp_delete. \nThe solutions are:</p>\n\n<ol>\n<li>Be sure to NOT have a period (.) in the extension when configuring the SSIS maintenance task.</li>\n<li>Be sure to click on the Include First-Level sub folders if they exist for each database backup.</li>\n<li>Be sure to click on the backup files at the top. The maintenance task does check the file type. For database backups, I believe it checks the backup file header.</li>\n</ol>\n\n<p>In my scenario, all of the above were correct. There are few comments on the web where some of said the routine xp_delete is buggy. </p>\n\n<p>When the backup files were not being deleted, I extracted the SQL for the maintenance and ran it from SSMS. The resulting message was the file was not a sql server backup file. This message was erroneous as the backup could be restored successfully, resulting in an operational database.</p>\n\n<p>The database commands used to verify the database were:</p>\n\n<pre><code>RESTORE HEADERONLY FROM DISK = N'&lt;file path\\filename&gt;.Bak'\nRESTORE VERIFYONLY FROM DISK = N'&lt;file path\\filename&gt;.bak'\n</code></pre>\n\n<p>Both of the above commands indicated the backup file was valid.</p>\n\n<p>Next I opened the event viewer and found messages indicating there were login errors for the connection manager. This was strange because I had validated the connection with the test connection button. The errors were not related to any account I had created.</p>\n\n<p>Event Viewer Message:</p>\n\n<blockquote>\n <p>*The description for Event ID 17052 from source MS SQL SERVER cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.\n If the event originated on another computer, the display information had to be saved with the event.</p>\n</blockquote>\n\n<p>The following information was included with the event: </p>\n\n<blockquote>\n <p>Severity: 16 Error:18456, OS: 18456 [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'domain\\servername$'.*</p>\n</blockquote>\n\n<p>Next I logged onto a machine where xp_delete was functioning correctly. After reviewing the active directory and not finding the system account, I proceeded to the event viewer to find similar messages. Here it became evident the account for domain\\server$ is mapped to system security. </p>\n\n<p>Next step was to compare the database security where xp_delete worked against the database where it did not work. There were 2 missing logins under security in the database where xp_delete did not work. \nThe 2 missing logins were:\nNT AUTHORITY\\SYSTEM\nNT Service\\MSSQLSERVER</p>\n\n<p>After adding NT service\\MSSQLSERVER, xp_delete successfully worked.</p>\n\n<p>One approach to testing is to use the maintenance task to delete an individual file.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6624/" ]
I'm trying to write some SQL that will delete files of type '.7z' that are older than 7 days. Here's what I've got that's not working: ``` DECLARE @DateString CHAR(8) SET @DateString = CONVERT(CHAR(8), DATEADD(d, -7, GETDATE()), 1) EXECUTE master.dbo.xp_delete_file 0, N'e:\Database Backups',N'7z', @DateString, 1 ``` I've also tried changing the '1' at the end to a '0'. This returns 'success', but the files aren't getting deleted. I'm using SQL Server 2005, Standard, w/SP2.
Had a similar problem, found various answers. Here's what I found. You can't delete 7z files with xp\_delete\_file. This is an undocumented extended stored procedure that's a holdover from SQL 2000. It checks the first line of the file to be deleted to verify that it is either a SQL backup file or a SQL report file. It doesn't check based on the file extension. From what I gather its intended use is in maintenance plans to cleanup old backups and plan reports. Here's a sample based on Tomalak's link to delete backup files older than 7 days. What trips people up is the 'sys' schema, the trailing slash in the folder path, and no dot in the file extension to look for. The user that SQL Server runs as also needs to have delete permissions on the folder. ``` DECLARE @DeleteDate datetime SET @DeleteDate = DateAdd(day, -7, GetDate()) EXECUTE master.sys.xp_delete_file 0, -- FileTypeSelected (0 = FileBackup, 1 = FileReport) N'D:\SQLbackups\', -- folder path (trailing slash) N'bak', -- file extension which needs to be deleted (no dot) @DeleteDate, -- date prior which to delete 1 -- subfolder flag (1 = include files in first subfolder level, 0 = not) ``` Note that xp\_delete\_file is broken in SP2 and won't work on report files; there's a hotfix for it at [<http://support.microsoft.com/kb/938085]>. I have not tested it with SP3. Since it's undocumented, xp\_delete\_file may go away or change in future versions of SQL Server. Many sites recommend a shell script to do the deletions instead.
212,604
<p>I have a function that is effectively a replacement for print, and I want to call it without parentheses, just like calling print.</p> <pre><code># Replace print $foo, $bar, "\n"; # with myprint $foo, $bar, "\n"; </code></pre> <p>In Perl, you can create subroutines with parameter templates and it allows exactly this behavior if you define a subroutine as</p> <pre><code>sub myprint(@) { ... } </code></pre> <p>Anything similar in PHP?</p>
[ { "answer_id": 212616, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": false, "text": "<p>No, you can't do that in PHP.\nPrint isn't actually a function, it's a \"language construct\".</p>\n" }, { "answer_id": 212626, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 6, "selected": true, "text": "<p>print is not a <a href=\"http://ca.php.net/manual/en/functions.variable-functions.php\" rel=\"noreferrer\">variable functions</a></p>\n\n<blockquote>\n <p>Because this is a language construct\n and not a function, it cannot be\n called using variable functions</p>\n</blockquote>\n\n<p>And :</p>\n\n<blockquote>\n <p>Variable functions</p>\n \n <p>PHP supports the concept of variable\n functions. This means that if a\n variable name has parentheses appended\n to it, PHP will look for a function\n with the same name as whatever the\n variable evaluates to, and will\n attempt to execute it. Among other\n things, this can be used to implement\n callbacks, function tables, and so\n forth.</p>\n</blockquote>\n" }, { "answer_id": 212652, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 4, "selected": false, "text": "<p>Only by editing the PHP codebase and adding a new language construct.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 215550, "author": "Steve Gattuso", "author_id": 29291, "author_profile": "https://Stackoverflow.com/users/29291", "pm_score": 2, "selected": false, "text": "<p>Nope, PHP won't allow you to do that.</p>\n" }, { "answer_id": 5452710, "author": "Marcelo", "author_id": 679386, "author_profile": "https://Stackoverflow.com/users/679386", "pm_score": 2, "selected": false, "text": "<p>I was looking for a way to code a echoh to do something like:<br></p>\n\n<pre><code>echoh \"hello\";\n</code></pre>\n\n<p>and get:<br></p>\n\n<pre><code>'hello&lt;br&gt;\\n'.\n</code></pre>\n\n<p>I guess one solution could be defining a constant and use it:</p>\n\n<pre><code>&lt;?php\nconst PHP_BR_EOL = \"&lt;br&gt;\\n\";\necho \"Hello\" . PHP_BR_EOL;\n?&gt;\n</code></pre>\n\n<p>Now I get:<br></p>\n\n<pre><code>Hello&lt;br&gt;\n</code></pre>\n\n<p>I know it requires more typing, but it is more complient with the examples on the PHP manual, and I use gvim with omnicomplete to save on the typing. Also it would be easy to do a global search/replace PHP_EOL by PHP_BR_EOL.</p>\n" }, { "answer_id": 52183017, "author": "Joshua", "author_id": 6768138, "author_profile": "https://Stackoverflow.com/users/6768138", "pm_score": 0, "selected": false, "text": "<p>That can't be done with PHP. Functions you declare must be called with brackets.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8454/" ]
I have a function that is effectively a replacement for print, and I want to call it without parentheses, just like calling print. ``` # Replace print $foo, $bar, "\n"; # with myprint $foo, $bar, "\n"; ``` In Perl, you can create subroutines with parameter templates and it allows exactly this behavior if you define a subroutine as ``` sub myprint(@) { ... } ``` Anything similar in PHP?
print is not a [variable functions](http://ca.php.net/manual/en/functions.variable-functions.php) > > Because this is a language construct > and not a function, it cannot be > called using variable functions > > > And : > > Variable functions > > > PHP supports the concept of variable > functions. This means that if a > variable name has parentheses appended > to it, PHP will look for a function > with the same name as whatever the > variable evaluates to, and will > attempt to execute it. Among other > things, this can be used to implement > callbacks, function tables, and so > forth. > > >
212,614
<p>Should a method that implements an interface method be annotated with <code>@Override</code>?</p> <p>The <a href="http://java.sun.com/javase/6/docs/api/java/lang/Override.html" rel="noreferrer">javadoc of the <code>Override</code> annotation</a> says: </p> <blockquote> <p>Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.</p> </blockquote> <p>I don't think that an interface is technically a superclass. Or is it?</p> <p><kbd><a href="https://stackoverflow.com/revisions/212614/5">Question Elaboration</a></kbd></p>
[ { "answer_id": 212624, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 9, "selected": true, "text": "<p>You should use @Override whenever possible. It prevents simple mistakes from being made. Example:</p>\n\n<pre><code>class C {\n @Override\n public boolean equals(SomeClass obj){\n // code ...\n }\n}\n</code></pre>\n\n<p>This doesn't compile because it doesn't properly override <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)\" rel=\"noreferrer\"><code>public boolean equals(Object obj)</code></a>.</p>\n\n<p>The same will go for methods that implement an interface (<strong>1.6 and above only</strong>) or override a Super class's method.</p>\n" }, { "answer_id": 212640, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 4, "selected": false, "text": "<p>I would use it at every opportunity. See <a href=\"https://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why\">When do you use Java's @Override annotation and why?</a></p>\n" }, { "answer_id": 212642, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "<p>I believe that javac behaviour has changed - with 1.5 it prohibited the annotation, with 1.6 it doesn't. The annotation provides an extra compile-time check, so if you're using 1.6 I'd go for it.</p>\n" }, { "answer_id": 213888, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 2, "selected": false, "text": "<p>Overriding your own methods inherited from your own classes will typically not break on refactorings using an ide. But if you override a method inherited from a library it is recommended to use it. If you dont, you will often get no error on a later library change, but a well hidden bug.</p>\n" }, { "answer_id": 213896, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 1, "selected": false, "text": "<p>Eclipse itself will add the <code>@Override</code> annotation when you tell it to \"generate unimplemented methods\" during creation of a class that implements an interface.</p>\n" }, { "answer_id": 490087, "author": "Fabian Steeg", "author_id": 18154, "author_profile": "https://Stackoverflow.com/users/18154", "pm_score": 2, "selected": false, "text": "<p>For me, often times this is the only reason some code requires Java 6 to compile. Not sure if it's worth it.</p>\n" }, { "answer_id": 964567, "author": "Silent Warrior", "author_id": 87582, "author_profile": "https://Stackoverflow.com/users/87582", "pm_score": 4, "selected": false, "text": "<p>JDK 5.0 does not allow you to use <code>@Override</code> annotation if you are implementing method declared in interface (its compilation error), but JDK 6.0 allows it. So may be you can configure your project preference according to your requirement. </p>\n" }, { "answer_id": 4342846, "author": "Jackie", "author_id": 410289, "author_profile": "https://Stackoverflow.com/users/410289", "pm_score": 2, "selected": false, "text": "<p>It's not a problem with JDK. In Eclipse Helios, it allows the @Override annotation for implemented interface methods, whichever JDK 5 or 6. As for Eclipse Galileo, the @Override annotation is not allowed, whichever JDK 5 or 6.</p>\n" }, { "answer_id": 8266820, "author": "GKelly", "author_id": 18744, "author_profile": "https://Stackoverflow.com/users/18744", "pm_score": 6, "selected": false, "text": "<p>You should always annotate methods with <code>@Override</code> if it's available. </p>\n\n<p>In JDK 5 this means overriding methods of superclasses, in JDK 6, and 7 it means overriding methods of superclasses, and implementing methods of interfaces. The reason, as mentioned previously, is it allows the compiler to catch errors where you think you are overriding (or implementing) a method, but are actually defining a new method (different signature). </p>\n\n<p>The <code>equals(Object)</code> vs. <code>equals(YourObject)</code> example is a standard case in point, but the same argument can be made for interface implementations.</p>\n\n<p>I'd imagine the reason it's not mandatory to annotate implementing methods of interfaces is that JDK 5 flagged this as a compile error. If JDK 6 made this annotation mandatory, it would break backwards compatibility. </p>\n\n<p>I am not an Eclipse user, but in other IDEs (IntelliJ), the <code>@Override</code> annotation is only added when implementing interface methods if the project is set as a JDK 6+ project. I would imagine that Eclipse is similar.</p>\n\n<p>However, I would have preferred to see a different annotation for this usage, maybe an <code>@Implements</code> annotation.</p>\n" }, { "answer_id": 22517730, "author": "spujia", "author_id": 4339042, "author_profile": "https://Stackoverflow.com/users/4339042", "pm_score": 2, "selected": false, "text": "<p>The problem with including the <code>@Override</code> is that it makes you think that you forgot to call the <code>super.theOverridenMethod()</code> method, which is <em>very confusing</em>. This should be crystal-clear. Perhaps Java should offer an <code>@Interface</code> to be used here. Oh well, yet another half-assed Java peculiarity...</p>\n" }, { "answer_id": 34366091, "author": "juanchito", "author_id": 2019874, "author_profile": "https://Stackoverflow.com/users/2019874", "pm_score": 3, "selected": false, "text": "<p>If a <strong>concrete</strong> class is not <strong>overriding</strong> an abstract method, using <code>@Override</code> for <strong>implementation</strong> is an open matter since the compiler will invariably warn you of any unimplemented methods. In these cases, an argument can be made that it detracts from readability -- it is more things to read on your code and, to a lesser degree, it is called <code>@Override</code> and not <code>@Implement</code>.</p>\n" }, { "answer_id": 39740106, "author": "ZhaoGang", "author_id": 2830167, "author_profile": "https://Stackoverflow.com/users/2830167", "pm_score": 2, "selected": false, "text": "<p>In java 6 and later versions, you can use <code>@Override</code> for a method implementing an interface. </p>\n\n<p>But, I donot think it make sense: override means you hava a method in the super class, and you are implementing it in the sub class. </p>\n\n<p>If you are implementing an interface, I think we should use <code>@Implement</code> or something else, but not the <code>@Override</code>. </p>\n" }, { "answer_id": 49185682, "author": "Zhao Pengfei", "author_id": 7608372, "author_profile": "https://Stackoverflow.com/users/7608372", "pm_score": 3, "selected": false, "text": "<p>By reading the javadoc in java8, you can find the following at the declaration of interface Override:</p>\n\n<p>If a method is annotated with this annotation type compilers are required to generate an error message unless at least one of the following conditions hold:</p>\n\n<ul>\n<li>The method does override or implement a method declared in a supertype.</li>\n<li>The method has a signature that is override-equivalent to that of any public method declared in {@linkplain Object}.</li>\n</ul>\n\n<p>So, at least in java8, you should use @Override on an implementation of an interface method.</p>\n" }, { "answer_id": 54490813, "author": "Madhu", "author_id": 1981792, "author_profile": "https://Stackoverflow.com/users/1981792", "pm_score": 2, "selected": false, "text": "<p>If the class that is implementing the <code>interface</code> is an <code>abstract</code> class, <code>@Override</code> is useful to ensure that the implementation is for an <code>interface</code> method; without the <code>@Override</code> an <code>abstract</code> class would just compile fine even if the implementation method signature does not match the method declared in the <code>interface</code>; the mismatched <code>interface</code> method would remain as unimplemented.\nThe Java doc cited by @Zhao</p>\n\n<blockquote>\n <p>The method does override or implement a method declared in a supertype</p>\n</blockquote>\n\n<p>is clearly referring to an <code>abstract</code> super class; an <code>interface</code> can not be called the supertype.\nSo, <code>@Override</code> is redundant and not sensible for <code>interface</code> method implementations in concrete classes.</p>\n" }, { "answer_id": 70855508, "author": "smilyface", "author_id": 2086966, "author_profile": "https://Stackoverflow.com/users/2086966", "pm_score": 1, "selected": false, "text": "<p>This might be too late answer. But I hope this example would help someone to understand why <code>@override</code> is so important (for a scenario like this)</p>\n<pre><code>public interface Restaurant(){\n public boolean getBill();\n public BigDecimal payAmount();\n}\n\npublic interface Food() extends Restaurant{\n public boolean haveSomeFood();\n public boolean drinkWater();\n}\n\npublic class Hungry() implements Food{\n public boolean haveSomeFood(){}\n public boolean drinkWater(){}\n public boolean getBill(){}\n public BigDecimal payAmount(){}\n}\n</code></pre>\n<p>In the above example, If I am <code>Hungry</code>, I can have <code>Food</code> from a <code>Restaurant</code>. But if I took out the implementation of Restaurant, I do not have to get a bill and no need to pay the amount!!!!</p>\n<p><strong>How?</strong><br></p>\n<ul>\n<li>The interface <code>Food</code> has the keyword <code>extends Restaurant</code> - which\nmeans the class Hungry is also implemented from the interface\nRestaurant.</li>\n<li>The methods actually overriden from the interface <em>does\nnot</em> have the keyword <code>@override</code></li>\n<li>So, if I remove the keyword extends\nRestaurant (or say if I remove the interface Restaurant, it will not\nshow any error.</li>\n</ul>\n<p>If there was <code>@override</code>, whenever I am trying to remove the Restaurant interface it will show compilation error.</p>\n<p><strong>Note</strong>: When you implement an interface, you might not know whether that interface is extended to another interface or can be extended or the inheritance may be removed. So it is always better to use <code>@override</code> keyword</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3565/" ]
Should a method that implements an interface method be annotated with `@Override`? The [javadoc of the `Override` annotation](http://java.sun.com/javase/6/docs/api/java/lang/Override.html) says: > > Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message. > > > I don't think that an interface is technically a superclass. Or is it? `[Question Elaboration](https://stackoverflow.com/revisions/212614/5)`
You should use @Override whenever possible. It prevents simple mistakes from being made. Example: ``` class C { @Override public boolean equals(SomeClass obj){ // code ... } } ``` This doesn't compile because it doesn't properly override [`public boolean equals(Object obj)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)). The same will go for methods that implement an interface (**1.6 and above only**) or override a Super class's method.
212,657
<p>Within a stored procedure, another stored procedure is being called within a cursor. For every call, the SQL Management Studio results window is showing a result. The cursor loops over 100 times and at that point the results window gives up with an error. Is there a way I can stop the stored procedure within the cursor from outputting any results?</p> <pre><code> WHILE @@FETCH_STATUS = 0 BEGIN EXEC @RC = dbo.NoisyProc SELECT @RValue2 = 1 WHERE @@ROWCOUNT = 0 FETCH NEXT FROM RCursor INTO @RValue1, @RValue2 END </code></pre> <p>Thanks!</p>
[ { "answer_id": 212670, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 0, "selected": false, "text": "<p>Place:</p>\n\n<pre><code>SET ROWCOUNT OFF\n/* the internal SP */\nSET ROWCOUNT ON\n</code></pre>\n\n<p>wrap that around the internal SP, or you could even do it around the SELECT statement from the originating query, that will prevent results from appearing.</p>\n" }, { "answer_id": 212833, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 5, "selected": true, "text": "<p>you could insert the results into a temp table, then drop the temp table</p>\n\n<pre><code>create table #tmp (columns)\n\nwhile\n ...\n insert into #tmp exec @RC=dbo.NoisyProc\n ...\nend\ndrop table #tmp\n</code></pre>\n\n<p>otherwise, can you modify the proc being called to accept a flag telling it not to output a result-set?</p>\n" }, { "answer_id": 213011, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 5, "selected": false, "text": "<p>You can discard the resultsets in SQL Server Mgmt Studio 2005 \nby following the steps below:</p>\n\n<p>\n&bull; Right-click in the query window<br/>&bull; Choose \"Query Options\"<br/>&bull; Click on the \"Results\" \"node\" in the left panel tree view<br/>&bull; Check \"Discard results after execution\" in the center/right of the form\n</p>\n\n<p>You can try it on</p>\n\n<pre><code>DECLARE @i int\nSET @i = 1\nWHILE (@i &lt;= 100)\n BEGIN\n SELECT @i as Iteration\n SET @i = @i + 1\n END\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 213059, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "<p>Cursors bad. Don't reuse stored proc code if it means you have to do a set-based function with a cursor. Better for performance to write the code in a set-nbased fashion. </p>\n\n<p>I think I'm concerned that you are more concerned with supressing the messages than you are that you have an error in the cursor. </p>\n" }, { "answer_id": 213328, "author": "Joe Pineda", "author_id": 21258, "author_profile": "https://Stackoverflow.com/users/21258", "pm_score": 1, "selected": false, "text": "<p>Probably the error comes from too much recordsets being returned, rather than a logic flaw on your SP or the cursor itself. Look at this example:</p>\n\n<pre><code>DECLARE @I INT\nSET @I=0\nWHILE @I&lt;200 BEGIN\n SELECT * FROM INFORMATION_SCHEMA.TABLES\n SET @I = @I + 1\nEND\n</code></pre>\n\n<p>Will run a number of times (slightly more than 100) then fail with:</p>\n\n<blockquote>\n <p>The query has exceeded the maximum number of result sets that can be displayed in the results grid. Only the first 100 result sets are displayed in the grid.</p>\n</blockquote>\n\n<p>The SSMS has a limit on the number of record-sets it can show you.\nOne quick way to by-pass that limitation is to press Ctrl+T (or menu Query->Results to->Results to Text) to force the output to be in plain text, rather than table-like recordsets. You'll reach another limit eventually (the results window can't handle an infinite amount of text output) yet it will be far greater.</p>\n\n<p>In the sample above you don't get the error after changing the results to be in text form!</p>\n" }, { "answer_id": 4994183, "author": "Estanislao", "author_id": 444920, "author_profile": "https://Stackoverflow.com/users/444920", "pm_score": 4, "selected": false, "text": "<p>I know this question is old, but you could set the <code>SET NOCOUNT ON</code> to prevent the SP to output a message for every row.</p>\n" }, { "answer_id": 62730206, "author": "Todd Albers", "author_id": 13508595, "author_profile": "https://Stackoverflow.com/users/13508595", "pm_score": 1, "selected": false, "text": "<p>This page is old and the replies are old. But, the best answer has not been upvoted to the top. I suppose it is because not enough explanation was provided.</p>\n<p>Use the NOCOUNT setting. Everyone should look at the NOCOUNT setting. The default setting is OFF.</p>\n<p>Changing the default setting of a this universally even on a new database may cause confusion for some coders\\users. I recommend using the approach of capturing the setting before changing it, then setting it back. This is shown in the example script below which demonstrates use of the NOCOUNT setting.</p>\n<p>Here is a good article.\n<a href=\"https://www.sqlshack.com/set-nocount-on-statement-usage-and-performance-benefits-in-sql-server/\" rel=\"nofollow noreferrer\">https://www.sqlshack.com/set-nocount-on-statement-usage-and-performance-benefits-in-sql-server/</a></p>\n<pre><code>DROP TABLE IF EXISTS TestTable\nGO\nCREATE TABLE TestTable (ID INT, TestText VARCHAR (40))\nGO\n\n-- Get the Original NOCOUNT setting and save it to @OriginalNoCountSettingIsOn\nDECLARE @options INT\nSET @options = @@OPTIONS\nDECLARE @OriginalNoCountSettingIsOn AS bit\nSET @OriginalNoCountSettingIsOn = IIF(( (512 &amp; @@OPTIONS) = 512 ),1,0)\n\n-- Now set NOCOUNT ON to suppress result output returned from INSERTS \n-- Note - this does not affect @@ROWCOUNT values from being set \nSET NOCOUNT ON -- &lt;---- Try running script with SET NOCOUNT ON and SET NOCOUNT OFF to See difference\n\nINSERT INTO TestTable (ID, TestText)\nVALUES (0, 'Test Row 1')\n\nINSERT INTO TestTable (ID, TestText)\nVALUES (0, 'Test Row 2'),\n (0, 'Test Row 3'),\n (0, 'Test Row 4')\n\nINSERT INTO TestTable (ID, TestText)\nVALUES (0, 'Test Row 5')\n\n/*Now set NOCOUNT back to original setting*/\nIF @OriginalNoCountSettingIsOn = 1 \nBEGIN\n SET NOCOUNT ON\nEND\nELSE\nBEGIN\n SET NOCOUNT OFF\nEND \n\nDROP TABLE IF EXISTS TestTable\nGO\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
Within a stored procedure, another stored procedure is being called within a cursor. For every call, the SQL Management Studio results window is showing a result. The cursor loops over 100 times and at that point the results window gives up with an error. Is there a way I can stop the stored procedure within the cursor from outputting any results? ``` WHILE @@FETCH_STATUS = 0 BEGIN EXEC @RC = dbo.NoisyProc SELECT @RValue2 = 1 WHERE @@ROWCOUNT = 0 FETCH NEXT FROM RCursor INTO @RValue1, @RValue2 END ``` Thanks!
you could insert the results into a temp table, then drop the temp table ``` create table #tmp (columns) while ... insert into #tmp exec @RC=dbo.NoisyProc ... end drop table #tmp ``` otherwise, can you modify the proc being called to accept a flag telling it not to output a result-set?
212,681
<p>I have a SQL Server 2000 database with around a couple of hundred tables. There are several SQL user accounts that can access this database but each one has different permissions granted on tables in the DB. </p> <p>How do I create a script to give me a report of the permissions granted to a particular user. i.e. to generate something like:</p> <pre><code>Table SELECT DELETE UPDATE INSERT ALTER ----- ------ ------ ------ ------ ----- Invoices Yes No Yes Yes No Orders Yes Yes Yes Yes No Customers Yes No Yes Yes No </code></pre> <p>and so on. It's Friday, my SQL-fu is low today and I have a million other things to do before getting finished here today and if someone had a handy script to do this already then I would be eternally grateful :)</p>
[ { "answer_id": 212680, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": 3, "selected": false, "text": "<p>Wow, no.</p>\n\n<p>Modern C++ compilers are excellent. Massive memory usage is more of a symptom of a poor design or large memory data set. The overhead needed for C++ classes is minimal and really not a problem these days.</p>\n\n<p>Object oriented programming is a way to write components in such a way that they can logically group actions related to a single concept (ie, all actions for a 'car' or all actions for a 'cat'). That's not to say it can't be misused to write spaghetti objects, but as they say, you can write COBOL in any language.</p>\n\n<p>As a further example, it's quite possible and accepted these days to write for embedded software platforms with C++ and objects. The slight speed decrease and memory usage increase (if any) is repaid a thousand times over by increased maintainability and code usability.</p>\n" }, { "answer_id": 212719, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 0, "selected": false, "text": "<p><strong>Think about the costs of an hour of a developer's time.</strong></p>\n\n<p><strong>Think about the cost of an hour of CPU time.</strong></p>\n\n<p>And that being said, the performance loss by coding object oriented is absolutely neglectable. Particularly considering that when your program computes, it computes <em>something</em> - and that is probably much more dependant on the nature of the algorithm used than on whether or not OOP is in use.</p>\n" }, { "answer_id": 212747, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "<p>I haven't read the book, but I have trouble believe that they wrote a book whose \"basis ...is that Object Oriented Programming is highly wasteful memory-wise\" (Full disclosure: Andy &amp; Barbara are friends of mine). </p>\n\n<p>Andy would never say the OOP is wasteful of memory. He WOULD say that a particular algorithm or technique is wasteful, and might recommend a less OO approach in some cases, but, he would be the first to argue that as a general rule OO designs are no more or less wasteful that any other style of programming. </p>\n\n<p>The argument that OO designs are wasteful largely came from the fact that the EXEs of C++ \"hello world\" programs tend to be larger that the EXEs of C \"hello world\" programs. This is mostly because iostreams is larger the printf (but then, iostreams does more). </p>\n" }, { "answer_id": 212830, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 2, "selected": false, "text": "<p>C++ and OOP are not inefficient per se, but it I have seen many C++ programs perform an operation in a less efficient manner than the equivalent C program. The biggest culprit is often due to lots of small memory allocations occurring due to <em>new</em>ing individual objects rather than <em>malloc</em>ing a whole bunch of them at once. Similarly, polymorphism and virtual functions are great, but they do incur an overhead that some C++ programmers are not aware of. Piecewise construction of objects can also be a lot slower than one dirty great <em>memset</em> of the aforementioned <em>malloc</em>ed array of structs.</p>\n\n<p>My guess is that for most applications, on modern computers, this is not really an issue. Given that C++ also includes all of C as a subset, there is also nothing to stop you mixing and matching paradigms as situations demand. Newer heap handlers are also way better than the early MS efforts, and are a bg help.</p>\n" }, { "answer_id": 212852, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>The basis of this book is that Object\n Oriented Programming is highly\n wasteful memory-wise, and that most\n source-code should not be written this\n way, rather that you should use all\n inline function calls and procedural\n programming.</p>\n</blockquote>\n\n<p>I would say this is a somewhat reductive summary of <a href=\"http://www.acceleratedcpp.com/details/contents.html\" rel=\"nofollow noreferrer\">the book</a>.</p>\n\n<p>In short, to answer the title question, I would continue to recommend both the book and the concepts included therein.</p>\n\n<p>I suspect that the advice is more along the lines that someone shouldn't create a class just to implement an algorithm, which I would say remains good advice.</p>\n" }, { "answer_id": 213446, "author": "Raindog", "author_id": 29049, "author_profile": "https://Stackoverflow.com/users/29049", "pm_score": -1, "selected": false, "text": "<p>Some of the answers are totally missing the point. OOP in C++ has many opportunities to be much faster than their C counterparts. I'll give the example from I think Effective C++ by Scott Meyers, which is that quicksort runs slower than C++ sort because the compiler is able to inline the function call easily in C++ whereas it is unable to do so in C due to quicksort being passed a function pointer. </p>\n\n<p>Additionally, nothing about c++ makes it slow, unlike other languages, any slowness is purely library implementations or algorithm design.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
I have a SQL Server 2000 database with around a couple of hundred tables. There are several SQL user accounts that can access this database but each one has different permissions granted on tables in the DB. How do I create a script to give me a report of the permissions granted to a particular user. i.e. to generate something like: ``` Table SELECT DELETE UPDATE INSERT ALTER ----- ------ ------ ------ ------ ----- Invoices Yes No Yes Yes No Orders Yes Yes Yes Yes No Customers Yes No Yes Yes No ``` and so on. It's Friday, my SQL-fu is low today and I have a million other things to do before getting finished here today and if someone had a handy script to do this already then I would be eternally grateful :)
I haven't read the book, but I have trouble believe that they wrote a book whose "basis ...is that Object Oriented Programming is highly wasteful memory-wise" (Full disclosure: Andy & Barbara are friends of mine). Andy would never say the OOP is wasteful of memory. He WOULD say that a particular algorithm or technique is wasteful, and might recommend a less OO approach in some cases, but, he would be the first to argue that as a general rule OO designs are no more or less wasteful that any other style of programming. The argument that OO designs are wasteful largely came from the fact that the EXEs of C++ "hello world" programs tend to be larger that the EXEs of C "hello world" programs. This is mostly because iostreams is larger the printf (but then, iostreams does more).
212,689
<p>I have implemented a pretty simple picture viewer that will allow the user to browse through a collection of images. They are loaded from the Internet, and displayed on the device through a <code>UIImageView</code> object. Something like this:</p> <pre><code>UIImage *image = [[UIImage alloc] initWithData:imageData]; [img setImage:image]; </code></pre> <p><code>imageData</code> is an instance of <code>NSData</code> that I use to load the contents of the image from an URL, and <code>img</code> is the <code>UIImageView</code> instance.</p> <p>It all works well, but the new image replaces the one being displayed before without any transitions, and I was wondering if there is an easy way to do a good animation transition to improve the user experience.</p> <p>Any idea how to do this? Code samples would be very appreciated.</p>
[ { "answer_id": 213327, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 2, "selected": false, "text": "<p>The trick is you make two UIImageView instances. You swap them in between calls to UIView +beginAnimations and +commitAnimations.</p>\n" }, { "answer_id": 223423, "author": "Jamey McElveen", "author_id": 30099, "author_profile": "https://Stackoverflow.com/users/30099", "pm_score": 1, "selected": false, "text": "<p>There are several ways to do it and I agree with Ben View Transitions is a great example. If you are looking for simple full screen transitions I would just consider starting a new utility application and look at toggleView method in the <code>RootViewController.m</code>. Try switching out the <code>UIViewAnimationTransitionFlipFromLeft</code> and <code>UIViewAnimationTransitionFlipFromRight</code> to <code>UIViewAnimationTransitionCurlUp</code> and <code>UIViewAnimationTransitionCurlDown</code> for a really nice transition effect (this only works on the device). </p>\n" }, { "answer_id": 353724, "author": "Rob", "author_id": 386102, "author_profile": "https://Stackoverflow.com/users/386102", "pm_score": 2, "selected": false, "text": "<p>Nothing different from what's been explained but in code, these are the available transitions:</p>\n\n<pre><code>typedef enum {\n UIViewAnimationTransitionNone,\n UIViewAnimationTransitionFlipFromLeft,\n UIViewAnimationTransitionFlipFromRight,\n UIViewAnimationTransitionCurlUp,\n UIViewAnimationTransitionCurlDown,\n } UIViewAnimationTransition;\n</code></pre>\n\n<p><strong>Code</strong> <em>(Put this in a callback like touchesEnded)</em>:</p>\n\n<pre><code>CGContextRef context = UIGraphicsGetCurrentContext();\n[UIView beginAnimations:nil context:context];\n\n[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:[self superview] cache:YES];\n\n// -- These don't work on the simulator and the curl up will turn into a fade -- //\n//[UIView setAnimationTransition: UIViewAnimationTransitionCurlUp forView:[self superview] cache:YES];\n//[UIView setAnimationTransition: UIViewAnimationTransitionCurlDown forView:[self superview] cache:YES];\n\n[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];\n[UIView setAnimationDuration:1.0];\n\n// Below assumes you have two subviews that you're trying to transition between\n[[self superview] exchangeSubviewAtIndex:0 withSubviewAtIndex:1];\n[UIView commitAnimations];\n</code></pre>\n" }, { "answer_id": 967816, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>here is what i have done: a fading.\ni put another UIImageView with the same UIImage and dimension called tmp.\ni replace the UIImage of the base UIImageView.\nThen i put the right image on the base (still covered by tmp).</p>\n\n<p>Next step is \n- to set alpha of tmp to zero, \n- to stretch the base UIImageView to right ratio of the new UIImage based on the height of the base.</p>\n\n<p>Here is the code:</p>\n\n<pre><code> UIImage *img = [params objectAtIndex:0]; // the right image\nUIImageView *view = [params objectAtIndex:1]; // the base\n\nUIImageView *tmp = [[UIImageView alloc] initWithImage:view.image]; // the one which will use to fade\ntmp.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);\n[view addSubview:tmp];\n\nview.image = img;\nfloat r = img.size.width / img.size.height;\nfloat h = view.frame.size.height;\nfloat w = h * r;\nfloat x = view.center.x - w/2;\nfloat y = view.frame.origin.y;\n\n[UIView beginAnimations:nil context:nil];\n[UIView setAnimationDuration:1.0];\n\ntmp.alpha = 0;\nview.frame = CGRectMake(x, y, w, h);\n\n[UIView commitAnimations];\n\n[tmp performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:1.5];\n[tmp performSelector:@selector(release) withObject:nil afterDelay:2];\n</code></pre>\n" }, { "answer_id": 3545591, "author": "Raj Pawan Gumdal", "author_id": 260665, "author_profile": "https://Stackoverflow.com/users/260665", "pm_score": 4, "selected": false, "text": "<p>I was just going through your post and had exactly the same requirement. The problem with all above solutions is, you will have to incorporate the logic of transition into your controller. In the sense the approach is not modular. Instead I wrote this subclass of UIImageView:</p>\n\n<p><strong>TransitionImageView.h file:</strong></p>\n\n<pre><code>#import &lt;UIKit/UIKit.h&gt;\n\n\n@interface TransitionImageView : UIImageView \n{\n UIImageView *mOriginalImageViewContainerView;\n UIImageView *mIntermediateTransitionView;\n}\n@property (nonatomic, retain) UIImageView *originalImageViewContainerView;\n@property (nonatomic, retain) UIImageView *intermediateTransitionView;\n\n#pragma mark -\n#pragma mark Animation methods\n-(void)setImage:(UIImage *)inNewImage withTransitionAnimation:(BOOL)inAnimation;\n\n@end\n</code></pre>\n\n<p><strong>TransitionImageView.m file:</strong></p>\n\n<pre><code>#import \"TransitionImageView.h\"\n\n#define TRANSITION_DURATION 1.0\n\n@implementation TransitionImageView\n@synthesize intermediateTransitionView = mIntermediateTransitionView;\n@synthesize originalImageViewContainerView = mOriginalImageViewContainerView;\n\n- (id)initWithFrame:(CGRect)frame {\n if ((self = [super initWithFrame:frame])) {\n // Initialization code\n }\n return self;\n}\n\n/*\n// Only override drawRect: if you perform custom drawing.\n// An empty implementation adversely affects performance during animation.\n- (void)drawRect:(CGRect)rect {\n // Drawing code\n}\n*/\n\n- (void)dealloc \n{\n [self setOriginalImageViewContainerView:nil];\n [self setIntermediateTransitionView:nil];\n [super dealloc];\n}\n\n#pragma mark -\n#pragma mark Animation methods\n-(void)setImage:(UIImage *)inNewImage withTransitionAnimation:(BOOL)inAnimation\n{\n if (!inAnimation)\n {\n [self setImage:inNewImage];\n }\n else\n {\n // Create a transparent imageView which will display the transition image.\n CGRect rectForNewView = [self frame];\n rectForNewView.origin = CGPointZero;\n UIImageView *intermediateView = [[UIImageView alloc] initWithFrame:rectForNewView];\n [intermediateView setBackgroundColor:[UIColor clearColor]];\n [intermediateView setContentMode:[self contentMode]];\n [intermediateView setClipsToBounds:[self clipsToBounds]];\n [intermediateView setImage:inNewImage];\n\n // Create the image view which will contain original imageView's contents:\n UIImageView *originalView = [[UIImageView alloc] initWithFrame:rectForNewView];\n [originalView setBackgroundColor:[UIColor clearColor]];\n [originalView setContentMode:[self contentMode]];\n [originalView setClipsToBounds:[self clipsToBounds]];\n [originalView setImage:[self image]];\n\n // Remove image from the main imageView and add the originalView as subView to mainView:\n [self setImage:nil];\n [self addSubview:originalView];\n\n // Add the transparent imageView as subview whose dimensions are same as the view which holds it.\n [self addSubview:intermediateView];\n\n // Set alpha value to 0 initially:\n [intermediateView setAlpha:0.0];\n [originalView setAlpha:1.0];\n [self setIntermediateTransitionView:intermediateView];\n [self setOriginalImageViewContainerView:originalView];\n [intermediateView release];\n [originalView release];\n\n // Begin animations:\n [UIView beginAnimations:@\"ImageViewTransitions\" context:nil];\n [UIView setAnimationDuration:(double)TRANSITION_DURATION];\n [UIView setAnimationDelegate:self];\n [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];\n [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];\n [[self intermediateTransitionView] setAlpha:1.0];\n [[self originalImageViewContainerView] setAlpha:0.0];\n [UIView commitAnimations];\n }\n}\n\n-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context\n{\n // Reset the alpha of the main imageView\n [self setAlpha:1.0];\n\n // Set the image to the main imageView:\n [self setImage:[[self intermediateTransitionView] image]];\n\n [[self intermediateTransitionView] removeFromSuperview];\n [self setIntermediateTransitionView:nil];\n\n [[self originalImageViewContainerView] removeFromSuperview];\n [self setOriginalImageViewContainerView:nil];\n}\n\n@end\n</code></pre>\n\n<p>You can even override the <code>-setImage</code> method of UIImageView and call my <code>-setImage:withTransitionAnimation:</code> method. If it is done like this make sure that you call <code>[super setImage:]</code> instead of <code>[self setImage:]</code> in the method <code>-setImage:withTransitionAnimation:</code> so that it wont end up in infinite recursive call!</p>\n\n<p>-Raj</p>\n" }, { "answer_id": 5689021, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 3, "selected": false, "text": "<pre><code>[UIView \n animateWithDuration:0.2 \n delay:0 \n options:UIViewAnimationCurveEaseOut\n animations:^{\n self.view0.alpha = 0;\n self.view1.alpha = 1;\n }\n completion:^(BOOL finished){\n view0.hidden = YES;\n }\n];\n</code></pre>\n" }, { "answer_id": 24158507, "author": "Manab Kumar Mal", "author_id": 2905967, "author_profile": "https://Stackoverflow.com/users/2905967", "pm_score": 2, "selected": false, "text": "<p>Please check the answer. I think you are looking for this:</p>\n\n<pre><code>imgvw.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@\"Your Image name as string\"]]];\nCATransition *transition = [CATransition animation];\ntransition.duration = 1.0f;\ntransition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];\ntransition.type = kCATransitionFade;\n[imgvw.layer addAnimation:transition forKey:nil];\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have implemented a pretty simple picture viewer that will allow the user to browse through a collection of images. They are loaded from the Internet, and displayed on the device through a `UIImageView` object. Something like this: ``` UIImage *image = [[UIImage alloc] initWithData:imageData]; [img setImage:image]; ``` `imageData` is an instance of `NSData` that I use to load the contents of the image from an URL, and `img` is the `UIImageView` instance. It all works well, but the new image replaces the one being displayed before without any transitions, and I was wondering if there is an easy way to do a good animation transition to improve the user experience. Any idea how to do this? Code samples would be very appreciated.
I was just going through your post and had exactly the same requirement. The problem with all above solutions is, you will have to incorporate the logic of transition into your controller. In the sense the approach is not modular. Instead I wrote this subclass of UIImageView: **TransitionImageView.h file:** ``` #import <UIKit/UIKit.h> @interface TransitionImageView : UIImageView { UIImageView *mOriginalImageViewContainerView; UIImageView *mIntermediateTransitionView; } @property (nonatomic, retain) UIImageView *originalImageViewContainerView; @property (nonatomic, retain) UIImageView *intermediateTransitionView; #pragma mark - #pragma mark Animation methods -(void)setImage:(UIImage *)inNewImage withTransitionAnimation:(BOOL)inAnimation; @end ``` **TransitionImageView.m file:** ``` #import "TransitionImageView.h" #define TRANSITION_DURATION 1.0 @implementation TransitionImageView @synthesize intermediateTransitionView = mIntermediateTransitionView; @synthesize originalImageViewContainerView = mOriginalImageViewContainerView; - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { // Initialization code } return self; } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ - (void)dealloc { [self setOriginalImageViewContainerView:nil]; [self setIntermediateTransitionView:nil]; [super dealloc]; } #pragma mark - #pragma mark Animation methods -(void)setImage:(UIImage *)inNewImage withTransitionAnimation:(BOOL)inAnimation { if (!inAnimation) { [self setImage:inNewImage]; } else { // Create a transparent imageView which will display the transition image. CGRect rectForNewView = [self frame]; rectForNewView.origin = CGPointZero; UIImageView *intermediateView = [[UIImageView alloc] initWithFrame:rectForNewView]; [intermediateView setBackgroundColor:[UIColor clearColor]]; [intermediateView setContentMode:[self contentMode]]; [intermediateView setClipsToBounds:[self clipsToBounds]]; [intermediateView setImage:inNewImage]; // Create the image view which will contain original imageView's contents: UIImageView *originalView = [[UIImageView alloc] initWithFrame:rectForNewView]; [originalView setBackgroundColor:[UIColor clearColor]]; [originalView setContentMode:[self contentMode]]; [originalView setClipsToBounds:[self clipsToBounds]]; [originalView setImage:[self image]]; // Remove image from the main imageView and add the originalView as subView to mainView: [self setImage:nil]; [self addSubview:originalView]; // Add the transparent imageView as subview whose dimensions are same as the view which holds it. [self addSubview:intermediateView]; // Set alpha value to 0 initially: [intermediateView setAlpha:0.0]; [originalView setAlpha:1.0]; [self setIntermediateTransitionView:intermediateView]; [self setOriginalImageViewContainerView:originalView]; [intermediateView release]; [originalView release]; // Begin animations: [UIView beginAnimations:@"ImageViewTransitions" context:nil]; [UIView setAnimationDuration:(double)TRANSITION_DURATION]; [UIView setAnimationDelegate:self]; [UIView setAnimationCurve:UIViewAnimationCurveEaseOut]; [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)]; [[self intermediateTransitionView] setAlpha:1.0]; [[self originalImageViewContainerView] setAlpha:0.0]; [UIView commitAnimations]; } } -(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { // Reset the alpha of the main imageView [self setAlpha:1.0]; // Set the image to the main imageView: [self setImage:[[self intermediateTransitionView] image]]; [[self intermediateTransitionView] removeFromSuperview]; [self setIntermediateTransitionView:nil]; [[self originalImageViewContainerView] removeFromSuperview]; [self setOriginalImageViewContainerView:nil]; } @end ``` You can even override the `-setImage` method of UIImageView and call my `-setImage:withTransitionAnimation:` method. If it is done like this make sure that you call `[super setImage:]` instead of `[self setImage:]` in the method `-setImage:withTransitionAnimation:` so that it wont end up in infinite recursive call! -Raj
212,697
<p>Every class that wants to use java.util.logging generally needs to declare a logger like this:</p> <pre><code>public class MyClass { private static Logger _log = Logger.getLogger(MyClass.class.getName()); } </code></pre> <p>How do you avoid this MyClass.class.getName() boilerplate code?</p>
[ { "answer_id": 212743, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": 2, "selected": false, "text": "<p>You don't need getName() if you're using a 1.2+ version of log4j, getLogger() accepts a Class argument. But as for the rest, there isn't any way around it if you want each class to have a static log member with its own category.</p>\n" }, { "answer_id": 212750, "author": "Ogre Psalm33", "author_id": 13140, "author_profile": "https://Stackoverflow.com/users/13140", "pm_score": 0, "selected": false, "text": "<p>You can shorthand this a tiny bit, as getLogger is overloaded to also just take the class. Like so:</p>\n\n<pre><code>public class MyClass {\n private static Logger _log = Logger.getLogger(MyClass.class);\n}\n</code></pre>\n\n<p>The Logger can be as fleixble or inflexible as you want it to be. You can grab a new logger for each class, as in your example above, and have a hierarchy of loggers where you can controll and turn on/off the logging by class. Or if your project is small or a prototype, etc, you could just call Logger.getRootLogger() - but you'll lose the flexibility of fine-tuning what you log and don't log. You could have a base class where the logger lives, and have everyone call that one, but again, you lose some flexibility:</p>\n\n<pre><code>public class MyBase {\n protected static Logger _log = Logger.getLogger(MyClass.class);\n}\n\npublic class MyClass extends MyBase {\n ....\n _log.info(\"Stuff....\");\n}\n</code></pre>\n\n<p>Bottom line, if you want to keep the ability to fine-tune configure your logging later in the project (turn on finer level debugging for just one class), then you may have to stick with the boilerplate in every class.</p>\n" }, { "answer_id": 212753, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": -1, "selected": false, "text": "<p>If you make the logger nonstatic, you can at least inherit it:</p>\n\n<pre><code>public class SomeBaseClass\n{\n protected Logger logger = Logger.getLogger(getClass());\n}\n\npublic class SubClass extends SomeBaseClass\n{\n public void doit() { logger.debug(\"doit!!!!\"); }\n}\n</code></pre>\n\n<p>That's how I've always done it.</p>\n" }, { "answer_id": 212754, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>If you go for package-level loggers, with the addition of a boilerplate class per package, you can write:</p>\n\n<pre><code>private static final Logger log = Logs.log;\n</code></pre>\n\n<p>There are hacks to read the class name of the caller (in fact the logging implementation has a hack to detect the current method), but I wouldn't recommend that.</p>\n" }, { "answer_id": 212904, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 5, "selected": true, "text": "<p>I have a template set up in Eclipse so that I only have to type a portion of the declaration, and then Eclipse will auto-complete the rest for me.</p>\n\n<pre><code>${:import(org.apache.log4j.Logger)}\nprivate final static Logger log = Logger.getLogger(${enclosing_type}.class);\n${cursor}\n</code></pre>\n\n<p>So, I only have to type <code>logger</code>, hit <code>Ctrl+Space</code>, followed by <code>Enter</code>, and Eclipse fills in the rest for me and adds the import declaration as well.</p>\n\n<p>This won't cut down on the amount of boilerplate code, but at least it cuts down on the amount of keystrokes.</p>\n" }, { "answer_id": 212992, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 2, "selected": false, "text": "<p>Have a look at using point cuts in your code</p>\n\n<p>I have not looked back since using them with spring.</p>\n\n<p>Here is an article on using AspectJ</p>\n\n<p><a href=\"http://www.developer.com/java/other/article.php/3109831\" rel=\"nofollow noreferrer\">http://www.developer.com/java/other/article.php/3109831</a></p>\n" }, { "answer_id": 213144, "author": "Snowtoad", "author_id": 13068, "author_profile": "https://Stackoverflow.com/users/13068", "pm_score": 2, "selected": false, "text": "<p>Depending on your logging needs, you could create a \"LoggingService\" class with static methods for logging to various \"channels\". I have found that I really don't need logging granularity down to the class level. You can name your loggers what every works best for you. We have been using this in large, enterprise applications for several years and the granularity has really not been an issue for us.</p>\n\n<p>The logging service initialized in a static initializer block...so to log a message:</p>\n\n<p>LoggingService.logError(\"blah\");</p>\n\n<p>No boilerplate code in each class.</p>\n\n<p>Here is an example logging service:</p>\n\n<pre><code>public class LoggingService {\n\n/**\n * A log for informational messages.\n */\nstatic private Logger infoLog;\n\n/**\n * A log for data access messages.\n */\nstatic private Logger dataAccessLog;\n\n/**\n * A log for debug messages.\n */\nstatic private Logger debugLog;\n\n/**\n * A log for error messages.\n */\nstatic private Logger errorLog;\n\n/**\n * A log for all XML related messages.\n */\nstatic private Logger xmlLog;\n\n/**\n * A log for all trace messages.\n */\nstatic private Logger traceLog;\n\n/**\n * A log for all warning messages.\n */\nstatic private Logger warnLog;\n\nstatic {\n\n //This is the bootstrap for the logging service.\n //Setup each logger\n infoLog = Logger.getLogger(\"com.company.logging.info\");\n dataAccessLog = Logger.getLogger(\"com.company.logging.dataaccess\");\n debugLog = Logger.getLogger(\"com.company.logging.debug\");\n errorLog = Logger.getLogger(\"com.company.logging.error\");\n xmlLog = Logger.getLogger(\"com.company.logging.xml\");\n traceLog = Logger.getLogger(\"com.company.logging.trace\");\n warnLog = Logger.getLogger(\"com.company.logging.warn\");\n\n // This must be set so isErrorEnabled() will work.\n errorLog.setLevel(Level.ERROR);\n warnLog.setLevel(Level.WARN);\n}\nstatic public void logDataAccess(String pMessage) {\n dataAccessLog.info(pMessage);\n}\n\nstatic public void logInfo(String pMessage) {\n infoLog.info(pMessage);\n}\n\nstatic public void logDebug(String pMessage) {\n debugLog.debug(pMessage);\n}\n\nstatic public void logTrace(String pMessage) {\n traceLog.debug(pMessage);\n}\n\nstatic public void logWarn(String pMessage) {\n warnLog.warn(pMessage);\n}\n\nstatic public void logError(String pMessage) {\n errorLog.error(pMessage);\n}\n\nstatic public void logError(String pMessage, Throwable pThrowable) {\n errorLog.error(pMessage, pThrowable);\n}\n\nstatic public void logXml(String pMessage, XmlBean pContainer) {\n\n if (!xmlLog.isInfoEnabled()) return;\n\n xmlLog.info(pMessage + \" : \" + JAXBHelper.marshal(pContainer));\n}\n\nstatic public boolean isInfoEnabled() {\n return infoLog.isInfoEnabled();\n}\n\nstatic public boolean isDataAccessEnabled() {\n return dataAccessLog.isInfoEnabled();\n}\n\nstatic public boolean isDebugEnabled() {\n return debugLog.isDebugEnabled();\n}\n\nstatic public boolean isErrorEnabled() {\n if (errorLog.getLevel().toInt() &gt;= Level.ERROR_INT) {\n return true;\n }\n return false;\n}\n\nstatic public boolean isTraceEnabled() {\n return traceLog.isDebugEnabled();\n}\n\nstatic public boolean isXmlEnabled() {\n return xmlLog.isInfoEnabled();\n}\n\nstatic public boolean isWarnEnabled() {\n return warnLog.isEnabledFor(Level.WARN);\n}\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 214121, "author": "bpapa", "author_id": 543, "author_profile": "https://Stackoverflow.com/users/543", "pm_score": 0, "selected": false, "text": "<p>Take a look at <a href=\"http://www.slf4j.org/manual.html\" rel=\"nofollow noreferrer\">SLF4J</a></p>\n" }, { "answer_id": 638025, "author": "Roland Tepp", "author_id": 1712, "author_profile": "https://Stackoverflow.com/users/1712", "pm_score": 2, "selected": false, "text": "<p>Actually, the common practice of using class names for logger names is lazy more than anything.</p>\n\n<p>The much better practice is to name loggers by the task context. This involves somewhat more thought process and planning but in the end, the result is much more meanigful granularity, where you can toggle logging levels for actual tasks rather than classes.</p>\n" }, { "answer_id": 23865539, "author": "Alireza Fattahi", "author_id": 2648077, "author_profile": "https://Stackoverflow.com/users/2648077", "pm_score": 1, "selected": false, "text": "<p>You can reduce that and many other boilerplate codes with lombok</p>\n\n<p><a href=\"https://github.com/rzwitserloot/lombok\" rel=\"nofollow\">https://github.com/rzwitserloot/lombok</a></p>\n\n<pre><code> @Slf4j\n public class LogExample {\n }\n</code></pre>\n\n<p>will be</p>\n\n<pre><code> public class LogExample {\n private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);\n }\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28604/" ]
Every class that wants to use java.util.logging generally needs to declare a logger like this: ``` public class MyClass { private static Logger _log = Logger.getLogger(MyClass.class.getName()); } ``` How do you avoid this MyClass.class.getName() boilerplate code?
I have a template set up in Eclipse so that I only have to type a portion of the declaration, and then Eclipse will auto-complete the rest for me. ``` ${:import(org.apache.log4j.Logger)} private final static Logger log = Logger.getLogger(${enclosing_type}.class); ${cursor} ``` So, I only have to type `logger`, hit `Ctrl+Space`, followed by `Enter`, and Eclipse fills in the rest for me and adds the import declaration as well. This won't cut down on the amount of boilerplate code, but at least it cuts down on the amount of keystrokes.
212,705
<p>I have a <code>&lt;div&gt;</code> that I want to be on a line by itself. According to <a href="http://www.w3schools.com/Css/pr_class_clear.asp" rel="nofollow noreferrer">W3Schools</a>, this rule:</p> <pre><code>div.foo { clear: both; } </code></pre> <p>...should mean this:</p> <blockquote> <p>"No floating elements allowed on either the left or the right side."</p> </blockquote> <p>However, if I float two <code>&lt;div&gt;</code> elements left, and apply the rule above to the first one, the second one does not budge.</p> <p>On the other hand, if I apply <code>"clear: left"</code> to the second <code>&lt;div&gt;</code>, it moves down to the next line. This is my normal approach, but I don't understand why I have to do it like this.</p> <p>Is the W3Schools description above poorly stated, or am I missing something? <strong>Is a clearing rule only able to move the element to which it is applied?</strong></p> <h2>Answer</h2> <p>Thanks Michael S and John D for the good explanations. Warren pointed to <a href="http://www.w3.org/TR/REC-CSS2" rel="nofollow noreferrer">the CSS2 spec</a>, and that's where I found this answer (emphasis mine):</p> <blockquote> <p>This property indicates which sides of an element's box(es) may not be adjacent to an <strong>earlier</strong> floating box.</p> </blockquote> <p>So: <code>clear</code> only affects the position of the element to which it is applied, relative to elements that appear before it the code.</p> <p>Disappointing that I can't tell my <code>&lt;div&gt;</code> to make other divs move down, but them's the breaks. :)</p>
[ { "answer_id": 212716, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 5, "selected": true, "text": "<p>When you apply clear to an element, it will move THAT element so that it doesn't have items left or right of it. It does not re-position any of the other elements, it simply moves the element to a position where nothing is around it.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Items above the item cleared are not moved, items below the element COULD be moved. Also note the additional comment in the comments</p>\n" }, { "answer_id": 212721, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "<p>I generally do the following for that effect:</p>\n\n<pre><code>float: left;\nclear: right;\n</code></pre>\n\n<p>I don't know if it applies merely to the element to which it is applied, though it makes sense.</p>\n\n<p>The specs are available here, though: <a href=\"http://www.w3.org/TR/REC-CSS2/\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/REC-CSS2/</a></p>\n" }, { "answer_id": 212733, "author": "John Dunagan", "author_id": 28939, "author_profile": "https://Stackoverflow.com/users/28939", "pm_score": 2, "selected": false, "text": "<p>Your css is parsing \"correctly.\" Your second div is still floated left, so even after you clear the first one, if there's room widthwise for the second one, it will fit floated left at the topmost point it can.</p>\n" }, { "answer_id": 212741, "author": "IAmCodeMonkey", "author_id": 27613, "author_profile": "https://Stackoverflow.com/users/27613", "pm_score": 2, "selected": false, "text": "<p>You apply clear to the element that you want on a new line. The clear that you use depends on the elements that you don't want it touching. If you want Image B to be on a new line and not touch Image A (which lets say is float: left), you would put Image B as {clear: left} not clear right as you would naturally think. You are clearing the float of the previous element.</p>\n" }, { "answer_id": 212837, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 2, "selected": false, "text": "<p>Yes, clearing only moves the element to which it is applied. However, the result feels different depending on whether the element is \"in flow\" or out of flow. I guess that is confusing you.</p>\n\n<p>If the element is in flow, clearing moves it down together with everything that follows. Think of it as moving current pen position (the place where next element should be placed) down. This behaviour is easy to undestand.</p>\n\n<p>If the element is out of flow, as the float in your example, only the element is moved, the pen position stays at the same place, unless other rules make them move. For example, a float is not allowed to start above a previous float.</p>\n\n<p>There is also a messy issue of margin collapsing. Clearing interrupts them, sometimes in an unintuitive way.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ]
I have a `<div>` that I want to be on a line by itself. According to [W3Schools](http://www.w3schools.com/Css/pr_class_clear.asp), this rule: ``` div.foo { clear: both; } ``` ...should mean this: > > "No floating elements allowed on either the left or the right side." > > > However, if I float two `<div>` elements left, and apply the rule above to the first one, the second one does not budge. On the other hand, if I apply `"clear: left"` to the second `<div>`, it moves down to the next line. This is my normal approach, but I don't understand why I have to do it like this. Is the W3Schools description above poorly stated, or am I missing something? **Is a clearing rule only able to move the element to which it is applied?** Answer ------ Thanks Michael S and John D for the good explanations. Warren pointed to [the CSS2 spec](http://www.w3.org/TR/REC-CSS2), and that's where I found this answer (emphasis mine): > > This property indicates which sides of an element's box(es) may not be adjacent to an **earlier** floating box. > > > So: `clear` only affects the position of the element to which it is applied, relative to elements that appear before it the code. Disappointing that I can't tell my `<div>` to make other divs move down, but them's the breaks. :)
When you apply clear to an element, it will move THAT element so that it doesn't have items left or right of it. It does not re-position any of the other elements, it simply moves the element to a position where nothing is around it. **Edit** Items above the item cleared are not moved, items below the element COULD be moved. Also note the additional comment in the comments
212,706
<p>What is the best way to reset a PIC18 using C code with the HiTech Pic18 C compiler?</p> <p>Edit:</p> <p>I am currenlty using</p> <pre><code>void reset() { #asm reset #endasm } </code></pre> <p>but there must be a better way</p>
[ { "answer_id": 212826, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "<p>Unless there's a library function defined by the compiler vendor's runtime library (if such a lib even exists in the microcontroller world ... but it should), then no. C itself certainly won't help you out, doing \"a reset\" is far too much of a platform-specific issue for C to cover it.</p>\n" }, { "answer_id": 212996, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>I use the ccsinfo.com compiler, which has a similar API call for resetting the PIC, but I would think the compiler's solution would do the right thing. </p>\n" }, { "answer_id": 213395, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 3, "selected": true, "text": "<p>There's a <a href=\"http://www.microchipc.com/HiTechCFAQ/index.php#_Toc475127553\" rel=\"nofollow noreferrer\">FAQ here</a>.</p>\n\n<p>Q: How do I reset the micro?</p>\n\n<blockquote>\n <p>One way is to reset all variables to\n their defaults, as listed in the PIC\n manual. Then, use assembly language\n to jump to location 0x0000 in the\n micro. </p>\n \n <p>#asm ljmp 0x0000</p>\n \n <p>#endasm</p>\n \n <p>This is quite safe to use, even when\n called within interrupts or\n procedures. The PIC 16x series micros\n have 8 stack levels. Each time a\n procedure is called, one stack level\n is used up for the return address. It\n is a circular buffer, so even if the\n micro is 7 procedure levels deep and\n in an interrupt when a reset is\n called, this is the new start of the\n stack buffer, and the micro will\n continue as per normal. </p>\n \n <p>Another way is to set watchdog the\n timer when the chip is programmed, and\n use CLRWDT() instructions all through\n the code. When you want the micro to\n reset, stop clearing the watchdog bit\n and the micro will reset after around\n 18ms to 2 seconds depending on the\n prescaler.</p>\n</blockquote>\n" }, { "answer_id": 218873, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 3, "selected": false, "text": "<p>The compilers usually have their own reset() function built in, but it just does exactly what your function does, and the actual name may vary from compiler to compiler.</p>\n\n<p>You are already doing it the best possible way.</p>\n" }, { "answer_id": 1202255, "author": "Brent", "author_id": 147289, "author_profile": "https://Stackoverflow.com/users/147289", "pm_score": 3, "selected": false, "text": "<p>Your answer is the best way I know of. The key is that you have the assembly instruction inside a function call, all by itself.\n The compiler will not optimize a function that has inline assembly in it, so if you include the reset instruction inline to a very large function, the compiler will not optimize any of the code in that function. You have avoided this by putting Reset in its own function. The code in this function won't be optimized, but who cares, since it is such a small function.</p>\n" }, { "answer_id": 59441046, "author": "Dan1138", "author_id": 10085080, "author_profile": "https://Stackoverflow.com/users/10085080", "pm_score": 1, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/users/9061264/mike\">Mike</a> has edited this original question from 11 years ago it seems doubtful the Original Poster needs a comprehensive answer. In fact the OP seems to have asked about or responded on just 2 topics regarding microcontrollers in the past 9 years.</p>\n<p>Given all that it may be helpful to look at some of the ways the PIC18F controller can be caused to begin execution from the reset vector with code that compiles with Hi-Tech C or XC8 as it is now called by Microchip.</p>\n<p>This code has been tested using MPLABX v5.25, XC8 v2.05 and the PIC18F45K20 controller.</p>\n<pre><code>/*\n * File: main.c\n * Author: dan1138\n * Target: PIC18F45K20\n * Compiler: XC8 v2.05\n *\n * PIC18F46K20\n * +---------+ +---------+ +----------+ +----------+\n * &lt;&gt; 1 : RC7/RX : -- 12 : NC : &lt;&gt; 23 : RA4 : -- 34 : NC :\n * LED4 &lt;&gt; 2 : RD4 : -- 13 : NC : &lt;&gt; 24 : RA5 : 32.768KHz -&gt; 35 : RC1/SOSI :\n * LED5 &lt;&gt; 3 : RD5 : &lt;&gt; 14 : RB4 : &lt;&gt; 25 : RE0 : &lt;&gt; 36 : RC2 :\n * LED6 &lt;&gt; 4 : RD6 : &lt;&gt; 15 : RB5/PGM : &lt;&gt; 26 : RE1 : &lt;&gt; 37 : RC3 :\n * GND -&gt; 5 : VSS : PGC &lt;&gt; 16 : RB6/PGC : &lt;&gt; 27 : RE2 : LED0 &lt;&gt; 38 : RD0 :\n * 3v3 -&gt; 6 : VDD : PGD &lt;&gt; 17 : RB7/PGD : 3v3 -&gt; 28 : VDD : LED1 &lt;&gt; 39 : RD1 :\n * SW1 &lt;&gt; 7 : RB0/INT : VPP -&gt; 18 : RE3/VPP : GND -&gt; 29 : VSS : LED2 &lt;&gt; 40 : RD2 :\n * &lt;&gt; 8 : RB1 : POT &lt;&gt; 19 : RA0/AN0 : 4MHz -&gt; 30 : RA7/OSC1 : LED3 &lt;&gt; 41 : RD3 :\n * &lt;&gt; 9 : RB2 : &lt;&gt; 20 : RA1 : 4MHz &lt;- 31 : RA6/OSC2 : &lt;&gt; 42 : RC4 :\n * &lt;&gt; 10 : RB3 : &lt;&gt; 21 : RA2 : 32.767KHz &lt;- 32 : RC0/SOSO : &lt;&gt; 43 : RC5 :\n * LED7 &lt;&gt; 11 : RD7 : &lt;&gt; 22 : RA3 : -- 33 : NC : &lt;&gt; 44 : RC6/TX :\n * +---------+ +---------+ +----------+ +----------+\n * TQFP-44\n *\n *\n * Created on December 21, 2019, 2:26 PM\n */\n\n/* Target specific configuration words */\n#pragma config FOSC = INTIO67, FCMEN = OFF\n#pragma config IESO = OFF, PWRT = OFF, BOREN = SBORDIS, BORV = 18\n#pragma config WDTEN = OFF, WDTPS = 32768, CCP2MX = PORTC, PBADEN = OFF\n#pragma config LPT1OSC = ON, HFOFST = ON\n#pragma config MCLRE = ON, STVREN = ON, LVP = OFF, XINST = OFF\n#pragma config CP0 = OFF, CP1 = OFF, CP2 = OFF, CP3 = OFF\n#pragma config CPB = OFF, CPD = OFF\n#pragma config WRT0 = OFF, WRT1 = OFF, WRT2 = OFF, WRT3 = OFF\n#pragma config WRTC = OFF, WRTB = OFF, WRTD = OFF\n#pragma config EBTR0 = OFF, EBTR1 = OFF, EBTR2 = OFF, EBTR3 = OFF\n#pragma config EBTRB = OFF\n\n/* Target specific definitions for special function registers */\n#include &lt;xc.h&gt;\n\n/* Declare the system oscillator frequency setup by the code */\n#define _XTAL_FREQ (4000000UL)\n\n/* reset instruction */\nvoid ResetMethod_1(void)\n{\n asm(&quot; reset&quot;);\n}\n\n/* long jump to absolute address zero */\nvoid ResetMethod_2(void)\n{\n INTCON = 0;\n asm(&quot; pop\\n ljmp 0&quot;);\n}\n\n/* return to absolute address zero */\nvoid ResetMethod_3(void)\n{\n INTCON = 0;\n asm(&quot; clrf TOSU\\n clrf TOSH\\n clrf TOSL\\n&quot;);\n}\n\n/* provoke stackoverflow reset */\nvoid ResetMethod_4(void)\n{\n INTCON = 0;\n while (1) \n {\n asm(&quot; push\\n&quot;);\n }\n}\n\n/* provoke stackunderflow reset */\nvoid ResetMethod_5(void)\n{\n INTCON = 0;\n STKPTR = 0;\n}\n\n/* clear the program counter */\nvoid ResetMethod_6(void)\n{\n INTCON = 0;\n asm(&quot; clrf PCLATU\\n clrf PCLATH\\n clrf PCL\\n&quot;);\n}\n\nvoid main(void)\n{\n INTCON = 0; /* Disable all interrupt sources */\n PIE1 = 0;\n PIE2 = 0;\n INTCON3bits.INT1IE = 0;\n INTCON3bits.INT2IE = 0;\n\n OSCCON = 0x50; /* set internal oscillator to 4MHz */\n OSCTUNEbits.TUN = 0; /* use factory calibration of internal oscillator */\n ANSEL = 0;\n ANSELH = 0;\n \n if(!RCONbits.nPOR)\n {\n RCONbits.nPOR = 1;\n LATD = 0;\n }\n \n TRISD = 0;\n /*\n * Application loop\n */\n while(1)\n {\n __delay_ms(500);\n if (LATDbits.LD0 == 0)\n {\n LATDbits.LD0 = 1;\n ResetMethod_1();\n }\n \n if (LATDbits.LD1 == 0)\n {\n LATDbits.LD1 = 1;\n ResetMethod_2();\n }\n\n if (LATDbits.LD2 == 0)\n {\n LATDbits.LD2 = 1;\n ResetMethod_3();\n }\n \n if (LATDbits.LD3 == 0)\n {\n LATDbits.LD3 = 1;\n ResetMethod_4();\n }\n\n if (LATDbits.LD4 == 0)\n {\n LATDbits.LD4 = 1;\n ResetMethod_5();\n }\n\n if (LATDbits.LD5 == 0)\n {\n LATDbits.LD5 = 1;\n ResetMethod_6();\n }\n }\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ]
What is the best way to reset a PIC18 using C code with the HiTech Pic18 C compiler? Edit: I am currenlty using ``` void reset() { #asm reset #endasm } ``` but there must be a better way
There's a [FAQ here](http://www.microchipc.com/HiTechCFAQ/index.php#_Toc475127553). Q: How do I reset the micro? > > One way is to reset all variables to > their defaults, as listed in the PIC > manual. Then, use assembly language > to jump to location 0x0000 in the > micro. > > > #asm ljmp 0x0000 > > > #endasm > > > This is quite safe to use, even when > called within interrupts or > procedures. The PIC 16x series micros > have 8 stack levels. Each time a > procedure is called, one stack level > is used up for the return address. It > is a circular buffer, so even if the > micro is 7 procedure levels deep and > in an interrupt when a reset is > called, this is the new start of the > stack buffer, and the micro will > continue as per normal. > > > Another way is to set watchdog the > timer when the chip is programmed, and > use CLRWDT() instructions all through > the code. When you want the micro to > reset, stop clearing the watchdog bit > and the micro will reset after around > 18ms to 2 seconds depending on the > prescaler. > > >