text
stringlengths
8
267k
meta
dict
Q: fmt:parseDate - a parse index locale can not be established Does anyone know the root cause of this error? I am feeding known good data to the fmt:parseDate tag (its db driven data controlled by us), and yet this error randomly pops up. I can't seem to find a way to replicate what causes this exception. A: How open is the website - the Locale comes from the user preferences in some cases Accept--Language header - perhaps the user is sending a bad value, maybe its from a Chrome browser :) . Here is a similar example
{ "language": "en", "url": "https://stackoverflow.com/questions/164559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you map enums to and from the database using NHibernate? Edit: Ryan raised a good point. I specifically want to be able to map to and from while still storing human-readable values in the database. That is, I don't want a bunch of enumeration integers in my database. A: According to the documentation you can either leave the type attribute of the property in your mapping file blank or you define it and specify the class name of the enumeration. Another way would be to convert the enumeration to an int and use the int as the mapped type. A: You have to implement a custom IUserType. See this post. A: I've never used NHibernate, but can't you just set the SQL datatype to int? A: I think you can just set the type to string: <property name="EnumProperty" Type="string" Length="50" NotNull="true" />
{ "language": "en", "url": "https://stackoverflow.com/questions/164564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keypoints morphing Is there a library/software which can accept a number of keypoints and matches of them between images and produce a morph? Or any ideas/algorithms on how to do it? A: Xmorph and GTK morph can do that -- although the key points must be parts of equivalent rectangle grids. The underlying algorithm can be accessed through a C API. A: An older piece of software by Gryphon Software could do image morphing. I saw an article about it from 1994. I couldn't find a company site, so they may be abandon ware now. Her is a quote from a Wikipedia article about a film editing technique called Dissolve. In non-linear video editing, a dissolve is done in software, by interpolating gradually between the RGB values of each pixel of the image. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/164574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MSXML from C++ - pretty print / indent newly created documents I'm writing out XML files using the MSXML parser, with a wrapper I downloaded from here: http://www.codeproject.com/KB/XML/JW_CXml.aspx. Works great except that when I create a new document from code (so not load from file and modify), the result is all in one big line. I'd like elements to be indented nicely so that I can read it easily in a text editor. Googling shows many people with the same question - asked around 2001 or so. Replies usually say 'apply an XSL transformation' or 'add your own whitespace nodes'. Especially the last one makes me go %( so I'm hoping that in 2008 there's an easier way to pretty MSXML output. So my question; is there, and how do I use it? A: Here's a modified version of the accepted answer that will transform in-memory (changes only in the last few lines but I'm posting the whole block for the convenience of future readers): bool CXml::FormatDOMDocument(IXMLDOMDocument *pDoc) { // Create the writer CComPtr <IMXWriter> pMXWriter; if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL))) { return false; } CComPtr <ISAXContentHandler> pISAXContentHandler; if (FAILED (pMXWriter.QueryInterface(&pISAXContentHandler))) { return false; } CComPtr <ISAXErrorHandler> pISAXErrorHandler; if (FAILED (pMXWriter.QueryInterface (&pISAXErrorHandler))) { return false; } CComPtr <ISAXDTDHandler> pISAXDTDHandler; if (FAILED (pMXWriter.QueryInterface (&pISAXDTDHandler))) { return false; } if (FAILED (pMXWriter->put_omitXMLDeclaration (VARIANT_FALSE)) || FAILED (pMXWriter->put_standalone (VARIANT_TRUE)) || FAILED (pMXWriter->put_indent (VARIANT_TRUE)) || FAILED (pMXWriter->put_encoding (L"UTF-8"))) { return false; } // Create the SAX reader CComPtr <ISAXXMLReader> pSAXReader; if (FAILED(pSAXReader.CoCreateInstance(__uuidof (SAXXMLReader), NULL, CLSCTX_ALL))) { return false; } if (FAILED(pSAXReader->putContentHandler (pISAXContentHandler)) || FAILED(pSAXReader->putDTDHandler (pISAXDTDHandler)) || FAILED(pSAXReader->putErrorHandler (pISAXErrorHandler)) || FAILED(pSAXReader->putProperty (L"http://xml.org/sax/properties/lexical-handler", CComVariant (pMXWriter))) || FAILED(pSAXReader->putProperty (L"http://xml.org/sax/properties/declaration-handler", CComVariant (pMXWriter)))) { return false; } // Perform the write bool success1 = SUCCEEDED(pMXWriter->put_output(CComVariant(pDoc.GetInterfacePtr()))); bool success2 = SUCCEEDED(pSAXReader->parse(CComVariant(pDoc.GetInterfacePtr()))); return success1 && success2; } A: Even my 2 cents arrive 7 years later I think the question still deserves a simple answer wrapped in just a few lines of code, which is possible by using Visual C++'s #import directive and the native C++ COM support library (offering smart pointers and encapsulating error handling). Note that like the accepted answer it doesn't try to fit into the CXml class the OP is using but rather shows the core idea. Also I assume msxml6. Pretty-printing to any stream void PrettyWriteXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, IStream* stream) { MSXML2::IMXWriterPtr writer(__uuidof(MSXML2::MXXMLWriter60)); writer->encoding = L"utf-8"; writer->indent = _variant_t(true); writer->standalone = _variant_t(true); writer->output = stream; MSXML2::ISAXXMLReaderPtr saxReader(__uuidof(MSXML2::SAXXMLReader60)); saxReader->putContentHandler(MSXML2::ISAXContentHandlerPtr(writer)); saxReader->putProperty(PUSHORT(L"http://xml.org/sax/properties/lexical-handler"), writer.GetInterfacePtr()); saxReader->parse(xmlDoc); } File stream If you need a stream writing to a file you need an implementation of the IStream interface. wtlext has got a class, which you can use or from which you can deduce how you can write your own. Another simple solution that has worked well for me is utilising the Ado Stream class: void PrettySaveXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, const wchar_t* filePath) { ADODB::_StreamPtr stream(__uuidof(ADODB::Stream)); stream->Type = ADODB::adTypeBinary; stream->Open(vtMissing, ADODB::adModeUnknown, ADODB::adOpenStreamUnspecified, _bstr_t(), _bstr_t()); PrettyWriteXmlDocument(xmlDoc, IStreamPtr(stream)); stream->SaveToFile(filePath, ADODB::adSaveCreateOverWrite); } Glueing it together A simplistic main function shows this in action: #include <stdlib.h> #include <objbase.h> #include <comutil.h> #include <comdef.h> #include <comdefsp.h> #import <msxml6.dll> #import <msado60.tlb> rename("EOF", "EndOfFile") // requires: /I $(CommonProgramFiles)\System\ado void PrettyWriteXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, IStream* stream); void PrettySaveXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, const wchar_t* filePath); int wmain() { CoInitializeEx(nullptr, COINIT_MULTITHREADED); try { MSXML2::IXMLDOMDocumentPtr xmlDoc(__uuidof(MSXML2::DOMDocument60)); xmlDoc->appendChild(xmlDoc->createElement(L"root")); PrettySaveXmlDocument(xmlDoc, L"xmldoc.xml"); } catch (const _com_error&) { } CoUninitialize(); return EXIT_SUCCESS; } // assume definitions of PrettyWriteXmlDocument and PrettySaveXmlDocument go here A: Try this, I found this years ago on the web. #include <msxml2.h> bool FormatDOMDocument (IXMLDOMDocument *pDoc, IStream *pStream) { // Create the writer CComPtr <IMXWriter> pMXWriter; if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL))) { return false; } CComPtr <ISAXContentHandler> pISAXContentHandler; if (FAILED (pMXWriter.QueryInterface(&pISAXContentHandler))) { return false; } CComPtr <ISAXErrorHandler> pISAXErrorHandler; if (FAILED (pMXWriter.QueryInterface (&pISAXErrorHandler))) { return false; } CComPtr <ISAXDTDHandler> pISAXDTDHandler; if (FAILED (pMXWriter.QueryInterface (&pISAXDTDHandler))) { return false; } if (FAILED (pMXWriter ->put_omitXMLDeclaration (VARIANT_FALSE)) || FAILED (pMXWriter ->put_standalone (VARIANT_TRUE)) || FAILED (pMXWriter ->put_indent (VARIANT_TRUE)) || FAILED (pMXWriter ->put_encoding (L"UTF-8"))) { return false; } // Create the SAX reader CComPtr <ISAXXMLReader> pSAXReader; if (FAILED (pSAXReader.CoCreateInstance (__uuidof (SAXXMLReader), NULL, CLSCTX_ALL))) { return false; } if (FAILED (pSAXReader ->putContentHandler (pISAXContentHandler)) || FAILED (pSAXReader ->putDTDHandler (pISAXDTDHandler)) || FAILED (pSAXReader ->putErrorHandler (pISAXErrorHandler)) || FAILED (pSAXReader ->putProperty ( L"http://xml.org/sax/properties/lexical-handler", CComVariant (pMXWriter))) || FAILED (pSAXReader ->putProperty ( L"http://xml.org/sax/properties/declaration-handler", CComVariant (pMXWriter)))) { return false; } // Perform the write return SUCCEEDED (pMXWriter ->put_output (CComVariant (pStream))) && SUCCEEDED (pSAXReader ->parse (CComVariant (pDoc))); } A: Unless the library has a format option then the only other way is to use XSLT, or an external pretty printer ( I think htmltidy can also do xml) There doen't seem to be an option in the codeproject lib but you can specify an XSLT stylesheet to MSXML. A: I've written a sed script a while back for basic xml indenting. You can use it as an external indenter if all else fails (save this to xmlindent.sed, and process your xml with sed -f xmlindent.sed <filename>). You might need cygwin or some other posix environment to use it though. Here's the source: :a />/!N;s/\n/ /;ta s/ / /g;s/^ *//;s/ */ /g /^<!--/{ :e /-->/!N;s/\n//;te s/-->/\n/;D; } /^<[?!][^>]*>/{ H;x;s/\n//;s/>.*$/>/;p;bb } /^<\/[^>]*>/{ H;x;s/\n//;s/>.*$/>/;s/^ //;p;bb } /^<[^>]*\/>/{ H;x;s/\n//;s/>.*$/>/;p;bb } /^<[^>]*[^\/]>/{ H;x;s/\n//;s/>.*$/>/;p;s/^/ /;bb } /</!ba { H;x;s/\n//;s/ *<.*$//;p;s/[^ ].*$//;x;s/^[^<]*//;ba } :b { s/[^ ].*$//;x;s/^<[^>]*>//;ba } Hrmp, tabs seem to be garbled... You can copy-waste from here instead: XML indenting with sed(1)
{ "language": "en", "url": "https://stackoverflow.com/questions/164575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Omitting XML processing instruction when serializing an object I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need it serialized without the processing instruction, however. The XmlSerializer class puts out something like this: <?xml version="1.0" encoding="utf-16" ?> <MyObject> <Property1>Data</Property1> <Property2>More Data</Property2> </MyObject> Is there any way to get something like the following, without processing the resulting text to remove the tag? <MyObject> <Property1>Data</Property1> <Property2>More Data</Property2> </MyObject> For those that are curious, my code looks like this... XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); StringBuilder builder = new StringBuilder(); using ( TextWriter stringWriter = new StringWriter(builder) ) { serializer.Serialize(stringWriter, comments); return builder.ToString(); } A: In 2.0, you would use XmLWriterSettings.OmitXmlDeclaration, and serialize to an XmlWriter - however I don't think this exists in 1.1; so not entirely useful - but just one more "consider upgrading" thing... and yes, I realise it isn't always possible. A: The following link will take you to a post where someone has a method of supressing the processing instruction by using an XmlWriter and getting into an 'Element' state rather than a 'Start' state. This causes the processing instruction to not be written. Suppress Processing Instruction If you pass an XmlWriter to the serializer, it will only emit a processing instruction if the XmlWriter's state is 'Start' (i.e., has not had anything written to it yet). // Assume we have a type named 'MyType' and a variable of this type named 'myObject' System.Text.StringBuilder output = new System.Text.StringBuilder(); System.IO.StringWriter internalWriter = new System.IO.StringWriter(output); System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(internalWriter); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyType)); writer.WriteStartElement("MyContainingElement"); serializer.Serialize(writer, myObject); writer.WriteEndElement(); In this case, the writer will be in a state of 'Element' (inside an element) so no processing instruction will be written. One you finish writing the XML, you can extract the text from the underlying stream and process it to your heart's content. A: I made a small correction XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); StringBuilder builder = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; using ( XmlWriter stringWriter = XmlWriter.Create(builder, settings) ) { serializer.Serialize(stringWriter, comments); return builder.ToString(); } A: What about omitting namespaces ? instead of using XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); namespaces.Add("", ""); ex: <message xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> A: If by "processing instruction" you mean the xml declaration, then you can avoid this by setting the OmitXmlDeclaration property of XmlWriterSettings. You'll need to serialize using an XmlWriter, to accomplish this. XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); StringBuilder builder = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; using ( XmlWriter stringWriter = new StringWriter(builder, settings) ) { serializer.Serialize(stringWriter, comments); return builder.ToString(); } But ah, this doesn't answer your question for 1.1. Well, for reference to others. A: This works in .NET 1.1. (But you should still consider upgrading) XmlSerializer s1= new XmlSerializer(typeof(MyClass)); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add( "", "" ); MyClass c= new MyClass(); c.PropertyFromDerivedClass= "Hallo"; sw = new System.IO.StringWriter(); s1.Serialize(new XTWND(sw), c, ns); .... /// XmlTextWriterFormattedNoDeclaration /// helper class : eliminates the XML Documentation at the /// start of a XML doc. /// XTWFND = XmlTextWriterFormattedNoDeclaration public class XTWFND : System.Xml.XmlTextWriter { public XTWFND(System.IO.TextWriter w) : base(w) { Formatting = System.Xml.Formatting.Indented; } public override void WriteStartDocument() { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/164585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do I install "SQL Server" ODBC Driver? I Have "SQL Native Client", but not "SQL Server" ODBC driver. I have SQL 2005 installed on my machine. Tried to fix by installing SQL Server client tools. Any ideas would be appreciated. I'm running Windows XP Pro. A: Found this Microsoft download. It says it provides the SQL Server ODBC driver. Edit: Here's the SP1 download: Service Pack 1. A: I found an article on repairing MDAC. Here is the short 1. In Windows Explorer, open the c:\Windows\Inf folder. Note If you cannot see the c:\Windows\Inf folder, follow these steps: a. On the desktop, double-click My Computer, and then on the Tools menu, click Folder Options. b. Click the View tab. c. Under Advanced settings, select the Show hidden files and folders check box. d. Clear the Hide extensions for known file types check box. e. Click OK. 2. In the C:\Windows\Inf folder, right-click the Mdac.inf file, and then click Install. ... A: You can also try the OpenLink ODBC Drivers for SQL Server. These support older and newer versions of SQL Server (from 4.2 up to very latest release). See: http://uda.openlinksw.com/ A: The Easysoft SQL Server ODBC Driver support both old and new versions of SQLServer http://www.easysoft.com/products/data_access/odbc-sql-server-driver/index.html
{ "language": "en", "url": "https://stackoverflow.com/questions/164593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Calling stored procedures I have a c# application that interfaces with the database only through stored procedures. I have tried various techniques for calling stored procedures. At the root is the SqlCommand class, however I would like to achieve several things: * *make the interface between c# and sql smoother, so that procedure calls look more like c# function calls *have an easy way to determine whether a given stored procedure is called anywhere in code. *make the creation of a procedure call quick and easy. I have explored various avenues. In one, I had a project that with its namespace structure mirrored the name structure of stored procedures, that way I could generate the name of the stored procedure from the name of the class, and I could tell whether a given stored procedure was in use by fining it in the namespace tree. What are some other experiences? A: You should try LINQ to SQL. A: When stored procedures are the interface to the database, I tend to wrap them in classes which reflect the problem domain, so that most of the application code is using these objects and not calling stored procedures, and not even knowing about the stored procedures or the database connection. The application objects, typically play amongst themselves. I think it's a mistake to mirror the SPs in your application, as, typically, your relational model is not 1-1 with your application domain object model. For example, typically I do not have application objects which represent link tables or other artifacts of database design and normalization. Those are collections of objects either contained in or returned by other objects. A lot is made of the impedance mismatch, but I think it's horses for courses - let databases do what they are good at and OO models do what they are good at. A: Have you looked into using the Enterprise Library from MS? It allows you to easily call stored procedures. I generally setup a class per database that is only for calling these stored procs. You can then have something similar to this (sorry it's vb.net and not c#): Public Shared Function GetOrg(ByVal OrgID As Integer) As System.Data.DataSet Return db.ExecuteDataSet("dbo.cp_GetOrg", OrgID) End Function Where db is defined as: Dim db As Microsoft.Practices.EnterpriseLibrary.Data.Database = DatabaseFactory.CreateDatabase() You then have this one function that is used to call the stored procedure. You can then search your code for this one function. A: When building my current product, one of the tools that I very much wanted to implement was a database class (like DatabaseFactory - only I didn't care for that one) that would simplify my development and remove some of the "gotchas." Within that class, I wanted to be able to call stored procedures as true C# functions using a function-to-sproc mapping like this: public int Call_MySproc(int paramOne, bool paramTwo, ref int outputParam) { ...parameter handling and sproc call here } The biggest issue you face when trying to do this, however, lies in the work needed to create C# functions that implement the sproc calls. Fortunately, it is easy to create a code generator to do this in T-SQL. I started with one created originally by Paul McKenzie and then modified it in various ways to generate C# code as I wanted it. You can either Google Paul McKenzie and look for his original code generator or, if you'd like to write to me at mark -at- BSDIWeb.com, I'll bundle up the source for my SQL class library and the associated sproc code generator and place it on our web site. If I get a request or two, I'll post it and then come back and edit this response to point others to the source as well. A: the simplest solution for what you want [and i'm not saying that it is better or worse than the other solutions] is to create a dataset and drag the stored procedures from the server explorer onto the dataset designer surface. This will create methods in the adapter that you can call and check for references. A: Although they aren't very fashionable, we use Typed DataSets as a front-end to all of our stored procedures. A: Microsoft's new Entity Framework provides just what you're asking for. EF is normally used to create proxy classes for database objects, but one thing a lot of people don't realize is that it also creates proxy methods for stored procedures (auto-generated, of course). This allows you to use your SPs just as though they were regular method calls. Check it out!
{ "language": "en", "url": "https://stackoverflow.com/questions/164594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I setup the permissions in Linux so that two users can update the same SVN working copy on the server? My server has both Subversion and Apache installed, and the Apache web directory is also a Subversion working copy. The reason for this is that the simple command svn update /server/staging will deploy the latest source to the staging server. Apache public web directory: /server/staging — (This is an SVN working copy.) I have two users on my server, 'richard' and 'austin'. They both are members of the 'developers' group. I recursively set permissions on the /server directory to richard:developers, using "sudo chown -R richard:developers /server". I then set the permissions to read, write and execute for both 'richard' and the 'developers' group. So surely, 'austin' should now be able to use the svn update /server/staging command? However, when he tries, he gets the error: svn: Can't open file '/server/staging/.svn/lock': Permission denied If I recursively change the owner of /server to austin:developers, he can run the command just fine, but then 'richard' can't. How do I fix the problem? I want to create a post-commit hook with to automatically deploy the staging site when files are committed, but I can't see a way for that to work for both users. The hook would be: /usr/bin/svn update /server/staging Using the same user account for both of them wouldn't really be an acceptable solution, and I'm not aware of any way to run the command inside the hook as 'root'. Any help is appreciated! A: Directory Set Group ID If the setgid bit on a directory entry is set, files in that directory will have the group ownership as the directory, instead of than the group of the user that created the file. This attribute is helpful when several users need access to certain files. If the users work in a directory with the setgid attribute set then any files created in the directory by any of the users will have the permission of the group. For example, the administrator can create a group called spcprj and add the users Kathy and Mark to the group spcprj. The directory spcprjdir can be created with the set GID bit set and Kathy and Mark although in different primary groups can work in the directory and have full access to all files in that directory, but still not be able to access files in each other's primary group. The following command will set the GID bit on a directory: chmod g+s spcprjdir The directory listing of the directory "spcprjdir": drwxrwsr-x 2 kathy spcprj 1674 Sep 17 1999 spcprjdir The "s'' in place of the execute bit in the group permissions causes all files written to the directory "spcprjdir" to belong to the group "spcprj" . edit: source = Linux Files and File Permissions A: I would set up svnserve which is a simple Subversion server using the svn:// protocol. You can set this up so it runs under its own user account, then the repository would only be accessed by that one user. This user could then have the correct privileges to run svn update /server/staging on a post-commit hook. A: in your svn repo, you can find a 'conf' directory where you set permissions. you have 3 files there: * *authz *passwd *svnserve.conf you set in the authz file which users have which kind of acces, per user or per group. you set groups there, SVN groups not linux user groups (hashed lines are comments): [groups] # harry_and_sally = harry,sally projectgroup = richard,austin # [/foo/bar] # harry = rw -- user harry has read/write access # * = -- everybody have no access # [repository:/baz/fuz] # @harry_and_sally = rw -- harry_and_sally group members have read/write access # * = r -- everyone has read access [/server/staging] @projectgroup = rw * = r work around this example and set your config. in the 'passwd' file you set up users passwords. execute cat passwd you'll get commented file with explanation how to set it up. A: I use WebDAV - all SVN updates and commits are handled via apache and I never have such problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/164597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I see my applications threads while debugging in Visual Studio? I would like to see the threads currently active in my application while debugging it. How can I do this using Visual Studio? A: While RichS' answer is technically correct, the information displayed in that window is not as helpful if you have a number of thread in wait states or sleeping. I would recommend you make sure you name your threads for better visibility in the Thread window. Use the Thread.Name property to assign a meaningful name to your thread. You'll be glad you did. A: If you are using VS 2008, check this screencast on VS 2008 multi-threading improvements.. A: Yes, go to Debug->Windows->Threads A: Also, give your threads names when you create them, it makes it easier to identify them in the threads tool window in visual studio. A: Debug | Windows | Threads or Ctrl+Alt+H A: I've been using Allinea's DDTLite plugin recently - drops into VS2008 (SP1) pretty well and gives a number of really really useful windows for managing multiple threads (stepping, breakpoints, ..) or even just seeing where threads are at the same time (a sort of tree like view of the stacks, it's really cool). A: You can simply track the threads either through visual studio or just from task manager. In the case of VS- after debugging your application just navigate to debug from upper menu options then goto to windows and then threads. Debug->Windows->Thread. sometimes you might not get information from VS thread windows so go to task manager from desktop and navigate to thread column. refer the image below. Here you go
{ "language": "en", "url": "https://stackoverflow.com/questions/164600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Why are try blocks expensive? I've heard the advice that you should avoid try catch blocks if possible since they're expensive. My question is specifically about the .NET platform: Why are try blocks expensive? Summary of Responses: There are clearly two camps on this issue: those that say that try blocks are expensive, and those that say "maybe a tiny little bit". Those that say try blocks are expensive normally mention the "high cost" of unwinding the call stack. Personally, I'm not convinced by that argument - specially after reading about how exceptions handlers are stored here. Jon Skeet sits on the "maybe a tiny little bit" camp, and has written two articles on exceptions and performance which you can find here. There was one article that I found extremely interesting: it talked about "other" performance implications of try blocks (not necessarily memory or cpu consumption). Peter Ritchie mentions that he found that code inside try blocks is not optimized as it'd otherwise be by the compiler. You can read about his findings here. Finally, there's a blog entry about the issue from the man that implemented exceptions in the CLR. Go take a look at Chris Brumme's article here. A: A try block is not expensive at all. Little or no cost is incurred unless an exception is thrown. And if an exception has been thrown, that's an exceptional circumstance and you don't care about performance any more. Does it matter if your program takes 0.001 seconds or 1.0 seconds to fall over? No, it does not. What matters is how good the information reported back to you is so you can fix it and stop it happening again. A: I think people really overestimate the performance cost of throwing exceptions. Yes, there's a performance hit, but it's relatively tiny. I ran the following test, throwing and catching a million exceptions. It took about 20 seconds on my Intel Core 2 Duo, 2.8 GHz. That's about 50K exceptions a second. If you're throwing even a small fraction of that, you've got some architecture problems. Here's my code: using System; using System.Diagnostics; namespace Test { class Program { static void Main(string[] args) { Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < 1000000; i++) { try { throw new Exception(); } catch {} } Console.WriteLine(sw.ElapsedMilliseconds); Console.Read(); } } } A: The compiler emits more IL when you wrap code inside a try/catch block; Look, for the following program : using System; public class Program { static void Main(string[] args) { Console.WriteLine("abc"); } } The compiler will emit this IL : .method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 13 (0xd) .maxstack 8 IL_0000: nop IL_0001: ldstr "abc" IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: nop IL_000c: ret } // end of method Program::Main While for the slightly modified version : using System; public class Program { static void Main(string[] args) { try { Console.WriteLine("abc"); } catch { } } } emits more : .method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 23 (0x17) .maxstack 1 IL_0000: nop .try { IL_0001: nop IL_0002: ldstr "abc" IL_0007: call void [mscorlib]System.Console::WriteLine(string) IL_000c: nop IL_000d: nop IL_000e: leave.s IL_0015 } // end .try catch [mscorlib]System.Object { IL_0010: pop IL_0011: nop IL_0012: nop IL_0013: leave.s IL_0015 } // end handler IL_0015: nop IL_0016: ret } // end of method Program::Main All these NOPs and others cost. A: IMO this whole discussion is like saying "wow lops are expensive because I need to increment a counter... i'm not going to use them any more", or "wow creating an object takes time, i'm not going to create a ton of objects any more." Bottom line is your adding code, presumably for a reason. If the lines of code didn't then incur some overhead, even if its 1 CPU cycle, then why would it exist? Nothing is free. The wise thing to do, as with any line of code you add to your application, is to only put it there if you need it to do something. If catching an exception is something you need to do, then do it... just like if you need a string to store something, create a new string. By the same means, if you declare a variable that isn't ever used, you are wasting memory and CPU cycles to create it and it should be removed. same with a try/catch. In other words, if there's code there to do something, then assume that doing something is going to consume CPU and/or memory in some way. A: It's not the block itself that's expensive, and it's not even catching an exception, per se, that's expensive, it's the runtime unwinding the call stack until it finds a stack frame that can handle the exception. Throwing an exception is pretty light weight, but if the runtime has to walk up six stack frames (i.e. six method calls deep) to find an appropriate exception handler, possibly executing finally blocks as it goes, you may see a noticeable amount of time passed. A: It's not try blocks you need to worry about as much as catch blocks. And then, it's not that you want to avoid writing the blocks: it's that you want as much as possible to write code that will never actually use them. A: You shouldn't avoid try/catch blocks as that generally means you aren't properly handling exceptions that might occur. Structured Exception Handling (SEH) is only expensive when an exception actually occurs as the runtime must walk the call stack looking for a catch handler, execute that handler (and there may be more than one), then execute the finally blocks, and then return control back to the code at the right location. Exceptions are not intended to be used to control program logic, but rather to indicate error conditions. One of the biggest misconceptions about exceptions is that they are for “exceptional conditions.” The reality is that they are for communicating error conditions. From a framework design perspective, there is no such thing as an “exceptional condition”. Whether a condition is exceptional or not depends on the context of usage, --- but reusable libraries rarely know how they will be used. For example, OutOfMemoryException might be exceptional for a simple data entry application; it’s not so exceptional for applications doing their own memory management (e.g. SQL server). In other words, one man’s exceptional condition is another man’s chronic condition. [http://blogs.msdn.com/kcwalina/archive/2008/07/17/ExceptionalError.aspx] A: I doubt if they are particularly expensive. A lot of times, they are necessary/required. Though I strongly recommend using them only when necessary and at the right places / level of nesting instead of rethrowing the exception at every call return. I would imagine the main reason for the advice was to say that you shouldnt be using try-catches where if---else would be a better approach. A: This is not something I would ever worry about. I would rather care about the clarity and safety of a try...finally block over concerning myself with how "expensive" it is. I personally don't use a 286, nor does anyone using .NET or Java either. Move on. Worry about writing good code that will affect your users and other developers instead of the underlying framework that is working fine for 99.999999% of the people using it. This is probably not very helpful, and I don't mean to be scathing but just highlighting perspective. A: Slightly O/T, but... There is fairly good design concept that says you should never require exception handling. This means simply that you should be able to query any object for any conditions that might throw an exception before that exception would be thrown. Like being able to say "writable()" before "write()", stuff like that. It's a decent idea, and if used, it makes checked exceptions in Java look kind stupid--I mean, checking for a condition and right after that, being forced to still write a try/catch for the same condition? It's a pretty good pattern, but checked exceptions can be enforced by the compiler, these checks can't. Also not all libraries are made using this design pattern--it's just something to keep in mind when you are thinking about exceptions. A: Every try needs to record a lot of information, e.g. stack pointers, values of CPU register, etc. so it can unwind the stack and bring back the state it has been when passing the try block in case an exception is thrown. Not only that every try needs to record a lot of information, when an exception is thrown, a lot of values needs to be restored. So a try is very expensive and a throw/catch is very expensive, too. That doesn't mean you shouldn't use exceptions, however, in performance critical code you should maybe not use too many tries and also not throw exceptions too often.
{ "language": "en", "url": "https://stackoverflow.com/questions/164613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: Using Crystal Reports in Visual Studio 2005 (C# .NET Windows App) I need to create reports in a C# .NET Windows app. I've got an SQL Server 2005 database, Visual Studio 2005 and am quite OK with creating stored procedures and datasets. Can someone please point me in the right direction for creating reports? I just can't seem work it out. Some examples would be a good start, or a simple How-to tutorial... anything really that is a bit better explained than the MSDN docs. I'm using the CrystalDecisions.Windows.Forms.CrystalReportViewer control to display the reports, I presume this is correct. If I'm about to embark on a long and complex journey, what's the simplest way to create and display reports that can also be printed? A: I have managed to make this work now. Brief Overview It works by having a 'data class' which is just a regular C# class containing variables and no code. This is then instantiated and filled with data and then placed inside an ArrayList. The ArrayList is bound to the report viewer, along with the name of the report to load. In the report designer '.Net Objects' are used, rather than communicating with the database. Explanation I created a class to hold the data for my report. This class is manually filled by me by manually retrieving data from the database. How you do this doesn't matter, but here's an example: DataSet ds = GeneratePickingNoteDataSet(id); foreach (DataRow row in ds.Tables[0].Rows) { CPickingNoteData pickingNoteData = new CPickingNoteData(); pickingNoteData.delivery_date = (DateTime)row["delivery_date"]; pickingNoteData.cust_po = (int)row["CustomerPONumber"]; pickingNoteData.address = row["CustomerAddress"].ToString(); // ... and so on ... rptData.Add(pickingNoteData); } The class is then put inside an ArrayList. Each element in the arraylist corresponds to one 'row' in the finished report. The first element in the list can also hold the report header data, and the last element in the list can hold the report footer data. And because this is an ArrayList, normal Array access can be used to get at them: ((CPickingNoteData)rptData[0]).header_date = DateTime.Now; ((CPickingNoteData)rptData[rptData.Count-1]).footer_serial = GenerateSerialNumber(); Once you have an arraylist full of data, bind it to your report viewer like this, where 'rptData' is of type 'ArrayList' ReportDocument reportDoc = new ReportDocument(); reportDoc.Load(reportPath); reportDoc.SetDataSource(rptData); crystalReportViewer.ReportSource = reportDoc; Now you will need to bind your data class to the report itself. You do this inside the designer: * *Open the Field Explorer tab (which might be under the 'View' menu), and right-click "Database Fields" *Click on 'Project Data' *Click on '.NET Objects' *Scroll down the list to find your data class (if it isn't there, compile your application) *Press '>>' and then OK *You can now drag the class members onto the report and arrange them as you want. A: Crystal is one possible option for creating reports. It has been around a long time and a lot of people seem to like it. You might want to take a look at SQL reporting services. I have used both but my preferance is SQL reporting services. Its pretty well integrated into studio and works similar to the other microsoft projects. Its also free with the sql express etc. This is a good article on beginning reporting services: http://www.simple-talk.com/sql/learn-sql-server/beginning-sql-server-2005-reporting-services-part-1/ A: You can use the report viewer with client side reporting built into vs.net (ReportBuilder/ReportViewer control). You can create reports the same way as you do for sql reporting services, except you dont need sql server(nor asp.net). Plus you have complete control over them(how you present, how you collect data, what layer they are generated in, what you do with them after generating, such as mailing them, sending to ftp, etc). You can also export as PDF and excel. And in your case building up a report from data and user input, this may work great as you can build up your own datasource and data as you go along. Once your data is ready to be reported on, bind it to your report. The reports can easily be built in Visual Studio 2005 (Add a report to your project), and be shown in a Winforms app using the ReportViewer control. Here is a great book i recommend to everyone to look at if interested in client side reports. It gives a lot of great info and many different scenarios and ways to use client side reporting. http://www.apress.com/book/view/9781590598542 A: I second alex's recommendation to look at sql reporting services - if you have a sql developer license, then you probably already have reporting services i don't like crystal reports, too much tedium in the designer (editing expressions all the time) too many server-deployment issues (check those license files!) A: I use Crystal. I will outline my method briefly, but be aware that I'm a one man shop and it may not translate to your environment. First, create a form with a CR Viewer. Then: 1) Figure out what data you need, and create a view that retrieves the desired columns. 2) Create a new Crystal report using the wizard giving your view as the source of the data. 3) Drag, drop, insert, delete, and whatever to rough your report into shape. Yes, it's tedious. 4) Create the necessary button click or whatever, and create the function in which to generate the report. 5) Retrieve the data to a DataTable (probably in a DataSet). You do not have to use the view. 6) Create the report object. Set the DataTable to be the DataSource. Assign the report object to the CR Viewer. This is one part for which there are examples. Comments: If you lose the window with the database fields, etc (Field Explorer), go to View/Document Outline. (It's my fantasy to have Bill Gates on a stage and ask him to find it.) The reason for setting up the view is that if you want to add a column, you revise the view, and the Field Explorer will update automatically. I've had all sorts of trouble doing it other ways. This method also is a work-around for a bug that requires scanning through all the tables resetting which table they point to. You want to hand Crystal a single table. You do not want to try to get Crystal to join tables, etc. I don't say it doesn't work; I say it's harder. There is (or was) documentation for the VS implementation of Crystal on the Business Objects web site, but I believe that it has disappeared behind a register/login screen. (I could stand more info on that myself.) I've had trouble getting Crystal to page break when I want, and not page break when I don't want, etc. It's far from the best report writer I've ever used and I do not understand why it seems to have put so many others out of business. In addition, their licensing policies are very difficult to deal with in a small, fluid organization. Edited to add example: AcctStatement oRpt = new AcctStatement() ; oRpt.Database.Tables[0].SetDataSource(dsRpt.Tables[0]); oRpt.SetParameterValue("plan_title",sPlanName) ; crViewer.ReportSource = oRpt ; A: I found the following websites solved my problems. Included here for future reference. CrystalReportViewer Object Model Tutorials for the tutorial on how to make the whole thing work. And also Setting up a project to use Crystal Reports and specifically preparing the form and adding the control A: i think this may help you out http://infynet.wordpress.com/2010/10/06/crystal-report-in-c/ A: I strongly recommend trying an alternative reporting solution - I have a lot of experience with Crystal, and have managed to do some funky things with it in .Net, but quite honestly the integration of Crystal and .Net is an absolute pig for anything but the simplest cases. A: I have tried RS. I am converting from RS back to Crystal. RS is just too heavy and slow (or something). There is no reason to have to wait 30 seconds for a report to render is RS when Crystal does it in under a second.
{ "language": "en", "url": "https://stackoverflow.com/questions/164621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to create and resolve relative paths? My app open file in subdirectory of directory where it is executed, subdirectory is called sample and it contains files: * *example.raf (example extension, non significant) *background.gif example.raf contains relative path to background.gif (in this case only file name cause the files is in same directory as raf) and opening of RAF causes application to read and display background.gif. When I use OpenFileDialog to load RAF file everything is alright, image loads correctly. I know that open file dialog changes in some way current working directory but i was unable to recreate this without calling open file dialog Unfortunately in case when i call raf reading method directly from code, without supplying path to file form OpenFileDialog like this LoadRAF("sample\\example.raf"); in this case i got problem, app try to load image from ExecutablePath and not from subdirectory which contains RAF file and image. Ofcourse it is normal behavior but in this case it is highkly unwanted. It is required to handle both relative and absolute type of paths in my app, so what should i do to solve this, how to change ExecutablePath or what other thing i can do to make this work at least as in case of OpenFileDialog? A: Next code from my project ZipSolution (http://zipsolution.codeplex.com/) shows how to resolve and create relative pathes in .net using System; using System.Collections.Generic; using System.Text; using System.IO; namespace ZipSolution { internal static class RelativePathDiscovery { /// <summary> /// Produces relative path when possible to go from baseLocation to targetLocation /// </summary> /// <param name="baseLocation">The root folder</param> /// <param name="targetLocation">The target folder</param> /// <returns>The relative path relative to baseLocation</returns> /// <exception cref="ArgumentNullException">base or target locations are null or empty</exception> public static string ProduceRelativePath(string baseLocation, string targetLocation) { if (string.IsNullOrEmpty(baseLocation)) { throw new ArgumentNullException("baseLocation"); } if (string.IsNullOrEmpty(targetLocation)) { throw new ArgumentNullException("targetLocation"); } if (!Path.IsPathRooted(baseLocation)) { return baseLocation; } if (!Path.IsPathRooted(targetLocation)) { return targetLocation; } if (string.Compare(Path.GetPathRoot(baseLocation), Path.GetPathRoot(targetLocation), true) != 0) { return targetLocation; } if (string.Compare(baseLocation, targetLocation, true) == 0) { return "."; } string resultPath = "."; if (!targetLocation.EndsWith(@"\")) { targetLocation = targetLocation + @"\"; } if (baseLocation.EndsWith(@"\")) { baseLocation = baseLocation.Substring(0, baseLocation.Length - 1); } while (!targetLocation.StartsWith(baseLocation + @"\", StringComparison.OrdinalIgnoreCase)) { resultPath = resultPath + @"\.."; baseLocation = Path.GetDirectoryName(baseLocation); if (baseLocation.EndsWith(@"\")) { baseLocation = baseLocation.Substring(0, baseLocation.Length - 1); } } resultPath = resultPath + targetLocation.Substring(baseLocation.Length); // preprocess .\ case return resultPath.Substring(2, resultPath.Length - 3); } /// <summary> /// Resolves the relative pathes /// </summary> /// <param name="relativePath">Relative path</param> /// <param name="basePath">base path for discovering</param> /// <returns>Resolved path</returns> public static string ResolveRelativePath(string relativePath, string basePath) { if (string.IsNullOrEmpty(basePath)) { throw new ArgumentNullException("basePath"); } if (string.IsNullOrEmpty(relativePath)) { throw new ArgumentNullException("relativePath"); } var result = basePath; if (Path.IsPathRooted(relativePath)) { return relativePath; } if (relativePath.EndsWith(@"\")) { relativePath = relativePath.Substring(0, relativePath.Length - 1); } if (relativePath == ".") { return basePath; } if (relativePath.StartsWith(@".\")) { relativePath = relativePath.Substring(2); } relativePath = relativePath.Replace(@"\.\", @"\"); if (!relativePath.EndsWith(@"\")) { relativePath = relativePath + @"\"; } while (!string.IsNullOrEmpty(relativePath)) { int lengthOfOperation = relativePath.IndexOf(@"\") + 1; var operation = relativePath.Substring(0, lengthOfOperation - 1); relativePath = relativePath.Remove(0, lengthOfOperation); if (operation == @"..") { result = Path.GetDirectoryName(result); } else { result = Path.Combine(result, operation); } } return result; } } } A: The OpenFileDialog is spitting out an absolute path behind the scenes. If you know the location of raf file you can do something like: string parentPath = Directory.GetParent(rafFilePath); string imagePath = Path.Combine(parentPath, imageFileNameFromRaf); imagePath will now contain the absolute path to your image derived from the image name contained in the raf file, and the directory the raf file was in. A: You can try to change the current directory to the directory containing your executable using Environment.CurrentDirectory before reading from relative paths. Or instead if you have a relative path (Path.IsPathRooted) you can combine (Path.Combine) your root directory with the relative path to have an absolute one.
{ "language": "en", "url": "https://stackoverflow.com/questions/164630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create grails war without version number How do I create a grails war file so that it doesn't have the version number (e.g. foo-0.1.war) attached to the end when I execute the 'grails war' command? A: Rolling up the other excellent answers. There are several options: Explicitly set it on the command line: grails war foo.war Set the app.version property to empty in application.properties will cause the war to be named foo.war. Explicitly set the name of the war using the grails.war.destFile property in Config.groovy A: In case anybody comes upon this article and is using Grails 1.3.x, the configuration option has changed from grails.war.destFile in Config.groovy to being grails.project.war.file in BuildConfig.groovy. Also the file name is relative to the project workspace, so it should have a value like: grails.project.war.file = "target/${appName}.war" This is according to the latest Grails documentation. A: Grails 3.x has switched to gradle and uses the war plugin. You can just specify name like this in the build.gradle file: war { archiveName 'foo.war' } A: I think you can specify the war name in the war command. grails war foo.war Also check the latest Grails documentation for where to set this as a configuration option. See the other answers for details. A: From the Grails Documentation, Chapter 17, Deployment There are also many ways in which you can customise the WAR file that is created. For example, you can specify a path (either absolute or relative) to the command that instructs it where to place the file and what name to give it: grails war /opt/java/tomcat-5.5.24/foobar.war Alternatively, you can add a line to Config.groovy that changes the default location and filename: grails.war.destFile = "foobar-prod.war" Of course, any command line argument that you provide overrides this setting. A: Another way to generate war files without version number is to keep the property, app.version, empty in the application.properties A: I am kind of late to the party... but anyway: I think the reason behind removing the version number is to eliminate the need to rename the war file so it deploys on "correct" context path /appName. If that's the case then a better option is to use a versioned war filename so you can deploy multiple versions at the same time on tomcat using the following naming pattern in grails-app/conf/BuildConfig.groovy: grails.project.war.file = "target/${appName}##${appVersion}.war" As explained in http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Parallel_deployment This method applies to wars in general, not only grails' wars.
{ "language": "en", "url": "https://stackoverflow.com/questions/164642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Is an int a 64-bit integer in 64-bit C#? In my C# source code I may have declared integers as: int i = 5; or Int32 i = 5; In the currently prevalent 32-bit world they are equivalent. However, as we move into a 64-bit world, am I correct in saying that the following will become the same? int i = 5; Int64 i = 5; A: I think what you may be confused by is that int is an alias for Int32 so it will always be 4 bytes, but IntPtr is suppose to match the word size of the CPU architecture so it will be 4 bytes on a 32-bit system and 8 bytes on a 64-bit system. A: No. The C# specification rigidly defines that int is an alias for System.Int32 with exactly 32 bits. Changing this would be a major breaking change. A: The int keyword in C# is defined as an alias for the System.Int32 type and this is (judging by the name) meant to be a 32-bit integer. To the specification: CLI specification section 8.2.2 (Built-in value and reference types) has a table with the following: * *System.Int32 - Signed 32-bit integer C# specification section 8.2.1 (Predefined types) has a similar table: * *int - 32-bit signed integral type This guarantees that both System.Int32 in CLR and int in C# will always be 32-bit. A: According to the C# specification ECMA-334, section "11.1.4 Simple Types", the reserved word int will be aliased to System.Int32. Since this is in the specification it is very unlikely to change. A: No matter whether you're using the 32-bit version or 64-bit version of the CLR, in C# an int will always mean System.Int32 and long will always mean System.Int64. A: The following will always be true in C#: sbyte signed 8 bits, 1 byte byte unsigned 8 bits, 1 byte short signed 16 bits, 2 bytes ushort unsigned 16 bits, 2 bytes int signed 32 bits, 4 bytes uint unsigned 32 bits, 4 bytes long signed 64 bits, 8 bytes ulong unsigned 64 bits, 8 bytes An integer literal is just a sequence of digits (eg 314159) without any of these explicit types. C# assigns it the first type in the sequence (int, uint, long, ulong) in which it fits. This seems to have been slightly muddled in at least one of the responses above. Weirdly the unary minus operator (minus sign) showing up before a string of digits does not reduce the choice to (int, long). The literal is always positive; the minus sign really is an operator. So presumably -314159 is exactly the same thing as -((int)314159). Except apparently there's a special case to get -2147483648 straight into an int; otherwise it'd be -((uint)2147483648). Which I presume does something unpleasant. Somehow it seems safe to predict that C# (and friends) will never bother with "squishy name" types for >=128 bit integers. We'll get nice support for arbitrarily large integers and super-precise support for UInt128, UInt256, etc. as soon as processors support doing math that wide, and hardly ever use any of it. 64-bit address spaces are really big. If they're ever too small it'll be for some esoteric reason like ASLR or a more efficient MapReduce or something. A: Will sizeof(testInt) ever be 8? No, sizeof(testInt) is an error. testInt is a local variable. The sizeof operator requires a type as its argument. This will never be 8 because it will always be an error. VS2010 compiles a c# managed integer as 4 bytes, even on a 64 bit machine. Correct. I note that section 18.5.8 of the C# specification defines sizeof(int) as being the compile-time constant 4. That is, when you say sizeof(int) the compiler simply replaces that with 4; it is just as if you'd said "4" in the source code. Does anyone know if/when the time will come that a standard "int" in C# will be 64 bits? Never. Section 4.1.4 of the C# specification states that "int" is a synonym for "System.Int32". If what you want is a "pointer-sized integer" then use IntPtr. An IntPtr changes its size on different architectures. A: int is always synonymous with Int32 on all platforms. It's very unlikely that Microsoft will change that in the future, as it would break lots of existing code that assumes int is 32-bits. A: Yes, as Jon said, and unlike the 'C/C++ world', Java and C# aren't dependent on the system they're running on. They have strictly defined lengths for byte/short/int/long and single/double precision floats, equal on every system. A: int without suffix can be either 32bit or 64bit, it depends on the value it represents. as defined in MSDN: When an integer literal has no suffix, its type is the first of these types in which its value can be represented: int, uint, long, ulong. Here is the address: https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/164643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Formatting Literal parameters of a C# code snippet Is there any way that I can change how a Literal of a code snippet renders when it is used in the code that the snippet generates? Specifically I'd like to know if I can have a literal called say, $PropertyName$ and then get the snippet engine to render "_$PropertyName$ where the first character is made lowercase. I can't afford R#. Please help :) A: You can enter a upper first letter, then a property name, then a lower first letter. Try this snippet: <?xml version="1.0" encoding="utf-8"?> <CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <Header> <Title>Notifiable Property</Title> <Author>Nikolay Makhonin</Author> <Shortcut>propn</Shortcut> <Description>Property With in Built Property Changed method implementation.</Description> <SnippetTypes> <SnippetType>SurroundsWith</SnippetType> <SnippetType>Expansion</SnippetType> </SnippetTypes> </Header> <Snippet> <Declarations> <Literal> <ID>Type</ID> <Default>Type</Default> </Literal> <Literal> <ID>P</ID> <Default>P</Default> </Literal> <Literal> <ID>roperty</ID> <Default>ropertyName</Default> </Literal> <Literal> <ID>p</ID> <Default>p</Default> </Literal> <Literal> <ID>Ownerclass</ID> <ToolTip>The owning class of this Property.</ToolTip> <Function>ClassName()</Function> <Default>Ownerclass</Default> </Literal> </Declarations> <Code Language="CSharp"> <![CDATA[#region $P$$roperty$ private Field<$Type$> _$p$$roperty$; public static readonly string $P$$roperty$PropertyName = GetPropertyName(() => (($Ownerclass$)null).$P$$roperty$); public $Type$ $P$$roperty$ { get { return _$p$$roperty$; } set { Set(ref _$p$$roperty$, value); } } #endregion ]]> </Code> </Snippet> </CodeSnippet> A: a "fix" may be to use a prefix in the naming or the member variable, i.e.: string m_$name$; string $name$ { get{return m_$name$;} set{m_$name$=value;} }; A: Unfortunately there seems to be no way. Snippets offer amazingly limited support for transformation functions as you can see. You have to stick with the VS standard solution, which is to write two literals: one for the property name, and the other for the member variable name.
{ "language": "en", "url": "https://stackoverflow.com/questions/164645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Where can I find a good collection of public domain owl ontologies for various domains? I am building an ontology-processing tool and need lots of examples of various owl ontologies, as people are building and using them in the real world. I'm not talking about foundational ontologies such as Cyc, I'm talking about smaller, domain-specific ones. A: There's no definitive collection afaik, but these links all have useful collections of OWL and RDFS ontologies: * *schemaweb.info *vocab.org *owlseek *linking open data constellation *RDF schema registry (rather old now) In addition, there are some general-purpose RDF/RDFS/OWL search engines you may find helpful: * *sindice *swoogle Ian A: My go-to site for this probably didn't exist at the time of the question. For latecomers like me: Linked Open Vocabularies I wish I'd found it much sooner! It's well-groomed, maintained, has all the most-popular ontologies, and has a good search engine. However, it doesn't include some specialized collections, most notably, (most of?) the stuff in OBO Foundry. A: Thanks! A couple more I found: * *OntoSelect - browsable ontology repository *Protege Ontology Library *CO-ODE Ontologies A: Within the life-science domain, the publically abvailable ontologies can be found listed on the OBO Foundry site. These ontologies can be queried via the ontology lookup service or the NCBO's Bioportal, which also contains additional resources. A: One more concept search tool: falcons A: There is also one good web engine for searching for ontologies. It is called Watson Semantic Web Search and you can try it here.
{ "language": "en", "url": "https://stackoverflow.com/questions/164648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Best Practices for Entity Framework and ASP.NET I've been driving myself crazy trying to get the Entity Framework to work as expected (or at least as I expect) in an ASP.NET environment, specifically dealing with objects belonging to different contexts when attempting to save to the database. What are the best practices when dealing with the Entity Framework and ASP.NET? A: Persistence Ignorance (POCO) Adapter for Entity Framework V1 http://blogs.gotdotnet.com/jkowalski/archive/2008/09/09/persistence-ignorance-poco-adapter-for-entity-framework-v1.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/164661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Office 2003 PIA Prerequisite in the .Net framework and Office 2007 What happens when the Office 2003 PIA prerequisite and launch condition in a Windows installer are run against an Office 2007 system? A: Yes, it will fail unless for the simple reason that Office 2003 is not installed. We create separate installers for Office 2007 and Office 2003. Also, there is a difference in the structure of Office 2003 add-ins versus Office 2007 add-ins. A: I believe the 2003 PIA require Office 2003 be installed (so I'm guessing it would fail). AFAIK, the 2003 interops won't work with the 2007 applications. More information about these types of scenarios can be found here. So even if it did install (pretty easy to test) you might not have a working application. Are you trying to get some 2003 Add-ins to work with Office 2007?
{ "language": "en", "url": "https://stackoverflow.com/questions/164689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET DBNull vs Nothing across all variable types? I am a little confused about null values and variables in .NET. (VB preferred) Is there any way to check the "nullness" of ANY given variable regardless of whether it was an object or a value type? Or does my null check have to always anticipate whether it's checking a value type (e.g. System.Integer) or an object? I guess what I'm looking for is a function that checks all possible kind of null-ness. That is, any type of variables that a) were never assigned a value since declared b) were assigned a null value from a data object (that came from a database) c) were set equals to another variable value which was null d) were set to an ASP.NET session/application variable that was never set or expired. Is there a general best-practice when it comes to handling null scenarios in .NET? UPDATE: When I talk about a value type being "null", what I really mean is a value type that was either never set or was at some point set equal to or cast from a null object. A: Value Types can't be null. It violates what it means to be a Value Type. You can wrap Value Types as Nullable(Of T) which gives you a great set of methods, and checks for Nothing do work. But you do have a lot of overhead with that wrapper. Perhaps you can clarify what you're trying to do? For completeness the VB syntax for Nullable wrappers is: Dim i as Nullable(Of Integer) = Nothing '.NET 2.0/3.0' Dim j as Integer? = Nothing '.NET 3.5' EDIT: Value Type are always preinitialized to a default value, 0 for numerics, false for Booleans, etc. A: Is this what you're after? if IsNothing(foo) OrElse IsDbNull(foo) Then ' Do Something Because foo Is Either Nothing or DBNull.Value End If In truth I'm not certain why you'd wish for this structure. The Only time I'd check for DBNULL.Value is when I'm using values that came from a database, and before I assign said value from a DATA Namespace class to some other class [i.e. dim b as string = dataReader(0)]. Typically, if you're concerned about an object having not been instantiated, or needing it to be re-instantiated, then just an IsNothing check will suffice. A: Normal value types (booleans, ints, longs, float, double, enum and structs) are not nullable. The default value for all value types is 0. The CLR won't let you access variables unless they have been set. You may think this isn't always the case, but sometimes the CLR steps in and initializes them for you. At a method level you must explicitly initialize all variables before they are used. Further, as others point out, since .net 2.0 there is a new generic type called Nullable<T>. There are some compiler shorthands in C# like int? means Nullable<int>, double? means Nullable<double> etc. You can only wrap Nullable<T> over non-nullable value types, which is fine since references already have the ability to be null. int? x = null; For an int?, while you can test against null, it's sometimes nicer to call x.HasValue(). In C# there's also the nullable coalescing operator ?? when you want to assign a nullable to a non-nullable value type. But if you don't have the operator, you can call GetValueOrDefault(). int y = x ?? 2; // y becomes 2 if x is null. int z = x.GetValueOrDefault(2); // same as y A: In .Net that are only two types of null that I am aware of, null (nothing in VB) and DbNull. If you are using a System.Nullable, you can use the same null checking syntax as you would with an object. If if your nullable object is boxed the .Net 2.0 CLR is smart enough to figure out the right way to handle this. The only case I have run into both types is in the data tier of an application where I might be accessing database data directly. For example, I have run into DbNull in a DataTable. To check for both of these null types in this situration, you could write an extension method like (sorry, in C#): static public bool IsNull(this object obj) { return obj != null && obj != DbNull.Value; } ... if(dataTable[0]["MyColumn"].IsNull()) { //do something } A: Value type variables can't contain null, that's because what null means, null means that the references points nowhere. I don't know on VB.net but on c# you can wrap value types to be nullables using the "?", like: int? a = null; A: As long as you're developing with Option Strict On, (a) shouldn't be an issue. The compiler will yell at you. If you're worried about checking for parameters, just use Public Sub MySub(ByVal param1 as MyObject, ByVal param2 as Integer) if param1 is nothing then Throw New ArgumentException("param1 cannot be null!") end if 'param2 cannot be null End Sub For (b), your database interaction layer should handle this. If you're using LINQ, there are ways to handle this. If you're using typed data sets, there an .IsMyVariableNull property on the row that gets auto-generated. For (c), you don't need to worry about value types, but reference types can be checked with a simple Is Nothing (or IsNot Nothing). For (d), you can apply the same logic after the read. Test the receiving variable against Nothing. For the most part, a simple check of Is Nothing will get you by. Your database interaction layer will help you handle the stickier case of null values in your data, but it's up to you to handle them appropriately.
{ "language": "en", "url": "https://stackoverflow.com/questions/164697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can I use C# style enumerations in Ruby? I just want to know the best way to emulate a C# style enumeration in Ruby. A: It's not quite the same, but I'll often build a hash for this kind of thing: STATES = {:open => 1, :closed => 2, :max => 3, :min => 4}.freeze() Freezing the hash keeps me from accidentally modifying its contents. Moreover, if you want to raise an error when accessing something that doesn't exist, you can use a defualt Proc to do this: STATES = Hash.new { |hash, key| raise NameError, "#{key} is not allowed" } STATES.merge!({:open => 1, :closed => 2, :max => 3, :min => 4}).freeze() STATES[:other] # raises NameError A: Specifically, I would like to be able to perform logical tests against the set of values given some variable. Example would be the state of a window: "minimized, maximized, closed, open" If you need the enumerations to map to values (eg, you need minimized to equal 0, maximised to equal 100, etc) I'd use a hash of symbols to values, like this: WINDOW_STATES = { :minimized => 0, :maximized => 100 }.freeze The freeze (like nate says) stops you from breaking things in future by accident. You can check if something is valid by doing this WINDOW_STATES.keys.include?(window_state) Alternatively, if you don't need any values, and just need to check 'membership' then an array is fine WINDOW_STATES = [:minimized, :maximized].freeze Use it like this WINDOW_STATES.include?(window_state) If your keys are going to be strings (like for example a 'state' field in a RoR app), then you can use an array of strings. I do this ALL THE TIME in many of our rails apps. WINDOW_STATES = %w(minimized maximized open closed).freeze This is pretty much what rails validates_inclusion_of validator is purpose built for :-) Personal Note: I don't like typing include? all the time, so I have this (it's only complicated because of the .in?(1, 2, 3) case: class Object # Lets us write array.include?(x) the other way round # Also accepts multiple args, so we can do 2.in?( 1,2,3 ) without bothering with arrays def in?( *args ) # if we have 1 arg, and it is a collection, act as if it were passed as a single value, UNLESS we are an array ourselves. # The mismatch between checking for respond_to on the args vs checking for self.kind_of?Array is deliberate, otherwise # arrays of strings break and ranges don't work right args.length == 1 && args.first.respond_to?(:include?) && !self.kind_of?(Array) ? args.first.include?( self ) : args.include?( self ) end end end This lets you type window_state.in? WINDOW_STATES A: I don't think Ruby supports true enums -- though, there are still solutions available. Enumerations and Ruby A: The easiest way to define an Enum in ruby to use a class with constant variables. class WindowState Open = 1 Closed = 2 Max = 3 Min = 4 end A: Making a class or hash as others have said will work. However, the Ruby thing to do is to use symbols. Symbols in Ruby start with a colon and look like this: greetingtype = :hello They are kind of like objects that consist only of a name.
{ "language": "en", "url": "https://stackoverflow.com/questions/164714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: API for creating installers on Windows There are lots of tools for creating installers on Windows (InstallShield, InnoSetup, NSIS, just to name a few). All tools I've seen fall in one or both of these categories * *Point-and-click. Nice GUI for creating the installer, but the installer definition/project file can not be manually edited. *Textfile: No (official) GUI. The installer is compiled from a definition in a text-file which is manually edited. The installers I'm building are all defined using a DSL (represented as YAML files), so using a GUI is out of the question, and creating is textfile is cumbersome although doable. What I really would want is a tool which exposes a (complete) API, through which I can control the creation of the installer. Are there any such tools out there? Edit: I'd love to hear about non-MSI based tools as well. MSI is not a requirement (rather the other way around...) A: Wix 3.0 beta has .NET support included for this purpose. I don't know how well it works but it includes documentation. It's a framework of types for manipulating the installation creation process and all that goodness, so I don't think you even need to write a line of WiX XML if you don't want to. A: WiX is a great tool, but you will have to do a lot of direct coding in order to make things happen. Fortunately the documentation is pretty good and there are several GUI tools, such as WixEdit on SourceForge to aid in the process. A: Well, there is the Windows Installer API which you could use to create MSI files directly, however I think you'd be better off using WiX. The "direct coding" will be much less than dealing with the Windows Installer API directly, I'm guessing that's probably going too "low level" for what you need. Depending on what you're looking to do, you could use WiX to generate an MSI and then tweak that afterwards using the API. What's wrong with generating XML? That's really going to be your simplest option... you won't need to manually edit it, just write your own code to generate the required XML from your DSL files and a few templates.
{ "language": "en", "url": "https://stackoverflow.com/questions/164719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Return custom structure from Popup window in Powerbuilder 9.0 How do you return values or structures from a Popup window in Powerbuilder 9.0? The CloseWithReturn is only valid for Response windows and thus is not available. When I set a value to the Message.PowerObjectParm, the value becomes null when the Popup window closes. I need to use a Popup window so the user can click back to the caller window and scroll through rows. Program flow: 1) Window A OpenWithParm 2) Window B is now open 3) User interacts with both windows 3) User closes Window B 4) Window B needs to pass a structure back to window A A: You can get around the "one instance" of parent limitation by passing in a reference to the parent window when opening the popup, and storing the reference in an instance variable. This also ensures you're talking to the right version of w_my_parent_window_name. A: You won't be able to accomplish this the way you are thinking. Since the window you are opening from the parent is not a Response window, the two aren't explicitly linked together. But you could accomplish this by having a public instance variable in the parent window that is of the type of your custom structure. Then from the child window before you close it, explicitly set the variable in the parent window via something like this: w_my_parent_window_name.istr_my_structure = lstr_my_structure This should only be done if there will only be one instance of w_my_parent_window_name instantiated. A: If you're using the PFC, if I remember right there was a service that you could use as well. A: Message.PowerObjectParm would work for passing an object. The reason it becomes NULL when the popup is closed is because structures are auto-instantiated and auto-destroyed. They are only valid within the scope that they are declared. For example, if it's declared within a function, it will be destroyed upon completion of the function; if it's an instance variable of the popup, it will be destroyed along with the popup when it's closed. You can copy the structure back into a variable of the same type on the parent window before closing the popup as Dougman suggests, or alternatively, you could use an object instead of a structure. E.g. just create custom object and declare public instance variables in it as you would the variables of the structure. You of course need to explicitly create and destroy the object. An object created by the popup will remain instantiated until explicitly destroyed, even after the popup itself is destroyed. A: There are always multiple ways to solve a problem. I'll propose another, even though the question is old... When you close the popup window, you can trigger a custom event on the parent window. Well, technically, you can trigger any event on the parent window, but I'd suggest creating a custom event specifically for this so that you can pass the structure as an argument to that event. A: Use a local structure variable to return the values selected and Just use Message.PowerObjectParm in the parent window and Validate the existence of the structure variable if closed the response window without any selection.
{ "language": "en", "url": "https://stackoverflow.com/questions/164727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redirect Standard Output Efficiently in .NET I am trying to call php-cgi.exe from a .NET program. I use RedirectStandardOutput to get the output back as a stream but the whole thing is very slow. Do you have any idea on how I can make that faster? Any other technique? Dim oCGI As ProcessStartInfo = New ProcessStartInfo() oCGI.WorkingDirectory = "C:\Program Files\Application\php" oCGI.FileName = "php-cgi.exe" oCGI.RedirectStandardOutput = True oCGI.RedirectStandardInput = True oCGI.UseShellExecute = False oCGI.CreateNoWindow = True Dim oProcess As Process = New Process() oProcess.StartInfo = oCGI oProcess.Start() oProcess.StandardOutput.ReadToEnd() A: You can use the OutputDataReceived event to receive data as it's pumped to StdOut. A: The problem is due a bad php.ini config. I had the same problem and i downloaded the Windows installer from: http://windows.php.net/download/. After that and commenting out not needed extensions, the conversion process is alà Speedy Gonzales, converting 20 php per second. You can safely use "oProcess.StandardOutput.ReadToEnd()". It's more readable and alomost as fast as using the thread solution. To use the thread solution in conjunction with a string you need to introduce an event or something. Cheers A: The best solution I have found is: private void Redirect(StreamReader input, TextBox output) { new Thread(a => { var buffer = new char[1]; while (input.Read(buffer, 0, 1) > 0) { output.Dispatcher.Invoke(new Action(delegate { output.Text += new string(buffer); })); }; }).Start(); } private void Window_Loaded(object sender, RoutedEventArgs e) { process = new Process { StartInfo = new ProcessStartInfo { CreateNoWindow = true, FileName = "php-cgi.exe", RedirectStandardOutput = true, UseShellExecute = false, WorkingDirectory = @"C:\Program Files\Application\php", } }; if (process.Start()) { Redirect(process.StandardOutput, textBox1); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/164736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What's the best way to create a "magnifying glass" on a 2D scene? I'm working on a game where I need to let the player look at a plane (e.g., a wall) through a lens (e.g., a magnifying glass). The game is to run on the iPhone, so my choices are Core Animation or OpenGL ES. My first idea (that I have not yet tried) is to do this using Core Animation. * *Create the wall and objects on it using CALayers. *Use CALayer's renderInContext: method to create an image of the wall as a background layer. *Crop the image to the lens shape, scale it up, then draw it over the background. *Draw the lens frame and "shiny glass" layer on top of all that. Notes: * *I am a lot more familiar with Core Animation than OpenGL, so maybe there is a much better way to do this with OpenGL. (Please tell me!) *If I am using CALayers that are not attached to a view, do I have to manage all animations myself? Or is there a straightforward way to run them manually? *3D perspective is not important; I'm just magnifying a flat wall. *I'm concerned that doing all of the above will be too slow for smooth animation. Before I commit a lot of code to writing this, my question is do you see any pitfalls in the plan above or can you recommend an easier way to do this? A: I have implemented a magnifying glass on the iPhone using a UIView. CA was way too slow. You can draw a CGImage into a UIView using it's drawRect method. Here's the steps in my drawRect: * *get the current context *create a path for clipping the view (circle) *scale the current transformation matrix (CTM) *move the current transformation matrix *draw the CGimage You can have the CGImage prerendered, then it's in the graphics memory. If you want something dynamic, draw it from scratch instead of drawing a CGImage. Very fast, looks great. A: That is how I'd do it, it sounds like a good plan. Whether you choose OGL or CA the basic principle is the same so I would stick with what you're more comfortable with. * *Identify the region you wish to magnify *Render this region to a separate surface *Render any border/overlay onto of the surface *Render your surface enlarged onto the main scene, clipping appropriately. In terms of performance you will have to try it and see (just make sure you test on actual hardware, because the simulator is far faster than the hardware). If it IS to slow then you can look at doing steps 2/3 less frequently, e.g every 2-3 frames. This will give some magnification lag but it may be perfectly acceptable. I suspect that performance between OGL / CA will be roughly equivalent. CA is built ontop of the OGL libraries but your cost is going to be doing the actual rendering, not the time spent in the layers.
{ "language": "en", "url": "https://stackoverflow.com/questions/164743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to avoid flicker while handling WM_ERASEBKGND in Windows dialog I have a dialog that resizes. It also has a custom background which I paint in response to a WM_ERASEBKGND call (currently a simple call to FillSolidRect). When the dialog is resized, there is tremendous flickering going on. To try and reduce the flickering I enumerate all child windows and add them to the clipping region. That seems to help a little -- now the flickering is mostly evident in all of the child controls as they repaint. How can I make the dialog flicker-free while resizing? I suspect double-buffering must play a part, but I'm not sure how to do that with a dialog with child controls (without making all child controls owner-draw or something like that). I should note that I'm using C++ (not .NET), and MFC, although pure Win32-based solutions are welcomed :) NOTE: One thing I tried but which didn't work (not sure why) was: CDC memDC; memDC.CreateCompatibleDC(pDC); memDC.FillSolidRect(rect, backgroundColor); pDC->BitBlt(0, 0, rect.Width(), rect.Height(), &memDC, 0, 0, SRCCOPY); A: Try adding the following line to your OnInitDialog function: ModifyStyle(0, WS_CLIPCHILDREN, 0); A: Do nothing in the WM_ERASEBKGND handling and do the erase as part of your main WM_PAINT. You can either paint smarter so that you only redraw the invalid areas, or more easily, double-buffer the drawing. By not doing anything in the erase background, you have all your drawing code in one location which should make it easier for others to follow and maintain. A: If you are targeting WinXP or higher, you can also use the WS_EX_COMPOSITED style to enable double-buffering by default for top-level windows with this style. Bear in mind this has its own set of limitations -- specifically, no more drawing out of OnPaint cycles using GetDC, etc. A: you can set parameter of your call to InvalidateRect method as false. This will prevent you to send WM_ERASEBKGND when the window will redraw. A: Double buffering is indeed the only way to make this work. Child controls will take care of themselves so long as you make sure CLIPCHILDREN. A: Assuming that "FillSolidRect" is the erase of your background then return TRUE from the WM_ERASEBKGND. To do the double buffering that you are almost doing in your code fragment, you will need to use CreateCompatibleBitmap and select that into your memDC.
{ "language": "en", "url": "https://stackoverflow.com/questions/164751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Best Practices - Should meta data and functional defining data be intermixed? Consider the case of a simple news article web application that has a DB table column of "Status" that is accessible by a radio button set of: Status - [x] Publish [ ] Draft [ ] Archive ...where "Publish" shows an article publicly and "Draft" and "Archive" do not. Functionally "Draft" and "Archive" do the same thing but carry additional meta data meanings. The two functional states of "show" and "hide" along with the meta data of "publish", "draft" and "archive" are intermixed in the same column of "status". Is this a good practice? While this is a very simple case, larger cases might reveal flaws with such a practice (or not...). A: Functional states are about behavior - they do not need to be modeled in your database. If your business logic only cares about "showing" articles with a status of "Published" - there's no reason to double the complexity of your data with a Show column. At the point that you decide your business logic needs additional data to make the decision whether to show or hide an article (perhaps an IsApproved flag), then you can store that data. Looking at it from a different angle - if you were to add another column of "Show", then what would an article with a status of "Draft" and "Show" = 1 do? According to your business rules, that is an invalid state. A: In this instance, I would say that this is the appropriate functionality. We've all seen WTF's in the media where someone accidentally hit show[x] and draft[x] at the same time. The way it is now, it is impossible to accidentally show a draft. This is important in newspapers as reporters are notorious for stuff like: John Doe, of StackOverflow said, "---I can't remember what that ugly f*cker said - Check the tape and fill in later" Which probably shouldn't be printed.
{ "language": "en", "url": "https://stackoverflow.com/questions/164752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access the last element in an array? $array = explode(".", $row[copy]); $a = $array.length -1; I want to return the last element of this array but all i get from this is -1. A: You can also use: $a = end($array); This also sets the arrays internal pointer to the end of the array, but it does get you the last element easily. A: Try count: $array = explode(".", $row[copy]); $a = count($array) - 1; $array[$a]; // last element A: You could also use array_pop(). This function takes an array, removes the last element of the array and returns that element. $array = explode(".", $row[copy]); $a = array_pop($array); This will modify the $array, removing the last element, so don't use it if you still need the array for something. A: If you just want everythng after the final . you could try $pos = strrpos($row['copy'], '.'); $str=($pos!==false) ? substr($row['copy'],$pos+1) : ''; This saves generating an array if all you needed was the last element. A: Actually, there is a function that does exactly what you want: end() $res = end( explode('.', $row['copy']) ); A: I think your second line should be more like: $index = count($array) - 1; $a = $array[$index]; If you want an element from an array you need to use square brackets. A: As this is tag as PHP, I'll assume you are using PHP, if so then you'll want to do: $array = explode(".", $row[copy]); $a = count($array) - 1; $value = $array[$a]; But this will only work if your keys are numeric and starting at 0. If you want to get the last element of an array, but don't have numeric keys or they don't start at 0, then: $array = explode(".", $row[copy]); $revArray = array_reverse($array, true); $value = $revArray[key($revArray)]; A: hi u can use this also : $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_pop($stack); print_r($stack); After this, $stack will have only 3 elements: Array ( [0] => orange [1] => banana [2] => apple ) and raspberry will be assigned to $fruit. A: My PHP is a bit rusty, but shouldn't this be: $array = explode(".", $row[$copy]); $a = $array[count($array)]; i.e.: isn't a "$" missing in front of "copy", and does .length actually work?
{ "language": "en", "url": "https://stackoverflow.com/questions/164767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to forward the TCP/IP traffic of a process in Windows XP? alt text http://img440.imageshack.us/img440/6950/problemyd1.png (The curly lines with dots represent a network route.) Having a process called "foo.exe", is there a way to forward everything it communicates over TCP/IP to a forwarding proxy located elsewhere? This forwarding should not reflect to other processes. Another question: if there are multiple network adapters, is it possible to force a process to use one specific adapter. Since in this example the targethost.com is known, I could just edit "system32\drivers\etc\hosts" to map targethost.com's IP to localhost, where on port 8765 would be the first forwarder waiting for an incoming connection and pass everything forward to proxy.foo.com. I was wondering if there's a more elegant way of doing this. This is not for malware, I'm doing some network testing with my complex home network. Thank you for warning us. Some free software for this would be perfect, alternatively a code idea (native or .net). Thank you very much. A: It's not too hard if you make your own computer a firewall, then your app connects to a port on your own computer, and that port is forwarded to both the original destination and logged or forwarded on to your spying computer. Alternatively you can make your other computer the firwall and have it log/forward the info. Finally you could use a sniffer. A: SocksCap will probably do the job (if you're OK with establishing a SOCKS proxy at proxy.foo.com). A: You could hook into the TCP stack, for example, by using the Windows Filtering Platform or its predecessors, or you could substitute the network libraries/calls of that particular process.
{ "language": "en", "url": "https://stackoverflow.com/questions/164768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Overcoming Windows User Object Handle Limit I'm looking for advanced strategies for dealing with User Object Handle limits when building heavy-weight windows interfaces. Please explain how you overcame or bypassed this issue using SWT or direct Windows GUI APIs. The only thing I am not interested in is strategies to optimize widget usage as I have done this extensively and it does not solve the problem, only makes it less likely. My Situation: I have an SWT based GUI that allows for multiple sessions within the same parent shell and within each session their are 3 separate places where a list of user generated comments are displayed. As a user opens multiple sessions and pulls data that populates those lists, the number of user object handles can increase dramatically depending on the number of comments. My current solutions: 1. I page the comments by default thereby limiting the number of comment rows in each session, but due to management demands, i also have what is effectively a "View All" button which bypasses this completely. 2. I custom draw all non-editable information in each row. This means each row utilizes only 2 object handles. 3. I created JNI calls which query the OS for the current usage and the Max usage. With this i can give indications to users that a crash is imminent. Needless to say, they ignore this warning. A: First off, are you sure the problem isn't desktop heap vs. handle count? Each handle can consume a certain amount of Windows desktop heap. One USER handle may eat a lot of space, some very little. I'm suggesting this to make sure you're not chasing user handle counts when it's really something else. (google for Microsoft's dheapmon tool, it may help) I've read that you can alter the maxes on handles by changing keys in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\ CurrentVersion\Windows\ USERProcessHandleQuota and GDIProcessHandleQuota This could be a short term fix for users. I'd approach this by first figuring out what 2 user handles need to be maintained for each item (like 2 for each item in a listbox?). This seems suspect. User handles are for only a few top-level Windows UI objects (Windows, menus, cursors, Window positions, icons, etc...). I don't see why your widget needs to keep 2 objects around for each item (is it an icon handle??). If you're looking to rip the whole thing apart - this sounds like a job for a virtual-mode List-View (LVS_OWNERDATA). A: You should think about using windowless controls. They are designed for precisely this situation. See "Windowless controls are not magic", by Raymond Chen A: Not only top-level windows, but most native controls use one user object each. See Give Me a Handle, and I'll Show You an Object for an in-depth explanation of user- and other handle types. This also means that SWT uses at least one user handle per widget, even for a Composite. If you truly are hitting the limit of 10000 user objects per process, and you don't have a leak, then your only option is to reduce the number of widget instances in your application. I wrote a blog article about how we did this for our application.
{ "language": "en", "url": "https://stackoverflow.com/questions/164776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: WinForms: Implementation question for having my UI run independently of my BLL layer? I am trying to do a Windows Forms application in an MVP style and - not having done much with threading before - am getting all confused. My UI is a set of very simple forms. Each of the forms implements an interface and contains a reference to a mediator class which lives in the Business Logic Layer and vice versa. So as simplified diagram looks like this: CheckInForm : ICheckIn <-------> CheckInMediator : ICheckInMediator ---------------------------------------------------------------------------------------- CheckInForm.Show() <-------- --------> AttemptCheckIn(CheckInInfo) CheckInForm.DisplayCheckInInfo(DisplayInfo) <-------- --------> CompleteCheckIn(AdditionalCheckInInfo) PleaseWaitDialog.Show() <-------- PleaseWaitDialog.Close() <-------- CheckInForm.Close() <-------- As you can see, the mediator classes control the UI, telling it when to display data, start up, close, etc. They even signify when a modal dialog should appear and when it should close (ie the PleaseWaitDialog above) The only thing the UI does is show data on the screen and relay input back to the mediator. This architecture is nice and decoupled and has been super-easy to test and prototype. Now that I'm putting it all together however I'm starting to run into threading issues. For example, if I want my PleaseWaitDialog to appear as a modal form (using ShowDialog()) over the CheckInForm until a timer controlled by the mediator counts out 5 seconds (remember, this is a simplification) I will get a cross-threading error if I call PleaseWaitDialog.Close() from the timer's callback. In a similar vein, if I have a modal dialog block the user from interacting with the UI I don't want that to block activity in the business layer unless I specify otherwise (such as with a confirmation dialog). What I think I would like to do is to run the mediators and business logic on the main thread and the UI on a completely separate thread and my first question is does this make sense to do? My second question is, how do I do something like have a class run in a separate thread? And how do I have the two communicate? I am making my way through the reading on .NET threading but I have a deadline and some examples for how to have a class on the main thread spawn a thread containing the UI and have them objects talk to each other could really help. A: Have you looked into the BackgroundWorker class? It's great for doing a lot of the simplified processing in the background type procedures and gives events that can be listned to do have your GUI display progress. A: You can manipulate WinForms controls from another thread, but you need to use Control.Invoke(), and you will pay a considerable performance penalty for every cross-thread call, due to the context switch and associated behind-the-scenes CLR voodoo. If you want to segregate the GUI from the business logic and infrastructure code in a multi-threaded application, I recommend switching to a messaging model using thread-safe queues. Every time the lower layer(s) need to tell the GUI to do something, they drop a message object into a queue which the GUI elements poll periodically via a Forms.Timer. This works particularly well for large, processor-intensive applications, because you can throttle the processing needs of the GUI updates to some extent by adjusting the update timer frequencies. For the calls going back the other way (GUI -> lower layers), you can just call mediator methods from the GUI code, as long as those calls return reasonably quickly - you need to be very careful about delaying the GUI thread, because the responsiveness of the whole application will suffer. If you have some calls where it is difficult to return quickly enough, you can add a second queue going the other way.
{ "language": "en", "url": "https://stackoverflow.com/questions/164789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I open an Access DB via ADO so that I can write, but others can only read? From the documentation, I would expect adModeShareDenyWrite to be the way, but it's not working right. I'm using an Access database via ADO. My connection string says Mode=8, which is adModeShareDenyWrite. But when I try to delete a row from a table, I get: Unspecified error, Description:Could not delete from specified tables., Source:Microsoft JET Database Engine In other words, the setting is preventing ME from updating the database using my OWN connection. I found a couple other posts on the web reporting the same thing, the adModeShareDenyWrite setting used with Access not working as documented. I am looking for a solution that doesn't involve an administrator changing permissions. It needs to be something that my program can control. My motivation here is to minimize the chances of database corruption. One of the causes of mdb file corruption documented by Microsoft is two apps writing to the same db. So, I want to make sure that only one app can have a write connection to the db. Others can read, but should fail when they try to write. Whoever makes a connection first wins. A: Cory Trager wrote: My motivation here is to minimize the chances of database corruption. One of the causes of mdb file corruption documented by Microsoft is two apps writing to the same db. So, I want to make sure that only one app can have a write connection to the db. Others can read, but should fail when they try to write. Whoever makes a connection first wins. Why are you worrying about it? Jet is by default a multi-user database engine. If somebody else is updating a table, the data pages involved will be locked as read-only (in the state they were before the write began). There is no realistic reason to fear corruption from mere multi-user interaction. Corruption of Jet databases usually happens because of dropped connections or an interruption of the connection during a write (such as users who force quit an app that is not responding as fast as they want). I think your fear of corruption is misplaced. On the other hand, you should still be able to open with an exclusive lock, and I'm not sure why it's not working. Have you considered using DAO instead of ADO to manipulate Jet data? Given that it's the native data interface (instead of a generic interface layer), it ought to be easier. A: One solution is to give them access to a copy of the database. They can change whatever they want, but it won't keep past your copying it over with the master. A: I suppose you access here an MDB file from a client interface, whatever it is, and others can also connect to the same file at the same time. When you use adModeShareDenyWrite in your connection mode, it means that you can still share the data with others (no locks of any kind on tables or records in the MDB file) but it can't be modified (this is why you get an error). One solution would be to manage your connection parameters, with something like that: (where you have a user object with a '.role' property, or anything equivalent ...) if activeUser.role = "admin" then m_connectionMode = adModeWrite else m_connectionMode = adModeShareDenyWrite endif Then you can open your ADO connection with the parameter m_connectionMode. Administrators will be given the right to insert/update/delete while other users will ony be able to view the data. This means you have somewhere in your program, or ideally in a table, some data saying who is what in your application. EDIT: Following multiples comments with Corey: You won't be able to do what you want to do in a straight way. My proposal: when the app accesses the database, it checks for a special file in the .mdb folder (whatever the file is). If this file exists, the app opens a "read-only" connection. If this file does not exist, the app creates the file (you can create one for example with "transferDatabase") and open a read-write connection. Once you quit the app, destroy the file. A: Corey Trager wrote: I am looking for a solution that doesn't involve an administrator changing permissions. It needs to be something that my program can control. Well, if the problem is due to NTFS permissions being read-only for the user, there isn't a thing you can do to make the MDB writable. You don't specify where the MDB is stored, on a server or on a local hard drive, but in either case, for a user to have WRITE permissions on the MDB, NTFS permissions have to be set to allow it (for a share on a server, it has to be allowed both on the SHARE and on the underlying file). If it's a local file, the best solution is to make sure that you're storing the file in a location in which user-level logons have full WRITE permission. This would be anywhere in the user profile, and just about nowhere else. That said, I'm not really suggesting that this is the source of your problem (I really can't say one way or the other), just pointing out that if it is the cause, then there's not a damned thing you can do programmatically to work around it. A: If you have multiple users connecting to an access database across a network you might want to consider upgrading to SqlServer instead of using Access.
{ "language": "en", "url": "https://stackoverflow.com/questions/164792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CLOS like object model for PHP I have returned to php development from Moose and I really miss CLOS like object model for php. Is there some kind of syntaxtic sugar which would allow me to write less code in php when dealing with objects? Just to stress this requirement a bit more. I don't want to write one thing in several places. I can live with part of code being generated automatically, but in the code that I have to see to develop I don't want to see redundant information which is just clutter (think: LISP macro if you really need more analogy). So this part can be also called DSL if that makes more sense. I would love to have at least roles (mixins), and some kind of introspection without re-inventing the weel. Code generators and auto-loaders might be one way to solve at least part of this problem. p.s. For JavaScript there is Joose, so similar API would be very useful. A: There are no mixins in php yet but there is an RFC for traits which will work roughly the same. http://wiki.php.net/rfc/traits Using overloading for __call can allow you to dispatch methods to other classes and have it look like a mixin. A: The Symfony project has a mechanism for mixins, allowing aspect oriented programming like in CLOS. Personally, I don't like this kind of hacking in userland spacee (At least not with PHP). I think you would be better off using the features that the language provides, and perhaps wait for something like traits to (maybe) make its way into the language. A: There is also new project http://github.com/huberry/phuby which implements roles in php!
{ "language": "en", "url": "https://stackoverflow.com/questions/164800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I access a public property of a User Control from codebehind? I have a user control in a repeater that I need to pass data to during the databound event, so I've created two public properties in the control. How do I access these properties from the page's codebehind class? A: During the databind event in the repeater? MyUserControl myControl = (MyUserControl)e.item.FindControl("NameInASPX"); myControl.MyCustomProperty = foo;
{ "language": "en", "url": "https://stackoverflow.com/questions/164802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NetBIOS vs. FQDN I've got an issue when accessing a web site, I can access it by using the NetBIOS name, but when accessing with the FQDN i get an error. Any ideas on how to troubleshoot this? (There is no DNS configured yet, we have modified the Hosts file to enter the related names and IP.) A: First, check the obvious: are there any typos in the file? Next, test out the name resolution. Something simple like pinging the web server by it's FQDN will do. See if the right IP is mentioned. * *If you get "unknown host", your client's hosts file does not have an entry for the FQDN you entered (check for typos in the host name), or, for some reason, your computer isn't reading your hosts file. *If you get the wrong IP address, then you have the wrong IP in your hosts file (check for typos in the IP address), your computer's DNS cache is polluted (try: ipconfig /flushdns on a Windows machine), or something else is overriding the lookup (duplicate entries in the hosts file?). Next up, try communicating with your web server. Using Telnet, speak HTTP to it, and see how it responds: telnet 192.168.0.1 80 Substitute your web server's IP address instead of 192.168.0.1. Provide the following lines: GET / HTTP/1.1 Host: fqdn.mywebserver.com Try the server's IP, server's netbios name, and finally the server's FQDN in place of fqdn.mywebserver.com. Be sure to press return twice after entering the host header. If the response is different between the netbios name and the FQDN, then it's a web server configuration issue; you need to adjust you virtual host settings (in Apache, the ServerAlias directive should be used to add additonal names. In IIS its in Web Site (tab) -> Advanced (button)). After that... I'm really out of ideas. A: Just to make sure, you have something like this 192.168.100.5 othermachine othermachine.mydomain.local with both the netbios and the FQDN in it and not just the IP and netbios name? A: Assuming, as dragonmantank mentioned above, that the FQDN is in your hosts file, I'd look at whether the web server software itself is configured to accept requests with the FQDN in the Host field.
{ "language": "en", "url": "https://stackoverflow.com/questions/164808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to rank a million images with a crowdsourced sort I'd like to rank a collection of landscape images by making a game whereby site visitors can rate them, in order to find out which images people find the most appealing. What would be a good method of doing that? * *Hot-or-Not style? I.e. show a single image, ask the user to rank it from 1-10. As I see it, this allows me to average the scores, and I would just need to ensure that I get an even distribution of votes across all the images. Fairly simple to implement. *Pick A-or-B? I.e. show two images, ask user to pick the better one. This is appealing as there is no numerical ranking, it's just a comparison. But how would I implement it? My first thought was to do it as a quicksort, with the comparison operations being provided by humans, and once completed, simply repeat the sort ad-infinitum. How would you do it? If you need numbers, I'm talking about one million images, on a site with 20,000 daily visits. I'd imagine a small proportion might play the game, for the sake of argument, lets say I can generate 2,000 human sort operations a day! It's a non-profit website, and the terminally curious will find it through my profile :) A: I don't like the Hot-or-Not style. Different people would pick different numbers even if they all liked the image exactly the same. Also I hate rating things out of 10, I never know which number to choose. Pick A-or-B is much simpler and funner. You get to see two images, and comparisons are made between the images on the site. A: These equations from Wikipedia makes it simpler/more effective to calculate Elo ratings, the algorithm for images A and B would be simple: * *Get Ne, mA, mB and ratings RA,RB from your database. *Calculate KA ,KB, QA, QB by using the number of comparisons performed (Ne) and the number of times that image was compared (m) and current ratings : * *Calculate EA and EB. * *Score the winner's S : the winner as 1, loser as 0, and if you have a draw as 0.5, *Calculate the new ratings for both using: *Update the new ratings RA,RB and counts mA,mB in the database. A: Most naive approaches to the problem have some serious issues. The worst is how bash.org and qdb.us displays quotes - users can vote a quote up (+1) or down (-1), and the list of best quotes is sorted by the total net score. This suffers from a horrible time bias - older quotes have accumulated huge numbers of positive votes via simple longevity even if they're only marginally humorous. This algorithm might make sense if jokes got funnier as they got older but - trust me - they don't. There are various attempts to fix this - looking at the number of positive votes per time period, weighting more recent votes, implementing a decay system for older votes, calculating the ratio of positive to negative votes, etc. Most suffer from other flaws. The best solution - I think - is the one that the websites The Funniest The Cutest, The Fairest, and Best Thing use - a modified Condorcet voting system: The system gives each one a number based on, out of the things that it has faced, what percentage of them it usually beats. So each one gets the percentage score NumberOfThingsIBeat / (NumberOfThingsIBeat + NumberOfThingsThatBeatMe). Also, things are barred from the top list until they've been compared to a reasonable percentage of the set. If there's a Condorcet winner in the set, this method will find it. Since that's unlikely, given the statistical nature, it finds the one that's the "closest" to being a Condorcet winner. For more information on implementing such systems the Wikipedia page on Ranked Pairs should be helpful. The algorithm requires people to compare two objects (your Pick-A-or-B option), but frankly, that's a good thing. I believe it's very well accepted in decision theory that humans are vastly better at comparing two objects than they are at abstract ranking. Millions of years of evolution make us good at picking the best apple off the tree, but terrible at deciding how closely the apple we picked hews to the true Platonic Form of appleness. (This is, by the way, why the Analytic Hierarchy Process is so nifty...but that's getting a bit off topic.) One final point to make is that SO uses an algorithm to find the best answers which is very similar to bash.org's algorithm to find the best quote. It works well here, but fails terribly there - in large part because an old, highly rated, but now outdated answer here is likely to be edited. bash.org doesn't allow editing, and it's not clear how you'd even go about editing decade-old jokes about now-dated internet memes even if you could... In any case, my point is that the right algorithm usually depends on the details of your problem. :-) A: You may want to go with a combination. First phase: Hot-or-not style (although I would go with a 3 option vote: Sucks, Meh/OK. Cool!) Once you've sorted the set into the 3 buckets, then I would select two images from the same bucket and go with the "Which is nicer" You could then use an English Soccer system of promotion and demotion to move the top few "Sucks" into the Meh/OK region, in order to refine the edge cases. A: Ranking 1-10 won't work, everyone has different levels. Someone who always gives 3-7 ratings would have his rankings eclipsed by people who always give 1 or 10. a-or-b is more workable. A: Wow, I'm late in the game. I like the ELO system very much so, but like Owen says it seems to me that you'd be slow building up any significant results. I believe humans have much greater capacity than just comparing two images, but you want to keep interactions to the bare minimum. So how about you show n images (n being any number you can visibly display on a screen, this may be 10, 20, 30 depending on user's preference maybe) and get them to pick which they think is best in that lot. Now back to ELO. You need to modify you ratings system, but keep the same spirit. You have in fact compared one image to n-1 others. So you do your ELO rating n-1 times, but you should divide the change of rating by n-1 to match (so that results with different values of n are coherent with one another). You're done. You've now got the best of all worlds. A simple rating system working with many images in one click. A: If you prefer using the Pick A or B strategy I would recommend this paper: http://research.microsoft.com/en-us/um/people/horvitz/crowd_pairwise.pdf Chen, X., Bennett, P. N., Collins-Thompson, K., & Horvitz, E. (2013, February). Pairwise ranking aggregation in a crowdsourced setting. In Proceedings of the sixth ACM international conference on Web search and data mining (pp. 193-202). ACM. The paper tells about the Crowd-BT model which extends the famous Bradley-Terry pairwise comparison model into crowdsource setting. It also gives an adaptive learning algorithm to enhance the time and space efficiency of the model. You can find a Matlab implementation of the algorithm on Github (but I'm not sure if it works). A: The defunct web site whatsbetter.com used an Elo style method. You can read about the method in their FAQ on the Internet Archive. A: I know this question is quite old but I thought I'd contribute I'd look at the TrueSkill system developed at Microsoft Research. It's like ELO but has a much faster convergence time (looks exponential compared to linear), so you get more out of each vote. It is, however, more complex mathematically. http://en.wikipedia.org/wiki/TrueSkill A: As others have said, ranking 1-10 does not work that well because people have different levels. The problem with the Pick A-or-B method is that its not guaranteed for the system to be transitive (A can beat B, but B beats C, and C beats A). Having nontransitive comparison operators breaks sorting algorithms. With quicksort, against this example, the letters not chosen as the pivot will be incorrectly ranked against each other. At any given time, you want an absolute ranking of all the pictures (even if some/all of them are tied). You also want your ranking not to change unless someone votes. I would use the Pick A-or-B (or tie) method, but determine ranking similar to the Elo ratings system which is used for rankings in 2 player games (originally chess): The Elo player-rating system compares players’ match records against their opponents’ match records and determines the probability of the player winning the matchup. This probability factor determines how many points a players’ rating goes up or down based on the results of each match. When a player defeats an opponent with a higher rating, the player’s rating goes up more than if he or she defeated a player with a lower rating (since players should defeat opponents who have lower ratings). The Elo System: * *All new players start out with a base rating of 1600 *WinProbability = 1/(10^(( Opponent’s Current Rating–Player’s Current Rating)/400) + 1) *ScoringPt = 1 point if they win the match, 0 if they lose, and 0.5 for a draw. *Player’s New Rating = Player’s Old Rating + (K-Value * (ScoringPt–Player’s Win Probability)) Replace "players" with pictures and you have a simple way of adjusting both pictures' rating based on a formula. You can then perform a ranking using those numeric scores. (K-Value here is the "Level" of the tournament. It's 8-16 for small local tournaments and 24-32 for larger invitationals/regionals. You can just use a constant like 20). With this method, you only need to keep one number for each picture which is a lot less memory intensive than keeping the individual ranks of each picture to each other picture. EDIT: Added a little more meat based on comments. A: Pick A-or-B its the simplest and less prone to bias, however at each human interaction it gives you substantially less information. I think because of the bias reduction, Pick is superior and in the limit it provides you with the same information. A very simple scoring scheme is to have a count for each picture. When someone gives a positive comparison increment the count, when someone gives a negative comparison, decrement the count. Sorting a 1-million integer list is very quick and will take less than a second on a modern computer. That said, the problem is rather ill-posed - It will take you 50 days to show each image only once. I bet though you are more interested in the most highly ranked images? So, you probably want to bias your image retrieval by predicted rank - so you are more likely to show images that have already achieved a few positive comparisons. This way you will more quickly just start showing 'interesting' images. A: I like the quick-sort option but I'd make a few tweeks: * *Keep the "comparison" results in a DB and then average them. *Get more than one comparison per view by giving the user 4-6 images and having them sort them. *Select what images to display by running qsort and recording and trimming anything that you don't have enough data on. Then when you have enough items recorded, spit out a page. The other fun option would be to use the crowd to teach a neural-net.
{ "language": "en", "url": "https://stackoverflow.com/questions/164831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "85" }
Q: Creating Project Fails in Visual Studio 2005 and VS2008 Every time I try to create a new project or solution in visual studio (2005 and 2008), I get an error saying, "Project Creation failed." I even tried running vs in administrative mode, but I still get the same answer. Anyone have any suggestions, in short of uninstalling all of VS and reinstalling it? A: It sounds like an Add-in behaving badly. Can you launch it in safe mode? devenv.exe /SafeMode A: Out of the blue i would guess a security/rights issue, eg. trying to create the solution on a drive/folder you don't have write access to, or has otherwise restricted rights. A: Is it in Vista, I know 2005 is known to have compatibility issues in Vista, dunno about 2008, but do they both have current updates? A: If you are running in administrator mode, and click run as administrator and have all the latest updates and no add-ins, I think you might have to reinstall it. Make sure you select all the development types you plan to use to get the sdks and not just the redistributables. If that doesn't work, you might talk to the microsoft reps. With some quick online research people really only had probelms like this before Visual Studio SP1, anything with 64 bit Vista has just been unable to compile ASP. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/164839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is in your .vimrc? Vi and Vim allow for really awesome customization, typically stored inside a .vimrc file. Typical features for a programmer would be syntax highlighting, smart indenting and so on. What other tricks for productive programming have you got, hidden in your .vimrc? I am mostly interested in refactorings, auto classes and similar productivity macros, especially for C#. A: I'm not the most advanced vim'er in the world, but here's a few I've picked up function! Mosh_Tab_Or_Complete() if col('.')>1 && strpart( getline('.'), col('.')-2, 3 ) =~ '^\w' return "\<C-N>" else return "\<Tab>" endfunction inoremap <Tab> <C-R>=Mosh_Tab_Or_Complete()<CR> Makes the tab-autocomplete figure out whether you want to place a word there or an actual tab(4 spaces). map cc :.,$s/^ *//<CR> Remove all opening whitespace from here to the end of the file. For some reason I find this useful a lot. set nu! set nobackup Show line numbers and don't create those annoying backup files. I've never restored anything from an old backup anyways. imap ii <C-[> While in insert, press i twice to go to command mode. I've never come across a word or variable with 2 i's in a row, and this way I don't have to have my fingers leave the home row or press multiple keys to switch back and forth. A: My heavily commented vimrc, with readline-esque (emacs) keybindings: if version >= 700 "------ Meta ------" " clear all autocommands! (this comment must be on its own line) autocmd! set nocompatible " break away from old vi compatibility set fileformats=unix,dos,mac " support all three newline formats set viminfo= " don't use or save viminfo files "------ Console UI & Text display ------" set cmdheight=1 " explicitly set the height of the command line set showcmd " Show (partial) command in status line. set number " yay line numbers set ruler " show current position at bottom set noerrorbells " don't whine set visualbell t_vb= " and don't make faces set lazyredraw " don't redraw while in macros set scrolloff=5 " keep at least 5 lines around the cursor set wrap " soft wrap long lines set list " show invisible characters set listchars=tab:>·,trail:· " but only show tabs and trailing whitespace set report=0 " report back on all changes set shortmess=atI " shorten messages and don't show intro set wildmenu " turn on wild menu :e <Tab> set wildmode=list:longest " set wildmenu to list choice if has('syntax') syntax on " Remember that rxvt-unicode has 88 colors by default; enable this only if " you are using the 256-color patch if &term == 'rxvt-unicode' set t_Co=256 endif if &t_Co == 256 colorscheme xoria256 else colorscheme peachpuff endif endif "------ Text editing and searching behavior ------" set nohlsearch " turn off highlighting for searched expressions set incsearch " highlight as we search however set matchtime=5 " blink matching chars for .x seconds set mouse=a " try to use a mouse in the console (wimp!) set ignorecase " set case insensitivity set smartcase " unless there's a capital letter set completeopt=menu,longest,preview " more autocomplete <Ctrl>-P options set nostartofline " leave my cursor position alone! set backspace=2 " equiv to :set backspace=indent,eol,start set textwidth=80 " we like 80 columns set showmatch " show matching brackets set formatoptions=tcrql " t - autowrap to textwidth " c - autowrap comments to textwidth " r - autoinsert comment leader with <Enter> " q - allow formatting of comments with :gq " l - don't format already long lines "------ Indents and tabs ------" set autoindent " set the cursor at same indent as line above set smartindent " try to be smart about indenting (C-style) set expandtab " expand <Tab>s with spaces; death to tabs! set shiftwidth=4 " spaces for each step of (auto)indent set softtabstop=4 " set virtual tab stop (compat for 8-wide tabs) set tabstop=8 " for proper display of files with tabs set shiftround " always round indents to multiple of shiftwidth set copyindent " use existing indents for new indents set preserveindent " save as much indent structure as possible filetype plugin indent on " load filetype plugins and indent settings "------ Key bindings ------" " Remap broken meta-keys that send ^[ for n in range(97,122) " ASCII a-z let c = nr2char(n) exec "set <M-". c .">=\e". c exec "map \e". c ." <M-". c .">" exec "map! \e". c ." <M-". c .">" endfor """ Emacs keybindings " first move the window command because we'll be taking it over noremap <C-x> <C-w> " Movement left/right noremap! <C-b> <Left> noremap! <C-f> <Right> " word left/right noremap <M-b> b noremap! <M-b> <C-o>b noremap <M-f> w noremap! <M-f> <C-o>w " line start/end noremap <C-a> ^ noremap! <C-a> <Esc>I noremap <C-e> $ noremap! <C-e> <Esc>A " Rubout word / line and enter insert mode noremap <C-w> i<C-w> noremap <C-u> i<C-u> " Forward delete char / word / line and enter insert mode noremap! <C-d> <C-o>x noremap <M-d> dw noremap! <M-d> <C-o>dw noremap <C-k> Da noremap! <C-k> <C-o>D " Undo / Redo and enter normal mode noremap <C-_> u noremap! <C-_> <C-o>u<Esc><Right> noremap! <C-r> <C-o><C-r><Esc> " Remap <C-space> to word completion noremap! <Nul> <C-n> " OS X paste (pretty poor implementation) if has('mac') noremap √ :r!pbpaste<CR> noremap! √ <Esc>√ endif """ screen.vim REPL: http://github.com/ervandew/vimfiles " send paragraph to parallel process vmap <C-c><C-c> :ScreenSend<CR> nmap <C-c><C-c> mCvip<C-c><C-c>`C imap <C-c><C-c> <Esc><C-c><C-c><Right> " set shell region height let g:ScreenShellHeight = 12 "------ Filetypes ------" " Vimscript autocmd FileType vim setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4 " Shell autocmd FileType sh setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4 " Lisp autocmd Filetype lisp,scheme setlocal equalprg=~/.vim/bin/lispindent.lisp expandtab shiftwidth=2 tabstop=8 softtabstop=2 " Ruby autocmd FileType ruby setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2 " PHP autocmd FileType php setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4 " X?HTML & XML autocmd FileType html,xhtml,xml setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2 " CSS autocmd FileType css setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4 " JavaScript " autocmd BufRead,BufNewFile *.json setfiletype javascript autocmd FileType javascript setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2 let javascript_enable_domhtmlcss=1 "------ END VIM-500 ------" endif " version >= 500 A: This isn't in my .vimrc file, but yesterday I learned about the ]p command. This pastes the contents of a buffer just like p does, but it automatically adjusts the indent to match the line the cursor is on! This is excellent for moving code around. A: syntax on set cindent set ts=4 set sw=4 set backspace=2 set laststatus=2 set nohlsearch set modeline set modelines=3 set ai map Q gq set vb t_vb= set nowrap set ss=5 set is set scs set ru map <F2> <Esc>:w<CR> map! <F2> <Esc>:w<CR> map <F10> <Esc>:qa<CR> map! <F10> <Esc>:qa<CR> map <F9> <Esc>:wqa<CR> map! <F9> <Esc>:wqa<CR> inoremap <s-up> <Esc><c-w>W<Ins> inoremap <s-down> <Esc><c-w>w<Ins> nnoremap <s-up> <c-w>W nnoremap <s-down> <c-w>w " Fancy middle-line <CR> inoremap <C-CR> <Esc>o nnoremap <C-CR> o " This is the way I like my quotation marks and various braces inoremap '' ''<Left> inoremap "" ""<Left> inoremap () ()<Left> inoremap <> <><Left> inoremap {} {}<Left> inoremap [] []<Left> inoremap () ()<Left> " Quickly set comma or semicolon at the end of the string inoremap ,, <End>, inoremap ;; <End>; au FileType python inoremap :: <End>: au FileType perl,python set foldlevel=0 au FileType perl,python set foldcolumn=4 au FileType perl,python set fen au FileType perl set fdm=syntax au FileType python set fdm=indent au FileType perl,python set fdn=4 au FileType perl,python set fml=10 au FileType perl,python set fdo=block,hor,mark,percent,quickfix,search,tag,undo,search au FileType perl,python abbr sefl self au FileType perl abbr sjoft shift au FileType perl abbr DUmper Dumper function! ToggleNumberRow() if !exists("g:NumberRow") || 0 == g:NumberRow let g:NumberRow = 1 call ReverseNumberRow() else let g:NumberRow = 0 call NormalizeNumberRow() endif endfunction " Reverse the number row characters function! ReverseNumberRow() " map each number to its shift-key character inoremap 1 ! inoremap 2 @ inoremap 3 # inoremap 4 $ inoremap 5 % inoremap 6 ^ inoremap 7 & inoremap 8 * inoremap 9 ( inoremap 0 ) inoremap - _ inoremap 90 ()<Left> " and then the opposite inoremap ! 1 inoremap @ 2 inoremap # 3 inoremap $ 4 inoremap % 5 inoremap ^ 6 inoremap & 7 inoremap * 8 inoremap ( 9 inoremap ) 0 inoremap _ - endfunction " DO the opposite to ReverseNumberRow -- give everything back function! NormalizeNumberRow() iunmap 1 iunmap 2 iunmap 3 iunmap 4 iunmap 5 iunmap 6 iunmap 7 iunmap 8 iunmap 9 iunmap 0 iunmap - "------ iunmap ! iunmap @ iunmap # iunmap $ iunmap % iunmap ^ iunmap & iunmap * iunmap ( iunmap ) iunmap _ inoremap () ()<Left> endfunction "call ToggleNumberRow() nnoremap <M-n> :call ToggleNumberRow()<CR> " Add use <CWORD> at the top of the file function! UseWord(word) let spec_cases = {'Dumper': 'Data::Dumper'} let my_word = a:word if has_key(spec_cases, my_word) let my_word = spec_cases[my_word] endif let was_used = search("^use.*" . my_word, "bw") if was_used > 0 echo "Used already" return 0 endif let last_use = search("^use", "bW") if 0 == last_use last_use = search("^package", "bW") if 0 == last_use last_use = 1 endif endif let use_string = "use " . my_word . ";" let res = append(last_use, use_string) return 1 endfunction function! UseCWord() let cline = line(".") let ccol = col(".") let ch = UseWord(expand("<cword>")) normal mu call cursor(cline + ch, ccol) endfunction function! GetWords(pattern) let cline = line(".") let ccol = col(".") call cursor(1,1) let temp_dict = {} let cpos = searchpos(a:pattern) while cpos[0] != 0 let temp_dict[expand("<cword>")] = 1 let cpos = searchpos(a:pattern, 'W') endwhile call cursor(cline, ccol) return keys(temp_dict) endfunction " Append the list of words, that match the pattern after cursor function! AppendWordsLike(pattern) let word_list = sort(GetWords(a:pattern)) call append(line("."), word_list) endfunction nnoremap <F7> :call UseCWord()<CR> " Useful to mark some code lines as debug statements function! MarkDebug() let cline = line(".") let ctext = getline(cline) call setline(cline, ctext . "##_DEBUG_") endfunction " Easily remove debug statements function! RemoveDebug() %g/#_DEBUG_/d endfunction au FileType perl,python inoremap <M-d> <Esc>:call MarkDebug()<CR><Ins> au FileType perl,python inoremap <F6> <Esc>:call RemoveDebug()<CR><Ins> au FileType perl,python nnoremap <F6> :call RemoveDebug()<CR> " end Perl settings nnoremap <silent> <F8> :TlistToggle<CR> inoremap <silent> <F8> <Esc>:TlistToggle<CR><Esc> function! AlwaysCD() if bufname("") !~ "^scp://" && bufname("") !~ "^sftp://" && bufname("") !~ "^ftp://" lcd %:p:h endif endfunction autocmd BufEnter * call AlwaysCD() function! DeleteRedundantSpaces() let cline = line(".") let ccol = col(".") silent! %s/\s\+$//g call cursor(cline, ccol) endfunction au BufWrite * call DeleteRedundantSpaces() set nobackup set nowritebackup set cul colorscheme evening autocmd FileType python set formatoptions=wcrq2l autocmd FileType python set inc="^\s*from" autocmd FileType python so /usr/share/vim/vim72/indent/python.vim autocmd FileType c set si autocmd FileType mail set noai autocmd FileType mail set ts=3 autocmd FileType mail set tw=78 autocmd FileType mail set shiftwidth=3 autocmd FileType mail set expandtab autocmd FileType xslt set ts=4 autocmd FileType xslt set shiftwidth=4 autocmd FileType txt set ts=3 autocmd FileType txt set tw=78 autocmd FileType txt set expandtab " Move cursor together with the screen noremap <c-j> j<c-e> noremap <c-k> k<c-y> " Better Marks nnoremap ' ` A: Some fixes for common typos have saved me a surprising amount of time: :command WQ wq :command Wq wq :command W w :command Q q iab anf and iab adn and iab ans and iab teh the iab thre there A: I use the following to keep all the temporary and backup files in one place: set backup set backupdir=~/.vim/backup set directory=~/.vim/tmp Saves cluttering working directories all over the place. You will have to create these directories first, vim will not create them for you. A: I didn't realize how many of my 3200 .vimrc lines were just for my quirky needs and would be pretty uninspiring to list here. But maybe that's why Vim is so useful... iab AlP ABCDEFGHIJKLMNOPQRSTUVWXYZ iab MoN January February March April May June July August September October November December iab MoO Jan Feb Mar Apr May Jun Jul Aug Sep Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec iab NuM 12345678901234567890123456789012345678901234567890123456789012345678901234567890 iab RuL ----+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0 " Highlight every other line map ,<Tab> :set hls<CR>/\\n.*\\n/<CR> " This is for working across multiple xterms and/or gvims " Transfer/read and write one block of text between vim sessions (capture whole line): " Write nmap ;w :. w! ~/.vimxfer<CR> " Read nmap ;r :r ~/.vimxfer<CR> " Append nmap ;a :. w! >>~/.vimxfer<CR> A: My 242-line .vimrc is not that interesting, but since nobody mentioned it, I felt like I must share the two most important mappings that have enhanced my workflow besides the default mappings: map <C-j> :bprev<CR> map <C-k> :bnext<CR> set hidden " this will go along Seriously, switching buffers is the thing to do very often. Windows, sure, but everything doesn't fit the screen so nicely. Similar set of maps for quick browsing of errors (see quickfix) and grep results: map <C-n> :cn<CR> map <C-m> :cp<CR> Simple, effortless and efficient. A: set nobackup set nocp set tabstop=4 set shiftwidth=4 set et set ignorecase set ai set ruler set showcmd set incsearch set dir=$temp " Make swap live in the %TEMP% directory syn on " Load the color scheme colo inkpot A: I use cscope from within vim (making great use of the multiple buffers). I use control-K to initiate most of the commands (stolen from ctags as I recall). Also, I've already generated the .cscope.out file. if has("cscope") set cscopeprg=/usr/local/bin/cscope set cscopetagorder=0 set cscopetag set cscopepathcomp=3 set nocscopeverbose cs add .cscope.out set csverb " " cscope find " " 0 or s: Find this C symbol " 1 or d: Find this definition " 2 or g: Find functions called by this function " 3 or c: Find functions calling this function " 4 or t: Find assignments to " 6 or e: Find this egrep pattern " 7 or f: Find this file " 8 or i: Find files #including this file " map ^Ks :cs find 0 <C-R>=expand("<cword>")<CR><CR> map ^Kd :cs find 1 <C-R>=expand("<cword>")<CR><CR> map ^Kg :cs find 2 <C-R>=expand("<cword>")<CR><CR> map ^Kc :cs find 3 <C-R>=expand("<cword>")<CR><CR> map ^Kt :cs find 4 <C-R>=expand("<cword>")<CR><CR> map ^Ke :cs find 6 <C-R>=expand("<cword>")<CR><CR> map ^Kf :cs find 7 <C-R>=expand("<cfile>")<CR><CR> map ^Ki :cs find 8 <C-R>=expand("%")<CR><CR> endif A: I keep my vimrc file up on github. You can find it here: http://github.com/developernotes/vim-setup/tree/master A: Someone (viz. Frew) who posted above had this line: "Automatically cd into the directory that the file is in:" autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ') I was doing something like that myself until I discovered the same thing could be accomplished with a built in setting: set autochdir I think something similar has happened to me a few different times. Vim has so many different built-in settings and options that it's sometimes quicker and easier to roll-your-own than search the docs for the built-in way to do it. A: I'm on OS X, so some of these might have better defaults on other platforms, but regardless: syntax on set tabstop=4 set expandtab set shiftwidth=4 A: map = }{!}fmt^M} map + }{!}fmt -p '> '^M} set showmatch = is for reformatting normal paragraphs. + is for reformatting paragraphs in quoted emails. showmatch is for flashing the matching parenthesis/bracket when I type a close parenthesis or bracket. A: Use the first available 'tags' file in the directory tree: :set tags=tags;/ Left and right are for switching buffers, not moving the cursor: map <right> <ESC>:bn<RETURN> map <left> <ESC>:bp<RETURN> Disable search highlighting with a single keypress: map - :nohls<cr> A: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab autoindent cindent set encoding=utf-8 fileencoding=utf-8 set nobackup nowritebackup noswapfile autoread set number set hlsearch incsearch ignorecase smartcase if has("gui_running") set lines=35 columns=140 colorscheme ir_black else colorscheme darkblue endif " bash like auto-completion set wildmenu set wildmode=list:longest inoremap <C-j> <Esc> " for lusty explorer noremap glr \lr noremap glf \lf noremap glb \lb " use ctrl-h/j/k/l to switch between splits map <c-j> <c-w>j map <c-k> <c-w>k map <c-l> <c-w>l map <c-h> <c-w>h " Nerd tree stuff let NERDTreeIgnore = ['\.pyc$', '\.pyo$'] noremap gn :NERDTree<Cr> " cd to the current file's directory noremap gc :lcd %:h<Cr> A: Put this in your vimrc: imap <C-l> <Space>=><Space> and never think about typing a hashrocket again. Yes, I know you don't need to in Ruby 1.9. But never mind that. My full vimrc is here. A: My latest addition is for highlighting of the current line set cul # highlight current line hi CursorLine term=none cterm=none ctermbg=3 # adjust color A: Update 2012: I'd now really recommend checking out vim-powerline which has replaced my old statusline script, albeit currently missing a few features I miss. I'd say that the statusline stuff in my vimrc was probably most interesting/useful out of the lot (ripped from the authors vimrc here and corresponding blog post here). Screenshot: status line http://img34.imageshack.us/img34/849/statusline.png Code: "recalculate the trailing whitespace warning when idle, and after saving autocmd cursorhold,bufwritepost * unlet! b:statusline_trailing_space_warning "return '[\s]' if trailing white space is detected "return '' otherwise function! StatuslineTrailingSpaceWarning() if !exists("b:statusline_trailing_space_warning") if !&modifiable let b:statusline_trailing_space_warning = '' return b:statusline_trailing_space_warning endif if search('\s\+$', 'nw') != 0 let b:statusline_trailing_space_warning = '[\s]' else let b:statusline_trailing_space_warning = '' endif endif return b:statusline_trailing_space_warning endfunction "return the syntax highlight group under the cursor '' function! StatuslineCurrentHighlight() let name = synIDattr(synID(line('.'),col('.'),1),'name') if name == '' return '' else return '[' . name . ']' endif endfunction "recalculate the tab warning flag when idle and after writing autocmd cursorhold,bufwritepost * unlet! b:statusline_tab_warning "return '[&et]' if &et is set wrong "return '[mixed-indenting]' if spaces and tabs are used to indent "return an empty string if everything is fine function! StatuslineTabWarning() if !exists("b:statusline_tab_warning") let b:statusline_tab_warning = '' if !&modifiable return b:statusline_tab_warning endif let tabs = search('^\t', 'nw') != 0 "find spaces that arent used as alignment in the first indent column let spaces = search('^ \{' . &ts . ',}[^\t]', 'nw') != 0 if tabs && spaces let b:statusline_tab_warning = '[mixed-indenting]' elseif (spaces && !&et) || (tabs && &et) let b:statusline_tab_warning = '[&et]' endif endif return b:statusline_tab_warning endfunction "recalculate the long line warning when idle and after saving autocmd cursorhold,bufwritepost * unlet! b:statusline_long_line_warning "return a warning for "long lines" where "long" is either &textwidth or 80 (if "no &textwidth is set) " "return '' if no long lines "return '[#x,my,$z] if long lines are found, were x is the number of long "lines, y is the median length of the long lines and z is the length of the "longest line function! StatuslineLongLineWarning() if !exists("b:statusline_long_line_warning") if !&modifiable let b:statusline_long_line_warning = '' return b:statusline_long_line_warning endif let long_line_lens = s:LongLines() if len(long_line_lens) > 0 let b:statusline_long_line_warning = "[" . \ '#' . len(long_line_lens) . "," . \ 'm' . s:Median(long_line_lens) . "," . \ '$' . max(long_line_lens) . "]" else let b:statusline_long_line_warning = "" endif endif return b:statusline_long_line_warning endfunction "return a list containing the lengths of the long lines in this buffer function! s:LongLines() let threshold = (&tw ? &tw : 80) let spaces = repeat(" ", &ts) let long_line_lens = [] let i = 1 while i <= line("$") let len = strlen(substitute(getline(i), '\t', spaces, 'g')) if len > threshold call add(long_line_lens, len) endif let i += 1 endwhile return long_line_lens endfunction "find the median of the given array of numbers function! s:Median(nums) let nums = sort(a:nums) let l = len(nums) if l % 2 == 1 let i = (l-1) / 2 return nums[i] else return (nums[l/2] + nums[(l/2)-1]) / 2 endif endfunction "statusline setup set statusline=%f "tail of the filename "display a warning if fileformat isnt unix set statusline+=%#warningmsg# set statusline+=%{&ff!='unix'?'['.&ff.']':''} set statusline+=%* "display a warning if file encoding isnt utf-8 set statusline+=%#warningmsg# set statusline+=%{(&fenc!='utf-8'&&&fenc!='')?'['.&fenc.']':''} set statusline+=%* set statusline+=%h "help file flag set statusline+=%y "filetype set statusline+=%r "read only flag set statusline+=%m "modified flag "display a warning if &et is wrong, or we have mixed-indenting set statusline+=%#error# set statusline+=%{StatuslineTabWarning()} set statusline+=%* set statusline+=%{StatuslineTrailingSpaceWarning()} set statusline+=%{StatuslineLongLineWarning()} set statusline+=%#warningmsg# set statusline+=%{SyntasticStatuslineFlag()} set statusline+=%* "display a warning if &paste is set set statusline+=%#error# set statusline+=%{&paste?'[paste]':''} set statusline+=%* set statusline+=%= "left/right separator function! SlSpace() if exists("*GetSpaceMovement") return "[" . GetSpaceMovement() . "]" else return "" endif endfunc set statusline+=%{SlSpace()} set statusline+=%{StatuslineCurrentHighlight()}\ \ "current highlight set statusline+=%c, "cursor column set statusline+=%l/%L "cursor line/total lines set statusline+=\ %P "percent through file set laststatus=2 Amongst other things, it informs on the status line of the usual standard file information but also includes additional things like warnings for :set paste, mixed indenting, trailing white space etc. Pretty useful if you're particularly anal about your code formatting. Furthermore and as shown in the screenshot, combining it with syntastic allows any syntax errors to be highlighted on it (assuming your language of choice has an associated syntax checker bundled. A: There isn't much actually in my .vimrc (even if it has 850 lines). Mostly settings and a few common and simple mappings that I was too lazy to extract into plugins. If you mean "template-files" by "auto-classes", I'm using a template-expander plugin -- on this same site, you'll find the ftplugins I've defined for C&C++ editing, some may be adapted to C# I guess. Regarding the refactoring aspect, there is a tip dedicated to this subject on http://vim.wikia.com ; IIRC the example code is for C#. It inspired me a refactoring plugin that still needs of lot of work (it needs to be refactored actually). You should have a look at the archives of vim mailing-list, specially the subjects about using vim as an effective IDE. Don't forget to have a look at :make, tags, ... HTH, A: Well, you'll have to scavenge my configs yourself. Have fun. Mostly it's just my desired setup, including mappings and random syntax-relevant stuff, as well as folding setup and some plugin configuration, a tex-compilation parser etc. BTW, something I found extremely useful is "highlight word under cursor": highlight flicker cterm=bold ctermfg=white au CursorMoved <buffer> exe 'match flicker /\V\<'.escape(expand('<cword>'), '/').'\>/' Note that only cterm and termfg are used, because I don't use gvim. If you want that to work in gvim just replac them with gui and guifg, respectively. A: I've tried to keep my .vimrc as generally useful as possible. A handy trick in there is a handler for .gpg files to edit them securely: au BufNewFile,BufReadPre *.gpg :set secure vimi= noswap noback nowriteback hist=0 binary au BufReadPost *.gpg :%!gpg -d 2>/dev/null au BufWritePre *.gpg :%!gpg -e -r 'name@email.com' 2>/dev/null au BufWritePost *.gpg u A: 1) I like a statusline (with the filename, ascii value (decimal), hex value, and the standard lines, cols, and %): set statusline=%t%h%m%r%=[%b\ 0x%02B]\ \ \ %l,%c%V\ %P " Always show a status line set laststatus=2 "make the command line 1 line high set cmdheight=1 2) I also like mappings for split windows. " <space> switches to the next window (give it a second) " <space>n switches to the next window " <space><space> switches to the next window and maximizes it " <space>= Equalizes the size of all windows " + Increases the size of the current window " - Decreases the size of the current window :map <space> <c-W>w :map <space>n <c-W>w :map <space><space> <c-W>w<c-W>_ :map <space>= <c-W>= if bufwinnr(1) map + <c-W>+ map - <c-W>- endif A: My .vimrc includes (among other, more usefull things) the following line: set statusline=%2*%n\|%<%*%-.40F%2*\|\ %2*%M\ %3*%=%1*\ %1*%2.6l%2*x%1*%1.9(%c%V%)%2*[%1*%P%2*]%1*%2B I got bored while learning for my high school finals. A: My mini version: syntax on set background=dark set shiftwidth=2 set tabstop=2 if has("autocmd") filetype plugin indent on endif set showcmd " Show (partial) command in status line. set showmatch " Show matching brackets. set ignorecase " Do case insensitive matching set smartcase " Do smart case matching set incsearch " Incremental search set hidden " Hide buffers when they are abandoned The big version, collected from various places: syntax on set background=dark set ruler " show the line number on the bar set more " use more prompt set autoread " watch for file changes set number " line numbers set hidden set noautowrite " don't automagically write on :next set lazyredraw " don't redraw when don't have to set showmode set showcmd set nocompatible " vim, not vi set autoindent smartindent " auto/smart indent set smarttab " tab and backspace are smart set tabstop=2 " 6 spaces set shiftwidth=2 set scrolloff=5 " keep at least 5 lines above/below set sidescrolloff=5 " keep at least 5 lines left/right set history=200 set backspace=indent,eol,start set linebreak set cmdheight=2 " command line two lines high set undolevels=1000 " 1000 undos set updatecount=100 " switch every 100 chars set complete=.,w,b,u,U,t,i,d " do lots of scanning on tab completion set ttyfast " we have a fast terminal set noerrorbells " No error bells please set shell=bash set fileformats=unix set ff=unix filetype on " Enable filetype detection filetype indent on " Enable filetype-specific indenting filetype plugin on " Enable filetype-specific plugins set wildmode=longest:full set wildmenu " menu has tab completion let maplocalleader=',' " all my macros start with , set laststatus=2 " searching set incsearch " incremental search set ignorecase " search ignoring case set hlsearch " highlight the search set showmatch " show matching bracket set diffopt=filler,iwhite " ignore all whitespace and sync " backup set backup set backupdir=~/.vim_backup set viminfo=%100,'100,/100,h,\"500,:100,n~/.viminfo "set viminfo='100,f1 " spelling if v:version >= 700 " Enable spell check for text files autocmd BufNewFile,BufRead *.txt setlocal spell spelllang=en endif " mappings " toggle list mode nmap <LocalLeader>tl :set list!<cr> " toggle paste mode nmap <LocalLeader>pp :set paste!<cr> A: Sometimes the simplest things are the most valuable. The 2 lines in my .vimrc that are totally indispensable: nore ; : nore , ; A: Misc. settings: * *Turn off annoying error bells: set noerrorbells set visualbell set t_vb= *Make cursor move as expected with wrapped lines: inoremap <Down> <C-o>gj inoremap <Up> <C-o>gk *Lookup ctags "tags" file up the directory, until one is found: set tags=tags;/ *Display SCons files wiith Python syntax: autocmd BufReadPre,BufNewFile SConstruct set filetype=python autocmd BufReadPre,BufNewFile SConscript set filetype=python A: You asked for it :-) "{{{Auto Commands " Automatically cd into the directory that the file is in autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ') " Remove any trailing whitespace that is in the file autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif " Restore cursor position to where it was before augroup JumpCursorOnEdit au! autocmd BufReadPost * \ if expand("<afile>:p:h") !=? $TEMP | \ if line("'\"") > 1 && line("'\"") <= line("$") | \ let JumpCursorOnEdit_foo = line("'\"") | \ let b:doopenfold = 1 | \ if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) | \ let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 | \ let b:doopenfold = 2 | \ endif | \ exe JumpCursorOnEdit_foo | \ endif | \ endif " Need to postpone using "zv" until after reading the modelines. autocmd BufWinEnter * \ if exists("b:doopenfold") | \ exe "normal zv" | \ if(b:doopenfold > 1) | \ exe "+".1 | \ endif | \ unlet b:doopenfold | \ endif augroup END "}}} "{{{Misc Settings " Necesary for lots of cool vim things set nocompatible " This shows what you are typing as a command. I love this! set showcmd " Folding Stuffs set foldmethod=marker " Needed for Syntax Highlighting and stuff filetype on filetype plugin on syntax enable set grepprg=grep\ -nH\ $* " Who doesn't like autoindent? set autoindent " Spaces are better than a tab character set expandtab set smarttab " Who wants an 8 character tab? Not me! set shiftwidth=3 set softtabstop=3 " Use english for spellchecking, but don't spellcheck by default if version >= 700 set spl=en spell set nospell endif " Real men use gcc "compiler gcc " Cool tab completion stuff set wildmenu set wildmode=list:longest,full " Enable mouse support in console set mouse=a " Got backspace? set backspace=2 " Line Numbers PWN! set number " Ignoring case is a fun trick set ignorecase " And so is Artificial Intellegence! set smartcase " This is totally awesome - remap jj to escape in insert mode. You'll never type jj anyway, so it's great! inoremap jj <Esc> nnoremap JJJJ <Nop> " Incremental searching is sexy set incsearch " Highlight things that we find with the search set hlsearch " Since I use linux, I want this let g:clipbrdDefaultReg = '+' " When I close a tab, remove the buffer set nohidden " Set off the other paren highlight MatchParen ctermbg=4 " }}} "{{{Look and Feel " Favorite Color Scheme if has("gui_running") colorscheme inkpot " Remove Toolbar set guioptions-=T "Terminus is AWESOME set guifont=Terminus\ 9 else colorscheme metacosm endif "Status line gnarliness set laststatus=2 set statusline=%F%m%r%h%w\ (%{&ff}){%Y}\ [%l,%v][%p%%] " }}} "{{{ Functions "{{{ Open URL in browser function! Browser () let line = getline (".") let line = matchstr (line, "http[^ ]*") exec "!konqueror ".line endfunction "}}} "{{{Theme Rotating let themeindex=0 function! RotateColorTheme() let y = -1 while y == -1 let colorstring = "inkpot#ron#blue#elflord#evening#koehler#murphy#pablo#desert#torte#" let x = match( colorstring, "#", g:themeindex ) let y = match( colorstring, "#", x + 1 ) let g:themeindex = x + 1 if y == -1 let g:themeindex = 0 else let themestring = strpart(colorstring, x + 1, y - x - 1) return ":colorscheme ".themestring endif endwhile endfunction " }}} "{{{ Paste Toggle let paste_mode = 0 " 0 = normal, 1 = paste func! Paste_on_off() if g:paste_mode == 0 set paste let g:paste_mode = 1 else set nopaste let g:paste_mode = 0 endif return endfunc "}}} "{{{ Todo List Mode function! TodoListMode() e ~/.todo.otl Calendar wincmd l set foldlevel=1 tabnew ~/.notes.txt tabfirst " or 'norm! zMzr' endfunction "}}} "}}} "{{{ Mappings " Open Url on this line with the browser \w map <Leader>w :call Browser ()<CR> " Open the Project Plugin <F2> nnoremap <silent> <F2> :Project<CR> " Open the Project Plugin nnoremap <silent> <Leader>pal :Project .vimproject<CR> " TODO Mode nnoremap <silent> <Leader>todo :execute TodoListMode()<CR> " Open the TagList Plugin <F3> nnoremap <silent> <F3> :Tlist<CR> " Next Tab nnoremap <silent> <C-Right> :tabnext<CR> " Previous Tab nnoremap <silent> <C-Left> :tabprevious<CR> " New Tab nnoremap <silent> <C-t> :tabnew<CR> " Rotate Color Scheme <F8> nnoremap <silent> <F8> :execute RotateColorTheme()<CR> " DOS is for fools. nnoremap <silent> <F9> :%s/$//g<CR>:%s// /g<CR> " Paste Mode! Dang! <F10> nnoremap <silent> <F10> :call Paste_on_off()<CR> set pastetoggle=<F10> " Edit vimrc \ev nnoremap <silent> <Leader>ev :tabnew<CR>:e ~/.vimrc<CR> " Edit gvimrc \gv nnoremap <silent> <Leader>gv :tabnew<CR>:e ~/.gvimrc<CR> " Up and down are more logical with g.. nnoremap <silent> k gk nnoremap <silent> j gj inoremap <silent> <Up> <Esc>gka inoremap <silent> <Down> <Esc>gja " Good call Benjie (r for i) nnoremap <silent> <Home> i <Esc>r nnoremap <silent> <End> a <Esc>r " Create Blank Newlines and stay in Normal mode nnoremap <silent> zj o<Esc> nnoremap <silent> zk O<Esc> " Space will toggle folds! nnoremap <space> za " Search mappings: These will make it so that going to the next one in a " search will center on the line it's found in. map N Nzz map n nzz " Testing set completeopt=longest,menuone,preview inoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>" inoremap <expr> <c-n> pumvisible() ? "\<lt>c-n>" : "\<lt>c-n>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>" inoremap <expr> <m-;> pumvisible() ? "\<lt>c-n>" : "\<lt>c-x>\<lt>c-o>\<lt>c-n>\<lt>c-p>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>" " Swap ; and : Convenient. nnoremap ; : nnoremap : ; " Fix email paragraphs nnoremap <leader>par :%s/^>$//<CR> "ly$O#{{{ "lpjjj_%A#}}}jjzajj "}}} "{{{Taglist configuration let Tlist_Use_Right_Window = 1 let Tlist_Enable_Fold_Column = 0 let Tlist_Exit_OnlyWindow = 1 let Tlist_Use_SingleClick = 1 let Tlist_Inc_Winwidth = 0 "}}} let g:rct_completion_use_fri = 1 "let g:Tex_DefaultTargetFormat = "pdf" let g:Tex_ViewRule_pdf = "kpdf" filetype plugin indent on syntax on A: Here is my .vimrc. I use Gvim 7.2 set guioptions=em set showtabline=2 set softtabstop=2 set shiftwidth=2 set tabstop=2 " Use spaces instead of tabs set expandtab set autoindent " Colors and fonts colorscheme inkpot set guifont=Consolas:h11:cANSI "TAB navigation like firefox :nmap <C-S-tab> :tabprevious<cr> :nmap <C-tab> :tabnext<cr> :imap <C-S-tab> <ESC>:tabprevious<cr>i :imap <C-tab> <ESC>:tabnext<cr>i :nmap <C-t> :tabnew<cr> :imap <C-t> <ESC>:tabnew<cr>i :map <C-w> :tabclose<cr> " No Backups and line numbers set nobackup set number set nuw=6 " swp files are saved to %Temp% folder set dir=$temp " sets the default size of gvim on open set lines=40 columns=90 A: What's in my .vimrc? ngn@macavity:~$ cat .vimrc " This file intentionally left blank The real config files lie under ~/.vim/ :) And most of the stuff there is parasiting on other people's efforts, blatantly adapted from vim.org to my editing advantage. A: Line numbers and syntax highlighting. set number syntax on A: This is my humble .vimrc. It is a work in progress (As it should always be), so forgive the messy layout and the commented out lines. " =====Key mapping " Insert empty line. nmap <A-o> o<ESC>k nmap <A-O> O<ESC>j " Insert one character. nmap <A-i> i <Esc>r nmap <A-a> a <Esc>r " Move on display lines in normal and visual mode. nnoremap j gj nnoremap k gk vnoremap j gj vnoremap k gk " Do not lose * register when pasting on visual selection. vmap p "zxP " Clear highlight search results with <esc> nnoremap <esc> :noh<return><esc> " Center screen on next/previous selection. map n nzz map N Nzz " <Esc> with jj. inoremap jj <Esc> " Switch jump to mark. nnoremap ' ` nnoremap ` ' " Last and next jump should center too. nnoremap <C-o> <C-o>zz nnoremap <C-i> <C-i>zz " Paste on new line. nnoremap <A-p> :pu<CR> nnoremap <A-S-p> :pu!<CR> " Quick paste on insert mode. inoremap <C-F> <C-R>" " Indent cursor on empty line. nnoremap <A-c> ddO nnoremap <leader>c ddO " Save and quit quickly. nnoremap <leader>s :w<CR> nnoremap <leader>q :q<CR> nnoremap <leader>Q :q!<CR> " The way it should have been. noremap Y y$ " Moving in buffers. nnoremap <C-S-tab> :bprev<CR> nnoremap <C-tab> :bnext<CR> " Using bufkill plugin. nnoremap <leader>b :BD<CR> nnoremap <leader>B :BD!<CR> nnoremap <leader>ZZ :w<CR>:BD<CR> " Moving and resizing in windows. nnoremap + <C-W>+ nnoremap _ <C-W>- nnoremap <C-h> <C-w>h nnoremap <C-j> <C-w>j nnoremap <C-k> <C-w>k nnoremap <C-l> <C-w>l nnoremap <leader>w <C-w>c " Moving in tabs noremap <c-right> gt noremap <c-left> gT nnoremap <leader>t :tabc<CR> " Moving around in insert mode. inoremap <A-j> <C-O>gj inoremap <A-k> <C-O>gk inoremap <A-h> <Left> inoremap <A-l> <Right> " =====General options " I copy a lot from external apps. set clipboard=unnamed " Don't let swap and backup files fill my working directory. set backupdir=c:\\temp,. " Backup files set directory=c:\\temp,. " Swap files set nocompatible set showmatch set hidden set showcmd " This shows what you are typing as a command. set scrolloff=3 " Allow backspacing over everything in insert mode set backspace=indent,eol,start " Syntax highlight syntax on filetype plugin on filetype indent on " =====Searching set ignorecase set hlsearch set incsearch " =====Indentation settings " autoindent just copies the indentation from the line above. "set autoindent " smartindent automatically inserts one extra level of indentation in some cases. set smartindent " cindent is more customizable, but also more strict. "set cindent set tabstop=4 set shiftwidth=4 " =====GUI options. " Just Vim without any gui. set guioptions-=m set guioptions-=T set lines=40 set columns=150 " Consolas is better, but Courier new is everywhere. "set guifont=Courier\ New:h9 set guifont=Consolas:h9 " Cool status line. set statusline=%<%1*===\ %5*%f%1*%(\ ===\ %4*%h%1*%)%(\ ===\ %4*%m%1*%)%(\ ===\ %4*%r%1*%)\ ===%====\ %2*%b(0x%B)%1*\ ===\ %3*%l,%c%V%1*\ ===\ %5*%P%1*\ ===%0* laststatus=2 colorscheme mildblack let g:sienna_style = 'dark' " =====Plugins " ===BufPos nnoremap <leader>ob :call BufWipeout()<CR> " ===SuperTab " Map SuperTab to space key. let g:SuperTabMappingForward = '<c-space>' let g:SuperTabMappingBackward = '<s-c-space>' let g:SuperTabDefaultCompletionType = 'context' " ===miniBufExpl " let g:miniBufExplMapWindowNavVim = 1 " let g:miniBufExplMapCTabSwitchBufs = 1 " let g:miniBufExplorerMoreThanOne = 0 " ===AutoClose " let g:AutoClosePairs = {'(': ')', '{': '}', '[': ']', '"': '"', "'": "'"} " ===NERDTree nnoremap <leader>n :NERDTreeToggle<CR> " ===delimitMate let delimitMate = "(:),[:],{:}" A: Almost everything is here. It is mainly programming oriented, in C++ in particular. A: My .vimrc and .bashrc plus my entire .vim folder (with all the plugins) are available at: http://code.google.com/p/pal-nix/. Here's my .vimrc for quick review: " .vimrc " " $Author$ " $Date$ " $Revision$ " * Initial Configuration * {{{1 " " change directory on open file, buffer switch etc. {{{2 set autochdir " turn on filetype detection and indentation {{{2 filetype indent plugin on " set tags file to search in parent directories with tags; {{{2 set tags=tags; " reload vimrc on update {{{2 autocmd BufWritePost .vimrc source % " set folds to look for markers {{{2 :set foldmethod=marker " automatically save view and reload folds {{{2 "au BufWinLeave * mkview "au BufWinEnter * silent loadview " behave like windows {{{2 "source $VIMRUNTIME/mswin.vim " can't use if on (use with gvim only) "behave mswin " load dictionary files for complete suggestion with Ctrl-n {{{2 set complete+=k autocmd FileType * exec('set dictionary+=~/.vim/dict/' . &filetype) " * User Interface * {{{1 " " turn on coloring {{{2 if has('syntax') syntax on endif " gvim color scheme of choice {{{2 if has('gui') so $VIMRUNTIME/colors/desert.vim endif " turn off annoying bell {{{2 set vb " set the directory for swp files {{{2 if(isdirectory(expand("$VIMRUNTIME/swp"))) set dir=$VIMRUNTIME/swp endif " have fifty lines of cmdline (etc) history {{{2 set history=50 " have cmdline completion (for filenames, help topics, option names) {{{2 " first list the available options and complete the longest common part, then " have further s cycle through the possibilities: set wildmode=list:longest,full " use "[RO]" for "[readonly]" to save space in the message line: {{{2 set shortmess+=r " display current mode and partially typed commands in status line {{{2 set showmode set showcmd " Text Formatting -- General {{{2 set nocompatible "prevents vim from emulating vi's original bugs set backspace=2 "make backspace work normal (indent, eol, start) set autoindent set smartindent "makes vim smartly guess indent level set tabstop=2 "sets up 2 space tabs set shiftwidth=2 "tells vim to use 2 spaces when text is indented set smarttab "uses shiftwidth for inserting s set expandtab "insert spaces instead of set softtabstop=2 "makes vim see multiple space characters as tabstops set showmatch "causes cursor to jump to bracket match set mat=5 "how many tenths of a second to blink matches set guioptions-=T "removes toolbar from gvim set ruler "ensures each window contains a status line set incsearch "vim will search for text as you type set hlsearch "highlight search terms set hl=l:Visual "use Visual mode's highlighting scheme --much better set ignorecase "ignore case in searches --faster this way set virtualedit=all "allows the cursor to stray beyond defined text set number "show line numbers in left margin set path=$PWD/** "recursively set the path of the project "get more information from the status line set statusline=[%n]\ %<%.99f\ %h%w%m%r%{exists('*CapsLockStatusline')?CapsLockStatusline():''}%y%=%-16(\ %l,%c-%v\ %)%P set laststatus=2 "keep status line showing set cursorline "highlight current line highlight CursorLine guibg=lightblue guifg=white ctermbg=blue ctermfg=white "set spell "spell check set spellsuggest=3 "suggest better spelling set spelllang=en "set language set encoding=utf-8 "set character encoding " * Macros * {{{1 " " Function keys {{{2 " Don't you always find yourself hitting instead of ? {{{3 inoremap noremap " turn off syntax highlighting {{{3 nnoremap :nohlsearch inoremap :nohlsearcha " NERD Tree Explorer {{{3 nnoremap :NERDTreeToggle " open tag list {{{3 nnoremap :TlistToggle " Spell check {{{3 nnoremap :set spell " No spell check {{{3 nnoremap :set nospell " refactor curly braces on keyword line {{{3 map :%s/) \?\n^\s*{/) {/g " useful mappings to paste and reformat/reindent {{{2 nnoremap P P'[v']= nnoremap p P'[v']= " * Scripts * {{{1 " :au Filetype html,xml,xsl source ~/.vim/scripts/closetag.vim " Modeline {{{1 " vim:set fdm=marker sw=4 ts=4: A: The return, backspace, spacebar and hyphen keys aren't bound to anything useful, so I map them to navigate more conveniently through the document: " Page down, page up, scroll down, scroll up noremap <Space> <C-f> noremap - <C-b> noremap <Backspace> <C-y> noremap <Return> <C-e> A: When I launch gVim without arguments, I want it to open in my "project" directory, so that I can do :find etc. However, when I launch it with files, I don't want it to switch directory, I want it to stay right there (in part, so that it opens the file I want it to open!). if argc() == 0 cd $PROJECT_DIR endif So that I can use :find from any file in the current project, I set up my path to look up the directory tree 'til it finds src or scripts and descends into those, at least until it hits c:\work which is the root of all of my projects. This allows me to open files in a project that is not current (i.e. PROJECT_DIR above specifies a different directory). set path+=src/**;c:/work,scripts/**;c:/work So that I get automatic saving and reloading, and exiting of insert mode when gVim loses focus, as well as automatic checkout from Perforce when editing a readonly file... augroup AutoSaveGroup autocmd! autocmd FocusLost *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel wa autocmd FileChangedRO *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel silent !p4 edit %:p autocmd FileChangedRO *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel w! augroup END augroup OutOfInsert autocmd! autocmd FocusLost * call feedkeys("\<C-\>\<C-N>") augroup END And finally, switch to the directory of the file in the current buffer so that it's easy to :e other files in that directory. augroup MiscellaneousTomStuff autocmd! " make up for the deficiencies in 'autochdir' autocmd BufEnter * silent! lcd %:p:h:gs/ /\\ / augroup END A: The line I can't live without and generally first appearing in my .vimrc: " prevent switch to Replece mode if <Insert> pressed in insert mode imap <Insert> <Nop> Another bit I can't live without is preserving the current line when hitting PgDown/PgUp: map <silent> <PageUp> 1000<C-U> map <silent> <PageDown> 1000<C-D> imap <silent> <PageUp> <C-O>1000<C-U> imap <silent> <PageDown> <C-O>1000<C-D> set nostartofline Disable the annoying matching parentheses highlighting: set noshowmatch let loaded_matchparen = 1 Disable syntax highlighting when editing huge (>4MB) files: au BufReadPost * if getfsize(bufname("%")) > 4*1024*1024 | \ set syntax= | \ endif And finally my simple in-line calculator: function CalcX(line_num) let l = getline(a:line_num) let expr = substitute( l, " *=.*$","","" ) exec ":let g:tmp_calcx = ".expr call setline(a:line_num, expr." = ".g:tmp_calcx) endfunction :map <silent> <F11> :call CalcX(".")<CR> A: Two functions that I use extensively are placeholders to jump to files and InsertChangeLog (), jointly "facilitate the creation of files with more friendly description " place holders snippets " File Templates " -------------- " <leader>j jumps to the next marker " iabbr <buffer> for for <+i+> in <+intervalo+>:<cr><tab><+i+> function! LoadFileTemplate() "silent! 0r ~/.vim/templates/%:e.tmpl syn match vimTemplateMarker "<+.\++>" containedin=ALL hi vimTemplateMarker guifg=#67a42c guibg=#112300 gui=bold endfunction function! JumpToNextPlaceholder() let old_query = getreg('/') echo search("<+.\\++>") exec "norm! c/+>/e\<CR>" call setreg('/', old_query) endfunction autocmd BufNewFile * :call LoadFileTemplate() nnoremap <leader>j :call JumpToNextPlaceholder()<CR>a inoremap <leader>j <ESC>:call JumpToNextPlaceholder()<CR>a fun! InsertChangeLog() normal(1G) call append(0, "Arquivo: <+Description+>") call append(1, "Criado: " . strftime("%a %d/%b/%Y hs %H:%M")) call append(2, "Last Change: " . strftime("%a %d/%b/%Y hs %H:%M")) call append(3, "autor: <+digite seu nome+>") call append(4, "site: <+digite o endereço de seu site+>") call append(5, "twitter: <+your twitter here+>") normal gg endfun A: " insert change log in files fun! InsertChangeLog() let l:flag=0 for i in range(1,5) if getline(i) !~ '.*Last Change.*' let l:flag = l:flag + 1 endif endfor if l:flag >= 5 normal(1G) call append(0, "File: <+Description+>") call append(1, "Created: " . strftime("%a %d/%b/%Y hs %H:%M")) call append(2, "Last Change: " . strftime("%a %d/%b/%Y hs %H:%M")) call append(3, "author: <+your name+>") call append(4, "site: <+site+>") call append(5, "twitter: <+your twitter here+>") normal gg endif endfun map <special> <F4> <esc>:call InsertChangeLog()<cr> " update changefile log " http://tech.groups.yahoo.com/group/vim/message/51005 fun! LastChange() let _s=@/ let l = line(".") let c = col(".") if line("$") >= 5 1,5s/\s*Last Change:\s*\zs.*/\="" . strftime("%Y %b %d %X")/ge endif let @/=_s call cursor(l, c) endfun autocmd BufWritePre * keepjumps call LastChange() function! JumpToNextPlaceholder() let old_query = getreg('/') echo search("<+.\\++>") exec "norm! c/+>/e\<CR>" call setreg('/', old_query) endfunction autocmd BufNewFile * :call LoadFileTemplate() nnoremap <special> <leader>j :call JumpToNextPlaceholder()<CR>a inoremap <special> <leader>j <ESC>:call JumpToNextPlaceholder()<CR>a " Cientific calculator command! -nargs=+ Calc :py print <args> py from math import * map ,c :Calc set statusline=%F%m%r%h%w\ \ ft:%{&ft}\ \ \ff:%{&ff}\ \ \%{strftime(\"%a\ %d/%m/%Y\ \ \%H:%M:%S\",getftime(expand(\"%:p\")))}%=\ \ \buf:%n\ \ \L:%04l\ C:%04v\ \ \T:%04L\ HEX:%03.3B\ ASCII:%03.3b\ %P set laststatus=2 " Always show statusline A: This isnt in my .vimrc but its related. In your .bashrc add this line alias :q=exit Its amazing how much I have used this, sometimes without even realising! A: My .vimrc is available on Github. Lots of small tweaks and handy bindings in there :) A: I put my .vimrc at http://dotfiles.org/~petdance/.vimrc, and I have some other files at dotfiles.org, too. A: My ~/.vimrc is pretty standard (mostly the $VIMRUNTIME/vimrc_example.vim), but I use my ~/.vim directory extensively, with custom scripts in ~/.vim/ftplugin and ~/.vim/syntax. A: my .vimrc. My word swap function is usually a big hit. A: Here are mine. They've been evolving for a number of years and they work equally well in Linux/Windows/OSX (last time I checked): vimrc and gvimrc A: " ************************** " * vim general options **** " ************************** set nocompatible set history=1000 set mouse=a " don't have files trying to override this .vimrc: set nomodeline " have <F1> prompt for a help topic, rather than displaying the introduction " page, and have it do this from any mode: nnoremap <F1> :help<Space> vmap <F1> <C-C><F1> omap <F1> <C-C><F1> map! <F1> <C-C><F1> set title " ************************** " * set visual options ***** " ************************** set nu set ruler syntax on " colorscheme oceandeep set background=dark set wildmenu set wildmode=list:longest,full " use "[RO]" for "[readonly]" set shortmess+=r set scrolloff=3 " display the current mode and partially-typed commands in the status line: set showmode set showcmd " don't make it look like there are line breaks where there aren't: set nowrap " ************************** " * set editing options **** " ************************** set autoindent filetype plugin indent on set backspace=eol,indent,start autocmd FileType text setlocal textwidth=80 autocmd FileType make set noexpandtab shiftwidth=8 " * Search & Replace " make searches case-insensitive, unless they contain upper-case letters: set ignorecase set smartcase " show the `best match so far' as search strings are typed: set incsearch " assume the /g flag on :s substitutions to replace all matches in a line: set gdefault " *************************** " * tab completion ********** " *************************** setlocal omnifunc=syntaxcomplete#Complete imap <Tab> <C-x><C-o> inoremap <tab> <c-r>=InsertTabWrapper()<cr> " *************************** " * keyboard mapping ******** " *************************** imap <A-1> <Esc>:tabn 1<CR>i imap <A-2> <Esc>:tabn 2<CR>i imap <A-3> <Esc>:tabn 3<CR>i imap <A-4> <Esc>:tabn 4<CR>i imap <A-5> <Esc>:tabn 5<CR>i imap <A-6> <Esc>:tabn 6<CR>i imap <A-7> <Esc>:tabn 7<CR>i imap <A-8> <Esc>:tabn 8<CR>i imap <A-9> <Esc>:tabn 9<CR>i map <A-1> :tabn 1<CR> map <A-2> :tabn 2<CR> map <A-3> :tabn 3<CR> map <A-4> :tabn 4<CR> map <A-5> :tabn 5<CR> map <A-6> :tabn 6<CR> map <A-7> :tabn 7<CR> map <A-8> :tabn 8<CR> map <A-9> :tabn 9<CR> " *************************** " * Utilities Needed ******** " *************************** function InsertTabWrapper() let col = col('.') - 1 if !col || getline('.')[col - 1] !~ '\k' return "\<tab>" else return "\<c-p>" endif endfunction " end of .vimrc A: Probably the most significant things below are the font choices and the colour schemes. Yes, I have spent far too long enjoyably fiddling with those things. :) "set tildeop set nosmartindent " set guifont=courier " awesome programming font " set guifont=peep:h09:cANSI " another nice looking font for programming and general use set guifont=Bitstream_Vera_Sans_MONO:h09:cANSI set lines=68 set tabstop=2 set shiftwidth=2 set expandtab set ignorecase set nobackup " set writebackup " Some of my favourite colour schemes, lovingly crafted over the years :) " very dark scarlet background, almost white text " hi Normal guifg=#FFFFF0 guibg=#3F0000 ctermfg=white ctermbg=Black " C64 colours "hi Normal guifg=#8CA1EC guibg=#372DB4 ctermfg=white ctermbg=Black " nice forest green background with bisque fg hi Normal guifg=#9CfCb1 guibg=#279A1D ctermfg=white ctermbg=Black " dark green background with almost white text "hi Normal guifg=#FFFFF0 guibg=#003F00 ctermfg=white ctermbg=Black " french blue background, almost white text "hi Normal guifg=#FFFFF0 guibg=#00003F ctermfg=white ctermbg=Black " slate blue bg, grey text "hi Normal guifg=#929Cb1 guibg=#20403F ctermfg=white ctermbg=Black " yellow/orange bg, black text hi Normal guifg=#000000 guibg=#f8db3a ctermfg=white ctermbg=Black A: set guifont=FreeMono\ 12 colorscheme default set nocompatible set backspace=indent,eol,start set nobackup "do not keep a backup file, use versions instead set history=10000 "keep 10000 lines of command line history set ruler "show the cursor position all the time set showcmd "display incomplete commands set showmode set showmatch set nojoinspaces "do not insert a space, when joining lines set whichwrap="" "do not jump to the next line when deleting "set nowrap filetype plugin indent on syntax enable set hlsearch set incsearch "do incremental searching set autoindent set noexpandtab set tabstop=4 set shiftwidth=4 set number set laststatus=2 set visualbell "do not beep set tabpagemax=100 set statusline=%F\ %h%m%r%=%l/%L\ \(%-03p%%\)\ %-03c\ "use listmode to make tabs visible and make them gray so they are not "disctrating too much set listchars=tab:»\ ,eol:¬,trail:. highlight NonText ctermfg=gray guifg=gray highlight SpecialKey ctermfg=gray guifg=gray highlight clear MatchParen highlight MatchParen cterm=bold set list match Todo /@todo/ "highlight doxygen todos "different tabbing settings for different file types if has("autocmd") autocmd FileType c setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab autocmd FileType cpp setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab autocmd FileType go setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab autocmd FileType make setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab autocmd FileType python setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab " doesnt work properly -- revise me autocmd CursorMoved * call RonnyHighlightWordUnderCursor() autocmd CursorMovedI * call RonnyHighlightWordUnderCursor() "jump to the end of the file if it is a logfile autocmd BufReadPost *.log normal G autocmd BufRead,BufNewFile *.go set filetype=go endif highlight Search ctermfg=white ctermbg=gray highlight IncSearch ctermfg=white ctermbg=gray highlight RonnyWordUnderCursorHighlight cterm=bold function! RonnyHighlightWordUnderCursor() python << endpython import vim # get the character under the cursor row, col = vim.current.window.cursor characterUnderCursor = '' try: characterUnderCursor = vim.current.buffer[row-1][col] except: pass # remove last search vim.command("match RonnyWordUnderCursorHighlight //") # if the cursor is currently located on a real word, move on and highlight it if characterUnderCursor.isalpha() or characterUnderCursor.isdigit() or characterUnderCursor is '_': # expand cword to get the word under the cursor wordUnderCursor = vim.eval("expand(\'<cword>\')") if wordUnderCursor is None : wordUnderCursor = "" # escape the word wordUnderCursor = vim.eval("RonnyEscapeString(\"" + wordUnderCursor + "\")") wordUnderCursor = "\<" + wordUnderCursor + "\>" currentSearch = vim.eval("@/") if currentSearch != wordUnderCursor : # highlight it, if it is not the currently searched word vim.command("match RonnyWordUnderCursorHighlight /" + wordUnderCursor + "/") endpython endfunction function! RonnyEscapeString(s) python << endpython import vim s = vim.eval("a:s") escapeMap = { '"' : '\\"', "'" : '\\''', "*" : '\\*', "/" : '\\/', #'' : '' } s = s.replace('\\', '\\\\') for before, after in escapeMap.items() : s = s.replace(before, after) vim.command("return \'" + s + "\'") endpython endfunction A: I've created my own syntax for my to do or checklist documents which highlights things like -> do this (in bold) !-> do this now (in orange) ++> doing this in process (in green) => this is done (in gray) I have the document in ./syntax/ as fc_comdoc.vim in vimrc to set this syntax for anything with my custom extension .txtcd or .txtap au BufNewFile,BufRead *.txtap,*.txtcd setf fc_comdoc A: I show fold contents and syntax groups on mouse-over: function! SyntaxBallon() let synID = synID(v:beval_lnum, v:beval_col, 0) let groupID = synIDtrans(synID) let name = synIDattr(synID, "name") let group = synIDattr(groupID, "name") return name . "\n" . group endfunction function! FoldBalloon() let foldStart = foldclosed(v:beval_lnum) let foldEnd = foldclosedend(v:beval_lnum) let lines = [] if foldStart >= 0 " we are in a fold let numLines = foldEnd - foldStart + 1 if (numLines > 17) " show only the first 8 and the last 8 lines let lines += getline(foldStart, foldStart + 8) let lines += [ '-- Snipped ' . (numLines - 16) . ' lines --'] let lines += getline(foldEnd - 8, foldEnd) else " show all lines let lines += getline(foldStart, foldEnd) endif endif " return result return join(lines, has("balloon_multiline") ? "\n" : " ") endfunction function! Balloon() if foldclosed(v:beval_lnum) >= 0 return FoldBalloon() else return SyntaxBallon() endfunction set balloonexpr=Balloon() set ballooneval A: set nocompatible syntax on set number set autoindent set smartindent set background=dark set tabstop=4 shiftwidth=4 set tw=80 set expandtab set mousehide set cindent set list listchars=tab:»·,trail:· set autoread filetype on filetype indent on filetype plugin on " abbreviations for c programming func LoadCAbbrevs() " iabbr do do {<CR>} while ();<C-O>3h<C-O> " iabbr for for (;;) {<CR>}<C-O>k<C-O>3l<C-O> " iabbr switch switch () {<CR>}<C-O>k<C-O>6l<C-O> " iabbr while while () {<CR>}<C-O>k<C-O>5l<C-O> " iabbr if if () {<CR>}<C-O>k<C-O>2l<C-O> iabbr #d #define iabbr #i #include endfunc au FileType c,cpp call LoadCAbbrevs() au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | \ exe "normal g'\"" | endif autocmd FileType python set nocindent shiftwidth=4 ts=4 foldmethod=indent Not much there. A: Just saw this now: :nnoremap <esc> :noh<return><esc> I found it in ViEmu Blog and I really dig this. A short explanation - It makes Esc turn off search highlight in normal mode. A: set tabstop=4 set shiftwidth=4 set cindent set noautoindent set noexpandtab set nocompatible set cino=:0(4u0 set backspace=indent,start set term=ansi let lpc_syntax_for_c=1 syntax enable autocmd FileType c set cin noai nosi autocmd FileType lpc set cin noai nosi autocmd FileType css set nocin ai noet autocmd FileType js set nocin ai noet autocmd FileType php set nocin ai noet function! DeleteFile(...) if(exists('a:1')) let theFile=a:1 elseif ( &ft == 'help' ) echohl Error echo "Cannot delete a help buffer!" echohl None return -1 else let theFile=expand('%:p') endif let delStatus=delete(theFile) if(delStatus == 0) echo "Deleted " . theFile else echohl WarningMsg echo "Failed to delete " . theFile echohl None endif return delStatus endfunction "delete the current file com! Rm call DeleteFile() "delete the file and quit the buffer (quits vim if this was the last file) com! RM call DeleteFile() <Bar> q! A: The results of years of my meddling with vim are all here. A: Useful stuff for C/C++ and svn usage (could be easily modified for git/hg/whatever). I set them to my F-keys. Not C#, but useful nonetheless. function! SwapFilesKeep() " Open a new window next to the current one with the matching .cpp/.h pair" let command = "echo " . bufname("%") . "|sed s,\h$,\H,|sed s,cpp,h,|sed s,H$,cpp," let newfilename = system(command) silent execute("vs " . newfilename) endfunction function! SwapFiles() " swap between .cpp and .h " let command = "echo " . bufname("%") . "|sed s,\h$,\H,|sed s,cpp,h,|sed s,H$,cpp," let newfilename = system(command) silent execute("e " . newfilename) endfunction function! SvnDiffAll() let tempfile = system("tempfile") silent execute ":!svn diff .>" . tempfile execute ":sf ".tempfile return endfunction function! SvnLog() let fn = expand('%') let tempfile = system("tempfile") silent execute ":!svn log -v " . fn . ">" . tempfile execute ":sf ".tempfile return endfunction function! SvnStatus() let tempfile = system("tempfile") silent execute ":!svn status .>" . tempfile execute ":sf ".tempfile return endfunction function! SvnDiff() " diff with BASE " let dir = expand('%:p:h') let fn = expand('%') let fn = substitute(fn,".*\\","","") let fn = substitute(fn,".*/","","") silent execute ":vert diffsplit " . dir . "/.svn/text-base/" . fn . ".svn-base" silent execute ":set ft=cpp" unlet fn dir return endfunction A: :map + v%zf # hit "+" to fold a function/loop anything within a paranthesis. :set expandtab # tab will be expanded as spaces as per the setting of ts (tabspace) A: set ai set si set sm set sta set ts=3 set sw=3 set co=130 set lines=50 set nowrap set ruler set showcmd set showmode set showmatch set incsearch set hlsearch set gfn=Consolas:h11 set guioptions-=T set clipboard=unnamed set expandtab set nobackup syntax on colors torte A: I tend to split my .vimrc into different sections so that I can turn different sections on and off on all the different machines I run on, i.e. some bits on windows some on linux etc: "***************************************** "* SECTION 1 - THINGS JUST FOR GVIM * "***************************************** if v:version >= 700 "Note: Other plugin files source ~/.vim/ben_init/bens_pscripts.vim "source ~/.vim/ben_init/stim_projects.vim "source ~/.vim/ben_init/temp_commands.vim "source ~/.vim/ben_init/wwatch.vim "Extract sections of code as a function (works in C, C++, Perl, Java) source ~/.vim/ben_init/functify.vim "Settings that relate to the look/feel of vim in the GUI source ~/.vim/ben_init/gui_settings.vim "General VIM settings source ~/.vim/ben_init/general_settings.vim "Settings for programming source ~/.vim/ben_init/c_programming.vim "Settings for completion source ~/.vim/ben_init/completion.vim "My own templating system source ~/.vim/ben_init/templates.vim "Abbreviations and interesting key mappings source ~/.vim/ben_init/abbrev.vim "Plugin configuration source ~/.vim/ben_init/plugin_config.vim "Wiki configuration source ~/.vim/ben_init/wiki_config.vim "Key mappings source ~/.vim/ben_init/key_mappings.vim "Auto commands source ~/.vim/ben_init/autocmds.vim "Handy Functions written by other people source ~/.vim/ben_init/handy_functions.vim "My own omni_completions source ~/.vim/ben_init/bens_omni.vim endif A: In addition to my vimrc I have a bigger collection of plugins. Everything is stored in a git repository at http://github.com/jceb/vimrc. " Author: Jan Christoph Ebersbach jceb AT e-jc DOT de """""""""""""""""""""""""""""""""""""""""""""""""" " ---------- Settings ---------- " """""""""""""""""""""""""""""""""""""""""""""""""" " Prevent modelines in files from being evaluated (avoids a potential " security problem wherein a malicious user could write a hazardous " modeline into a file) (override default value of 5) set modeline set modelines=5 " ########## miscellaneous options ########## set nocompatible " Use Vim defaults instead of 100% vi compatibility set whichwrap=<,> " Cursor key move the cursor to the next/previous line if pressed at the end/beginning of a line set backspace=indent,eol,start " more powerful backspacing set viminfo='20,\"50 " read/write a .viminfo file, don't store more than set history=100 " keep 50 lines of command line history set incsearch " Incremental search set hidden " hidden allows to have modified buffers in background set noswapfile " turn off backups and files set nobackup " Don't keep a backup file set magic " special characters that can be used in search patterns set grepprg=grep\ --exclude='*.svn-base'\ -n\ $*\ /dev/null " don't grep through svn-base files " Try do use the ack program when available let tmp = '' for i in ['ack', 'ack-grep'] let tmp = substitute (system ('which '.i), '\n.*', '', '') if v:shell_error == 0 exec "set grepprg=".tmp."\\ -a\\ -H\\ --nocolor\\ --nogroup" break endif endfor unlet tmp "set autowrite " Automatically save before commands like :next and :make " Suffixes that get lower priority when doing tab completion for filenames. " These are files we are not likely to want to edit or read. set suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc,.pdf,.exe "set autochdir " move to the directory of the edited file set ssop-=options " do not store global and local values in a session set ssop-=folds " do not store folds " ########## visual options ########## set wildmenu " When 'wildmenu' is on, command-line completion operates in an enhanced mode. set wildcharm=<C-Z> set showmode " If in Insert, Replace or Visual mode put a message on the last line. set guifont=monospace\ 8 " guifont + fontsize set guicursor=a:blinkon0 " cursor-blinking off!! set ruler " show the cursor position all the time set nowrap " kein Zeilenumbruch set foldmethod=indent " Standardfaltungsmethode set foldlevel=99 " default fold level set winminheight=0 " Minimal Windowheight set showcmd " Show (partial) command in status line. set showmatch " Show matching brackets. set matchtime=2 " time to show the matching bracket set hlsearch " highlight search set linebreak set lazyredraw " no readraw when running macros set scrolloff=3 " set X lines to the curors - when moving vertical.. set laststatus=2 " statusline is always visible set statusline=(%{bufnr('%')})\ %t\ \ %r%m\ #%{expand('#:t')}\ (%{bufnr('#')})%=[%{&fileformat}:%{&fileencoding}:%{&filetype}]\ %l,%c\ %P " statusline "set mouse=n " mouse only in normal mode support in vim "set foldcolumn=1 " show folds set number " draw linenumbers set nolist " list nonprintable characters set sidescroll=0 " scroll X columns to the side instead of centering the cursor on another screen set completeopt=menuone " show the complete menu even if there is just one entry set listchars+=precedes:<,extends:> " display the following nonprintable characters if $LANG =~ ".*\.UTF-8$" || $LANG =~ ".*utf8$" || $LANG =~ ".*utf-8$" set listchars+=tab:»·,trail:·" display the following nonprintable characters endif set guioptions=aegitcm " disabled menu in gui mode "set guioptions=aegimrLtT set cpoptions=aABceFsq$ " q: When joining multiple lines leave the cursor at the position where it would be when joining two lines. " $: When making a change to one line, don't redisplay the line, but put a '$' at the end of the changed text. " v: Backspaced characters remain visible on the screen in Insert mode. colorscheme peaksea " default color scheme " default color scheme " if &term == '' || &term == 'builtin_gui' || &term == 'dumb' if has('gui_running') set background=light " use colors that fit to a light background else set background=light " use colors that fit to a light background "set background=dark " use colors that fit to a dark background endif syntax on " syntax highlighting " ########## text options ########## set smartindent " always set smartindenting on set autoindent " always set autoindenting on set backspace=2 " Influences the working of <BS>, <Del>, CTRL-W and CTRL-U in Insert mode. set textwidth=0 " Don't wrap words by default set shiftwidth=4 " number of spaces to use for each step of indent set tabstop=4 " number of spaces a tab counts for set noexpandtab " insert spaces instead of tab set smarttab " insert spaces only at the beginning of the line set ignorecase " Do case insensitive matching set smartcase " overwrite ignorecase if pattern contains uppercase characters set formatoptions=lcrqn " no automatic linebreak set pastetoggle=<F11> " put vim in pastemode - usefull for pasting in console-mode set fileformats=unix,dos,mac " favorite fileformats set encoding=utf-8 " set default-encoding to utf-8 set iskeyword+=_,- " these characters also belong to a word set matchpairs+=<:> """""""""""""""""""""""""""""""""""""""""""""""""" " ---------- Special Configuration ---------- " """""""""""""""""""""""""""""""""""""""""""""""""" " ########## determine terminal encoding ########## "if has("multi_byte") && &term != 'builtin_gui' " set termencoding=utf-8 " " " unfortunately the normal xterm supports only latin1 " if $TERM == "xterm" || $TERM == "xterm-color" || $TERM == "screen" || $TERM == "linux" || $TERM_PROGRAM == "GLterm" " let propv = system("xprop -id $WINDOWID -f WM_LOCALE_NAME 8s ' $0' -notype WM_LOCALE_NAME") " if propv !~ "WM_LOCALE_NAME .*UTF.*8" " set termencoding=latin1 " endif " endif " " for the possibility of using a terminal to input and read chinese " " characters " if $LANG == "zh_CN.GB2312" " set termencoding=euc-cn " endif "endif " Set paper size from /etc/papersize if available (Debian-specific) if filereadable('/etc/papersize') let s:papersize = matchstr(system('/bin/cat /etc/papersize'), '\p*') if strlen(s:papersize) let &printoptions = "paper:" . s:papersize endif unlet! s:papersize endif """""""""""""""""""""""""""""""""""""""""""""""""" " ---------- Autocommands ---------- " """""""""""""""""""""""""""""""""""""""""""""""""" filetype plugin on " automatically load filetypeplugins filetype indent on " indent according to the filetype if !exists("autocommands_loaded") let autocommands_loaded = 1 augroup templates " read templates " au BufNewFile ?akefile,*.mk TSkeletonSetup Makefile " au BufNewFile *.tex TSkeletonSetup latex.tex " au BufNewFile build*.xml TSkeletonSetup antbuild.xml " au BufNewFile test*.py,*Test.py TSkeletonSetup pyunit.py " au BufNewFile *.py TSkeletonSetup python.py augroup END augroup filetypesettings " Do word completion automatically au FileType debchangelog setl expandtab au FileType asciidoc,mkd,txt,mail call DoFastWordComplete() au FileType tex,plaintex setlocal makeprg=pdflatex\ \"%:p\" au FileType mkd setlocal autoindent au FileType java,c,cpp setlocal noexpandtab nosmarttab au FileType mail setlocal textwidth=70 au FileType mail call FormatMail() au FileType mail setlocal formatoptions=tcrqan au FileType mail setlocal comments+=b:-- au FileType txt setlocal formatoptions=tcrqn textwidth=72 au FileType asciidoc,mkd,tex setlocal formatoptions=tcrq textwidth=72 au FileType xml,docbk,xhtml,jsp setlocal formatoptions=tcrqn au FileType ruby setlocal shiftwidth=2 au BufReadPost,BufNewFile * set formatoptions-=o " o is really annoying au BufReadPost,BufNewFile * call ReadIncludePath() " Special Makefilehandling au FileType automake,make setlocal list noexpandtab au FileType xsl,xslt,xml,html,xhtml runtime! scripts/closetag.vim " Omni completion settings "au FileType c setlocal completefunc=ccomplete#Complete au FileType css setlocal omnifunc=csscomplete#CompleteCSS "au FileType html setlocal completefunc=htmlcomplete#CompleteTags "au FileType js setlocal completefunc=javascriptcomplete#CompleteJS "au FileType php setlocal completefunc=phpcomplete#CompletePHP "au FileType python setlocal completefunc=pythoncomplete#Complete "au FileType ruby setlocal completefunc=rubycomplete#Complete "au FileType sql setlocal completefunc=sqlcomplete#Complete "au FileType * setlocal completefunc=syntaxcomplete#Complete "au FileType xml setlocal completefunc=xmlcomplete#CompleteTags au FileType help setlocal nolist " insert a prompt for every changed file in the commit message "au FileType svn :1![ -f "%" ] && awk '/^[MDA]/ { print $2 ":\n - " }' % augroup END augroup hooks " replace "Last Modified: with the current time" au BufWritePre,FileWritePre * call LastMod() " line highlighting in insert mode autocmd InsertLeave * set nocul autocmd InsertEnter * set cul " move to the directory of the edited file "au BufEnter * if isdirectory (expand ('%:p:h')) | cd %:p:h | endif " jump to last position in the file au BufRead * if line("'\"") > 0 && line("'\"") <= line("$") && &filetype != "mail" | exe "normal g`\"" | endif " jump to last position every time a buffer is entered "au BufEnter * if line("'x") > 0 && line("'x") <= line("$") && line("'y") > 0 && line("'y") <= line("$") && &filetype != "mail" | exe "normal g'yztg`x" | endif "au BufLeave * if &modifiable | exec "normal mxHmy" augroup END augroup highlight " make visual mode dark cyan au FileType * hi Visual ctermfg=Black ctermbg=DarkCyan gui=bold guibg=#a6caf0 " make cursor red au BufEnter,BufRead,WinEnter * :call SetCursorColor() " hightlight trailing spaces and tabs and the defined print margin "au FileType * hi WhiteSpaceEOL_Printmargin ctermfg=black ctermbg=White guifg=Black guibg=White au FileType * hi WhiteSpaceEOL_Printmargin ctermbg=White guibg=White au FileType * let m='' | if &textwidth > 0 | let m='\|\%' . &textwidth . 'v.' | endif | exec 'match WhiteSpaceEOL_Printmargin /\s\+$' . m .'/' augroup END endif """""""""""""""""""""""""""""""""""""""""""""""""" " ---------- Functions ---------- " """""""""""""""""""""""""""""""""""""""""""""""""" " set cursor color function! SetCursorColor() hi Cursor ctermfg=black ctermbg=red guifg=Black guibg=Red endfunction call SetCursorColor() " change dir the root of a debian package function! GetPackageRoot() let sd = getcwd() let owd = sd let cwd = owd let dest = sd while !isdirectory('debian') lcd .. let owd = cwd let cwd = getcwd() if cwd == owd break endif endwhile if cwd != sd && isdirectory('debian') let dest = cwd endif return dest endfunction " vim tip: Opening multiple files from a single command-line function! Sp(dir, ...) let split = 'sp' if a:dir == '1' let split = 'vsp' endif if(a:0 == 0) execute split else let i = a:0 while(i > 0) execute 'let files = glob (a:' . i . ')' for f in split (files, "\n") execute split . ' ' . f endfor let i = i - 1 endwhile windo if expand('%') == '' | q | endif endif endfunction com! -nargs=* -complete=file Sp call Sp(0, <f-args>) com! -nargs=* -complete=file Vsp call Sp(1, <f-args>) " reads the file .include_path - useful for C programming function! ReadIncludePath() let include_path = expand("%:p:h") . '/.include_path' if filereadable(include_path) for line in readfile(include_path, '') exec "setl path +=," . line endfor endif endfunction " update last modified line in file fun! LastMod() let line = line(".") let column = col(".") let search = @/ " replace Last Modified in the first 20 lines if line("$") > 20 let l = 20 else let l = line("$") endif " replace only if the buffer was modified if &mod == 1 silent exe "1," . l . "g/Last Modified:/s/Last Modified:.*/Last Modified: " . \ strftime("%a %d. %b %Y %T %z %Z") . "/" endif let @/ = search " set cursor to last position before substitution call cursor(line, column) endfun " toggles show marks plugin "fun! ToggleShowMarks() " if exists('b:sm') && b:sm == 1 " let b:sm=0 " NoShowMarks " setl updatetime=4000 " else " let b:sm=1 " setl updatetime=200 " DoShowMarks " endif "endfun " reformats an email fun! FormatMail() " workaround for the annoying mutt send-hook behavoir silent! 1,/^$/g/^X-To: .*/exec 'normal gg'|exec '/^To: /,/^Cc: /-1d'|1,/^$/s/^X-To: /To: /|exec 'normal dd'|exec '?Cc'|normal P silent! 1,/^$/g/^X-Cc: .*/exec 'normal gg'|exec '/^Cc: /,/^Bcc: /-1d'|1,/^$/s/^X-Cc: /Cc: /|exec 'normal dd'|exec '?Bcc'|normal P silent! 1,/^$/g/^X-Bcc: .*/exec 'normal gg'|exec '/^Bcc: /,/^Subject: /-1d'|1,/^$/s/^X-Bcc: /Bcc: /|exec 'normal dd'|exec '?Subject'|normal P " delete signature silent! /^> --[\t ]*$/,/^-- $/-2d " fix quotation silent! /^\(On\|In\) .*$/,/^-- $/-1:s/>>/> >/g silent! /^\(On\|In\) .*$/,/^-- $/-1:s/>\([^\ \t]\)/> \1/g " delete inner and trailing spaces normal :%s/[\xa0\x0d\t ]\+$//g normal :%s/\([^\xa0\x0d\t ]\)[\xa0\x0d\t ]\+\([^\xa0\x0d\t ]\)/\1 \2/g " format text normal gg " convert bad formated umlauts to real characters normal :%s/\\\([0-9]*\)/\=nr2char(submatch(1))/g normal :%s/&#\([0-9]*\);/\=nr2char(submatch(1))/g " break undo sequence normal iu exec 'silent! /\(^\(On\|In\) .*$\|\(schrieb\|wrote\):$\)/,/^-- $/-1!par '.&tw.'gqs0' " place the cursor before my signature silent! /^-- $/-1 " clear search buffer let @/ = "" endfun " insert selection at mark a fun! Insert() range exe "normal vgvmzomy\<Esc>" normal `y let lineA = line(".") let columnA = col(".") normal `z let lineB = line(".") let columnB = col(".") " exchange marks if lineA > lineB || lineA <= lineB && columnA > columnB " save z in c normal mc " store y in z normal `ymz " set y to old z normal `cmy endif exe "normal! gvd`ap`y" endfun " search with the selection of the visual mode fun! VisualSearch(direction) range let l:saved_reg = @" execute "normal! vgvy" let l:pattern = escape(@", '\\/.*$^~[]') let l:pattern = substitute(l:pattern, "\n$", "", "") if a:direction == '#' execute "normal! ?" . l:pattern . "^M" elseif a:direction == '*' execute "normal! /" . l:pattern . "^M" elseif a:direction == '/' execute "normal! /" . l:pattern else execute "normal! ?" . l:pattern endif let @/ = l:pattern let @" = l:saved_reg endfun " 'Expandvar' expands the variable under the cursor fun! <SID>Expandvar() let origreg = @" normal yiW if (@" == "@\"") let @" = origreg else let @" = eval(@") endif normal diW"0p let @" = origreg endfun " execute the bc calculator fun! <SID>Bc(exp) setlocal paste normal mao exe ":.!echo 'scale=2; " . a:exp . "' | bc" normal 0i "bDdd`a"bp setlocal nopaste endfun fun! <SID>RFC(number) silent exe ":e http://www.ietf.org/rfc/rfc" . a:number . ".txt" endfun " The function Nr2Hex() returns the Hex string of a number. func! Nr2Hex(nr) let n = a:nr let r = "" while n let r = '0123456789ABCDEF'[n % 16] . r let n = n / 16 endwhile return r endfunc " The function String2Hex() converts each character in a string to a two " character Hex string. func! String2Hex(str) let out = '' let ix = 0 while ix < strlen(a:str) let out = out . Nr2Hex(char2nr(a:str[ix])) let ix = ix + 1 endwhile return out endfunc " translates hex value to the corresponding number fun! Hex2Nr(hex) let r = 0 let ix = strlen(a:hex) - 1 while ix >= 0 let val = 0 if a:hex[ix] == '1' let val = 1 elseif a:hex[ix] == '2' let val = 2 elseif a:hex[ix] == '3' let val = 3 elseif a:hex[ix] == '4' let val = 4 elseif a:hex[ix] == '5' let val = 5 elseif a:hex[ix] == '6' let val = 6 elseif a:hex[ix] == '7' let val = 7 elseif a:hex[ix] == '8' let val = 8 elseif a:hex[ix] == '9' let val = 9 elseif a:hex[ix] == 'a' || a:hex[ix] == 'A' let val = 10 elseif a:hex[ix] == 'b' || a:hex[ix] == 'B' let val = 11 elseif a:hex[ix] == 'c' || a:hex[ix] == 'C' let val = 12 elseif a:hex[ix] == 'd' || a:hex[ix] == 'D' let val = 13 elseif a:hex[ix] == 'e' || a:hex[ix] == 'E' let val = 14 elseif a:hex[ix] == 'f' || a:hex[ix] == 'F' let val = 15 endif let r = r + val * Power(16, strlen(a:hex) - ix - 1) let ix = ix - 1 endwhile return r endfun " mathematical power function fun! Power(base, exp) let r = 1 let exp = a:exp while exp > 0 let r = r * a:base let exp = exp - 1 endwhile return r endfun " Captialize movent/selection function! Capitalize(type, ...) let sel_save = &selection let &selection = "inclusive" let reg_save = @@ if a:0 " Invoked from Visual mode, use '< and '> marks. silent exe "normal! `<" . a:type . "`>y" elseif a:type == 'line' silent exe "normal! '[V']y" elseif a:type == 'block' silent exe "normal! `[\<C-V>`]y" else silent exe "normal! `[v`]y" endif silent exe "normal! `[gu`]~`]" let &selection = sel_save let @@ = reg_save endfunction " Find file in current directory and edit it. function! Find(...) let path="." if a:0==2 let path=a:2 endif let l:list=system("find ".path. " -name '".a:1."' | grep -v .svn ") let l:num=strlen(substitute(l:list, "[^\n]", "", "g")) if l:num < 1 echo "'".a:1."' not found" return endif if l:num != 1 let tmpfile = tempname() exe "redir! > " . tmpfile silent echon l:list redir END let old_efm = &efm set efm=%f if exists(":cgetfile") execute "silent! cgetfile " . tmpfile else execute "silent! cfile " . tmpfile endif let &efm = old_efm " Open the quickfix window below the current window botright copen call delete(tmpfile) endif endfunction """""""""""""""""""""""""""""""""""""""""""""""""" " ---------- Plugin Settings ---------- " """""""""""""""""""""""""""""""""""""""""""""""""" " hide dotfiles by default - the gh mapping quickly changes this behavior let g:netrw_list_hide = '\(^\|\s\s\)\zs\.\S\+' " Do not go to active window. "let g:bufExplorerFindActive = 0 " Don't show directories. "let g:bufExplorerShowDirectories = 0 " Sort by full file path name. "let g:bufExplorerSortBy = 'fullpath' " Show relative paths. "let g:bufExplorerShowRelativePath = 1 " don't allow autoinstalling of scripts let g:GetLatestVimScripts_allowautoinstall = 0 " load manpage-plugin runtime! ftplugin/man.vim " load matchit-plugin runtime! macros/matchit.vim " minibuf explorer "let g:miniBufExplModSelTarget = 1 "let g:miniBufExplorerMoreThanOne = 0 "let g:miniBufExplModSelTarget = 0 "let g:miniBufExplUseSingleClick = 1 "let g:miniBufExplMapWindowNavVim = 1 "let g:miniBufExplVSplit = 25 "let g:miniBufExplSplitBelow = 1 "let g:miniBufExplForceSyntaxEnable = 1 "let g:miniBufExplTabWrap = 1 " calendar plugin " let g:calendar_weeknm = 4 " xml-ftplugin configuration let xml_use_xhtml = 1 " :ToHTML let html_number_lines = 1 let html_use_css = 1 let use_xhtml = 1 " LatexSuite "let g:Tex_DefaultTargetFormat = 'pdf' "let g:Tex_Diacritics = 1 " python-highlightings let python_highlight_all = 1 " Eclim settings "let org.eclim.user.name = g:tskelUserName "let org.eclim.user.email = g:tskelUserEmail "let g:EclimLogLevel = 4 " info "let g:EclimBrowser = "x-www-browser" "let g:EclimShowCurrentError = 1 " nnoremap <silent> <buffer> <tab> :call eclim#util#FillTemplate("${", "}")<CR> " nnoremap <silent> <buffer> <leader>i :JavaImport<CR> " nnoremap <silent> <buffer> <leader>d :JavaDocSearch -x declarations<CR> " nnoremap <silent> <buffer> <CR> :JavaSearchContext<CR> " nnoremap <silent> <buffer> <CR> :AntDoc<CR> " quickfix notes plugin map <Leader>n <Plug>QuickFixNote nnoremap <F6> :QFNSave ~/.vimquickfix/ nnoremap <S-F6> :e ~/.vimquickfix/ nnoremap <F7> :cgetfile ~/.vimquickfix/ nnoremap <S-F7> :caddfile ~/.vimquickfix/ nnoremap <S-F8> :!rm ~/.vimquickfix/ " EnhancedCommentify updated keybindings vmap <Leader><Space> <Plug>VisualTraditional nmap <Leader><Space> <Plug>Traditional let g:EnhCommentifyTraditionalMode = 'No' let g:EnhCommentifyPretty = 'No' let g:EnhCommentifyRespectIndent = 'Yes' " FuzzyFinder keybinding nnoremap <leader>fb :FufBuffer<CR> nnoremap <leader>fd :FufDir<CR> nnoremap <leader>fD :FufDir <C-r>=expand('%:~:.:h').'/'<CR><CR> nmap <leader>Fd <leader>fD nmap <leader>FD <leader>fD nnoremap <leader>ff :FufFile<CR> nnoremap <leader>fF :FufFile <C-r>=expand('%:~:.:h').'/'<CR><CR> nmap <leader>FF <leader>fF nnoremap <leader>ft :FufTextMate<CR> nnoremap <leader>fr :FufRenewCache<CR> "let g:FuzzyFinderOptions = {} "let g:FuzzyFinderOptions = { 'Base':{}, 'Buffer':{}, 'File':{}, 'Dir':{}, "\ 'MruFile':{}, 'MruCmd':{}, 'Bookmark':{}, "\ 'Tag':{}, 'TaggedFile':{}, "\ 'GivenFile':{}, 'GivenDir':{}, 'GivenCmd':{}, "\ 'CallbackFile':{}, 'CallbackItem':{}, } let g:fuf_onelinebuf_location = 'botright' let g:fuf_maxMenuWidth = 300 let g:fuf_file_exclude = '\v\~$|\.o$|\.exe$|\.bak$|\.swp$|((^|[/\\])\.[/\\]$)|\.pyo|\.pyc|autom4te\.cache|blib|_build|\.bzr|\.cdv|cover_db|CVS|_darcs|\~\.dep|\~\.dot|\.git|\.hg|\~\.nib|\.pc|\~\.plst|RCS|SCCS|_sgbak|\.svn' " YankRing nnoremap <silent> <F8> :YRShow<CR> let g:yankring_history_file = '.yankring_history_file' let g:yankring_replace_n_pkey = '<c-\>' let g:yankring_replace_n_nkey = '<c-m>' " supertab let g:SuperTabDefaultCompletionType = "<c-n>" " TagList let Tlist_Show_One_File = 1 " UltiSnips "let g:UltiSnipsJumpForwardTrigger = "<tab>" "let g:UltiSnipsJumpBackwardTrigger = "<S-tab>" " NERD Commenter nmap <leader><space> <plug>NERDCommenterToggle vmap <leader><space> <plug>NERDCommenterToggle imap <C-c> <ESC>:call NERDComment(0, "insert")<CR> " disable unused Mark mappings nmap <leader>_r <plug>MarkRegex vmap <leader>_r <plug>MarkRegex nmap <leader>_n <plug>MarkClear vmap <leader>_n <plug>MarkClear nmap <leader>_* <plug>MarkSearchCurrentNext nmap <leader>_# <plug>MarkSearchCurrentPrev nmap <leader>_/ <plug>MarkSearchAnyNext nmap <leader>_# <plug>MarkSearchAnyPrev nmap <leader>__* <plug>MarkSearchNext nmap <leader>__# <plug>MarkSearchPrev " Nerd Tree explorer mapping nmap <leader>e :NERDTree<CR> " TaskList settings let g:tlWindowPosition = 1 """""""""""""""""""""""""""""""""""""""""""""""""" " ---------- Keymappings ---------- " """""""""""""""""""""""""""""""""""""""""""""""""" " edit/reload .vimrc-Configuration nnoremap gce :e $HOME/.vimrc<CR> nnoremap gcl :source $HOME/.vimrc<CR>:echo "Configuration reloaded"<CR> " un/hightlight current line nnoremap <silent> <Leader>H :match<CR> nnoremap <silent> <Leader>h mk:exe 'match Search /<Bslash>%'.line(".").'l/'<CR> " spellcheck off, german, englisch nnoremap gsg :setlocal invspell spelllang=de<CR> nnoremap gse :setlocal invspell spelllang=en<CR> " switch to previous/next buffer nnoremap <silent> <c-p> :bprevious<CR> nnoremap <silent> <c-n> :bnext<CR> " kill/delete trailing spaces and tabs nnoremap <Leader>kt msHmt:silent! %s/[\t \x0d]\+$//g<CR>:let @/ = ""<CR>:echo "Deleted trailing spaces"<CR>'tzt`s vnoremap <Leader>kt :s/[\t \x0d]\+$//g<CR>:let @/ = ""<CR>:echo "Deleted trailing, spaces"<CR> " kill/reduce inner spaces and tabs to a single space/tab nnoremap <Leader>ki msHmt:silent! %s/\([^\xa0\x0d\t ]\)[\xa0\x0d\t ]\+\([^\xa0\x0d\t ]\)/\1 \2/g<CR>:let @/ = ""<CR>:echo "Deleted inner spaces"<CR>'tzt`s vnoremap <Leader>ki :s/\([^\xa0\x0d\t ]\)[\xa0\x0d\t ]\+\([^\xa0\x0d\t ]\)/\1 \2/g<CR>:let @/ = ""<CR>:echo "Deleted inner spaces"<CR> " start new undo sequences when using certain commands in insert mode inoremap <C-U> <C-G>u<C-U> inoremap <C-W> <C-G>u<C-W> inoremap <BS> <C-G>u<BS> inoremap <C-H> <C-G>u<C-H> inoremap <Del> <C-G>u<Del> " swap two words " http://www.vim.org/tips/tip.php?tip_id=329 nmap <silent> gw "_yiw:s/\(\%#[ÄÖÜäöüßa-zA-Z0-9]\+\)\(\_W\+\)\([ÄÖÜäöüßa-zA-Z0-9]\+\)/\3\2\1/<CR><C-o><C-l>:let @/ = ""<CR> nmap <silent> gW "_yiW:s/\(\%#[ÄÖÜäöüßa-zA-Z0-9-+*_]\+\)\(\_W\+\)\([ÄÖÜäöüßa-zA-Z0-9-+*_]\+\)/\3\2\1/<CR><C-o><C-l>:let @/ = ""<CR> " Capitalize movement nnoremap <silent> gC :set opfunc=Capitalize<CR>g@ vnoremap <silent> gC :<C-U>call Capitalize(visualmode(), 1)<CR> " delete search-register nnoremap <silent> <leader>/ :let @/ = ""<CR> " browse current buffer/selection in www-browser nnoremap <Leader>b :!x-www-browser %:p<CR>:echo "WWW-Browser started"<CR> vnoremap <Leader>b y:!x-www-browser <C-R>"<CR>:echo "WWW-Browser started"<CR> " lookup/translate inner/selected word in dictionary " recode is only needed for non-utf-8-text " nnoremap <Leader>T mayiw`a:exe "!dict -P - -- $(echo " . @" . "\| recode latin1..utf-8)"<CR> "nnoremap <Leader>t mayiw`a:exe "!dict -P - -- " . @"<CR> " vnoremap <Leader>T may`a:exe "!dict -P - -- $(echo " . @" . "\| recode latin1..utf-8)"<CR> "vnoremap <Leader>t may`a:exe "!dict -P - -- " . @"<CR> " delete words in insert mode like expected - doesn't work properly at " the end of the line inoremap <C-BS> <C-w> " Switch buffers nnoremap <silent> [b :ls<Bar>let nr = input("Buffer: ")<Bar>if nr != ''<Bar>exe ":b " . nr<Bar>endif<CR> " Search for the occurence of the word under the cursor nnoremap <silent> [I [I:le A: http://github.com/elventails/vim/blob/master/vimrc Has extras for CakePHP/PHP/Git enjoy! Will add nice options you guys are using to it and update the repo; Cheers, A: A lot of this comes from the wiki btw. set nocompatible source $VIMRUNTIME/mswin.vim behave mswin set nobackup set tabstop=4 set nowrap set guifont=Droid_Sans_Mono:h9:cANSI colorscheme torte set shiftwidth=4 set ic syn off set nohls set acd set autowrite noremap \c "+yy noremap \x "+dd noremap \t :tabnew<CR> noremap \2 I"<Esc>A"<Esc> noremap \3 bi'<Esc>ea'<Esc> noremap \" i"<Esc>ea"<Esc> noremap ?2 Bi"<Esc>Ea"<Esc> set matchpairs+=<:> nnoremap <C-N> :next<CR> nnoremap <C-P> :prev<CR> nnoremap <Tab> :bnext<CR> nnoremap <S-Tab> :bprevious<CR> nnoremap \w :let @/=expand("<cword>")<Bar>split<Bar>normal n<CR> nnoremap \W :let @/='\<'.expand("<cword>").'\>'<Bar>split<Bar>normal n<CR> autocmd FileType xml exe ":silent %!xmllint --format --recover - " autocmd FileType cpp set tabstop=2 shiftwidth=2 expandtab autoindent smarttab autocmd FileType sql set tabstop=2 shiftwidth=2 expandtab autoindent smarttab " Map key to toggle opt function MapToggle(key, opt) let cmd = ':set '.a:opt.'! \| set '.a:opt."?\<CR>" exec 'nnoremap '.a:key.' '.cmd exec 'inoremap '.a:key." \<C-O>".cmd endfunction command -nargs=+ MapToggle call MapToggle(<f-args>) map <F6> :if exists("syntax_on") <Bar> syntax off <Bar> else <Bar> syntax enable <Bar> endif <CR> " Display-altering option toggles MapToggle <F7> hlsearch MapToggle <F8> wrap MapToggle <F9> list " Behavior-altering option toggles MapToggle <F10> scrollbind MapToggle <F11> ignorecase MapToggle <F12> paste set pastetoggle=<F12> A: The super money part from my .vimrc is how it shows a "»" character each place there's a tab, and how it highlights "bad" whitespace in red. Bad whitespace is stuff like tabs in the middle of a line or invisible spaces at the end. syntax enable " Incremental search without highlighting. set incsearch set nohlsearch " Show ruler. set ruler " Try to keep 2 lines above/below the current line in view for context. set scrolloff=2 " Other file types. autocmd BufReadPre,BufNew *.xml set filetype=xml " Flag problematic whitespace (trailing spaces, spaces before tabs). highlight BadWhitespace term=standout ctermbg=red guibg=red match BadWhitespace /[^* \t]\zs\s\+$\| \+\ze\t/ " If using ':set list' show things nicer. execute 'set listchars=tab:' . nr2char(187) . '\ ' set list highlight Tab ctermfg=lightgray guifg=lightgray 2match Tab /\t/ " Indent settings for code: 4 spaces, do not use tab character. "set tabstop=4 shiftwidth=4 autoindent smartindent shiftround "autocmd FileType c,cpp,java,xml,python,cs setlocal expandtab softtabstop=4 "autocmd FileType c,cpp,java,xml,python,cs 2match BadWhitespace /[^\t]\zs\t/ set tabstop=8 shiftwidth=4 autoindent smartindent shiftround set expandtab softtabstop=4 2match BadWhitespace /[^\t]\zs\t\+/ " Automatically show matching brackets. set showmatch " Auto-complete file names after <TAB> like bash does. set wildmode=longest,list set wildignore=.svn,CVS,*.swp " Show current mode and currently-typed command. set showmode set showcmd " Use mouse if possible. " set mouse=a " Use Ctrl-N and Ctrl-P to move between files. nnoremap <C-N> :confirm next<Enter> nnoremap <C-P> :confirm prev<Enter> " Confirm saving and quitting. set confirm " So yank behaves like delete, i.e. Y = D. map Y y$ " Toggle paste mode with F5. set pastetoggle=<F5> " Don't exit visual mode when shifting. vnoremap < <gv vnoremap > >gv " Move up and down by visual lines not buffer lines. nnoremap <Up> gk vnoremap <Up> gk nnoremap <Down> gj vnoremap <Down> gj A: I can't live without TAB Completion " Intelligent tab completion inoremap <silent> <Tab> <C-r>=<SID>InsertTabWrapper(1)<CR> inoremap <silent> <S-Tab> <C-r>=<SID>InsertTabWrapper(-1)<CR> function! <SID>InsertTabWrapper(direction) let idx = col('.') - 1 let str = getline('.') if a:direction > 0 && idx >= 2 && str[idx - 1] == ' ' \&& str[idx - 2] =~? '[a-z]' if &softtabstop && idx % &softtabstop == 0 return "\<BS>\<Tab>\<Tab>" else return "\<BS>\<Tab>" endif elseif idx == 0 || str[idx - 1] !~? '[a-z]' return "\<Tab>" elseif a:direction > 0 return "\<C-p>" else return "\<C-n>" endif endfunction A: I made a function that automatically sends your text to a private pastebin. let g:pfx='' " prefix for private pastebin. function PBSubmit() python << EOF import vim import urllib2 as url import urllib pfx = vim.eval( 'g:pfx' ) URL = 'http://' if pfx == '': URL += 'pastebin.com/pastebin.php' else: URL += pfx + '.pastebin.com/pastebin.php' data = urllib.urlencode( { 'code2': '\n'.join( vim.current.buffer ).decode( 'utf-8' ).encode( 'latin-1' ), 'email': '', 'expiry': 'd', 'format': 'text', 'parent_pid': '', 'paste': 'Send', 'poster': '' } ) url.urlopen( URL, data ) print 'Submitted to ' + URL EOF endfunction map <Leader>pb :call PBSubmit()<CR> A: My favorite bit of my .vimrc is a set of mappings for working with macros: nnoremap <Leader>qa mqGo<Esc>"ap nnoremap <Leader>qb mqGo<Esc>"bp nnoremap <Leader>qc mqGo<Esc>"cp <SNIP> nnoremap <Leader>qz mqGo<Esc>"zp nnoremap <Leader>Qa G0"ad$dd'q nnoremap <Leader>Qb G0"bd$dd'q nnoremap <Leader>Qc G0"cd$dd'q <SNIP> nnoremap <Leader>Qz G0"zd$dd'q With this \q[a-z] will mark your location, and print the contents of the given register at the bottom of the current file and \Q[a-z] will put the contents of the last line into the given register and go back to your marked location. Makes it really easy to edit a macro or copy and tweak one macro into a new register. A: My .vimrc, the plugins i use and other tweaks are customized to help me with the tasks i preform most frequently: * *Use Mutt/Vim to read/write emails *Write C code under GNU/Linux, usually with glib, gobject, gstreamer *Browse/Read C source code *Work with Python, Ruby on Rails or Bash scripts *Develop web applications with HTML, Javascript, CSS I have some more info about my Vim configuration here A: Some of my favorite customizations that I haven't found to be all too common: " Windows *********************************************************************" set equalalways " Multiple windows, when created, are equal in size" set splitbelow splitright " Put the new windows to the right/bottom" " Insert new line in command mode *********************************************" map <S-Enter> O<ESC> " Insert above current line" map <Enter> o<ESC> " Insert below current line" " After selecting something in visual mode and shifting, I still want that" " selection intact ************************************************************" vmap > >gv vmap < <gv A: I have this in my ~/.vim/after/syntax/vim.vim file: What it does is: * *highlights the word blue in the color blue *highlights the wrod red in the color red *etc Ie: so if you go: highlight JakeRedKeywords cterm=bold term=bold ctermbg=black ctermfg=Red The word red will be red and the word black will be black. Here is the code: syn cluster vimHiCtermColors contains=vimHiCtermColorBlack,vimHiCtermColorBlue,vimHiCtermColorBrown,vimHiCtermColorCyan,vimHiCtermColorDarkBlue,vimHiCtermColorDarkcyan,vimHiCtermColorDarkgray,vimHiCtermColorDarkgreen,vimHiCtermColorDarkgrey,vimHiCtermColorDarkmagenta,vimHiCtermColorDarkred,vimHiCtermColorDarkyellow,vimHiCtermColorGray,vimHiCtermColorGreen,vimHiCtermColorGrey,vimHiCtermColorLightblue,vimHiCtermColorLightcyan,vimHiCtermColorLightgray,vimHiCtermColorLightgreen,vimHiCtermColorLightgrey,vimHiCtermColorLightmagenta,vimHiCtermColorLightred,vimHiCtermColorMagenta,vimHiCtermColorRed,vimHiCtermColorWhite,vimHiCtermColorYellow syn case ignore syn keyword vimHiCtermColorYellow yellow contained syn keyword vimHiCtermColorBlack black contained syn keyword vimHiCtermColorBlue blue contained syn keyword vimHiCtermColorBrown brown contained syn keyword vimHiCtermColorCyan cyan contained syn keyword vimHiCtermColorDarkBlue darkBlue contained syn keyword vimHiCtermColorDarkcyan darkcyan contained syn keyword vimHiCtermColorDarkgray darkgray contained syn keyword vimHiCtermColorDarkgreen darkgreen contained syn keyword vimHiCtermColorDarkgrey darkgrey contained syn keyword vimHiCtermColorDarkmagenta darkmagenta contained syn keyword vimHiCtermColorDarkred darkred contained syn keyword vimHiCtermColorDarkyellow darkyellow contained syn keyword vimHiCtermColorGray gray contained syn keyword vimHiCtermColorGreen green contained syn keyword vimHiCtermColorGrey grey contained syn keyword vimHiCtermColorLightblue lightblue contained syn keyword vimHiCtermColorLightcyan lightcyan contained syn keyword vimHiCtermColorLightgray lightgray contained syn keyword vimHiCtermColorLightgreen lightgreen contained syn keyword vimHiCtermColorLightgrey lightgrey contained syn keyword vimHiCtermColorLightmagenta lightmagenta contained syn keyword vimHiCtermColorLightred lightred contained syn keyword vimHiCtermColorMagenta magenta contained syn keyword vimHiCtermColorRed red contained syn keyword vimHiCtermColorWhite white contained syn keyword vimHiCtermColorYellow yellow contained syn match vimHiCtermFgBg contained "\ccterm[fb]g="he=e-1 nextgroup=vimNumber,@vimHiCtermColors,vimFgBgAttrib,vimHiCtermError highlight vimHiCtermColorBlack ctermfg=black ctermbg=white highlight vimHiCtermColorBlue ctermfg=blue highlight vimHiCtermColorBrown ctermfg=brown highlight vimHiCtermColorCyan ctermfg=cyan highlight vimHiCtermColorDarkBlue ctermfg=darkBlue highlight vimHiCtermColorDarkcyan ctermfg=darkcyan highlight vimHiCtermColorDarkgray ctermfg=darkgray highlight vimHiCtermColorDarkgreen ctermfg=darkgreen highlight vimHiCtermColorDarkgrey ctermfg=darkgrey highlight vimHiCtermColorDarkmagenta ctermfg=darkmagenta highlight vimHiCtermColorDarkred ctermfg=darkred highlight vimHiCtermColorDarkyellow ctermfg=darkyellow highlight vimHiCtermColorGray ctermfg=gray highlight vimHiCtermColorGreen ctermfg=green highlight vimHiCtermColorGrey ctermfg=grey highlight vimHiCtermColorLightblue ctermfg=lightblue highlight vimHiCtermColorLightcyan ctermfg=lightcyan highlight vimHiCtermColorLightgray ctermfg=lightgray highlight vimHiCtermColorLightgreen ctermfg=lightgreen highlight vimHiCtermColorLightgrey ctermfg=lightgrey highlight vimHiCtermColorLightmagenta ctermfg=lightmagenta highlight vimHiCtermColorLightred ctermfg=lightred highlight vimHiCtermColorMagenta ctermfg=magenta highlight vimHiCtermColorRed ctermfg=red highlight vimHiCtermColorWhite ctermfg=white highlight vimHiCtermColorYellow ctermfg=yellow A: Here's mine ! Thanks for sharing. You can find other stuff about vim plugins here: http://github.com/ametaireau/dotfiles/ Hope it helps. " My .vimrc configuration file. " ============================= " " Plugins " ------- " Comes with a set of utilities to enhance the user experience. " Django and python snippets are possible thanks to the snipmate " plugin. " " A also uses taglist and NERDTree vim plugins. " " Shortcuts " ---------- " Here are some shortcuts I like to use when editing text using VIM: " " <alt-left/right> to navigate trough tabs " <ctrl-e> to display the explorator " <ctrl-p> for the code explorator " <ctrl-space> to autocomplete " <ctrl-n> enter tabnew to open a new file " <alt-h> highlight the lines of more than 80 columns " <ctrl-h> set textwith to 80 cols " <maj-k> when on a python file, open the related pydoc documentation " ,v and ,V to show/edit and reload the vimrc configuration file colorscheme evening syntax on " syntax highlighting filetype on " to consider filetypes ... filetype plugin on " ... and in plugins set directory=~/.vim/swp " store the .swp files in a specific path set expandtab " enter spaces when tab is pressed set tabstop=4 " use 4 spaces to represent tab set softtabstop=4 set shiftwidth=4 " number of spaces to use for auto indent set autoindent " copy indent from current line on new line set number " show line numbers set backspace=indent,eol,start " make backspaces more powerful set ruler " show line and column number set showcmd " show (partial) command in status line set incsearch " highlight search set noignorecase set infercase set nowrap " shortcuts map <c-n> :tabnew map <silent><c-e> :NERDTreeToggle <cr> map <silent><c-p> :TlistToggle <cr> nnoremap <a-right> gt nnoremap <a-left> gT command W w !sudo tee % > /dev/null map <buffer> K :execute "!pydoc " . expand("<cword>")<CR> map <F2> :set textwidth=80 <cr> " Replace trailing slashes map <F3> :%s/\s\+$//<CR>:exe ":echo'trailing slashes removes'"<CR> map <silent><F6> :QFix<CR> " edit vim quickly map ,v :sp ~/.vimrc<CR><C-W>_ map <silent> ,V :source ~/.vimrc<CR>:filetype detect<CR>:exe ":echo'vimrc reloaded'"<CR> " configure expanding of tabs for various file types au BufRead,BufNewFile *.py set expandtab au BufRead,BufNewFile *.c set noexpandtab au BufRead,BufNewFile *.h set noexpandtab au BufRead,BufNewFile Makefile* set noexpandtab " remap CTRL+N to CTRL + space inoremap <Nul> <C-n> " Omnifunc completers autocmd FileType python set omnifunc=pythoncomplete#Complete " Tlist configuration let Tlist_GainFocus_On_ToggleOpen = 1 let Tlist_Close_On_Select = 0 let Tlist_Auto_Update = 1 let Tlist_Process_File_Always = 1 let Tlist_Use_Right_Window = 1 let Tlist_WinWidth = 40 let Tlist_Show_One_File = 1 let Tlist_Show_Menu = 0 let Tlist_File_Fold_Auto_Close = 0 let Tlist_Ctags_Cmd = '/usr/bin/ctags' let tlist_css_settings = 'css;e:SECTIONS' " NerdTree configuration let NERDTreeIgnore = ['\.pyc$', '\.pyo$'] " Highlight more than 80 columns lines on demand nnoremap <silent><F1> \ :if exists('w:long_line_match') <Bar> \ silent! call matchdelete(w:long_line_match) <Bar> \ unlet w:long_line_match <Bar> \ elseif &textwidth > 0 <Bar> \ let w:long_line_match = matchadd('ErrorMsg', '\%>'.&tw.'v.\+', -1) <Bar> \ else <Bar> \ let w:long_line_match = matchadd('ErrorMsg', '\%>80v.\+', -1) <Bar> \ endif<CR> command -bang -nargs=? QFix call QFixToggle(<bang>0) function! QFixToggle(forced) if exists("g:qfix_win") && a:forced == 0 cclose unlet g:qfix_win else copen 10 let g:qfix_win = bufnr("$") endif endfunction A: "{{{1 Защита от множественных загрузок if exists("b:dollarHOMEslashdotvimrcFileLoaded") finish endif let b:dollarHOMEslashdotvimrcFileLoaded=1 " set t_Co=8 " set t_Sf=[3%p1%dm " set t_Sb=[4%p1%dm "{{{1 Options "{{{2 set set nocompatible set background=dark set display+=lastline "set iminsert=0 "set imsearch=0 set grepprg=grep\ -nH\ $* set expandtab set tabstop=4 set shiftwidth=4 set softtabstop=4 set backspace=indent,eol,start set autoindent set nosmartindent set backup set conskey set bioskey set browsedir=buffer " bomb may work bad set nobomb exe "set backupdir=".$HOME."/.vimbackup,." set backupext=~ set history=32 set ruler set showcmd set hlsearch set incsearch set nocindent set textwidth=80 set complete=.,i,d,t,w,b,u,k " set conskey set noconfirm set cscopetag set cscopetagorder=1 " set copyindent " !may be not safe set exrc set secure " set foldclose set noswapfile " set swapsync=sync set fsync set guicursor="a:block-blinkoff0" set autowriteall set hidden set nojoinspaces set nostartofline " set virtualedit+=onemore set lazyredraw set visualbell set makeef=make.##.err.log set modelines=16 set more set virtualedit+=block set winaltkeys=no set fileencodings=utf-8,cp1251,koi8-r,default set encoding=utf-8 set list set listchars=tab:>-,trail:-,nbsp:_ set magic set pastetoggle=<F1> set foldmethod=marker set wildmenu set wildcharm=<Tab> set formatoptions=arcoqn12w "set formatoptions+=t set scrolloff=2 "{{{3 define keys "{{{4 get keys from zkbd if isdirectory($HOME."/.zkbd") && \filereadable($HOME."/.zkbd/".$TERM."-pc-linux-gnu") let s:keys=split(system("cat ". \shellescape($HOME."/.zkbd/".$TERM."-pc-linux-gnu"). \" | grep \"^key\\\\[\" | ". \"sed -re \"s/^key\\\\[([[:alnum:]]*)\\\\]='(.*)'\\$". \"/\\\\1=\\\\2/g\""), "\\n") for key in s:keys let tmp=split(key, "=") if tmp[0]=~"^F\\d\\+$" execute "set <".tmp[0].">=". \substitute(tmp[1], "\\^\\[", "\<ESC>", "g") endif endfor endif " function g:DefineKeys() "{{{4 screen if 0 && $_SECONDLAUNCH set <F1>=[11~ set <F2>=[12~ set <F3>=[13~ set <F4>=[14~ set <F5>=[15~ set <F6>=[17~ set <F7>=[18~ set <F8>=[19~ set <F9>=[20~ set <F10>=[21~ set <F11>=[23~ set <F12>=[24~ set <S-F1>=[23~ set <S-F2>=[24~ set <S-F3>=[25~ set <S-F4>=[26~ set <S-F5>=[28~ set <S-F6>=[29~ set <S-F7>=[31~ set <S-F8>=[32~ set <S-F9>=[33~ set <S-F10>=[34~ set <S-F11>=[23$ set <S-F12>=[24$ set <HOME>=[7~ set <END>=[8~ "{{{4 xterm elseif $TERM=="xterm" set <M-a>=a set <M-b>=b set <M-c>=c set <M-d>=d set <M-e>=e set <M-f>=f set <M-g>=g set <M-h>=h set <M-i>=i set <M-j>=j set <M-k>=k set <M-l>=l set <M-m>=m set <M-n>=n set <M-o>=o set <M-p>=p set <M-q>=q set <M-r>=r set <M-s>=s set <M-t>=t set <M-u>=u set <M-v>=v set <M-w>=w set <M-x>=x set <M-y>=y set <M-z>=z "set <M-SPACE>= "set <Left>=OD "set <S-Left>=O2D "set <C-Left>=O5D "set <Right>=OC "set <S-Right>=O2C "set <C-Right>=O5C "set <Up>=OA "set <S-Up>=O2A "set <C-Up>=O5A "set <Down>=OB "set <S-Down>=O2B "set <C-Down>=O5B set <F1>=[11~ set <F2>=[12~ set <F3>=[13~ set <F4>=[14~ set <F5>=[15~ set <F6>=[17~ set <F7>=[18~ set <F8>=[19~ set <F9>=[20~ set <F10>=[21~ set <F11>=[23~ set <F12>=[24~ "set <C-F1>= "set <C-F2>= "set <C-F3>= "set <C-F4>= "set <C-F5>=[15;5~ "set <C-F6>=[17;5~ " "set <C-F7>=[18;5~ "set <C-F8>=[19;5~ "set <C-F9>=[20;5~ "set <C-F10>=[21;5~ "set <C-F11>=[23;5~ "set <C-F12>=[24;5~ set <S-F1>=[11;2~ set <S-F2>=[12;2~ set <S-F3>=[13;2~ set <S-F4>=[14;2~ set <S-F5>=[15;2~ set <S-F6>=[17;2~ set <S-F7>=[18;2~ set <S-F8>=[19;2~ set <S-F9>=[20;2~ set <S-F10>=[21;2~ set <S-F11>=[23;2~ set <S-F12>=[24;2~ set <END>=OF set <S-END>=O2F set <S-HOME>=O2H set <HOME>=OH set <DEL>= " set <PageUp>=[5~ " set <PageDown>=[6~ " noremap <DEL> " inoremap <DEL> " cnoremap <DEL> set <S-Del>=[3;2~ " set <C-Del>=[3;5~ " set <M-Del>=[3;3~ "{{{4 rxvt --- aterm elseif $TERM=="rxvt" set <M-a>=a set <M-b>=b set <M-c>=c set <M-d>=d set <M-e>=e set <M-f>=f set <M-g>=g set <M-h>=h set <M-i>=i set <M-j>=j set <M-k>=k set <M-l>=l set <M-m>=m set <M-n>=n set <M-o>=o set <M-p>=p set <M-q>=q set <M-r>=r set <M-s>=s set <M-t>=t set <M-u>=u set <M-v>=v set <M-w>=w set <M-x>=x set <M-y>=y set <M-z>=z set <F1>=OP set <F2>=OQ set <F3>=OR set <F4>=OS set <F5>=[15~ set <F6>=[17~ set <F7>=[18~ set <F8>=[19~ set <F9>=[20~ set <F10>=[21~ set <F11>=[23~ set <F12>=[24~ set <S-F1>=[23~ set <S-F2>=[24~ set <S-F3>=[25~ set <S-F4>=[26~ set <S-F5>=[28~ set <S-F6>=[29~ set <S-F7>=[31~ set <S-F8>=[32~ set <S-F9>=[33~ set <S-F10>=[34~ set <S-F11>=[23$ set <S-F12>=[24$ " set <C-S-F2>=[24^ " set <C-S-F3>=[25^ " set <C-S-F4>=[26^ " set <C-S-F5>=[28^ " set <C-S-F6>=[29^ " set <C-S-F7>=[31^ " set <C-S-F8>=[32^ " set <C-S-F9>=[33^ " set <C-S-F10>=[34^ " set <C-S-F11>=[23@ " set <C-S-F12>=[24@ " set <M-F5>=<F5> " set <M-F6>=<F6> " set <M-F7>=<F7> " set <M-F8>=<F8> " set <M-F9>=<F9> " set <M-F10>=<F10> " set <M-F11>=<F11> " set <M-F12>=<F12> " set <M-S-F5>=<S-F5> " set <M-S-F6>=<S-F6> " set <M-S-F7>=<S-F7> " set <M-S-F8>=<S-F8> " set <M-S-F9>=<S-F9> " set <M-S-F10>=<S-F10> " set <M-S-F11>=<S-F11> " set <M-S-F12>=<S-F12> "{{{4 rxvt-unicode --- urxvt elseif $TERM=="rxvt-unicode" set <M-a>=a set <M-b>=b set <M-c>=c set <M-d>=d set <M-e>=e set <M-f>=f set <M-g>=g set <M-h>=h set <M-i>=i set <M-j>=j set <M-k>=k set <M-l>=l set <M-m>=m set <M-n>=n set <M-o>=o set <M-p>=p set <M-q>=q set <M-r>=r set <M-s>=s set <M-t>=t set <M-u>=u set <M-v>=v set <M-w>=w set <M-x>=x set <M-y>=y set <M-z>=z set <F1>=[11~ set <F2>=[12~ set <F3>=[13~ set <F4>=[14~ set <F5>=[15~ set <F6>=[17~ set <F7>=[18~ set <F8>=[19~ set <F9>=[20~ set <F10>=[21~ set <F11>=[23~ set <F12>=[24~ " fluxbox!<<<<<<<<<<<<<<<<<<<<<<<<<<<<< set <S-F1>=[23~ set <S-F2>=[24~ set <S-F3>=[25~ set <S-F4>=[26~ set <S-F5>=[28~ set <S-F6>=[29~ set <S-F7>=[31~ set <S-F8>=[32~ set <S-F9>=[33~ set <S-F10>=[34~ set <S-F11>=[23$ set <S-F12>=[24$ " set <C-F1>=[11^ " set <C-F2>=[12^ " set <C-F3>=[13^ " set <C-F4>=[14^ " set <C-F5>=[15^ " set <C-F6>=[17^ " set <C-F7>=[18^ " set <C-F8>=[19^ " set <C-F9>=[20^ " set <C-F10>=[21^ " set <C-F11>=[23^ " set <C-F12>=[24^ " openbox!<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " set <S-F1>=[23~ " set <S-F2>=[24~ " set <S-F3>=[25~ " set <S-F4>=[26~ " set <S-F5>=[28~ " set <S-F6>=[29~ " set <S-F7>=[31~ " set <S-F8>=[32~ " set <S-F9>=[33~ " set <S-F10>=[34~ " set <S-F11>=[23$ " set <S-F12>=[24$ " set <C-S-F2>=[24^ " set <C-S-F3>=[25^ " set <C-S-F4>=[26^ " set <C-S-F5>=[28^ " set <C-S-F6>=[29^ " set <C-S-F7>=[31^ " set <C-S-F8>=[32^ " set <C-S-F9>=[33^ " set <C-S-F10>=[34^ " set <C-S-F11>=[23@ " set <C-S-F12>=[24@ " set <M-F5>=<F5> " set <M-F6>=<F6> " set <M-F7>=<F7> " set <M-F8>=<F8> " set <M-F9>=<F9> " set <M-F10>=<F10> " set <M-F11>=<F11> " set <M-F12>=<F12> " set <M-S-F5>=<S-F5> " set <M-S-F6>=<S-F6> " set <M-S-F7>=<S-F7> " set <M-S-F8>=<S-F8> " set <M-S-F9>=<S-F9> " set <M-S-F10>=<S-F10> " set <M-S-F11>=<S-F11> " set <M-S-F12>=<S-F12> endif " autocmd! DefineKeys " endfunction " "{{{4 autocmd " augroup DefineKeys " autocmd BufEnter * call g:DefineKeys() " augroup END "{{{2 filetipe filetype plugin indent on syntax on "{{{2 let "{{{ NERDCommenter let NERDShutUp=1 let NERDSpaceDelims=1 "}}} let g:c_syntax_for_h=1 let g:xml_syntax_folding=1 let paste_mode=0 " 0 = normal, 1 = paste "{{{3 keys if $TERM=="rxvt-unicode" " " fluxbox!<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " let g:C_F1="\<ESC>[11^" " let g:C_F2="\<ESC>[12^" " let g:C_F3="\<ESC>[13^" " let g:C_F4="\<ESC>[14^" " let g:C_F5="\<ESC>[15^" " let g:C_F6="\<ESC>[17^" " let g:C_F7="\<ESC>[18^" " let g:C_F8="\<ESC>[19^" " let g:C_F9="\<ESC>[20^" " let g:C_F10="\<ESC>[21^" " let g:C_F11="\<ESC>[23^" " let g:C_F12="\<ESC>[24^" " let g:M_S_F1="\<ESC>\<ESC>[23$" " let g:M_S_F2="\<ESC>\<ESC>[24$" " let g:M_S_F3="\<ESC>\<ESC>[25$" " let g:M_S_F4="\<ESC>\<ESC>[26$" " let g:M_S_F5="\<ESC>\<ESC>[28$" " let g:M_S_F6="\<ESC>\<ESC>[29$" " let g:M_S_F7="\<ESC>\<ESC>[31$" " let g:M_S_F8="\<ESC>\<ESC>[32$" " let g:M_S_F9="\<ESC>\<ESC>[33$" " let g:M_S_F10="\<ESC>\<ESC>[34$" " let g:M_S_F11="\<ESC>\<ESC>[23$" " let g:M_S_F12="\<ESC>\<ESC>[24$" " let g:M_C_F1="\<ESC>\<ESC>[11^" " let g:M_C_F2="\<ESC>\<ESC>[12^" " let g:M_C_F3="\<ESC>\<ESC>[13^" " let g:M_C_F4="\<ESC>\<ESC>[14^" " let g:M_C_F5="\<ESC>\<ESC>[15^" " let g:M_C_F6="\<ESC>\<ESC>[17^" " let g:M_C_F7="\<ESC>\<ESC>[18^" " let g:M_C_F8="\<ESC>\<ESC>[19^" " let g:M_C_F9="\<ESC>\<ESC>[20^" " let g:M_C_F10="\<ESC>\<ESC>[21^" " let g:M_C_F11="\<ESC>\<ESC>[23^" " let g:M_C_F12="\<ESC>\<ESC>[24^" " endif "{{{3 Настройки :TOhtml let html_number_lines=1 " let html_ignore_folding=1 let html_use_css=1 let html_no_pre=0 let use_xhtml=1 "{{{3 Предотвратить загрузку let loaded_cmdalias=0 "{{{3 Mine " let g:kmaps={"en": "", "ru": "russian-dvp"} "{{{1 Syntax highlight TooLongLine term=reverse ctermfg=Yellow ctermbg=Red 2match TooLongLine /\S\%>81v/ "{{{1 Autocommands autocmd VimLeavePre * silent mksession! ~/.vim/lastSession.vim au BufWritePost * if getline(1) =~ "^#!" | execute "silent! !chmod a+x %" | \endif autocmd BufRead,BufWinEnter * let &l:modifiable=(!(&ro && !&bt=="quickfix")) "{{{1 Digraphs digraphs ca 94 "^ digraphs ga 96 "` digraphs ti 126 "~ "{{{1 Menus " menu Encoding.koi8-r :e ++enc=8bit-koi8-r<CR> " menu Encoding.windows-1251 :e ++enc=8bit-cp1251<CR> " menu Encoding.ibm-866 :e ++enc=8bit-ibm866<CR> " menu Encoding.utf-8 :e ++enc=2byte-utf-8<CR> " menu Encoding.ucs-2le :e ++enc=ucs-2le<CR> "{{{1 Команды function s:Substitute(sstring, line1, line2) execute a:line1.",".a:line2."!perl -pi -e 'use encoding \"utf8\"; s'". \escape(shellescape(a:sstring), '%!'). \" 2>/dev/null" endfunction command -range=% -nargs=+ S call s:Substitute(<q-args>, <line1>, <line2>) "{{{1 Mappings "{{{2 Menu mappings "{{{2 function mappings " "{{{3 Function Eatchar function Eatchar(pat) let l:pat=((a:pat=="")?("*"):(a:pat)) let c = nr2char(getchar(0)) return (c =~ l:pat) ? '' : c endfunction "{{{3 CleverTab - tab to autocomplete and move indent function CleverTab() if strpart( getline('.'), col('.')-2, 1) =~ '^\k$' return "\<C-n>" else return "\<Tab>" endif endfunction inoremap <Tab> <C-R>=CleverTab()<CR> "{{{3 Keymap switch function! SwitchKeymap(kmaps, knum) let s:kmapvals=values(a:kmaps) if a:knum=="+" let s:ki=index(s:kmapvals, &keymap) echo s:ki if s:ki==-1 let &keymap=s:kmapvals[0] return elseif s:ki>=len(a:kmaps)-1 let &keymap=s:kmapvals[0] return endif let &keymap=s:kmapvals[s:ki+1] return elseif has_key(a:kmaps, a:knum) let &keymap=a:kmaps[a:knum] return endif let s:ki=0 for val in s:kmapvals if s:ki==a:knum let &keymap=val return endif let s:ki+=1 endfor let &keymap=s:kmapvals[0] endfunction " inoremap <S-Tab> <C-\><C-o>:call<SPACE>SwitchKeymap(g:kmaps,<SPACE>"+")<C-m> "{{{2 ToggleVerbose function! ToggleVerbose() let g:verboseflag = !g:verboseflag if g:verboseflag exe "set verbosefile=".$HOME."/.logs/vim/verbose.log set verbose=15 else set verbose=0 set verbosefile= endif endfunction noremap <F4>sv :call<SPACE>ToggleVerbose() inoremap <F4>sv <C-o>:call<SPACE>ToggleVerbose() "{{{2 Other mappings "{{{3 <.*F12> mappings - for some browsing noremap <F12> :TlistToggle<CR> inoremap <F12> <C-O>:TlistToggle<CR> inoremap <S-F12> <C-O>:BufExplorer<CR> noremap <S-F12> :BufExplorer<CR> inoremap <M-F12> <C-O>:NERDTreeToggle<CR> noremap <M-F12> :NERDTreeToggle<CR> "{{{3 yank/paste vnoremap <C-Insert> "+y nnoremap <S-Insert> "+p inoremap <S-Insert> <C-o><S-Insert> vnoremap p "_da<C-r><C-r>"<CR><ESC> "{{{3 Motions "{{{4 Left/Right replace cnoremap <C-b> <Left> cnoremap <C-f> <Right> inoremap <C-b> <C-\><C-o>h inoremap <C-f> <C-o>a cnoremap <M-b> <C-Right> inoremap <M-b> <C-o>w inoremap <M-f> <C-o>b cnoremap <M-f> <C-Left> "{{{4 Page Up/Down nnoremap <C-b> <C-U><C-U> inoremap <PageUp> <C-O><C-U><C-O><C-U> nnoremap <C-f> <C-D><C-D> inoremap <PageDown> <C-O><C-D><C-O><C-D> "{{{4 Up/Down inoremap <C-G> <C-\><C-o>gk inoremap <Up> <C-\><C-o>gk inoremap <Down> <C-\><C-o>gj inoremap <C-l> <C-\><C-o>gj nnoremap <Down> gj vnoremap <Down> gj nnoremap j gj vnoremap j gj nnoremap gj j vnoremap gj j nnoremap gk k vnoremap gk k nnoremap k gk vnoremap k gk nnoremap <Up> gk vnoremap <Up> gk "{{{4 Smart <HOME> and <END> " imap <HOME> <C-o>g^ " imap <C-O>g^<HOME> <C-o>^ " inoremap <C-o>^<HOME> <C-o>0 " imap <END> <C-o>g$ " inoremap <C-o>g$<END> <C-o>$ " nmap <HOME> <C-o>g^ " nmap <C-O>g^<HOME> ^ " nnoremap <C-o>^<HOME> 0 " nmap <END> g$ " nnoremap <C-o>g$<END> $ "{{{3 <F3> and searching noremap <F3> :nohl<CR> inoremap <S-F3> <C-o>:nohl<CR> inoremap <F3> <C-o>n "{{{3 <F2> for saving, <F10> for exiting noremap <F2> :up<CR> inoremap <F2> <C-o>:up<CR> inoremap <F10> <ESC>ZZ noremap <F10> <ESC>ZZ inoremap <S-F10> <ESC>:q!<CR> noremap <S-F10> :q!<CR> inoremap <C-F10> <ESC>:silent<SPACE>mksession<SPACE>session.vim<CR>:wq! noremap <C-F10> :silent<SPACE>mksession<SPACE>session.vim<CR>:wq! "{{{3 Something inoremap <C-z> <C-o>u noremap <F1> :set paste!<C-m> inoremap <C-^> <C-O><C-^> inoremap <C-d> <Del> cnoremap <C-d> <Del> "{{{3 <C-j> inoremap <C-j>j <C-o>:bn<CR> inoremap <C-j>J <C-o>:bN<CR> noremap <C-j>j :bn<CR> noremap <C-j>J :bN<CR> "{{{3 for visual inoremap <S-Left> <C-o>vge inoremap <S-Up> <C-o>vk inoremap <S-Down> <C-o>vj inoremap <S-Right> <C-o>ve inoremap <S-End> <C-o>v$ inoremap <S-Home> <C-o>v$o^ vnoremap A <C-c>i "{{{3 <F4> "{{{4 <F4> folds noremap <F4>{ a{{{<ESC> inoremap <F4>{ {{{ noremap <F4>} a}}}<ESC> inoremap <F4>} }}} inoremap <F4>[ <C-o>o{{{<C-o>:call NERDComment(0,"norm")<C-m> noremap <F4>[ o{{{<C-o>:call NERDComment(0,"norm")<C-m> inoremap <F4>] <C-o>o}}}<C-o>:call NERDComment(0,"norm")<C-m> noremap <F4>] o}}}<C-o>:call NERDComment(0,"norm")<C-m> "{{{4 <F4> folds inoremap <F4>f <C-o>za<C-o>j<C-o>^ noremap <F4>f zaj "{{{4 <F4> yank/paste/delete inoremap <F4>p <C-o>p inoremap <F4>gp <C-o>"+p inoremap <F4>y( <C-o>ya) inoremap <F4>yl <C-o>yy inoremap <F4>gy( <C-o>"+ya) inoremap <F4>gyl <C-o>"+yy inoremap <F4>P <C-o>P inoremap <F4>d( <C-o>da) inoremap <F4>dl <C-o>dd "{{{4 <F4> frequently used expressions inoremap <F4>c \033[m<C-/><C-o>h "{{{4 <F4> alternate imap <F4>a <C-o>:A<C-m> map <F4>a :A<C-m> "}}} "}}} "{{{3 «,» " " &lower " &upper " &1st " &2nd " &both lower and upper (or both 1st and 2nd) " prefixed with &e " prefixed with &E " is &Prefix for smth " &prefixed with (([what]p(prefix))) " -: nothing " +: added " /: replaced " [invc]: for modes insert, normal, visual, command (for insert mode if " omitted) " | vimrc | | | | | " | i n v c | tex | c | html | vim | other " ----+-----------------+--------+--------+-------+-------+--------------------- " a | l l | | | | | " b | b - - b | +Pu | +eb+Eb | | | " c | l b | +u | | | | " d | b b b | | | | | " e | Pl Pl | | +l+Pu | | | " f | b(eb) - - b | | | | /u | zsh:+el " g | | | | | | " h | b(el) - - b(el) | /u | | | | sh:/u+eu " i | l l - l | | | | | " j | | | | | | " k | | | | | | " l | l | +Pu | | | | make:+u " m | l l | /[in]m | +u | | | " n | l | /l+u | | /l | /l | " o | l | | | | | " p | - - - b | +el | | | | " q | b(eb) | +Pl | | | | " r | | +u | | | | " s | l(el) - - b | +u | +u | | +u+eu | make,perl,zsh:+u " t | b(el) - - l | +eu | | | | " u | l - - b | | | +u | +u | " v | | | | | | " w | b - - b | | | | | " x | | | | | | " y | l l l | | | | | " z | | | | | | " ' " | b | /b | | | | " ; : | 1 | | | | | " , . | b 2 - 1 | | | +e2 | | " ? ! | | | | | | " < > | | +b | | +b+eb | +1 | " - _ | | +1 | | +b | | " @ / | b | | | | | " = | | | | | | " "{{{4 insert inoremap ,<SPACE> ,<SPACE> inoremap ,<Esc> , inoremap ,<BS> <Nop> inoremap ,ef <C-o>I{<C-m><C-o>o}<C-o>O inoremap ,eF <C-m>{<C-m><C-o>o}<C-o>O inoremap ,F {<C-o>o}<C-o>O inoremap ,f {}<C-\><C-o>h inoremap ,h []<C-\><C-o>h inoremap ,s ()<C-\><C-o>h inoremap ,u <LT>><C-\><C-o>h inoremap ,es (<C-\><C-o>E<C-o>a)<C-\><C-o>h inoremap ,H [[::]]<C-o>F: inoremap ,eh [::]<C-o>F: inoremap ,, \ inoremap ,. <C-o>== inoremap ,w <C-o>w inoremap ,W <C-o>W inoremap ,b <C-o>b inoremap ,B <C-o>B inoremap ,a <C-o>A inoremap ,i <C-o>I inoremap ,l <C-o>o inoremap ,o <C-o>O inoremap ,dw <C-o>"zdaw inoremap ,p <C-o>"zp inoremap ,P <C-o>"zP inoremap ,yw <C-o>"zyaw inoremap ,y <C-o>"zy inoremap ,d <C-o>"zd inoremap ,D <C-o>"_d inoremap ,c <C-o>:call<SPACE>NERDComment(0,"toggle")<C-m> inoremap ,ec <C-o>:call<SPACE>NERDComment(0,"toEOL")<C-m> inoremap ,t <C-r>=Tr3transliterate(input("Translit: "))<C-m> inoremap ,T <C-o>b<C-o>"tdiw<C-r><C-r>=Tr3transliterate(@t)<C-m> inoremap ,et <C-o>B<C-o>"tdiW<C-r><C-r>=Tr3transliterate(@t)<C-m> inoremap ,/ <C-x><C-f> inoremap ,@ <C-o>:w!<C-m> inoremap ,; <C-o>% inoremap ,m <C-\><C-o>:call system("make &")<C-m> inoremap ,n \<C-m> inoremap ,q «»<C-\><C-o>h inoremap ,Q „“<C-\><C-o>h inoremap ,eq “”<C-\><C-o>h inoremap ,eQ ‘’<C-\><C-o>h inoremap ," ""<C-\><C-o>h inoremap ,' ''<C-\><C-o>h "{{{4 visual vnoremap ,y "zy vnoremap ,d "zd vnoremap ,D "_d vnoremap ,p "zp "{{{4 command cnoremap ,s ()<Left> cnoremap ,S \(\)<Left><Left> cnoremap ,U \<LT>\><Left><Left> cnoremap ,u <LT>><Left> cnoremap ,F \{}<Left> cnoremap ,f {}<Left> cnoremap ,h []<Left> cnoremap ,H [[::]]<Left><Left><Left> cnoremap ,eh [::]<Left><Left> cnoremap ,i <Home> cnoremap ,a <End> cnoremap ,, \ cnoremap ,. <C-r>: cnoremap ,p <C-r>" cnoremap ,P <C-r>+ cnoremap ,z <C-r>z cnoremap ,t <C-r>=Tr3transliterate(input("Translit: "))<C-m> cnoremap ,b <C-Left> cnoremap ,w <C-Right> cnoremap ,B <C-Left> cnoremap ,W <C-Right> "{{{4 normal nnoremap ,C :! nnoremap ,c :call<SPACE>NERDComment(0,"toggle")<C-m> nnoremap ,d "_ nnoremap ,D "_d nnoremap ,m :call system("make &")<C-m> nnoremap ,a $ nnoremap ,i ^ nnoremap ,, == nnoremap ,y "zy nnoremap ,p "zp nnoremap ,P "zP "{{{1 Functions "{{{1 nohlsearch " vim: ft=vim:fenc=utf-8:ts=4 A: Here are some parts of my vimrc and files sourced from the vimrc: Using F10 to toggle common boolean settings: " F10 inverts 'wrap' xnoremap <F10> :<C-U>set wrap! <Bar> set wrap? <CR>gv nnoremap <F10> :set wrap! <Bar> set wrap? <CR> inoremap <F10> <C-O>:set wrap! <Bar> set wrap? <CR> " Shift-F10 inverts 'virtualedit' xnoremap <S-F10> :<C-U>set ve=<C-R>=(&ve == 'all') ? '' : 'all'<return> ve?<CR>gv nnoremap <S-F10> :set ve=<C-R>=(&ve == 'all') ? '' : 'all'<return> ve?<CR> inoremap <S-F10> <C-O>:set ve=<C-R>=(&ve == 'all') ? '' : 'all'<return> ve?<CR> " Ctrl-F10 inverts 'hidden' xnoremap <C-F10> :<C-U>set hidden! <Bar> set hidden? <CR>gv nnoremap <C-F10> :set hidden! <Bar> set hidden? <CR> inoremap <C-F10> <C-O>:set hidden! <Bar> set hidden? <CR> Using F11 and F12 to move around quickfix entries " F11 and F12 to go to resp. previous and next item in quickfix entries nnoremap <F11> :silent! cc<CR>:silent! cp <CR>:call ErrBlink()<CR> nnoremap <F12> :silent! cc<CR>:silent! cn <CR>:call ErrBlink()<CR> " Shift-F11 and Shift-F12 to go to resp prev. and next file in quickfix list nnoremap <S-F11> :silent! cc<CR>:silent! cpf<CR>:call ErrBlink()<CR> nnoremap <S-F12> :silent! cc<CR>:silent! cnf<CR>:call ErrBlink()<CR> " Ctrl-F11 and Ctrl-F1 to recall older and newer quickfix lists nnoremap <C-F11> :silent! col <CR>:call ErrBlink()<CR> nnoremap <C-F12> :silent! cnew<CR>:call ErrBlink()<CR> Search visually selected text with * and # (prefix with _ to keep old search also) xnoremap <silent> _* :<C-U> \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR> \gvy/<C-R><C-R>/\|<C-R><C-R>=substitute( \substitute(escape(@", '/\.*$^~['), '\s\+', '\\s\\+', 'g'), '\_s\+', '\\_s*', 'g')<CR><CR> \gV:call setreg('"', old_reg, old_regtype)<CR> xnoremap <silent> _# :<C-U> \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR> \gvy?<C-R><C-R>/\|<C-R><C-R>=substitute( \substitute(escape(@", '?\.*$^~['), '\s\+', '\\s\\+', 'g'), '\_s\+', '\\_s*', 'g')<CR><CR> \gV:call setreg('"', old_reg, old_regtype)<CR> xnoremap <silent> * :<C-U> \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR> \gvy/<C-R><C-R>=substitute( \substitute(escape(@", '/\.*$^~['), '\s\+', '\\s\\+', 'g'), '\_s\+', '\\_s*', 'g')<CR><CR> \gV:call setreg('"', old_reg, old_regtype)<CR> xnoremap <silent> # :<C-U> \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR> \gvy?<C-R><C-R>=substitute( \substitute(escape(@", '?\.*$^~['), '\s\+', '\\s\\+', 'g'), '\_s\+', '\\_s*', 'g')<CR><CR> \gV:call setreg('"', old_reg, old_regtype)<CR> Using F1 and F3 to search (shift to add results to current ones) set grepprg=ack " F2 uses ack to search a Perl pattern nnoremap <F2> :grep<space> nnoremap <S-F2> :grepadd<space> " F3 uses vim to search current pattern nnoremap <F3> :noautocmd vim // **/*<C-F>Bhhi nnoremap <F3><F3> :noautocmd vim /<C-R><C-O>// **/*<Return> " F3 to search the current highlighted pattern xnoremap <F3> "zy:noautocmd vim /\M<C-R>=escape(@z,'\/')<CR>/ **/*<CR> nnoremap <S-F3> :noautocmd vimgrepadd // **/*<C-F>Bhhi nnoremap <S-F3><S-F3> :noautocmd vimgrepadd /<C-R><C-O>// **/*<Return> xnoremap <S-F3> "zy:noautocmd vimgrepadd /\M<C-R>=escape(@z,'\/')<CR>/ **/*<CR> Do not store replaced text when pasting in visual mode xnoremap p pgvy Help functions " Have cursor line and column blink a bit function! BlinkHere() for i in range(1,6) set cursorline! cursorcolumn! redraw sleep 30m endfor endfunction " Blink on mappings to quickfix commands function! ErrBlink() silent! cw silent! normal! z17 silent! cc silent! normal! zz silent! call BlinkHere() endfunction Automatically sort quickfix list function! s:CompareQuickfixEntries(i1, i2) if bufname(a:i1.bufnr) == bufname(a:i2.bufnr) return a:i1.lnum == a:i2.lnum ? 0 : (a:i1.lnum < a:i2.lnum ? -1 : 1) else return bufname(a:i1.bufnr) < bufname(a:i2.bufnr) ? -1 : 1 endif endfunction function! s:SortUniqQFList() let sortedList = sort(getqflist(), 's:CompareQuickfixEntries') let uniqedList = [] let last = '' for item in sortedList let this = bufname(item.bufnr) . "\t" . item.lnum if this !=# last call add(uniqedList, item) let last = this endif endfor call setqflist(uniqedList) endfunction autocmd! QuickfixCmdPost * call s:SortUniqQFList() A: My (pretty heavily customized) vimrc is probably too long to post it here, so I'll just link to it instead: https://github.com/majutsushi/etc/blob/master/vim/.vimrc There are some useful tidbits in there that I either wrote myself or picked up somewhere like a statusbar with all kinds of information that I find useful. A screenshot is on the website of this plugin I wrote: http://majutsushi.github.com/tagbar/
{ "language": "en", "url": "https://stackoverflow.com/questions/164847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "157" }
Q: Can someone compare a Fuzzy Query to a LuceneDictionary solution? According to this post on how to do query auto-completionsuggestions in lucene getting "Did You Mean" functionality best involves using a LuceneDictionary. But I probably would have used a fuzzy query for this before reading this post. Now I'm wondering which is faster, which is easier to implement? A: Have you looked at some NGram wrappers for Lucene. They are the best ways to do the "did you mean" functionality in Lucene. I found this page for the docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/164849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I set the focus inside the Yahoo Rich Text Editor I have a an HTML form which contains the YAHOO rich text editor on it. When I display the form I want the YAHOO editor to have focus so that the cursor is ready to accept input without the user having to click on it or tab into it A: I got this from the documenation over at the YUI library. Specifically at a sample titled Editor - Basic Buttons var myEditor = new YAHOO.widget.Editor('editor', {focusAtStart:true}); myEditor.render(); The key here is the the "focusAtStart" attribute as part of the optional attributes object A: I haven't employed the YAHOO rich text editor, but wouldn't it work, if you use a window.onload event ?-) A: Like roenving, I have never used the YAHOO rich text editor, but it should work with the window.onload event. Let's say you specified id="yahoo_text_editor" for your YAHOO rich text editor. Then, do <body onload="document.getElementById('yahoo_text_editor').focus()"> Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/164855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the vxWorks shared memory anchor? In the vxWorks memory map, there is an area (bellow the load address of vxWorks) which is described as the "shared memory anchor". What is it used for? A: In an environment with multiple single-board computers plugged into a common backplane (such as VMEbus), the VxMP variant of VxWorks adds "local" and "global" properties to common VxWorks objects. For example, you can have a "global" message queue that reside on one of those single-board computers but messages can be sent to and received from that message queue from any of the other single-board computers (all running VxWorks with VxMP). To accomplish this feat, a "shared memory" area is identified on each single-board computer, and all boards know all other board's shared memory addresses, and they communicate through these shared memory areas (and special drivers). When each board is booted, it must discover where its shared memory area is, hence this value, the "Shared Memory Anchor".
{ "language": "en", "url": "https://stackoverflow.com/questions/164857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does the assign then evaluate of each parameter "pattern" have a name? The following snippet of C# code: int i = 1; string result = String.Format("{0},{1},{2}", i++, i++, i++); Console.WriteLine(result); writes out: 1,2,3 Before I tried this in the compiler I was expecting the assignments to take place and then the evaluations, so my expected output was: 1,1,1 So my question is: Does this "pattern" (is it called a pattern?) of assign and then evaluate each parameter have a name? EDIT: I'm referring to the pattern of evaluating and assigning the parameters to the String.Format() function. Not the incrementing of i. (I may be incorrectly using the word evaluate in the question above because if the parameter was say (i + j) then we know that it would be evaluated before it was assigned. When using the word evaluate in that context I'm referring to the incrementing of i.) A: The order of evaluation of arguments is strictly left-to-right in C#. When you evaluate the expression i++, what happens is the value of i is calculated and pushed, then the value of i is incremented. The ++ operator on System.Int32 is effectively a function with the special name ++ and the special syntax of calling it by writing a reference to a variable and then the characters ++. So in effect, what you wrote is // assume this function is defined: int Inc(ref int i) { var old = i; i = i + 1; return old; } ... int i = 1; string result = String.Format("{0},{1},{2}", Inc(ref i), Inc(ref i), Inc(ref i)); Console.WriteLine(result); ... Since arguments are evaluated left-to-right, Inc(ref i) is called 3 times, each time incrementing i after passing the current value of i to String.Format(...). This is exactly what happens in your code, as well. A: The arguments of a function are evaluated left-to-right in C#. This is not the case in C/C++, where the standard says the order of evaluation is undefined.
{ "language": "en", "url": "https://stackoverflow.com/questions/164858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I split a pipe-separated string in a list? Here at work, we are working on a newsletter system that our clients can use. As an intern one of my jobs is to help with the smaller pieces of the puzzle. In this case what I need to do is scan the logs of the email server for bounced messages and add the emails and the reason the email bounced to a "bad email database". The bad emails table has two columns: 'email' and 'reason' I use the following statement to get the information from the logs and send it to the Perl script grep " 550 " /var/log/exim/main.log | awk '{print $5 "|" $23 " " $24 " " $25 " " $26 " " $27 " " $28 " " $29 " " $30 " " $31 " " $32 " " $33}' | perl /devl/bademails/getbademails.pl If you have sugestions on a more efficient awk script, then I would be glad to hear those too but my main focus is the Perl script. The awk pipes "foo@bar.com|reason for bounce" to the Perl script. I want to take in these strings, split them at the | and put the two different parts into their respective columns in the database. Here's what I have: #!usr/bin/perl use strict; use warnings; use DBI; my $dbpath = "dbi:mysql:database=system;host=localhost:3306"; my $dbh = DBI->connect($dbpath, "root", "******") or die "Can't open database: $DBI::errstr"; while(<STDIN>) { my $line = $_; my @list = # ? this is where i am confused for (my($i) = 0; $i < 1; $i++) { if (defined($list[$i])) { my @val = split('|', $list[$i]); print "Email: $val[0]\n"; print "Reason: $val[1]"; my $sth = $dbh->prepare(qq{INSERT INTO bademails VALUES('$val[0]', '$val[1]')}); $sth->execute(); $sth->finish(); } } } exit 0; A: I'm not sure what you want to put in @list? If the awk pipes one line per entry, you'll have that in $line, and you don't need the for loop on the @list. That said, if you're going to pipe it into Perl, why bother with the grep and AWK in the first place? #!/ust/bin/perl -w use strict; while (<>) { next unless / 550 /; my @tokens = split ' ', $_; my $addr = $tokens[4]; my $reason = join " ", @tokens[5..$#tokens]; # ... DBI code } Side note about the DBI calls: you should really use placeholders so that a "bad email" wouldn't be able to inject SQL into your database. A: Why not forgo the grep and awk and go straight to Perl? Disclaimer: I have not checked if the following code compiles: while (<STDIN>) { next unless /550/; # skips over the rest of the while loop my @fields = split; my $email = $fields[4]; my $reason = join(' ', @fields[22..32]); ... } EDIT: See @dland's comment for a further optimisation :-) Hope this helps? A: Have you considered using App::Ack instead? Instead of shelling out to an external program, you can just use Perl instead. Unfortunately, you'll have to read through the ack program code to really get a sense of how to do this, but you should get a more portable program as a result. A: my(@list) = split /\|/, $line; This will generate more than two entries in @list if you have extra pipe symbols in the tail of the line. To avoid that, use: $line =~ m/^([^|]+)\|(.*)$/; my(@list) = ($1, $2); The dollar in the regex is arguably superfluous, but also documents 'end of line'. A: Something like this would work: while(<STDIN>) { my $line = $_; chomp($line); my ($email,$reason) = split(/\|/, $line); print "Email: $email\n"; print "Reason: $reason"; my $sth = $dbh->prepare(qq{INSERT INTO bademails VALUES(?, ?)}); $sth->execute($email, $reason); $sth->finish(); } You might find it easier to just do the whole thing in Perl. "next unless / 550 /" could replace the grep and a regex could probably replace the awk.
{ "language": "en", "url": "https://stackoverflow.com/questions/164865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to write from Java to the Windows Event Log? How can I write from Java to the Windows Event Log? A: You can use JNA to write to the Event Log directly without the need of any native DLLs. See Advapi32 and Advapi32Util classes for various event log methods (ships since JNA 3.2.8). If you're using Log4j, consider Log4jna instead of NTEventLogAppender. A: You can also use the eventcreate command on Windows XP Pro and above. String command = "eventcreate " + " /l APPLICATION" + " /so \"" + applicationObjectName + "\"" + " /t " + lvl + " /id " + id + " /d \"" + description + "\""; Runtime.getRuntime().exec(command); For XP home and lower, you could create a vbs application that writes using the wscript.shell.eventcreate method. However you sacrifice the ability to specify source. Example: http://www.ozzu.com/mswindows-forum/posting-event-log-with-batch-files-t76791.html A: Back in 2001 JavaWorld published an article on how to write messages to the Windows NT Event Log. Or, you can take a look at the Log4j NTEventLogAppender class. A: Log4J is a Java-based logging utility. The class NTEventLogAppender can be used to "append to the NT event log system". See the documentation here: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/nt/NTEventLogAppender.html Edit: There is a newer version, Log4j 2 "that provides significant improvements over its predecessor."
{ "language": "en", "url": "https://stackoverflow.com/questions/164879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: If I grab a paramenter out of the query string, is it URL decoded? In .NET if I do something like: string temp = Request.QueryString["myKey"]; is the value in temp already URL decoded? A: Yes, it is.
{ "language": "en", "url": "https://stackoverflow.com/questions/164890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Limitations in running Ruby/Rails on windows In the installation documentation to RoR it mentions that there are many limitations to running Ruby on Rails on Windows, and in some cases, whole libraries do not work. How bad are these limitations, should I always default to Linux to code / run RoR, and is Iron Ruby expected to fix these limitations or are they core to the OS itself? EDIT Thanks for the answer around installation and running on Linux, but I am really trying to understand the limitations in functionality as referenced in the installation documentation, and non-working libraries - I am trying to find a link to the comment, but it was referenced in an installation read me when I installed the msi package I think EDIT Thanks for the references to IronRuby lately, it is certainly a project to watch, and as it, obviously, is a .NET language, it will be invaluable if it lives up to the promises. Eventually, however, in my case, I just bit the bullet and installed an Ubuntu server. <bias> I should've done it years ago </bias> A: I found getting a development environment up and running with Instant Rails on Windows was really simple. Especially when using Netbeans or Radrails as the IDE. Less than a 10 minute job. What did those who struggled find to be the problem? A: I've been developing Rails on a Windows PC for a couple of years and had no real problems installing back when I first started. However I recently re-built my machine and struggled to get the One-Click Ruby installer working and the latest version of Gems. So this is what I tried. Option 1: Run a Linux Virtual Machine I was really impressed with Charles Roper's idea of running Rails within a Linux virtual machine, and this is the route I intially went for. It all went pretty smoothly and I've been documenting it at budanters.blogspot.com. However I've been struggling with accessing the MySQL server (in Linux Virtual Machine) from the Windows host. Option 2: Use jRuby I recently installed the Windows version of NetBeans 6.5 Ruby bundle, and without being aware of it, this installs JRuby and the Rails gems. The IDE has a UI to install Gems, and I've now got my old application back up and running in my development enviromnent. Update November 2009 I now use Netbeans 6.7 on Windows and in the whole I am very happy with it. The only downsides are that it installs JRuby 1.2, and I needed to install JRuby 1.3 manually to get something working (I can't remember what) and I have been completely unable to get deployment working with either Capistrano or Vlad the Deployer to work. Vlad uses Open4 which doesn't work with JRuby. Update May 2010 Netbeans 6.8 comes with JRuby 1.4 so no longer have to fiddle around with manually installing JRuby 1.3. Also it seems that in JRuby 1.5 Open4 will now work, which means Vlad might start working. A: Nobody mentioned Bitnami RubyStack yet? I've been using it for years, together with RadRails. Includes Apache, MySQL/Postgre, phpmyadmin, git etc. Optional Ruby 1.9.2/Rails 3.0b. You may also run the Ubuntu flavor of RubyStack in a VM but I haven't tried that yet. A: There is a packaged installer available at http://railsinstaller.org/ which is worth checking out. A: Personally I found getting Ruby + Rails up and running on windows a piece of cake. From download to browsing to my first 'HelloWorld' app took me all of 15 minutes. I didn't even bother with any of the InstantRails stuff. Subsequently I can't say I encountered any of the reported speed problems or issues with Gems under Windows. These guys also do a nice Ruby developers add on for Visual Studio: http://www.sapphiresteel.com/ A: When I last fiddled around with Rails on windows, I used Instant Rails and found it to be a fairly painful process, except for the lack of updates to Instant Rails (which, from the look of the website is still a little bit of a problem, as instant Rails 2.0 uses ROR 2.0, while the newest version is 2.1). You might also look into the answers to this question as it mentions a number of other ways to get RoR running on windows easily. A: Here's an overview of the current issues with Rails on Windows: * *Ruby and Rails are slower on Windows than they are on Unix-like OS's. *A few gems and libraries don't work on Windows. *Some Unix-isms aren't available on Windows (examples). *The community is mostly on either Mac or Linux (This is a particularly hard one to deal with; nobody wants to be alone on one island when the rest of the tribe are partying, having fun and getting along great over on the other island. Community is important. It seems that most Windows developers that start with Rails quickly switch to a Mac or Linux. However, the small community of Windows Ruby users that do persist are extremely friendly, dedicated and knowledgeable - go say hi.) Note much of the advice that follows is now outdated due to the magnificent efforts of the RubyInstaller team in bringing stability, compatibility and performance to Ruby on Windows. I no longer have to use VirtualBox, which says a lot about how far Ruby on Windows has come. If you want more technical detail, the following are required reading. : * *Ruby for Windows - Part 1 *Is Windows a supported platform for Ruby? I guess not *Testing the new One-Click Ruby Installer for Windows *Still playing with Ruby on Windows *Chatting with Luis Lavena (Ruby on Windows) Choice quote from that last one is: AkitaOnRails: The most obvious thing is that any Gem with C Extensions without proper binaries for Windows will fail. Trying to execute shell commands will fail and RubyInline as well. What else? Luis Lavena: Hehe, that's just the tip of the iceberg Having said all that, I don't find developing with Rails on Windows too painful. Using Ruby is, for the most part, a pleasure. I'd avoid InstantRails because, to be frank, it's just as easy to install Ruby properly using the one-click installer, then doing a gem install rails. If you need Apache and MySQL, WAMP is a good bet, although even these aren't required if you just stick with Mongrel and SQLite. What I've taken to doing recently is running VirtualBox with an instance of Ubuntu Server that closely mirrors the deployment server. I map a network drive to the Ubuntu Server, then I edit and run my code directly on the VM. It uses hardly any memory (it's currently using ~43MB; contrast that with Firefox, which is using ~230MB) and Rails actually performs better than running it natively on Windows. Plus you can experiment with your virtual server in relative safety. It's a really nice setup, I highly recommend it. Finally, here are a couple of Ruby/Rails blogs aimed at Windows users: * *DEV_MEM.dump_to(:blog) (Luis Lavena) *Softies on Rails *Ruby On Windows A: You have windows options for getting everything up and installed, such as Instantrails: However, my personal experience with trying to get colleagues up and running on windows is that it's a pretty painful experience. You should be able to get most (if not everything) running, but be prepared to spend a bit of time mucking round (and getting frustrated). YMMV I would probably recommend either Linux or Mac for rails development (but I'm slightly biased against windows, so you may need to take that with a grain of salt). A: An option if you're stuck on Windows is to have virtual servers running Linux / BSD / what-have-you. It solves lots of other problems also (allowing you to try multiple server configurations easily, etc.). A: The biggest limitation of running under Windows is that a lot of things are super slow. See this thread. For a discussion. Simple things like "script/console" and running rake tasks will take 5 times longer on Windows than they do on Linux or Mac. Other limitations are: * *No IE6 on Vista. *BackgroundRB and a many other c based gems do not work on Windows. *No passenger A: If you can't get away from windows use VMware and run some form of linux (ubuntu is popular). Your No.1 limitation will be compiled gems which do not play nicely on windows. The majority of tutorials assume you're on some form of *nix, it's when you start to break outside of basic scaffolding when you'll feel the pain. Image manipulation, full-text search and even some db adapters will either only run on *nix or are a pain to setup. The majority of web hosts run linux too, it's good to be developing on the same platform as your host, to avoid deployment headaches. A: In general, Rails performance is a problem on Windows. As far as your deployment setup, you can either run Rails in FCGI or use mongrel (and set up either Apache or IIS as a proxy). mod_rails (http://www.modrails.com) is the best deployment option for Rails today, but doesn't run on Windows. You might find more luck using JRuby on Windows to run Rails in whatever JVM environment you want (tomcat, J2EE server, etc). IronRuby isn't there yet to run Rails in a production environment, but eventually it will be aimed at running Rails inside any ASP.NET environment (IIS). A: You could just use Cygwin and it's version of Ruby. That gets rid of the arguments about compiled gems not working on Windows - I've managed to compile a lot of gems that way. A: I'm not a rails developer myself but I thought this may be of interest. Microsoft has released IronRuby 1.0, it's a version of Ruby that runs on the .NET platform that apparently runs 4x faster than the official Rails implementation on Windows. http://www.drdobbs.com/open-source/224600662 Official site http://ironruby.codeplex.com/ A: For a speedup you could try my loader speeder upper (helps rails run faster in doze): https://github.com/rdp/faster_require Also checkout spork, which works in doze A: Alternative of RailsIntaller is RailsFTW. The Ruby & Rails are more updated.
{ "language": "en", "url": "https://stackoverflow.com/questions/164896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "81" }
Q: How would I package and sell a Django app? Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on. I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup. A: You'll never be able to keep the source code from people who really want it. It's best to come to grips with this fact now, and save yourself the headache later. A: Don't try and obfuscate or encrypt the code - it will never work. I would suggest selling the Django application "as a service" - either host it for them, or sell them the code and support. Write up a contract that forbids them from redistributing it. That said, if you were determined to obfuscate the code in some way - you can distribute python applications entirely as .pyc (Python compiled byte-code).. It's how Py2App works. It will still be re-distributable, but it will be very difficult to edit the files - so you could add some basic licensing stuff, and not have it foiled by a few #s.. As I said, I don't think you'll succeed in anti-piracy via encryption or obfuscation etc.. Depending on your clients, a simple contract, and maybe some really basic checks will go a long much further than some complicated decryption system (And make the experience of using your application better, instead of hopefully not any worse) A: May I speak frankly, as a friend? Unless your app is Really Amazing, you may not get many buyers. Why waste the time on lawyers, obfuscation, licensing and whatnot? You stand to gain a better reputation by open-sourcing your code...and maintaining it. Django comes from the open-source end of the spectrum from licensing (and obfuscating). Granted, the MIT license is more common than the GPL; still they are both very far removed from anything like Microsoft's EULA. A lot of Djangophiles will balk at closed source code, simply because that's what Microsoft does. Also, people will trust your code more, since they will be able to read it and verify that it contains no malicious code. Remember, "obfuscating" means "hiding;" and who will really know exactly what you've hidden? Granted, there's no easy way to monetize open-sourced code. But you could offer your services or even post a campaign on Pledgie.com, for those who are thankful for all your great work. A: One thing you might want to consider is what FogBugz does. Simply include a small binary (perhaps a C program) that is compiled for the target platforms and contains the code to validate the license. This way you can keep the honest people honest with minimal headache on your part. A: You could package the whole thing up as an Amazon Machine Instance (AMI), and then have them run your app on Amazon EC2. The nice thing about this solution is that Amazon will take care of billing for you, and since you're distributing the entire machine image, you can be certain that all your clients are using the same LAMP stack. The AMI is an encrypted machine image that is configured however you want it. You can have Amazon bill the client with a one-time fee, usage-based fee, or monthly fee. Of course, this solution requires that your clients host their app at Amazon, and pay the appropriate fees. A: The way I'd go about it is this: * *Encrypt all of the code *Write an installer that contacts the server with the machine's hostname and license file and gets the decryption key, then decrypts the code and compiles it to python bytecode *Add (in the installer) a module that checks the machine's hostname and license file on import and dies if it doesn't match This way the user only has to contact the server when the hostname changes and on first install, but you get a small layer of security. You could change the hostname to something more complex, but there's really no need -- anyone that wants to pirate this will do so, but a simple mechanism like that will keep honest people honest. A: "Encrypting" Python source code (or bytecode, or really bytecode for any language that uses it -- not just Python) is like those little JavaScript things some people put on web pages to try to disable the right-hand mouse button, declaring "now you can't steal my images!" The workarounds are trivial, and will not stop a determined person. If you're really serious about selling a piece of Python software, you need to act serious. Pay an attorney to draw up license/contract terms, have people agree to them at the time of purchase, and then just let them have the actual software. This means you'll have to haul people into court if they violate the license/contract terms, but you'd have to do that no matter what (e.g., if somebody breaks your "encryption" and starts distributing your software), and having the actual proper form of legal words already set down on paper, with their signature, will be far better for your business in the long term. If you're really that paranoid about people "stealing" your software, though, just stick with a hosted model and don't give them access to the server. Plenty of successful businesses are based around that model.
{ "language": "en", "url": "https://stackoverflow.com/questions/164901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: Windows Forms - Enter keypress activates submit button? How can I capture enter keypresses anywhere on my form and force it to fire the submit button event? A: You can subscribe to the KeyUp event of the TextBox. private void txtInput_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) DoSomething(); } A: private void textBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) button.PerformClick(); } A: You can designate a button as the "AcceptButton" in the Form's properties and that will catch any "Enter" keypresses on the form and route them to that control. See How to: Designate a Windows Forms Button as the Accept Button Using the Designer and note the few exceptions it outlines (multi-line text-boxes, etc.) A: If you set your Form's AcceptButton property to one of the Buttons on the Form, you'll get that behaviour by default. Otherwise, set the KeyPreview property to true on the Form and handle its KeyDown event. You can check for the Enter key and take the necessary action. A: The Form has a KeyPreview property that you can use to intercept the keypress. A: As previously stated, set your form's AcceptButton property to one of its buttons AND set the DialogResult property for that button to DialogResult.OK, in order for the caller to know if the dialog was accepted or dismissed. A: Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key. On detection call whatever code you would have for the "submit" button. A: Simply use this.Form.DefaultButton = MyButton.UniqueID; **Put your button id in place of 'MyButton'. A: if (e.KeyCode.ToString() == "Return") { //do something }
{ "language": "en", "url": "https://stackoverflow.com/questions/164903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "109" }
Q: How to enable STRICT_ALL_TABLES' for single MySQL database? Is there a way to enable STRICT_ALL_TABLES for a single MySQL database? A: set sql_mode = 'STRICT_ALL_TABLES'; will do it. A: You can set the default SQL mode by starting mysqld with the --sql-mode="modes" option, or by using sql-mode="modes" in my.cnf (Unix operating systems) or my.ini (Windows). modes is a list of different modes separated by comma (“,”) characters. The default value is empty (no modes set). The modes value also can be empty (--sql-mode="" on the command line, or sql-mode="" in my.cnf on Unix systems or in my.ini on Windows) if you want to clear it explicitly. ref MySql Website A: Don't think you can do this directly but you might get close with setting Strict for the current session when working on a particular database. Could do this in the config files of specific users.
{ "language": "en", "url": "https://stackoverflow.com/questions/164914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Code for extending the NETCF MainMenu to support background color property I've searched for the solution to change the background color on the Compact Framework's MainMenu control, and the only answer I've found is that you need to create a custom control. Does anyone have example code for this? A: I did something vaguely similar where I wanted to handle the WM_EXITMENULOOP message which was not available as an event in .NETCF. The solution was to "subclass" the Main Menu, an old MFC trick where you replace the WndProc function with your own, handle any windows messages (WM_EXITMENULOOP in my case) and call the base class WndProc for everything else. Some sample code is available on Alex Yakhnin's blog on how to subclass a control: Example of subclassing a window in .NETCF In your case you'd actually be subclassing the Form that the MainMenu resides on, and I think WM_DRAWITEM would be the windows message you'd want to handle yourself. I haven't tried changing the background color myself so not totally sure this will work, but subclassing would be where I'd start. A: There is no way of doing this. Your right in that you'll probably need to create your own control. This was something I was considering doing anyway to make the application go on Windows CE and Windows Mobile. The problem with adding menus when the application needs to work with both is that the menu goes to the top of the screen on Windows CE and covers any controls that might be there. It would be less hassle in the long run just make a new control. A: I tried to do something similar a while back and discovered that you have to write your own menu; essentially from scratch. I gave up because the project I was working on couldn't afford the expense. I also discovered that OpenNETCF has a pretty awesome menu control. I don't know if it's included in their free software, but it might be worth looking into.
{ "language": "en", "url": "https://stackoverflow.com/questions/164915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I display a decimal value to 2 decimal places? When displaying the value of a decimal currently with .ToString(), it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places. Do I use a variation of .ToString() for this? A: You can use system.globalization to format a number in any required format. For example: system.globalization.cultureinfo ci = new system.globalization.cultureinfo("en-ca"); If you have a decimal d = 1.2300000 and you need to trim it to 2 decimal places then it can be printed like this d.Tostring("F2",ci); where F2 is string formating to 2 decimal places and ci is the locale or cultureinfo. for more info check this link http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx A: I know this is an old question, but I was surprised to see that no one seemed to post an answer that; * *Didn't use bankers rounding *Keeps the value as a decimal. This is what I would use: decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero); http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx A: https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx This link explains in detail how you can handle your problem and what you can do if you want to learn more. For simplicity purposes, what you want to do is double whateverYouWantToChange = whateverYouWantToChange.ToString("F2"); if you want this for a currency, you can make it easier by typing "C2" instead of "F2" A: Given decimal d=12.345; the expressions d.ToString("C") or String.Format("{0:C}", d) yield $12.35 - note that the current culture's currency settings including the symbol are used. Note that "C" uses number of digits from current culture. You can always override default to force necessary precision with C{Precision specifier} like String.Format("{0:C2}", 5.123d). A: If you want it formatted with commas as well as a decimal point (but no currency symbol), such as 3,456,789.12... decimalVar.ToString("n2"); A: The most applicable solution is decimalVar.ToString("#.##"); A: decimalVar.ToString("F"); This will: * *Round off to 2 decimal places eg. 23.456 → 23.46 *Ensure that there are always 2 decimal places eg. 23 → 23.00; 12.5 → 12.50 Ideal for displaying currency. Check out the documentation on ToString("F") (thanks to Jon Schneider). A: There's a very important characteristic of Decimal that isn't obvious: A Decimal 'knows' how many decimal places it has based upon where it came from The following may be unexpected : Decimal.Parse("25").ToString() => "25" Decimal.Parse("25.").ToString() => "25" Decimal.Parse("25.0").ToString() => "25.0" Decimal.Parse("25.0000").ToString() => "25.0000" 25m.ToString() => "25" 25.000m.ToString() => "25.000" Doing the same operations with Double will result in zero decimal places ("25") for all of the above examples. If you want a decimal to 2 decimal places there's a high likelyhood it's because it's currency in which case this is probably fine for 95% of the time: Decimal.Parse("25.0").ToString("c") => "$25.00" Or in XAML you would use {Binding Price, StringFormat=c} One case I ran into where I needed a decimal AS a decimal was when sending XML to Amazon's webservice. The service was complaining because a Decimal value (originally from SQL Server) was being sent as 25.1200 and rejected, (25.12 was the expected format). All I needed to do was Decimal.Round(...) with 2 decimal places to fix the problem regardless of the source of the value. // generated code by XSD.exe StandardPrice = new OverrideCurrencyAmount() { TypedValue = Decimal.Round(product.StandardPrice, 2), currency = "USD" } TypedValue is of type Decimal so I couldn't just do ToString("N2") and needed to round it and keep it as a decimal. A: Double Amount = 0; string amount; amount=string.Format("{0:F2}", Decimal.Parse(Amount.ToString())); A: If you need to keep only 2 decimal places (i.e. cut off all the rest of decimal digits): decimal val = 3.14789m; decimal result = Math.Floor(val * 100) / 100; // result = 3.14 If you need to keep only 3 decimal places: decimal val = 3.14789m; decimal result = Math.Floor(val * 1000) / 1000; // result = 3.147 A: Here is a little Linqpad program to show different formats: void Main() { FormatDecimal(2345.94742M); FormatDecimal(43M); FormatDecimal(0M); FormatDecimal(0.007M); } public void FormatDecimal(decimal val) { Console.WriteLine("ToString: {0}", val); Console.WriteLine("c: {0:c}", val); Console.WriteLine("0.00: {0:0.00}", val); Console.WriteLine("0.##: {0:0.##}", val); Console.WriteLine("==================="); } Here are the results: ToString: 2345.94742 c: $2,345.95 0.00: 2345.95 0.##: 2345.95 =================== ToString: 43 c: $43.00 0.00: 43.00 0.##: 43 =================== ToString: 0 c: $0.00 0.00: 0.00 0.##: 0 =================== ToString: 0.007 c: $0.01 0.00: 0.01 0.##: 0.01 =================== A: Math.Round Method (Decimal, Int32) A: Very rarely would you want an empty string if the value is 0. decimal test = 5.00; test.ToString("0.00"); //"5.00" decimal? test2 = 5.05; test2.ToString("0.00"); //"5.05" decimal? test3 = 0; test3.ToString("0.00"); //"0.00" The top rated answer is incorrect and has wasted 10 minutes of (most) people's time. A: Mike M.'s answer was perfect for me on .NET, but .NET Core doesn't have a decimal.Round method at the time of writing. In .NET Core, I had to use: decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero); A hacky method, including conversion to string, is: public string FormatTo2Dp(decimal myNumber) { // Use schoolboy rounding, not bankers. myNumber = Math.Round(myNumber, 2, MidpointRounding.AwayFromZero); return string.Format("{0:0.00}", myNumber); } A: If you just need this for display use string.Format String.Format("{0:0.00}", 123.4567m); // "123.46" http://www.csharp-examples.net/string-format-double/ The "m" is a decimal suffix. About the decimal suffix: http://msdn.microsoft.com/en-us/library/364x0z75.aspx A: decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m or decimalVar.ToString("0.##"); // returns "0.5" when decimalVar == 0.5m or decimalVar.ToString("0.00"); // returns "0.50" when decimalVar == 0.5m A: None of these did exactly what I needed, to force 2 d.p. and round up as 0.005 -> 0.01 Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p. then rounding to ensure we do not have more than 2 d.p. Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero) 6.665m.ToString() -> "6.67" 6.6m.ToString() -> "6.60" A: The top-rated answer describes a method for formatting the string representation of the decimal value, and it works. However, if you actually want to change the precision saved to the actual value, you need to write something like the following: public static class PrecisionHelper { public static decimal TwoDecimalPlaces(this decimal value) { // These first lines eliminate all digits past two places. var timesHundred = (int) (value * 100); var removeZeroes = timesHundred / 100m; // In this implementation, I don't want to alter the underlying // value. As such, if it needs greater precision to stay unaltered, // I return it. if (removeZeroes != value) return value; // Addition and subtraction can reliably change precision. // For two decimal values A and B, (A + B) will have at least as // many digits past the decimal point as A or B. return removeZeroes + 0.01m - 0.01m; } } An example unit test: [Test] public void PrecisionExampleUnitTest() { decimal a = 500m; decimal b = 99.99m; decimal c = 123.4m; decimal d = 10101.1000000m; decimal e = 908.7650m Assert.That(a.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture), Is.EqualTo("500.00")); Assert.That(b.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture), Is.EqualTo("99.99")); Assert.That(c.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture), Is.EqualTo("123.40")); Assert.That(d.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture), Is.EqualTo("10101.10")); // In this particular implementation, values that can't be expressed in // two decimal places are unaltered, so this remains as-is. Assert.That(e.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture), Is.EqualTo("908.7650")); } A: var arr = new List<int>() { -4, 3, -9, 0, 4, 1 }; decimal result1 = arr.Where(p => p > 0).Count(); var responseResult1 = result1 / arr.Count(); decimal result2 = arr.Where(p => p < 0).Count(); var responseResult2 = result2 / arr.Count(); decimal result3 = arr.Where(p => p == 0).Count(); var responseResult3 = result3 / arr.Count(); Console.WriteLine(String.Format("{0:#,0.000}", responseResult1)); Console.WriteLine(String.Format("{0:#,0.0000}", responseResult2)); Console.WriteLine(String.Format("{0:#,0.00000}", responseResult3)); you can put as many 0 as you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/164926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "795" }
Q: How to find out if a certain value exists as a primary key in mySql? What is the best way to find out if a primary key with a certain value already exists in a table? I can think of: SELECT key FROM table WHERE key = 'value'; and count the results, or: SELECT SQL_CALC_FOUND_ROWS key FROM table WHERE key = 'value' LIMIT 1; SELECT FOUND_ROWS(); A: I think either of your suggestions in the question are suitable. Depending on how you are using this though, you can potentially save time by doing an INSERT IGNORE, which allows you to insert a new row if the primary key doesn't exist. If it does exist, the error is ignored so you can continue as normal. Other similar options depending on your usage include using the REPLACE or the INSERT ON DUPLICATE KEY UPDATE types of inserts. This allows you to update the existing entry if the primary key already exists, otherwise it just inserts your new entry. A: Do the first and count the results (always 0 or 1). Easy and fast. A: I'd do: SELECT 1 FROM table WHERE id key = 'value' Anything else is likely to interfere with query optimisation a little, so I'd stick with that. Edit: Although I just realised I don't think I've ever done that in MySQL, although I can't see why it wouldn't work. A: Example Select count(key) into :result from table where key = :theValue If your trying to decide between an insert or update, use a MERGE statement in Oracle. I believe MS-SQL is something like an UPSERT statement. A: SELECT 1 FROM mytable WHERE mykey = 'value' LIMIT 1 A: I think it would be more intuitive and simplier to use IF EXISTS. IF EXISTS (SELECT key FROM table WHERE key = 'value') PRINT 'Found it!' ELSE PRINT 'Cannot find it!'
{ "language": "en", "url": "https://stackoverflow.com/questions/164927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I add internationalization to my Perl script? I'm looking at introducing multi-lingual support to a mature CGI application written in Perl. I had originally considered rolling my own solution using a Perl hash (stored on disk) for translation files but then I came across a CPAN module which appears to do just what I want (i18n). Does anyone have any experience with internationalization (specifically the i18n CPAN module) in Perl? Is the i18n module the preferred method for multi-lingual support or should I reconsider a custom solution? Thanks A: If you have the time then do take a look at the way the I18N is done in the Jifty framework - although initially quite confusing it is very elegant and usable. They overload _ so that you can use _("text to translate") anywhere in the code. These strings are then translated using Locale::Maketext as normal. What makes it really powerful is that they defer the translation until the string is needed using Scalar::Defer so that you can start adding the strings at any time, even before you know which language they will be translated into. For example in config files etc. This really make I18N easy to work with. A: There is a Perl Journal article on software localisation. It will provide you with a good idea of what you can expect when adding multi-lingual support. It's beautifully written and humourous. Specifically, the article is written by the folks who wrote and maintain Locale::Maketext, so I would recommend that module simply based upon the amount of pain it is clear the authors have had to endure to make it work correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/164931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How are exponents calculated? I'm trying to determine the asymptotic run-time of one of my algorithms, which uses exponents, but I'm not sure of how exponents are calculated programmatically. I'm specifically looking for the pow() algorithm used for double-precision, floating point numbers. A: Unless they've discovered a better way to do it, I believe that approximate values for trig, logarithmic and exponential functions (for exponential growth and decay, for example) are generally calculated using arithmetic rules and Taylor Series expansions to produce an approximate result accurate to within the requested precision. (See any Calculus book for details on power series, Taylor series, and Maclaurin series expansions of functions.) Please note that it's been a while since I did any of this so I couldn't tell you, for example, exactly how to calculate the number of terms in the series you need to include guarantee an error that small enough to be negligible in a double-precision calculation. For example, the Taylor/Maclaurin series expansion for e^x is this: +inf [ x^k ] x^2 x^3 x^4 x^5 e^x = SUM [ --- ] = 1 + x + --- + ----- + ------- + --------- + .... k=0 [ k! ] 2*1 3*2*1 4*3*2*1 5*4*3*2*1 If you take all of the terms (k from 0 to infinity), this expansion is exact and complete (no error). However, if you don't take all the terms going to infinity, but you stop after say 5 terms or 50 terms or whatever, you produce an approximate result that differs from the actual e^x function value by a remainder which is fairly easy to calculate. The good news for exponentials is that it converges nicely and the terms of its polynomial expansion are fairly easy to code iteratively, so you might (repeat, MIGHT - remember, it's been a while) not even need to pre-calculate how many terms you need to guarantee your error is less than precision because you can test the size of the contribution at each iteration and stop when it becomes close enough to zero. In practice, I do not know if this strategy is viable or not - I'd have to try it. There are important details I have long since forgotten about. Stuff like: machine precision, machine error and rounding error, etc. Also, please note that if you are not using e^x, but you are doing growth/decay with another base like 2^x or 10^x, the approximating polynomial function changes. A: I've had a chance to look at fdlibm's implementation. The comments describe the algorithm used: * n * Method: Let x = 2 * (1+f) * 1. Compute and return log2(x) in two pieces: * log2(x) = w1 + w2, * where w1 has 53-24 = 29 bit trailing zeros. * 2. Perform y*log2(x) = n+y' by simulating muti-precision * arithmetic, where |y'|<=0.5. * 3. Return x**y = 2**n*exp(y'*log2) followed by a listing of all the special cases handled (0, 1, inf, nan). The most intense sections of the code, after all the special-case handling, involve the log2 and 2** calculations. And there are no loops in either of those. So, the complexity of floating-point primitives notwithstanding, it looks like a asymptotically constant-time algorithm. Floating-point experts (of which I'm not one) are welcome to comment. :-) A: The usual approach, to raise a to the b, for an integer exponent, goes something like this: result = 1 while b > 0 if b is odd result *= a b -= 1 b /= 2 a = a * a It is generally logarithmic in the size of the exponent. The algorithm is based on the invariant "a^b*result = a0^b0", where a0 and b0 are the initial values of a and b. For negative or non-integer exponents, logarithms and approximations and numerical analysis are needed. The running time will depend on the algorithm used and what precision the library is tuned for. Edit: Since there seems to be some interest, here's a version without the extra multiplication. result = 1 while b > 0 while b is even a = a * a b = b / 2 result = result * a b = b - 1 A: You can use exp(n*ln(x)) for calculating xn. Both x and n can be double-precision, floating point numbers. Natural logarithm and exponential function can be calculated using Taylor series. Here you can find formulas: http://en.wikipedia.org/wiki/Taylor_series A: If I were writing a pow function targeting Intel, I would return exp2(log2(x) * y). Intel's microcode for log2 is surely faster than anything I'd be able to code, even if I could remember my first year calculus and grad school numerical analysis. A: e^x = (1 + fraction) * (2^exponent), 1 <= 1 + fraction < 2 x * log2(e) = log2(1 + fraction) + exponent, 0 <= log2(1 + fraction) < 1 exponent = floor(x * log2(e)) 1 + fraction = 2^(x * log2(e) - exponent) = e^((x * log2(e) - exponent) * ln2) = e^(x - exponent * ln2), 0 <= x - exponent * ln2 < ln2
{ "language": "en", "url": "https://stackoverflow.com/questions/164964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Enumerating the list of DSN's set up on a computer I have an Excel application in which I want to present the user with a list of the Data Source Names (ie: DSN's), whereby s/he can choose what data source to use. Hopefully once I've got the list, I can easily access the DSN properties to connect to the appropriate database. Please note, I do not want to use a DSN-less connection. A: The DSN entries are stored in the registry in the following keys. HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data Sources HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources This contains the list of all defined DSN. This acts as an global index and the specific details for each DSN are stored in a key with the DSN name under: HKEY_CURRENT_USER\Software\ODBC\ODBC.INI HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI Create some entries in both User DSN and System DSN tabs from Data Sources (ODBC) control panel applet and check how these values are stored in the registry. The following example enumerate the DSN defined for the user trough Control Panel > Administrative Tools > Data Sources (ODBC) [User Dsn Tab]. http://support.microsoft.com/kb/178755 Option Explicit Private Declare Function RegOpenKeyEx Lib "advapi32.dll" _ Alias "RegOpenKeyExA" _ (ByVal hKey As Long, _ ByVal lpSubKey As String, _ ByVal ulOptions As Long, _ ByVal samDesired As Long, phkResult As Long) As Long Private Declare Function RegEnumValue Lib "advapi32.dll" _ Alias "RegEnumValueA" _ (ByVal hKey As Long, _ ByVal dwIndex As Long, _ ByVal lpValueName As String, _ lpcbValueName As Long, _ ByVal lpReserved As Long, _ lpType As Long, _ lpData As Any, _ lpcbData As Long) As Long Private Declare Function RegCloseKey Lib "advapi32.dll" _ (ByVal hKey As Long) As Long Const HKEY_CLASSES_ROOT = &H80000000 Const HKEY_CURRENT_USER = &H80000001 Const HKEY_LOCAL_MACHINE = &H80000002 Const HKEY_USERS = &H80000003 Const ERROR_SUCCESS = 0& Const SYNCHRONIZE = &H100000 Const STANDARD_RIGHTS_READ = &H20000 Const STANDARD_RIGHTS_WRITE = &H20000 Const STANDARD_RIGHTS_EXECUTE = &H20000 Const STANDARD_RIGHTS_REQUIRED = &HF0000 Const STANDARD_RIGHTS_ALL = &H1F0000 Const KEY_QUERY_VALUE = &H1 Const KEY_SET_VALUE = &H2 Const KEY_CREATE_SUB_KEY = &H4 Const KEY_ENUMERATE_SUB_KEYS = &H8 Const KEY_NOTIFY = &H10 Const KEY_CREATE_LINK = &H20 Const KEY_READ = ((STANDARD_RIGHTS_READ Or _ KEY_QUERY_VALUE Or _ KEY_ENUMERATE_SUB_KEYS Or _ KEY_NOTIFY) And _ (Not SYNCHRONIZE)) Const REG_DWORD = 4 Const REG_BINARY = 3 Const REG_SZ = 1 Private Sub Command1_Click() Dim lngKeyHandle As Long Dim lngResult As Long Dim lngCurIdx As Long Dim strValue As String Dim lngValueLen As Long Dim lngData As Long Dim lngDataLen As Long Dim strResult As String lngResult = RegOpenKeyEx(HKEY_CURRENT_USER, _ "SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources", _ 0&, _ KEY_READ, _ lngKeyHandle) If lngResult <> ERROR_SUCCESS Then MsgBox "Cannot open key" Exit Sub End If lngCurIdx = 0 Do lngValueLen = 2000 strValue = String(lngValueLen, 0) lngDataLen = 2000 lngResult = RegEnumValue(lngKeyHandle, _ lngCurIdx, _ ByVal strValue, _ lngValueLen, _ 0&, _ REG_DWORD, _ ByVal lngData, _ lngDataLen) lngCurIdx = lngCurIdx + 1 If lngResult = ERROR_SUCCESS Then strResult = strResult & lngCurIdx & ": " & Left(strValue, lngValueLen) & vbCrLf End If Loop While lngResult = ERROR_SUCCESS Call RegCloseKey(lngKeyHandle) Call MsgBox(strResult, vbInformation) End Sub A: You can use the SQLDataSources function of the ODBC API. See MSDN documentation. A: Extremely cool solution. I ran into an issue where CURRENT_USER wasn't showing all the DSN's, certainly not the one I needed. I changed it to LOCAL_MACHINE and saw all DSN's that showed up in the Connection Manager, including the subset that showed up under CURRENT_USER. http://msdn.microsoft.com/en-us/library/windows/desktop/ms712603(v=vs.85).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/164967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: RegEx for matching UK Postcodes I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance: Matches * *CW3 9SS *SE5 0EG *SE50EG *se5 0eg *WC2H 7LT No Match * *aWC2H 7LT *WC2H 7LTa *WC2H How do I solve this problem? A: It looks like we're going to be using ^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$, which is a slightly modified version of that sugested by Minglis above. However, we're going to have to investigate exactly what the rules are, as the various solutions listed above appear to apply different rules as to which letters are allowed. After some research, we've found some more information. Apparently a page on 'govtalk.gov.uk' points you to a postcode specification govtalk-postcodes. This points to an XML schema at XML Schema which provides a 'pseudo regex' statement of the postcode rules. We've taken that and worked on it a little to give us the following expression: ^((GIR &0AA)|((([A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]))) &[0-9][ABD-HJLNP-UW-Z]{2}))$ This makes spaces optional, but does limit you to one space (replace the '&' with '{0,} for unlimited spaces). It assumes all text must be upper-case. If you want to allow lower case, with any number of spaces, use: ^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$ This doesn't cover overseas territories and only enforces the format, NOT the existence of different areas. It is based on the following rules: Can accept the following formats: * *“GIR 0AA” *A9 9ZZ *A99 9ZZ *AB9 9ZZ *AB99 9ZZ *A9C 9ZZ *AD9E 9ZZ Where: * *9 can be any single digit number. *A can be any letter except for Q, V or X. *B can be any letter except for I, J or Z. *C can be any letter except for I, L, M, N, O, P, Q, R, V, X, Y or Z. *D can be any letter except for I, J or Z. *E can be any of A, B, E, H, M, N, P, R, V, W, X or Y. *Z can be any letter except for C, I, K, M, O or V. Best wishes Colin A: Here's a regex based on the format specified in the documents which are linked to marcj's answer: /^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$/ The only difference between that and the specs is that the last 2 characters cannot be in [CIKMOV] according to the specs. Edit: Here's another version which does test for the trailing character limitations. /^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-BD-HJLNP-UW-Z]{2}$/ A: Some of the regexs above are a little restrictive. Note the genuine postcode: "W1K 7AA" would fail given the rule "Position 3 - AEHMNPRTVXY only used" above as "K" would be disallowed. the regex: ^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$ Seems a little more accurate, see the Wikipedia article entitled 'Postcodes in the United Kingdom'. Note that this regex requires uppercase only characters. The bigger question is whether you are restricting user input to allow only postcodes that actually exist or whether you are simply trying to stop users entering complete rubbish into the form fields. Correctly matching every possible postcode, and future proofing it, is a harder puzzle, and probably not worth it unless you are HMRC. A: I wanted a simple regex, where it's fine to allow too much, but not to deny a valid postcode. I went with this (the input is a stripped/trimmed string): /^([a-z0-9]\s*){5,8}$/i This allows the shortest possible postcodes like "L1 8JQ" as well as the longest ones like "OL14 5ET". Because it allows up to 8 characters, it will also allow incorrect 8 character postcodes if there is no space: "OL145ETX". But again, this is a simplistic regex, for when that's good enough. A: Whilst there are many answers here, I'm not happy with either of them. Most of them are simply broken, are too complex or just broken. I looked at @ctwheels answer and I found it very explanatory and correct; we must thank him for that. However once again too much "data" for me, for something so simple. Fortunately, I managed to get a database with over 1 million active postcodes for England only and made a small PowerShell script to test and benchmark the results. UK Postcode specifications: Valid Postcode Format. This is "my" Regex: ^([a-zA-Z]{1,2}[a-zA-Z\d]{1,2})\s(\d[a-zA-Z]{2})$ Short, simple and sweet. Even the most unexperienced can understand what is going on. Explanation: ^ asserts position at start of a line 1st Capturing Group ([a-zA-Z]{1,2}[a-zA-Z\d]{1,2}) Match a single character present in the list below [a-zA-Z] {1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy) a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive) A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive) Match a single character present in the list below [a-zA-Z\d] {1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy) a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive) A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive) \d matches a digit (equivalent to [0-9]) \s matches any whitespace character (equivalent to [\r\n\t\f\v ]) 2nd Capturing Group (\d[a-zA-Z]{2}) \d matches a digit (equivalent to [0-9]) Match a single character present in the list below [a-zA-Z] {2} matches the previous token exactly 2 times a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive) A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive) $ asserts position at the end of a line Result (postcodes checked): TOTAL OK: 1469193 TOTAL FAILED: 0 ------------------------------------------------------------------------- Days : 0 Hours : 0 Minutes : 5 Seconds : 22 Milliseconds : 718 Ticks : 3227185939 TotalDays : 0.00373516891087963 TotalHours : 0.0896440538611111 TotalMinutes : 5.37864323166667 TotalSeconds : 322.7185939 TotalMilliseconds : 322718.5939 A: There is no such thing as a comprehensive UK postcode regular expression that is capable of validating a postcode. You can check that a postcode is in the correct format using a regular expression; not that it actually exists. Postcodes are arbitrarily complex and constantly changing. For instance, the outcode W1 does not, and may never, have every number between 1 and 99, for every postcode area. You can't expect what is there currently to be true forever. As an example, in 1990, the Post Office decided that Aberdeen was getting a bit crowded. They added a 0 to the end of AB1-5 making it AB10-50 and then created a number of postcodes in between these. Whenever a new street is build a new postcode is created. It's part of the process for obtaining permission to build; local authorities are obliged to keep this updated with the Post Office (not that they all do). Furthermore, as noted by a number of other users, there's the special postcodes such as Girobank, GIR 0AA, and the one for letters to Santa, SAN TA1 - you probably don't want to post anything there but it doesn't appear to be covered by any other answer. Then, there's the BFPO postcodes, which are now changing to a more standard format. Both formats are going to be valid. Lastly, there's the overseas territories source Wikipedia. +----------+----------------------------------------------+ | Postcode | Location | +----------+----------------------------------------------+ | AI-2640 | Anguilla | | ASCN 1ZZ | Ascension Island | | STHL 1ZZ | Saint Helena | | TDCU 1ZZ | Tristan da Cunha | | BBND 1ZZ | British Indian Ocean Territory | | BIQQ 1ZZ | British Antarctic Territory | | FIQQ 1ZZ | Falkland Islands | | GX11 1AA | Gibraltar | | PCRN 1ZZ | Pitcairn Islands | | SIQQ 1ZZ | South Georgia and the South Sandwich Islands | | TKCA 1ZZ | Turks and Caicos Islands | +----------+----------------------------------------------+ Next, you have to take into account that the UK "exported" its postcode system to many places in the world. Anything that validates a "UK" postcode will also validate the postcodes of a number of other countries. If you want to validate a UK postcode the safest way to do it is to use a look-up of current postcodes. There are a number of options: * *Ordnance Survey releases Code-Point Open under an open data licence. It'll be very slightly behind the times but it's free. This will (probably - I can't remember) not include Northern Irish data as the Ordnance Survey has no remit there. Mapping in Northern Ireland is conducted by the Ordnance Survey of Northern Ireland and they have their, separate, paid-for, Pointer product. You could use this and append the few that aren't covered fairly easily. *Royal Mail releases the Postcode Address File (PAF), this includes BFPO which I'm not sure Code-Point Open does. It's updated regularly but costs money (and they can be downright mean about it sometimes). PAF includes the full address rather than just postcodes and comes with its own Programmers Guide. The Open Data User Group (ODUG) is currently lobbying to have PAF released for free, here's a description of their position. *Lastly, there's AddressBase. This is a collaboration between Ordnance Survey, Local Authorities, Royal Mail and a matching company to create a definitive directory of all information about all UK addresses (they've been fairly successful as well). It's paid-for but if you're working with a Local Authority, government department, or government service it's free for them to use. There's a lot more information than just postcodes included. A: here's how we have been dealing with the UK postcode issue: ^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$ Explanation: * *expect 1 or 2 a-z chars, upper or lower fine *expect 1 or 2 numbers *expect 0 or 1 a-z char, upper or lower fine *optional space allowed *expect 1 number *expect 2 a-z, upper or lower fine This gets most formats, we then use the db to validate whether the postcode is actually real, this data is driven by openpoint https://www.ordnancesurvey.co.uk/opendatadownload/products.html hope this helps A: Basic rules: ^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$ Postal codes in the U.K. (or postcodes, as they’re called) are composed of five to seven alphanumeric characters separated by a space. The rules covering which characters can appear at particular positions are rather complicated and fraught with exceptions. The regular expression just shown therefore sticks to the basic rules. Complete rules: If you need a regex that ticks all the boxes for the postcode rules at the expense of readability, here you go: ^(?:(?:[A-PR-UWYZ][0-9]{1,2}|[A-PR-UWYZ][A-HK-Y][0-9]{1,2}|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]) [0-9][ABD-HJLNP-UW-Z]{2}|GIR 0AA)$ Source: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s16.html Tested against our customers database and seems perfectly accurate. A: I use the following regex that I have tested against all valid UK postcodes. It is based on the recommended rules, but condensed as much as reasonable and does not make use of any special language specific regex rules. ([A-PR-UWYZ]([A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y])?|[0-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2}) It assumes that the postcode has been converted to uppercase and has not leading or trailing characters, but will accept an optional space between the outcode and incode. The special "GIR0 0AA" postcode is excluded and will not validate as it's not in the official Post Office list of postcodes and as far as I'm aware will not be used as registered address. Adding it should be trivial as a special case if required. A: First half of postcode Valid formats * *[A-Z][A-Z][0-9][A-Z] *[A-Z][A-Z][0-9][0-9] *[A-Z][0-9][0-9] *[A-Z][A-Z][0-9] *[A-Z][A-Z][A-Z] *[A-Z][0-9][A-Z] *[A-Z][0-9] Exceptions Position 1 - QVX not used Position 2 - IJZ not used except in GIR 0AA Position 3 - AEHMNPRTVXY only used Position 4 - ABEHMNPRVWXY Second half of postcode * *[0-9][A-Z][A-Z] Exceptions Position 2+3 - CIKMOV not used Remember not all possible codes are used, so this list is a necessary but not sufficent condition for a valid code. It might be easier to just match against a list of all valid codes? A: To check a postcode is in a valid format as per the Royal Mail's programmer's guide: |----------------------------outward code------------------------------| |------inward code-----| #special↓ α1 α2 AAN AANA AANN AN ANN ANA (α3) N AA ^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) [0-9][ABD-HJLNP-UW-Z]{2})$ All postcodes on doogal.co.uk match, except for those no longer in use. Adding a ? after the space and using case-insensitive match to answer this question: 'se50eg'.match(/^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2})$/ig); Array [ "se50eg" ] A: This one allows empty spaces and tabs from both sides in case you don't want to fail validation and then trim it sever side. ^\s*(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})\s*$) A: Through empirical testing and observation, as well as confirming with https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation, here is my version of a Python regex that correctly parses and validates a UK postcode: UK_POSTCODE_REGEX = r'(?P<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[A-Z]{2})' This regex is simple and has capture groups. It does not include all of the validations of legal UK postcodes, but only takes into account the letter vs number positions. Here is how I would use it in code: @dataclass class UKPostcode: postcode_area: str district: str sector: int postcode: str # https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation # Original author of this regex: @jontsai # NOTE TO FUTURE DEVELOPER: # Verified through empirical testing and observation, as well as confirming with the Wiki article # If this regex fails to capture all valid UK postcodes, then I apologize, for I am only human. UK_POSTCODE_REGEX = r'(?P<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[A-Z]{2})' @classmethod def from_postcode(cls, postcode): """Parses a string into a UKPostcode Returns a UKPostcode or None """ m = re.match(cls.UK_POSTCODE_REGEX, postcode.replace(' ', '')) if m: uk_postcode = UKPostcode( postcode_area=m.group('postcode_area'), district=m.group('district'), sector=m.group('sector'), postcode=m.group('postcode') ) else: uk_postcode = None return uk_postcode def parse_uk_postcode(postcode): """Wrapper for UKPostcode.from_postcode """ uk_postcode = UKPostcode.from_postcode(postcode) return uk_postcode Here are unit tests: @pytest.mark.parametrize( 'postcode, expected', [ # https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation ( 'EC1A1BB', UKPostcode( postcode_area='EC', district='1A', sector='1', postcode='BB' ), ), ( 'W1A0AX', UKPostcode( postcode_area='W', district='1A', sector='0', postcode='AX' ), ), ( 'M11AE', UKPostcode( postcode_area='M', district='1', sector='1', postcode='AE' ), ), ( 'B338TH', UKPostcode( postcode_area='B', district='33', sector='8', postcode='TH' ) ), ( 'CR26XH', UKPostcode( postcode_area='CR', district='2', sector='6', postcode='XH' ) ), ( 'DN551PT', UKPostcode( postcode_area='DN', district='55', sector='1', postcode='PT' ) ) ] ) def test_parse_uk_postcode(postcode, expected): uk_postcode = parse_uk_postcode(postcode) assert(uk_postcode == expected) A: I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; archive of XML, see Wikipedia for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given. The RegEx supplied by the UK Government was: ([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2}) As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try. A: ^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$ Regular expression to match valid UK postcodes. In the UK postal system not all letters are used in all positions (the same with vehicle registration plates) and there are various rules to govern this. This regex takes into account those rules. Details of the rules: First half of postcode Valid formats [A-Z][A-Z][0-9][A-Z] [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9] [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z] [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions Position - First. Contraint - QVX not used Position - Second. Contraint - IJZ not used except in GIR 0AA Position - Third. Constraint - AEHMNPRTVXY only used Position - Forth. Contraint - ABEHMNPRVWXY Second half of postcode Valid formats [0-9][A-Z][A-Z] Exceptions Position - Second and Third. Contraint - CIKMOV not used http://regexlib.com/REDetails.aspx?regexp_id=260 A: I had a look into some of the answers above and I'd recommend against using the pattern from @Dan's answer (c. Dec 15 '10), since it incorrectly flags almost 0.4% of valid postcodes as invalid, while the others do not. Ordnance Survey provide service called Code Point Open which: contains a list of all the current postcode units in Great Britain I ran each of the regexs above against the full list of postcodes (Jul 6 '13) from this data using grep: cat CSV/*.csv | # Strip leading quotes sed -e 's/^"//g' | # Strip trailing quote and everything after it sed -e 's/".*//g' | # Strip any spaces sed -E -e 's/ +//g' | # Find any lines that do not match the expression grep --invert-match --perl-regexp "$pattern" There are 1,686,202 postcodes total. The following are the numbers of valid postcodes that do not match each $pattern: '^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$' # => 6016 (0.36%) '^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$' # => 0 '^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}$' # => 0 Of course, these results only deal with valid postcodes that are incorrectly flagged as invalid. So: '^.*$' # => 0 I'm saying nothing about which pattern is the best regarding filtering out invalid postcodes. A: To add to this list a more practical regex that I use that allows the user to enter an empty string is: ^$|^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,1}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$ This regex allows capital and lower case letters with an optional space in between From a software developers point of view this regex is useful for software where an address may be optional. For example if a user did not want to supply their address details A: I recently posted an answer to this question on UK postcodes for the R language. I discovered that the UK Government's regex pattern is incorrect and fails to properly validate some postcodes. Unfortunately, many of the answers here are based on this incorrect pattern. I'll outline some of these issues below and provide a revised regular expression that actually works. Note My answer (and regular expressions in general): * *Only validates postcode formats. *Does not ensure that a postcode legitimately exists. * *For this, use an appropriate API! See Ben's answer for more info. If you don't care about the bad regex and just want to skip to the answer, scroll down to the Answer section. The Bad Regex The regular expressions in this section should not be used. This is the failing regex that the UK government has provided developers (not sure how long this link will be up, but you can see it in their Bulk Data Transfer documentation): ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$ Problems Problem 1 - Copy/Paste See regex in use here. As many developers likely do, they copy/paste code (especially regular expressions) and paste them expecting them to work. While this is great in theory, it fails in this particular case because copy/pasting from this document actually changes one of the characters (a space) into a newline character as shown below: ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$ The first thing most developers will do is just erase the newline without thinking twice. Now the regex won't match postcodes with spaces in them (other than the GIR 0AA postcode). To fix this issue, the newline character should be replaced with the space character: ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$ ^ Problem 2 - Boundaries See regex in use here. ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$ ^^ ^ ^ ^^ The postcode regex improperly anchors the regex. Anyone using this regex to validate postcodes might be surprised if a value like fooA11 1AA gets through. That's because they've anchored the start of the first option and the end of the second option (independently of one another), as pointed out in the regex above. What this means is that ^ (asserts position at start of the line) only works on the first option ([Gg][Ii][Rr] 0[Aa]{2}), so the second option will validate any strings that end in a postcode (regardless of what comes before). Similarly, the first option isn't anchored to the end of the line $, so GIR 0AAfoo is also accepted. ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$ To fix this issue, both options should be wrapped in another group (or non-capturing group) and the anchors placed around that: ^(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2}))$ ^^ ^^ Problem 3 - Improper Character Set See regex in use here. ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$ ^^ The regex is missing a - here to indicate a range of characters. As it stands, if a postcode is in the format ANA NAA (where A represents a letter and N represents a number), and it begins with anything other than A or Z, it will fail. That means it will match A1A 1AA and Z1A 1AA, but not B1A 1AA. To fix this issue, the character - should be placed between the A and Z in the respective character set: ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$ ^ Problem 4 - Wrong Optional Character Set See regex in use here. ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$ ^ I swear they didn't even test this thing before publicizing it on the web. They made the wrong character set optional. They made [0-9] option in the fourth sub-option of option 2 (group 9). This allows the regex to match incorrectly formatted postcodes like AAA 1AA. To fix this issue, make the next character class optional instead (and subsequently make the set [0-9] match exactly once): ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?)))) [0-9][A-Za-z]{2})$ ^ Problem 5 - Performance Performance on this regex is extremely poor. First off, they placed the least likely pattern option to match GIR 0AA at the beginning. How many users will likely have this postcode versus any other postcode; probably never? This means every time the regex is used, it must exhaust this option first before proceeding to the next option. To see how performance is impacted check the number of steps the original regex took (35) against the same regex after having flipped the options (22). The second issue with performance is due to the way the entire regex is structured. There's no point backtracking over each option if one fails. The way the current regex is structured can greatly be simplified. I provide a fix for this in the Answer section. Problem 6 - Spaces See regex in use here This may not be considered a problem, per se, but it does raise concern for most developers. The spaces in the regex are not optional, which means the users inputting their postcodes must place a space in the postcode. This is an easy fix by simply adding ? after the spaces to render them optional. See the Answer section for a fix. Answer 1. Fixing the UK Government's Regex Fixing all the issues outlined in the Problems section and simplifying the pattern yields the following, shorter, more concise pattern. We can also remove most of the groups since we're validating the postcode as a whole (not individual parts): See regex in use here ^([A-Za-z][A-Ha-hJ-Yj-y]?[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}|[Gg][Ii][Rr] ?0[Aa]{2})$ This can further be shortened by removing all of the ranges from one of the cases (upper or lower case) and using a case-insensitive flag. Note: Some languages don't have one, so use the longer one above. Each language implements the case-insensitivity flag differently. See regex in use here. ^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$ Shorter again replacing [0-9] with \d (if your regex engine supports it): See regex in use here. ^([A-Z][A-HJ-Y]?\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0A{2})$ 2. Simplified Patterns Without ensuring specific alphabetic characters, the following can be used (keep in mind the simplifications from 1. Fixing the UK Government's Regex have also been applied here): See regex in use here. ^([A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0A{2})$ And even further if you don't care about the special case GIR 0AA: ^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$ 3. Complicated Patterns I would not suggest over-verification of a postcode as new Areas, Districts and Sub-districts may appear at any point in time. What I will suggest potentially doing, is added support for edge-cases. Some special cases exist and are outlined in this Wikipedia article. Here are complex regexes that include the subsections of 3. (3.1, 3.2, 3.3). In relation to the patterns in 1. Fixing the UK Government's Regex: See regex in use here ^(([A-Z][A-HJ-Y]?\d[A-Z\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\d[A-Z]{2}|BFPO ?\d{1,4}|(KY\d|MSR|VG|AI)[ -]?\d{4}|[A-Z]{2} ?\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$ And in relation to 2. Simplified Patterns: See regex in use here ^(([A-Z]{1,2}\d[A-Z\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\d[A-Z]{2}|BFPO ?\d{1,4}|(KY\d|MSR|VG|AI)[ -]?\d{4}|[A-Z]{2} ?\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$ 3.1 British Overseas Territories The Wikipedia article currently states (some formats slightly simplified): * *AI-1111: Anguila *ASCN 1ZZ: Ascension Island *STHL 1ZZ: Saint Helena *TDCU 1ZZ: Tristan da Cunha *BBND 1ZZ: British Indian Ocean Territory *BIQQ 1ZZ: British Antarctic Territory *FIQQ 1ZZ: Falkland Islands *GX11 1ZZ: Gibraltar *PCRN 1ZZ: Pitcairn Islands *SIQQ 1ZZ: South Georgia and the South Sandwich Islands *TKCA 1ZZ: Turks and Caicos Islands *BFPO 11: Akrotiri and Dhekelia *ZZ 11 & GE CX: Bermuda (according to this document) *KY1-1111: Cayman Islands (according to this document) *VG1111: British Virgin Islands (according to this document) *MSR 1111: Montserrat (according to this document) An all-encompassing regex to match only the British Overseas Territories might look like this: See regex in use here. ^((ASCN|STHL|TDCU|BBND|[BFS]IQQ|GX\d{2}|PCRN|TKCA) ?\d[A-Z]{2}|(KY\d|MSR|VG|AI)[ -]?\d{4}|(BFPO|[A-Z]{2}) ?\d{2}|GE ?CX)$ 3.2 British Forces Post Office Although they've been recently changed it to better align with the British postcode system to BF# (where # represents a number), they're considered optional alternative postcodes. These postcodes follow(ed) the format of BFPO, followed by 1-4 digits: See regex in use here ^BFPO ?\d{1,4}$ 3.3 Santa? There's another special case with Santa (as mentioned in other answers): SAN TA1 is a valid postcode. A regex for this is very simply: ^SAN ?TA1$ A: Most of the answers here didn't work for all the postcodes I have in my database. I finally found one that validates with all, using the new regex provided by the government: https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf It isn't in any of the previous answers so I post it here in case they take the link down: ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$ UPDATE: Updated regex as pointed by Jamie Bull. Not sure if it was my error copying or it was an error in the government's regex, the link is down now... UPDATE: As ctwheels found, this regex works with the javascript regex flavor. See his comment for one that works with the pcre (php) flavor. A: According to this Wikipedia table This pattern cover all the cases (?:[A-Za-z]\d ?\d[A-Za-z]{2})|(?:[A-Za-z][A-Za-z\d]\d ?\d[A-Za-z]{2})|(?:[A-Za-z]{2}\d{2} ?\d[A-Za-z]{2})|(?:[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]{2})|(?:[A-Za-z]{2}\d[A-Za-z] ?\d[A-Za-z]{2}) When using it on Android\Java use \\d A: This is the regex Google serves on their i18napis.appspot.com domain: GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4} A: An old post but still pretty high in google results so thought I'd update. This Oct 14 doc defines the UK postcode regular expression as: ^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([**AZ**a-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$ from: https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/359448/4__Bulk_Data_Transfer_-_additional_validation_valid.pdf The document also explains the logic behind it. However, it has an error (bolded) and also allows lower case, which although legal is not usual, so amended version: ^(GIR 0AA)|((([A-Z][0-9]{1,2})|(([A-Z][A-HJ-Y][0-9]{1,2})|(([A-Z][0-9][A-Z])|([A-Z][A-HJ-Y][0-9]?[A-Z])))) [0-9][A-Z]{2})$ This works with new London postcodes (e.g. W1D 5LH) that previous versions did not. A: I've been looking for a UK postcode regex for the last day or so and stumbled on this thread. I worked my way through most of the suggestions above and none of them worked for me so I came up with my own regex which, as far as I know, captures all valid UK postcodes as of Jan '13 (according to the latest literature from the Royal Mail). The regex and some simple postcode checking PHP code is posted below. NOTE:- It allows for lower or uppercase postcodes and the GIR 0AA anomaly but to deal with the, more than likely, presence of a space in the middle of an entered postcode it also makes use of a simple str_replace to remove the space before testing against the regex. Any discrepancies beyond that and the Royal Mail themselves don't even mention them in their literature (see http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf and start reading from page 17)! Note: In the Royal Mail's own literature (link above) there is a slight ambiguity surrounding the 3rd and 4th positions and the exceptions in place if these characters are letters. I contacted Royal Mail directly to clear it up and in their own words "A letter in the 4th position of the Outward Code with the format AANA NAA has no exceptions and the 3rd position exceptions apply only to the last letter of the Outward Code with the format ANA NAA." Straight from the horse's mouth! <?php $postcoderegex = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i'; $postcode2check = str_replace(' ','',$postcode2check); if (preg_match($postcoderegex, $postcode2check)) { echo "$postcode2check is a valid postcode<br>"; } else { echo "$postcode2check is not a valid postcode<br>"; } ?> I hope it helps anyone else who comes across this thread looking for a solution. A: Postcodes are subject to change, and the only true way of validating a postcode is to have the complete list of postcodes and see if it's there. But regular expressions are useful because they: * *are easy to use and implement *are short *are quick to run *are quite easy to maintain (compared to a full list of postcodes) *still catch most input errors But regular expressions tend to be difficult to maintain, especially for someone who didn't come up with it in the first place. So it must be: * *as easy to understand as possible *relatively future proof That means that most of the regular expressions in this answer aren't good enough. E.g. I can see that [A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y] is going to match a postcode area of the form AA1A — but it's going to be a pain in the neck if and when a new postcode area gets added, because it's difficult to understand which postcode areas it matches. I also want my regular expression to match the first and second half of the postcode as parenthesised matches. So I've come up with this: (GIR(?=\s*0AA)|(?:[BEGLMNSW]|[A-Z]{2})[0-9](?:[0-9]|(?<=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9])[A-HJ-NP-Z])?)\s*([0-9][ABD-HJLNP-UW-Z]{2}) In PCRE format it can be written as follows: /^ ( GIR(?=\s*0AA) # Match the special postcode "GIR 0AA" | (?: [BEGLMNSW] | # There are 8 single-letter postcode areas [A-Z]{2} # All other postcode areas have two letters ) [0-9] # There is always at least one number after the postcode area (?: [0-9] # And an optional extra number | # Only certain postcode areas can have an extra letter after the number (?<=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9]) [A-HJ-NP-Z] # Possible letters here may change, but [IO] will never be used )? ) \s* ([0-9][ABD-HJLNP-UW-Z]{2}) # The last two letters cannot be [CIKMOV] $/x For me this is the right balance between validating as much as possible, while at the same time future-proofing and allowing for easy maintenance. A: Have a look at the python code on this page: http://www.brunningonline.net/simon/blog/archives/001292.html I've got some postcode parsing to do. The requirement is pretty simple; I have to parse a postcode into an outcode and (optional) incode. The good new is that I don't have to perform any validation - I just have to chop up what I've been provided with in a vaguely intelligent manner. I can't assume much about my import in terms of formatting, i.e. case and embedded spaces. But this isn't the bad news; the bad news is that I have to do it all in RPG. :-( Nevertheless, I threw a little Python function together to clarify my thinking. I've used it to process postcodes for me. A: I have the regex for UK Postcode validation. This is working for all type of Postcode either inner or outer ^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))) || ^((GIR)[ ]?(0AA))$|^(([A-PR-UWYZ][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][A-HJKS-UW0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][ABEHMNPRVWXY0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$ This is working for all type of format. Example: AB10-------------------->ONLY OUTER POSTCODE A1 1AA------------------>COMBINATION OF (OUTER AND INNER) POSTCODE WC2A-------------------->OUTER A: We were given a spec: UK postcodes must be in one of the following forms (with one exception, see below): § A9 9AA § A99 9AA § AA9 9AA § AA99 9AA § A9A 9AA § AA9A 9AA where A represents an alphabetic character and 9 represents a numeric character. Additional rules apply to alphabetic characters, as follows: § The character in position 1 may not be Q, V or X § The character in position 2 may not be I, J or Z § The character in position 3 may not be I, L, M, N, O, P, Q, R, V, X, Y or Z § The character in position 4 may not be C, D, F, G, I, J, K, L, O, Q, S, T, U or Z § The characters in the rightmost two positions may not be C, I, K, M, O or V The one exception that does not follow these general rules is the postcode "GIR 0AA", which is a special valid postcode. We came up with this: /^([A-PR-UWYZ][A-HK-Y0-9](?:[A-HJKS-UW0-9][ABEHMNPRV-Y0-9]?)?\s*[0-9][ABD-HJLNP-UW-Z]{2}|GIR\s*0AA)$/i But note - this allows any number of spaces in between groups. A: The accepted answer reflects the rules given by Royal Mail, although there is a typo in the regex. This typo seems to have been in there on the gov.uk site as well (as it is in the XML archive page). In the format A9A 9AA the rules allow a P character in the third position, whilst the regex disallows this. The correct regex would be: (GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKPSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2}) Shortening this results in the following regex (which uses Perl/Ruby syntax): (GIR 0AA)|([A-PR-UWYZ](([0-9]([0-9A-HJKPSTUW])?)|([A-HK-Y][0-9]([0-9ABEHMNPRVWXY])?))\s?[0-9][ABD-HJLNP-UW-Z]{2}) It also includes an optional space between the first and second block. A: What i have found in nearly all the variations and the regex from the bulk transfer pdf and what is on wikipedia site is this, specifically for the wikipedia regex is, there needs to be a ^ after the first |(vertical bar). I figured this out by testing for AA9A 9AA, because otherwise the format check for A9A 9AA will validate it. For Example checking for EC1D 1BB which should be invalid comes back valid because C1D 1BB is a valid format. Here is what I've come up with for a good regex: ^([G][I][R] 0[A]{2})|^((([A-Z-[QVX]][0-9]{1,2})|([A-Z-[QVX]][A-HK-Y][0-9]{1,2})|([A-Z-[QVX]][0-9][ABCDEFGHJKPSTUW])|([A-Z-[QVX]][A-HK-Y][0-9][ABEHMNPRVWXY])) [0-9][A-Z-[CIKMOV]]{2})$ A: Below method will check the post code and provide complete info const isValidUKPostcode = postcode => { try { postcode = postcode.replace(/\s/g, ""); const fromat = postcode .toUpperCase() .match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/); const finalValue = `${fromat[1]} ${fromat[2]}`; const regex = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$/i; return { isValid: regex.test(postcode), formatedPostCode: finalValue, error: false, message: 'It is a valid postcode' }; } catch (error) { return { error: true , message: 'Invalid postcode'}; } }; console.log(isValidUKPostcode('GU348RR')) {isValid: true, formattedPostcode: "GU34 8RR", error: false, message: "It is a valid postcode"} console.log(isValidUKPostcode('sdasd4746asd')) {error: true, message: "Invalid postcode!"} valid_postcode('787898523') result => {error: true, message: "Invalid postcode"} A: I needed a version that would work in SAS with the PRXMATCH and related functions, so I came up with this: ^[A-PR-UWYZ](([A-HK-Y]?\d\d?)|(\d[A-HJKPSTUW])|([A-HK-Y]\d[ABEHMNPRV-Y]))\s?\d[ABD-HJLNP-UW-Z]{2}$ Test cases and notes: /* Notes The letters QVX are not used in the 1st position. The letters IJZ are not used in the second position. The only letters to appear in the third position are ABCDEFGHJKPSTUW when the structure starts with A9A. The only letters to appear in the fourth position are ABEHMNPRVWXY when the structure starts with AA9A. The final two letters do not use the letters CIKMOV, so as not to resemble digits or each other when hand-written. */ /* Bits and pieces 1st position (any): [A-PR-UWYZ] 2nd position (if letter): [A-HK-Y] 3rd position (A1A format): [A-HJKPSTUW] 4th position (AA1A format): [ABEHMNPRV-Y] Last 2 positions: [ABD-HJLNP-UW-Z] */ data example; infile cards truncover; input valid 1. postcode &$10. Notes &$100.; flag = prxmatch('/^[A-PR-UWYZ](([A-HK-Y]?\d\d?)|(\d[A-HJKPSTUW])|([A-HK-Y]\d[ABEHMNPRV-Y]))\s?\d[ABD-HJLNP-UW-Z]{2}$/',strip(postcode)); cards; 1 EC1A 1BB Special case 1 1 W1A 0AX Special case 2 1 M1 1AE Standard format 1 B33 8TH Standard format 1 CR2 6XH Standard format 1 DN55 1PT Standard format 0 QN55 1PT Bad letter in 1st position 0 DI55 1PT Bad letter in 2nd position 0 W1Z 0AX Bad letter in 3rd position 0 EC1Z 1BB Bad letter in 4th position 0 DN55 1CT Bad letter in 2nd group 0 A11A 1AA Invalid digits in 1st group 0 AA11A 1AA 1st group too long 0 AA11 1AAA 2nd group too long 0 AA11 1AAA 2nd group too long 0 AAA 1AA No digit in 1st group 0 AA 1AA No digit in 1st group 0 A 1AA No digit in 1st group 0 1A 1AA Missing letter in 1st group 0 1 1AA Missing letter in 1st group 0 11 1AA Missing letter in 1st group 0 AA1 1A Missing letter in 2nd group 0 AA1 1 Missing letter in 2nd group ; run; A: I stole this from an XML document and it seems to cover all cases without the hard coded GIRO: %r{[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}}i (Ruby syntax with ignore case) A: I did the regex for UK postcode validation today, as far as I know, it works for all UK postcodes, it works if you put a space or if you don't. ^((([a-zA-Z][0-9])|([a-zA-Z][0-9]{2})|([a-zA-Z]{2}[0-9])|([a-zA-Z]{2}[0-9]{2})|([A-Za-z][0-9][a-zA-Z])|([a-zA-Z]{2}[0-9][a-zA-Z]))(\s*[0-9][a-zA-Z]{2})$) Let me know if there's a format it doesn't cover
{ "language": "en", "url": "https://stackoverflow.com/questions/164979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "230" }
Q: PHP 4 and 5, Ctrl-C, system(), and child processes I have a PHP script that uses the system() call to execute other (potentially long-running) programs (for interest: NCBI BLAST, phrap, primer3 and other programs for doing DNA sequence analysis and assembly). I'm running under Windows XP, using the CLI version of PHP from a command prompt, or as a service. (In either case I communicate with it via a queue of tasks in a database table). Under PHP4: when I hit Ctrl+C the script is stopped and any child process running at the time is also stopped. Under PHP5: when I hit Ctrl+C the script stops, but the child is left running. Similarly, when running the script as a service, stopping the service when running it with PHP4 stops the child, with PHP5 the child continues to run. I have tried writing a minimal test application, and found the same behaviour. The test PHP script just uses system() to execute a C program (that just sleeps for 30 seconds) and then waits for a key to be pressed. I had a look at the source for PHP 4.4.9 and 5.2.6 but could see no differences in the system() code that looked like they would cause this. I also had a quick look at the startup code for the CLI application and didn't see any differences in signal handling. Any hints on what might have caused this, or a workaround, would be appreciated. Thanks. A: This issue occurs in at least PHP 5.1.2. When a SIGINT is sent via CTRL+C or CTRL+BREAK, the handler is called. If this handler sends a SIGTERM to other children, the signals are not received. SIGINT can be sent via posix_kill() and it work exactly as expected-- This only applies when initiated via a hard break. From: http://php.oregonstate.edu/manual/en/function.pcntl-signal.php The document has sample code for trapping CTRL+C and sending posix_kill to children. It has lots of other code and info on child precesses and signals. A: Instead of using system(), have a look at proc_open(), proc_close() and proc_terminate().
{ "language": "en", "url": "https://stackoverflow.com/questions/164981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Referencing build artifacts from an svn:external build in .Net project This is a continuation question from a previous question I have asked I now have a /externals directory in the root of my project tree. Inside this I have a reference to another project. I'm able to script the build of all my externals in the main project NAnt script. The result of these builds are as follows: /externals/external-project1/build/buildartifacts/{dlls|html|js} /externals/external-project2/build/buildartifacts/{dlls|html|js} This is all well and good, but now I'm curious as to how my main project should reference these build artifacts. For example, let's say that external project builds a DLL that some of my codebase depends on. Should I simply reference the DLL in the build artifacts directory or should I implement another NAnt task that copies these to a /thirdparty/libs/ folder? This means that my build is now dependent on the ability to build this external project (which could either be internal, or thirdparty). Is it a good idea to check in the latest set of build artifacts to ensure that the main build won't break because of dependent builds breaking? Hope that's clear enough. Just writing this down has a least clarified the problem for me :-). --Edit-- Thanks guys. I think I'm going to implement the "checkout a revision", but since the builds are so quick I'm not going to check in any build artifiacts. Also going to have to figure out how to deal with the dependencies of the external project (eg: prototype, swfobject, etc). A: I'd say build them once and check the build artifacts in /public/ext/some_dependency/ref (obviously, the naming of that folder is up to you :-)) and reference them from there. My main reason is that you seldom need to build external dependencies every time you do a build of your product. In general external dependencies should be changing rarely. Plus, you want strict control over when you pick external dependency changes, to avoid introducing instability during the coding phase. As a extension to this, I would add a separate CI task that would build the external dependencies only and check them in the aforementioned folder upon some external condition - a commit in the dependency source folder or something else. A: One of the recommendations I had (which I think came from the Pragmatic Version Control book by Mike Mason) to refer to particular revision in your external, so that you always get the same version of the external dependency until you explicitly choose to change it. At this point, you have probably interactively built it once to make sure it works, so relying on it to build every time isn't really an issue, which avoids the need to add some indirection in your build tasks. If you choose to have the indirection, and for some reason a build does fail on an external, it is possible this will be missed as the next nant task will pick up the previous binary.
{ "language": "en", "url": "https://stackoverflow.com/questions/164990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CHAR() or VARCHAR() as primary key in an ISAM MySQL table? I need a simple table with a user name and password field in MySQL. Since user names must be unique, it makes sense to me to make them the primary key. Is it better to use CHAR() or VARCHAR() as a primary key? A: may as well just use a user ID index, it's much faster for joins vs char/varchar. the two seconds it takes to add that now could save you a lot of time later if you accidently have to expand the functionality of your schema. some pitfalls to think about: * *say we add a few tables at a future date, what if someone wants to change a username? *say the app is more successful then we think, and we have to look at optimization, do you really want to redo your schema at this point to reduce the overhead of a varchar'ed index? A: I would work hard to NOT use CHAR() or VARCHAR() as a PK but use an int with an auto_increment instead. This allows you to use that user_id in child tables if needed and queries on the PK should be faster. If you have to use either a CHAR() or VARCHAR(), I'd go with the CHAR() since it's a fixed width. I'm not 100% sure how MySQL deals with VARCHAR()'s but most database engines have to do some magic under the hood to help the engine know where the VARCHAR() fields ends and where the next field begins, a CHAR() makes it straight forward and keeps the engine from having to think to much. A: [I would work hard to NOT use CHAR() or VARCHAR() as a PK but use an int with an auto_increment instead.] +1 Put a unique constraint of the username but use the int field as the PK A: I don't see CHAR used much in any MySQL databases i've worked on. I would go with the VARCHAR For a CHAR(30) for example, the entire 30 characters are stored in the table meaning every entry will take up the same space, even if your username is only 10 characters long. Using VARCHAR(30) it will only use enough space to store the string you have entered. On a small table it wont make much difference, but on a larger table the VARCHAR should prove to keep it smaller overall.
{ "language": "en", "url": "https://stackoverflow.com/questions/164991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do I discover the return value at the end of a function when debugging in VS2008? Using C# in Visual Studio 2008 and stepping through a function in the debugger I get to the end of a function and am on the final curly brace } and about to return. Is there a way to find out what value the function is about to return? This is necessary if the return value is calculated such as: return (x.Func() > y.Func()); A: It's a little low level, but if you switch to disassembly then you can single step through the instructions and see what the return value is being set to. It is typically set in the @eax register. You can place a breakpoint on the ret instructions and inspect the register at that point if you don't want to single step through it. A: You can put (x.Func() > y.Func()) in a watch window to evaluate it, and see the result. Unless the statement is return ValueChangesAfterEveryCall(); you should be fine. A: I am still using VS 2003 with C++, so this may or may not apply. If you use the "auto" tab (near the "locals" and "watch" tabs), it will tell you the return value of a function once you return. A: I'd actually recommend refactoring the code to put the individual function returns in local variables. That way, yourself and others don't have to jump through hoops when debugging the code to figure out a particular evaluation. Generally, this produces code that is easier to debug and, consequently, easier for others to understand and maintain. int sumOfSomething = x.Func(); int pendingSomethings = y.Func(); return (sumOfSomething > pendingSomethings);
{ "language": "en", "url": "https://stackoverflow.com/questions/164996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Installing .NET 3.5 on a server with .NET 2.0 applications I would like to upgrade my web projects on an IIS 5 server from .NET 2.0 to .NET 3.5. These web applications live on a server with other web applications that will not be upgraded to .NET 3.5. The server administrator is reluctant to install .NET 3.5 because he is afraid it will break the applications on that machine that are running 2.0 and 1.1. As far as I know this WON'T be a problem since .NET 3.5 is an addition to 2.0 more than it is a new Framework. I would like the communities help gathering evidence to show him that their concerns are moot and it won't hurt the other applications. Thanks in advance. A: If you have .NET 2 SP1 you shouldn't have a problem. To be exact .NET 3 & 3.5 are built on top of .NET 2.0 SP 1, we had a problem deploying 3.5 onto a server which only had .NET 2 (not SP1) and it caused the apps on there to break. The reason is your core framework assemblies in .NET 2 are upgraded and have new version numbers which the app wasn't compiled against. A: It won't have any problem and you will be able to run your 2.0 and 3.5 application using the same server. This is because the code base for both of the frameworks is the same. A: I've upgraded a couple servers from .net 1.1 to 2.0 & 3.5ץ there haven't been any problems. A: Walk the server administrator through the content of the redistributable for 3.5. It adds a lot of new dlls it doesn't update anything in the 2.0.x directory. You might want to show him how the apps targeting 3.5 are still using System.dll etc from the 2.0.x framework directory. A: Both frameworks can run concurrently. In fact, that is the default behavior. One caveat though, make sure that you don't use the same application pool for apps using different versions of the framework. Otherwise you will get "Server Application Unavailable" errors. Use a different app pool for each set of applications. A: Installing 3.5 will modify your .NET 2.0 web.config file and a few others. This certainly breaks at least 1 application I use. Uninstalling 3.5 will revert the files and fixes the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/165010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.NET 1.1 Performance Issue I'm doing some profiling on a 1.1 app and have identified a problem. It seems that this function is taking forever to load on a certain page: ParserCacheItem System.Web.UI.TemplateControlParser.CompileAndGetParserCacheItem(String, String, HttpContext) I've searched around with no luck about what this does. Does anyone know what this function is doing? If I knew then maybe it would shed some light on the situation. Thanks!? A: Its really a process of elimination. I've had similar problems where it seemed where I was the only one that had encounted a particular issue. By breaking my page down I found the control that was causing the timeout/error and did some more specific searches around it. I then found that the error actually had nothing to do with the symptoms I was experiencing, it was being masked by other issues. It is an investment in time but you might find that there's some control or part of your page thats timing out for some completely unobvious reason and isn't being reported in anyway. You did hint that page was complex. A: What does the page consist of? Have you tried: * *removing all elements from the page and running the profiler again and seeing if the same error occurs, if it doesn't add each element back to narrow down what was causing it *are all the namespace references correct for the .aspx? *have you tried running the app on another box thats running IIS to see if configuration might be the issue?
{ "language": "en", "url": "https://stackoverflow.com/questions/165014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my Excel export have a blank row at the top? In ASP.NET, I am exporting some data to Excel by simply binding a DataSet to a GridView and then setting the ContentType to Excel. My ASPX page is very simple and looks like this: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExamExportReport.aspx.cs" Inherits="Cabi.CamCentral.Web.Pages.Utility.ExamExportReport" %> <html> <body> <form id="form1" runat="server"> <asp:GridView ID="gridExam" AutoGenerateColumns="true" runat="server"> </asp:GridView> </form> </body> </html> In the Page_Load method of the code behind, I am doing this: protected void Page_Load(object sender, EventArgs e) { BindGrid(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "attachment; filename=ExamExport.xls"); } Generally, everything works fine, and the Excel file pops up with the right data. The problem is that the Excel file always ends up with a blank first row right above the column headers. I just can't figure out what is causing this. Maybe it's something about the form tag? Maybe I need to add some styling or something to strip out padding or margins? I've tried a bunch of things but I just can't get rid of that dang first blank row. Has anyone else run into this? Any solutions? A: @azamsharp - I found the solution elsewhere while you were replying. :-) It turns out that removing the form tag entirely from the ASPX page is the trick, and the only way to do this is to override the VerifyRenderingInServerForm method as you are doing. If you update your solution to include the fact that you need to remove the form tag from the page, I will accept your answer. Thanks. A: Here is my code that works fine: protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindData(); } } private void BindData() { string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true"; SqlConnection myConnection = new SqlConnection(connectionString); SqlDataAdapter ad = new SqlDataAdapter("select * from products", myConnection); DataSet ds = new DataSet(); ad.Fill(ds); gvProducts.DataSource = ds; gvProducts.DataBind(); } protected void ExportGridView(object sender, EventArgs e) { Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gvProducts.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } public override void VerifyRenderingInServerForm(Control control) { } A: An easier solution is to override the Render (HtmlTextWriter writer) method and make it empty: protected override void Render(HtmlTextWriter writer){} http://c-sharpe.blogspot.com/2009/05/get-rid-of-blank-row-when-exporting-to.html
{ "language": "en", "url": "https://stackoverflow.com/questions/165025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Redundancy vs dependencies: which is worse? When working on developing new software i normally get stuck with the redundancy vs dependencies problem. That is, to either accept a 3rd party library that i have a huge dependencies to or code it myself duplicate all the effect but reduce the dependencies. Though I've recently been trying to come up with a metric way of weighing up either redundancy in the code and dependencies in the code. For the most part, I've concluded reducing redundancy increases you dependencies in your code. Reducing the dependencies in your code increases redundancy. So its very much counter each other out. So my question is: Whats a good metric you've used in the past and do use to weigh up dependencies or redundancy in your code? One thing I think is soo important is if you choose the dependencies route is you need the tool sets in place so you can quickly examine all the routines and functions that use a specified function. Without those tools set, it seems like redundancy wins. P.S Following on from an article Article A: I would definitely recommend reading Joels essay on this: "In Defense of Not-Invented-Here Syndrome" For a dependency, the best metric I can think of would be "would the world grind to a halt if this disappeared". For example if the STL of C++ magically went away, tons of programs would stop working. If .Net or Java disappeared, our economy would probably take a beating due to the number of products that stopped working... I would think in those terms. Of course many things are a shade of gray between "end of world" and "meh" if they disappeared. The closer the dependency is to potentially causing the end-of-the-world if it dissapeared, the more likely it is to be stable, have an active user base, have its issues well-knows, etc. The more users the better. Its analogous to being a small consumer of some hardware component. Sometimes hardware goes obsolete. Why? Because no one uses it. If you're a small company and need to get a component for your product, you will pick what is commonly available--what the "big players" order in large quantities, hoping this means that (a) the component won't disappear, (b) the problems with the component are well known, (c) there's a large, informed user base and (d) it might cost less and be more readily available. Sometimes though, you need that special flux-capacitor part and you take the risk that the company selling it to you might not care to keep producing flux-capacitors if you are only ordering 20 a year, and no one seems to care :). In this case, it might be worth developing your own flux capacitor instead of relying on that unreliable Doc Brown Inc. Just don't buy Plutonium from the Libyans. If you've dealt in manufacturing something (especially when you're making far fewer than millions of them per year), you've had to deal with with this problem. Software dependencies, I believe, need to be understood in very similar terms. How to quantify this into a real metric? Roughly count how many people depend on something. If its high, the risk of the dependency hurting you is much lower, and you can decide at what point the risk is too much. A: I hadn't really considered the criteria I use to decide whether to employ a third party library or not before, but having thought about it, probably the following, in no particular order: * *How widespread the library is (am I going to be able to find support if I need it) *How likely am I to need to do unexpected things with it (am I going to end up embarking on a three week mission to add the functionality I need?) *How much of it do I need to use (am I going to spend days learning the ins and outs just to make use of one feature) *How stable it appears to be (more trouble than it's worth?) *How stable the interface is (are things likely to change in the next year or two?) *How interesting is the problem (would I be personally better off implementing it myself? will I learn anything useful?) A: A possible alternative is to use the external software if it provides a lot of value to your project, but hide this behind a simplified (and more consistent to your project) interface. This allows you to leverage the power of a third party library, but with much reduced complexity (and as such redundancy) in calling the library. The interface ensures that you don't let the specific style of the third party library bleed into your project and allows you to easily replace it with an internal implementation as and when you think that might be necessary. A sign of when this is happening might be that the interface you want to support is hampered by the third party library. The significant downside to this is that it does require extra development and add a certain maintenance impact (this increases with the amount of functionality you need from the library), but allows you to leverage the third party library without too much coupling and without all of your developers needing to understand it. A good example of this would be the use of an object relation mapper (Hibernate\NHibernate) behind a set of repositories or data access objects, or factories being implemented with an dependency injection framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/165041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Stop Excel from automatically converting certain text values to dates Does anyone happen to know if there is a token I can add to my csv for a certain field so Excel doesn't try to convert it to a date? I'm trying to write a .csv file from my application and one of the values happens to look enough like a date that Excel is automatically converting it from text to a date. I've tried putting all of my text fields (including the one that looks like a date) within double quotes, but that has no effect. A: (Assuming Excel 2003...) When using the Text-to-Columns Wizard has, in Step 3 you can dictate the data type for each of the columns. Click on the column in the preview and change the misbehaving column from "General" to "Text." A: This is a only way I know how to accomplish this without messing inside the file itself. As usual with Excel, I learned this by beating my head on the desk for hours. Change the .csv file extension to .txt; this will stop Excel from auto-converting the file when it's opened. Here's how I do it: open Excel to a blank worksheet, close the blank sheet, then File => Open and choose your file with the .txt extension. This forces Excel to open the "Text Import Wizard" where it'll ask you questions about how you want it to interpret the file. First you choose your delimiter (comma, tab, etc...), then (here's the important part) you choose a set columns of columns and select the formatting. If you want exactly what's in the file then choose "Text" and Excel will display just what's between the delimiters. A: I had a similar problem and this is the workaround that helped me without having to edit the csv file contents: If you have the flexibility to name the file something other than ".csv", you can name it with a ".txt" extension, such as "Myfile.txt" or "Myfile.csv.txt". Then when you open it in Excel (not by drag and drop, but using File->Open or the Most Recently Used files list), Excel will provide you with a "Text Import Wizard". In the first page of the wizard, choose "Delimited" for the file type. In the second page of the wizard choose "," as the delimiter and also choose the text qualifier if you have surrounded your values by quotes In the third page, select every column individually and assign each the type "Text" instead of "General" to stop Excel from messing with your data. Hope this helps you or someone with a similar problem! A: (EXCEL 2007 and later) How to force excel not to "detect" date formats without editing the source file Either: * *rename the file as .txt *If you can't do that, instead of opening the CSV file directly in excel, create a new workbook then go to Data > Get external data > From Text and select your CSV. Either way, you will be presented with import options, simply select each column containing dates and tell excel to format as "text" not "general". A: What I have done for this same problem was to add the following before each csv value: "=""" and one double quote after each CSV value, before opening the file in Excel. Take the following values for example: 012345,00198475 These should be altered before opening in Excel to: "="""012345","="""00198475" After you do this, every cell value appears as a formula in Excel and so won't be formatted as a number, date, etc. For example, a value of 012345 appears as: ="012345" A: None of the solutions offered here is a good solution. It may work for individual cases, but only if you're in control of the final display. Take my example: my work produces list of products they sell to retail. This is in CSV format and contain part-codes, some of them start with zero's, set by manufacturers (not under our control). Take away the leading zeroes and you may actually match another product. Retail customers want the list in CSV format because of back-end processing programs, that are also out of our control and different per customer, so we cannot change the format of the CSV files. No prefixed'=', nor added tabs. The data in the raw CSV files is correct; it's when customers open those files in Excel the problems start. And many customers are not really computer savvy. They can just about open and save an email attachment. We are thinking of providing the data in two slightly different formats: one as Excel Friendly (using the options suggested above by adding a TAB, the other one as the 'master'. But this may be wishful thinking as some customers will not understand why we need to do this. Meanwhile we continue to keep explaining why they sometimes see 'wrong' data in their spreadsheets. Until Microsoft makes a proper change I see no proper resolution to this, as long as one has no control over how end-users use the files. A: I have jus this week come across this convention, which seems to be an excellent approach, but I cannot find it referenced anywhere. Is anyone familiar with it? Can you cite a source for it? I have not looked for hours and hours but am hoping someone will recognize this approach. Example 1: =("012345678905") displays as 012345678905 Example 2: =("1954-12-12") displays as 1954-12-12, not 12/12/1954. A: Hi I have the same issue, I write this vbscipt to create another CSV file. The new CSV file will have a space in font of each field, so excel will understand it as text. So you create a .vbs file with the code below (for example Modify_CSV.vbs), save and close it. Drag and Drop your original file to your vbscript file. It will create a new file with "SPACE_ADDED" to file name in the same location. Set objArgs = WScript.Arguments Set objFso = createobject("scripting.filesystemobject") dim objTextFile dim arrStr ' an array to hold the text content dim sLine ' holding text to write to new file 'Looping through all dropped file For t = 0 to objArgs.Count - 1 ' Input Path inPath = objFso.GetFile(wscript.arguments.item(t)) ' OutPut Path outPath = replace(inPath, objFso.GetFileName(inPath), left(objFso.GetFileName(inPath), InStrRev(objFso.GetFileName(inPath),".") - 1) & "_SPACE_ADDED.csv") ' Read the file set objTextFile = objFso.OpenTextFile(inPath) 'Now Creating the file can overwrite exiting file set aNewFile = objFso.CreateTextFile(outPath, True) aNewFile.Close 'Open the file to appending data set aNewFile = objFso.OpenTextFile(outPath, 8) '2=Open for writing 8 for appending ' Reading data and writing it to new file Do while NOT objTextFile.AtEndOfStream arrStr = split(objTextFile.ReadLine,",") sLine = "" 'Clear previous data For i=lbound(arrStr) to ubound(arrStr) sLine = sLine + " " + arrStr(i) + "," Next 'Writing data to new file aNewFile.WriteLine left(sLine, len(sLine)-1) 'Get rid of that extra comma from the loop Loop 'Closing new file aNewFile.Close Next ' This is for next file set aNewFile=nothing set objFso = nothing set objArgs = nothing A: I have found that putting an '=' before the double quotes will accomplish what you want. It forces the data to be text. eg. ="2008-10-03",="more text" EDIT (according to other posts): because of the Excel 2007 bug noted by Jeffiekins one should use the solution proposed by Andrew: "=""2008-10-03""" A: 2018 The only proper solution that worked for me (and also without modifying the CSV). Excel 2010: * *Create new workbook *Data > From Text > Select your CSV file *In the popup, choose "Delimited" radio button, then click "Next >" *Delimiters checkboxes: tick only "Comma" and uncheck the other options, then click "Next >" *In the "Data preview", scroll to the far right, then hold shift and click on the last column (this will select all columns). Now in the "Column data format" select the radio button "Text", then click "Finish". Excel office365: (client version) * *Create new workbook *Data > From Text/CSV > Select your CSV file *Data type detection > do not detect Note: Excel office365 (web version), as I'm writing this, you will not be able to do that. A: WARNING: Excel '07 (at least) has a(nother) bug: if there's a comma in the contents of a field, it doesn't parse the ="field, contents" correctly, but rather puts everything after the comma into the following field, regardless of the quotation marks. The only workaround I've found that works is to eliminate the = when the field contents include a comma. This may mean that there are some fields that are impossible to represent exactly "right" in Excel, but by now I trust no-one is too surprised. A: While creating the string to be written to my CSV file in C# I had to format it this way: "=\"" + myVariable + "\"" A: Its not the Excel. Windows does recognize the formula, the data as a date and autocorrects. You have to change the Windows settings. "Control Panel" (-> "Switch to Classic View") -> "Regional and Language Options" -> tab "Regional Options" -> "Customize..." -> tab "Numbers" -> And then change the symbols according to what you want. http://www.pcreview.co.uk/forums/enable-disable-auto-convert-number-date-t3791902.html It will work on your computer, if these settings are not changed for example on your customers' computer they will see dates instead of data. A: Without modifying your csv file you can: * *Change the excel Format Cells option to "text" *Then using the "Text Import Wizard" to define the csv cells. *Once imported delete that data *then just paste as plain text excel will properly format and separate your csv cells as text formatted ignoring auto date formats. Kind of a silly work around, but it beats modifying the csv data before importing. Andy Baird and Richard sort of eluded to this method, but missed a couple important steps. A: In my case, "Sept8" in a csv file generated using R was converted into "8-Sept" by Excel 2013. The problem was solved by using write.xlsx2() function in the xlsx package to generate the output file in xlsx format, which can be loaded by Excel without unwanted conversion. So, if you are given a csv file, you can try loading it into R and converting it into xlsx using the write.xlsx2() function. A: I know this is an old question, but the problem is not going away soon. CSV files are easy to generate from most programming languages, rather small, human-readable in a crunch with a plain text editor, and ubiquitous. The problem is not only with dates in text fields, but anything numeric also gets converted from text to numbers. A couple of examples where this is problematic: * *ZIP/postal codes *telephone numbers *government ID numbers which sometimes can start with one or more zeroes (0), which get thrown away when converted to numeric. Or the value contains characters that can be confused with mathematical operators (as in dates: /, -). Two cases that I can think of that the "prepending =" solution, as mentioned previously, might not be ideal is * *where the file might be imported into a program other than MS Excel (MS Word's Mail Merge function comes to mind), *where human-readability might be important. My hack to work around this If one pre/appends a non-numeric and/or non-date character in the value, the value will be recognized as text and not converted. A non-printing character would be good as it will not alter the displayed value. However, the plain old space character (\s, ASCII 32) doesn't work for this as it gets chopped off by Excel and then the value still gets converted. But there are various other printing and non-printing space characters that will work well. The easiest however is to append (add after) the simple tab character (\t, ASCII 9). Benefits of this approach: * *Available from keyboard or with an easy-to-remember ASCII code (9), *It doesn't bother the importation, *Normally does not bother Mail Merge results (depending on the template layout - but normally it just adds a wide space at the end of a line). (If this is however a problem, look at other characters e.g. the zero-width space (ZWSP, Unicode U+200B) *is not a big hindrance when viewing the CSV in Notepad (etc), *and could be removed by find/replace in Excel (or Notepad etc). *You don't need to import the CSV, but can simply double-click to open the CSV in Excel. If there's a reason you don't want to use the tab, look in an Unicode table for something else suitable. Another option might be to generate XML files, for which a certain format also is accepted for import by newer MS Excel versions, and which allows a lot more options similar to .XLS format, but I don't have experience with this. So there are various options. Depending on your requirements/application, one might be better than another. Addition It needs to be said that newer versions (2013+) of MS Excel don't open the CSV in spreadsheet format any more - one more speedbump in one's workflow making Excel less useful... At least, instructions exist for getting around it. See e.g. this Stackoverflow: How to correctly display .csv files within Excel 2013? . A: In Excel 2010 open a new sheet. On the Data ribbon click "Get External Data From Text". Select your CSV file then click "Open". Click "Next". Uncheck "Tab", place a check mark next to "Comma", then click "Next". Click anywhere on the first column. While holding the shift key drag the slider across until you can click in the last column, then release the shift key. Click the "text" radio button then click "Finish" All columns will be imported as text, just as they were in the CSV file. A: Still an issue in Microsoft Office 2016 release, rather disturbing for those of us working with gene names such as MARC1, MARCH1, SEPT1 etc. The solution I've found to be the most practical after generating a ".csv" file in R, that will then be opened/shared with Excel users: * *Open the CSV file as text (notepad) *Copy it (ctrl+a, ctrl+c). *Paste it in a new excel sheet -it will all paste in one column as long text strings. *Choose/select this column. *Go to Data- "Text to columns...", on the window opened choose "delimited" (next). Check that "comma" is marked (marking it will already show the separation of the data to columns below) (next), in this window you can choose the column you want and mark it as text (instead of general) (Finish). HTH A: Here is the simple method we use at work here when generating the csv file in the first place, it does change the values a bit so it is not suitable in all applications: Prepend a space to all values in the csv This space will get stripped off by excel from numbers such as " 1"," 2.3" and " -2.9e4" but will remain on dates like " 01/10/1993" and booleans like " TRUE", stopping them being converted into excel's internal data types. It also stops double quotes being zapped on read in, so a foolproof way of making text in a csv remain unchanged by excel EVEN IF is some text like "3.1415" is to surround it with double quotes AND prepend the whole string with a space, i.e. (using single quotes to show what you would type) ' "3.1415"'. Then in excel you always have the original string, except it is surrounded by double quotes and prepended by a space so you need to account for those in any formulas etc. A: Working off of Jarod's solution and the issue brought up by Jeffiekins, you could modify "May 16, 2011" to "=""May 16, 2011""" A: I know this is an old thread. For the ones like me, who still have this problem using Office 2013 via PowerShell COM object can use the opentext method. The problem is that this method has many arguments, that are sometimes mutual exclusive. To resolve this issue you can use the invoke-namedparameter method introduced in this post. An example would be $ex = New-Object -com "Excel.Application" $ex.visible = $true $csv = "path\to\your\csv.csv" Invoke-NamedParameter ($ex.workbooks) "opentext" @{"filename"=$csv; "Semicolon"= $true} Unfortunately I just discovered that this method somehow breaks the CSV parsing when cells contain line breaks. This is supported by CSV but Microsoft's implementation seems to be bugged. Also it did somehow not detect German-specific chars. Giving it the correct culture did not change this behaviour. All files (CSV and script) are saved with utf8 encoding. First I wrote the following code to insert the CSV cell by cell. $ex = New-Object -com "Excel.Application" $ex.visible = $true; $csv = "path\to\your\csv.csv"; $ex.workbooks.add(); $ex.activeWorkbook.activeSheet.Cells.NumberFormat = "@"; $data = import-csv $csv -encoding utf8 -delimiter ";"; $row = 1; $data | %{ $obj = $_; $col = 1; $_.psobject.properties.Name |%{if($row -eq1){$ex.ActiveWorkbook.activeSheet.Cells.item($row,$col).Value2= $_ };$ex.ActiveWorkbook.activeSheet.Cells.item($row+1,$col).Value2 =$obj.$_; $col++ }; $row++;} But this is extremely slow, which is why I looked for an alternative. Apparently, Excel allows you to set the values of a range of cells with a matrix. So I used the algorithm in this blog to transform the CSV in a multiarray. function csvToExcel($csv,$delimiter){ $a = New-Object -com "Excel.Application" $a.visible = $true $a.workbooks.add() $a.activeWorkbook.activeSheet.Cells.NumberFormat = "@" $data = import-csv -delimiter $delimiter $csv; $array = ($data |ConvertTo-MultiArray).Value $starta = [int][char]'a' - 1 if ($array.GetLength(1) -gt 26) { $col = [char]([int][math]::Floor($array.GetLength(1)/26) + $starta) + [char](($array.GetLength(1)%26) + $Starta) } else { $col = [char]($array.GetLength(1) + $starta) } $range = $a.activeWorkbook.activeSheet.Range("a1:"+$col+""+$array.GetLength(0)) $range.value2 = $array; $range.Columns.AutoFit(); $range.Rows.AutoFit(); $range.Cells.HorizontalAlignment = -4131 $range.Cells.VerticalAlignment = -4160 } function ConvertTo-MultiArray { param( [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)] [PSObject[]]$InputObject ) BEGIN { $objects = @() [ref]$array = [ref]$null } Process { $objects += $InputObject } END { $properties = $objects[0].psobject.properties |%{$_.name} $array.Value = New-Object 'object[,]' ($objects.Count+1),$properties.count # i = row and j = column $j = 0 $properties |%{ $array.Value[0,$j] = $_.tostring() $j++ } $i = 1 $objects |% { $item = $_ $j = 0 $properties | % { if ($item.($_) -eq $null) { $array.value[$i,$j] = "" } else { $array.value[$i,$j] = $item.($_).tostring() } $j++ } $i++ } $array } } csvToExcel "storage_stats.csv" ";" You can use above code as is; it should convert any CSV into Excel. Just change the path to the CSV and the delimiter character at the bottom. A: EASIEST SOLUTION I just figured this out today. * *Open in Word *Replace all hyphens with en dashes *Save and Close *Open in Excel Once you are done editing, you can always open it back up in Word again to replace the en dashes with hyphens again. A: A workaround using Google Drive (or Numbers if you're on a Mac): * *Open the data in Excel *Set the format of the column with incorrect data to Text (Format > Cells > Number > Text) *Load the .csv into Google Drive, and open it with Google Sheets *Copy the offending column *Paste column into Excel as Text (Edit > Paste Special > Text) Alternatively if you're on a Mac for step 3 you can open the data in Numbers. A: (EXCEL 2016 and later, actually I have not tried in older versions) * *Open new blank page *Go to tab "Data" *Click "From Text/CSV" and choose your csv file *Check in preview whether your data is correct. *In сase when some column is converted to date click "edit" and then select type Text by clicking on calendar in head of column *Click "Close & Load" A: If someone still looking for answer, the line below worked perfectly for me I entered =("my_value"). i.e. =("04SEP2009") displayed as 04SEP2009 not as 09/04/2009 The same worked for integers more than 15 digits. They weren't getting trimmed anymore. A: If you can change the file source data If you're prepared to alter the original source CSV file, another option is to change the 'delimiter' in the data, so if your data is '4/11' (or 4-11) and Excel converts this to 4/11/2021 (UK or 11-4-2021 US), then changing the '/' or '-' character to something else will thwart the unwantwed Excel date conversion. Options may include: * *Tilde ('~') *Plus ('+') *Underscore ('_') *Double-dash ('--') *En-dash (Alt 150) *Em-dash (Alt 151) *(Some other character!) Note: moving to Unicode or other non-ascii/ansi characters may complicate matters if the file is to be used elsewhere. So, '4-11' converted to '4~11' with a tilde will NOT be treated as a date! For large CSV files, this has no additional overhead (ie: extra quotes/spaces/tabs/formula constructs) and just works when the file is opened directly (ie: double-clicking the CSV to open) and avoids pre-formatting columns as text or 'importing' the CSV file as text. A search/replace in Notepad (or similar tool) can easily convert to/from the alternative delimiter, if necessary. Import the original data In newer versions of Excel you can import the data (outlined in other answers). In older versions of Excel, you can install the 'Power Query' add-in. This tool can also import CSVs without conversion. Choose: Power Query tab/From file/From Text-CSV, then 'Load' to open as a table. (You can choose 'do not detect data types' from the 'data type detection' options). A: Okay found a simple way to do this in Excel 2003 through 2007. Open a blank xls workbook. Then go to Data menu, import external data. Select your csv file. Go through the wizard and then in "column data format" select any column that needs to be forced to "text". This will import that entire column as a text format preventing Excel from trying to treat any specific cells as a date. A: This issue is still present in Mac Office 2011 and Office 2013, I cannot prevent it happening. It seems such a basic thing. In my case I had values such as "1 - 2" & "7 - 12" within the CSV enclosed correctly within inverted commas, this automatically converts to a date within excel, if you try subsequently convert it to just plain text you would get a number representation of the date such as 43768. Additionally it reformats large numbers found in barcodes and EAN numbers to 123E+ numbers again which cannot be converted back. I have found that Google Drive's Google Sheets doesnt convert the numbers to dates. The barcodes do have commas in them every 3 characters but these are easily removed. It handles CSVs really well especially when dealing with MAC / Windows CSVs. Might save someone sometime. A: I do this for credit card numbers which keep converting to scientific notation: I end up importing my .csv into Google Sheets. The import options now allow to disable automatic formatting of numeric values. I set any sensitive columns to Plain Text and download as xlsx. It's a terrible workflow, but at least my values are left the way they should be. A: I made this VBA macro which basically formats the output range as text before pasting the numbers. It works perfectly for me when I want to paste values such as 8/11, 23/6, 1/3, etc. without Excel interpreting them as dates. Sub PasteAsText() ' Created by Lars-Erik Sørbotten, 2017-09-17 Call CreateSheetBackup Columns(ActiveCell.Column).NumberFormat = "@" Dim DataObj As MSForms.DataObject Set DataObj = New MSForms.DataObject DataObj.GetFromClipboard ActiveCell.PasteSpecial End Sub I'm very interested in knowing if this works for other people as well. I've been looking for a solution to this problem for a while, but I haven't seen a quick VBA solution to it that didn't include inserting ' in front of the input text. This code retains the data in its original form. A: If your working in Javascript and trying to upload CSV with cell value Martin18 or any string with number it shows some date value in JSON Solution: const bstr = event.target.result; const wb = XLSX.read(bstr, { type: 'string', raw: true }); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_json(ws, { header: 1, defval: ''}); it works for me :) Source of solution : https://github.com/SheetJS/sheetjs/issues/940 A: CSV - comma separated values. Just create/edit through text editor instead of xls/xlsx/exel. In editing you can set date in required format and it must be kept intact. This is assuming same file is then getting processed programatically. A: SELECT CONCAT('\'',NOW(),'\''), firstname, lastname FROM your_table INTO OUTFILE 'export.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' A: Prefixing space in double quotes resolved the issue!! I had data like "7/8" in one of the .csv file columns and MS-Excel was converting it to date as "07-Aug". But with "LibreOffice Calc" there was no issue. To resolve this, I just prefixed space character(added space before 7) like " 7/8" and it worked for me. This is tested for Excel-2007. A: If you put an inverted comma at the start of the field, it will be interpreted as text. Example: 25/12/2008 becomes '25/12/2008 You are also able to select the field type when importing. A: An alternate method: Convert the format of the column you want to change to 'Text'. Select all the cells you want to preserve, copy. Without deselecting those columns, click "Edit > Paste Special > As values" Save as CSV. Note that this has to be the last thing you do to the file because when you reopen it, it will format itself as dates since cell formats cannot be saved in CSV files. A: Paste table into word. Do a search/replace and change all - (dashes) into -- (double dash). Copy and paste into Excel. Can do same for other symbols (/), etc. If need to change back to a dash once in Excel, just format the column to text, then make the change. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/165042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "607" }
Q: Letters within integers. What are they? This is an excerpt of code from a class I am working with in Java (below). Obviously the code is defining a static variable named EPSILON with the data type double. What I don't understand is the "1E-14" part. What kind of number is that? What does it mean? final double EPSILON = 1E-14; A: The "E" notation is scientific notation. You'll see it on calculators too. It means "one times (ten to the power of -14)". For another example, 2E+6 == 2,000,000. A: 1E3 => 1000 1E-1 => 0.1 1E-2 => 0.01 It's a way for writing 1 * 10-14 A: That's Exponential notation A: In your case, this is equivalent to writing: final double EPSILON = 0.00000000000001; except you don't have to count the zeros. This is called scientific notation and is helpful when writing very large or very small numbers. A: 1E-14 is 1 times 10 to the power of -14
{ "language": "en", "url": "https://stackoverflow.com/questions/165043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How do I uninstall the .NET framework? I'm having a problem running a VS 2005 app on some machines and not others. I looked up the error message on google and found a post by someone who had the same error and fixed it by uninstalling and reinstalling the .NET framework. When I try to do that, Windows won't let me because it is in use. Am I expected to uninstall everything that is using the framework first, then uninstall the framework, then reinstall, etc.? Does anyone know of an easier way? A: Boot into safe mode and uninstall the framework from add/remove programs. A: Check out Aaron Stebner's .NET Framework Cleanup Tool. Works quite nicely.
{ "language": "en", "url": "https://stackoverflow.com/questions/165066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: (Apache) Error log beautifier Anyone knows of a good error log beautifier? (should be able to handle apache error logs). Should be open source / free, preferably with a web interface A: I use http://www.librelogiciel.com/software/ScanErrLog/action_Presentation It runs through the error log producing a summary webpage, or some other formats. While it's best run from a regular cron-job (and it will keep a record of what it's parsed before to save effort), it can also be run as a CGI (though the demo appears to be broken). A: You can see a sample report generated using Analog and Report Magic at this address: http://www.reportmagic.org/sample/index.html. The Failure Report is simple, but is a starting point. A: I use Webalizer to process my website's logs. Its web-interface might be a bit dated but it's very powerful, reliable and can handle very large logs. It's also quite easy to set up which a big plus in my book as you don't want to be worrying about the software, you just want to visualise the data. A: Apache Chainsaw
{ "language": "en", "url": "https://stackoverflow.com/questions/165072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Map an object reference with HashTable I'd like to map a reference to an object instead of the object value with an HashTable configMapping.Add("HEADERS_PATH", Me.headers_path) that way when I'm going to retrieve the value of "HEADERS_PATH" I'll be able to assign a value to Me.headers_path something like the " & " operator in C A: I am assuming that Me.headers_path is a System.String. Because System.String are immutable what you want cannot be achieved. But you can add an extra level of indirection to achieve a similar behavior. All problems in computer science can be solved by another level of indirection. Butler Lampson Sample in C# (Please be kind to edit to VB and remove this comment later): public class Holder<T> { public T Value { get; set; } } ... Holder<String> headerPath = new Holder<String>() { Value = "this is a test" }; configMapping.Add("HEADERS_PATH", headerPath); ... ((Holder<String>)configMapping["HEADERS_PATH"]).Value = "this is a new test"; // headerPath.Value == "this is a new test" A: make headers_path be a propriety (with set) A: This would appear to be a dictionary, which in .Net 2.0 you could define as Dictionary if the references you want to update are always strings, or Dictionary (not recommended) if you want to get an arbitrary reference. If you need to replace the values in the dictionary you could define your own class and provide some helper methods to make this easier. A: I am not entirely sure what you want to do. Assuming that smink is correct then here is the VB translation of his code. Sorry I can't edit it, I don't think I have enough rep yet. public class Holder(Of T) public Value as T end class ... Dim headerPath as new Holder(Of String) headerPath.Value = "this is a test" configMapping.Add("HEADERS_PATH", headerPath) ... Directcast(configMapping["HEADERS_PATH"]),Holder(Of String)).Value = "this is a new test" 'headerPath.Value now equals "this is a new test" @marcj - you need to escape the angled brackets in your answer, so use &lt; for a < and &gt; for a >. Again sorry I couldn't just edit your post for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/165075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert a Link Using CSS I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate: <table><tr><td class="case">123456</td></tr></table> I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz). So I'd like that "123456" to be changed to a link of this form: <a href="http://bugs.example.com/fogbugz/default.php?123456">123456</a> Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number. A: Not possible with CSS, plus that's not what CSS is for any way. Client-side Javascript or Server-side (insert language of choice) is the way to go. A: Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript.. function makeCasesClickable(){ var cells = document.getElementsByTagName('td') for (var i = 0, cell; cell = cells[i]; i++){ if (cell.className != 'case') continue var caseId = cell.innerHTML cell.innerHTML = '' var link = document.createElement('a') link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId link.appendChild(document.createTextNode(caseId)) cell.appendChild(link) } } You can apply it with something like onload = makeCasesClickable, or simply include it right at the end of the page. A: here is a jQuery solution specific to your HTML posted: $('.case').each(function() { var link = $(this).html(); $(this).contents().wrap('<a href="example.com/script.php?id='+link+'"></a>'); }); in essence, over each .case element, will grab the contents of the element, and throw them into a link wrapped around it. A: I don't think it's possible with CSS. CSS is only supposed to affect the looks and layout of your content. This seems like a job for a PHP script (or some other language). You didn't give enough information for me to know the best way to do it, but maybe something like this: function case_link($id) { return '<a href="http://bugs.example.com/fogbuz/default.php?' . $id . '">' . $id . '</a>'; } Then later in your document: <table><tr><td class="case"><?php echo case_link('123456'); ?></td></tr></table> And if you want an .html file, just run the script from the command line and redirect the output to an .html file. A: You could have something like this (using Javascript). Inside <head>, have <script type="text/javascript" language="javascript"> function getElementsByClass (className) { var all = document.all ? document.all : document.getElementsByTagName('*'); var elements = new Array(); for (var i = 0; i < all.length; i++) if (all[i].className == className) elements[elements.length] = all[i]; return elements; } function makeLinks(className, url) { nodes = getElementsByClass(className); for(var i = 0; i < nodes.length; i++) { node = nodes[i]; text = node.innerHTML node.innerHTML = '<a href="' + url + text + '">' + text + '</a>'; } } </script> And then at the end of <body> <script type="text/javascript" language="javascript"> makeLinks("case", "http://bugs.example.com/fogbugz/default.php?"); </script> I've tested it, and it works fine. A: I know this is an old question, but I stumbled upon this post looking for a solution for creating hyperlinks using CSS and ended up making my own, could be of interest for someone stumbling across this question like I did: Here's a php function called 'linker();'that enables a fake CSS attribute connect: 'url.com'; for an #id defined item. just let the php call this on every item of HTML you deem link worthy. the inputs are the .css file as a string, using: $style_cont = file_get_contents($style_path); and the #id of the corresponding item. Heres the whole thing: function linker($style_cont, $id_html){ if (strpos($style_cont,'connect:') !== false) { $url; $id_final; $id_outer = '#'.$id_html; $id_loc = strpos($style_cont,$id_outer); $connect_loc = strpos($style_cont,'connect:', $id_loc); $next_single_quote = stripos($style_cont,"'", $connect_loc); $next_double_quote = stripos($style_cont,'"', $connect_loc); if($connect_loc < $next_single_quote) { $link_start = $next_single_quote +1; $last_single_quote = stripos($style_cont, "'", $link_start); $link_end = $last_single_quote; $link_size = $link_end - $link_start; $url = substr($style_cont, $link_start, $link_size); } else { $link_start = $next_double_quote +1; $last_double_quote = stripos($style_cont, '"', $link_start); $link_end = $last_double_quote; $link_size = $link_end - $link_start; $url = substr($style_cont, $link_start, $link_size); //link! } $connect_loc_rev = (strlen($style_cont) - $connect_loc) * -1; $id_start = strrpos($style_cont, '#', $connect_loc_rev); $id_end = strpos($style_cont,'{', $id_start); $id_size = $id_end - $id_start; $id_raw = substr($style_cont, $id_start, $id_size); $id_clean = rtrim($id_raw); //id! if (strpos($url,'http://') !== false) { $url_clean = $url; } else { $url_clean = 'http://'.$url; }; if($id_clean[0] == '#') { $id_final = $id_clean; if($id_outer == $id_final) { echo '<a href="'; echo $url_clean; echo '" target="_blank">'; }; }; }; }; this could probably be improved/shortened using commands like .wrap() or getelementbyID() because it only generates the <a href='blah'> portion, but seeing as </a> disappears anyway without a opening clause it still works if you just add them everywhere :D
{ "language": "en", "url": "https://stackoverflow.com/questions/165082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Can I push to more than one repository in a single command in git? Basically I wanted to do something like git push mybranch to repo1, repo2, repo3 right now I'm just typing push many times, and if I'm in a hurry to the the pushing done, I just send them all to the background git push repo1 & git push repo2 & I'm just wondering if git natively supports what I want to do, or if maybe there's a clever script out there, or maybe a way to edit the local repo config file to say a branch should be pushed to multiple remotes. A: What I do is have a single bare repository that lives in my home directory that I push to. The post-update hook in that repository then pushes or rsyncs to several other publicly visible locations. Here is my hooks/post-update: #!/bin/sh # # An example hook script to prepare a packed repository for use over # dumb transports. # # To enable this hook, make this file executable by "chmod +x post-update". # Update static info that will be used by git clients accessing # the git directory over HTTP rather than the git protocol. git-update-server-info # Copy git repository files to my web server for HTTP serving. rsync -av --delete -e ssh /home/afranco/repositories/public/ afranco@slug.middlebury.edu:/srv/www/htdocs/git/ # Upload to github git-push --mirror github A: You can have several URLs per remote in git, even though the git remote command did not appear to expose this last I checked. In .git/config, put something like this: [remote "public"] url = git@github.com:kch/inheritable_templates.git url = kch@homeserver:projects/inheritable_templates.git Now you can say “git push public” to push to both repos at once.
{ "language": "en", "url": "https://stackoverflow.com/questions/165092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: "invalid use of incomplete type" error with partial template specialization The following code: template <typename S, typename T> struct foo { void bar(); }; template <typename T> void foo <int, T>::bar() { } gives me the error invalid use of incomplete type 'struct foo<int, T>' declaration of 'struct foo<int, T>' (I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument: template <typename S> struct foo { void bar(); }; template <> void foo <int>::bar() { } then it compiles correctly. A: Although coppro mentioned two solutions already and Anonymous explained the second one, it took me quite some time to understand the first one. Maybe the following code is helpful for someone stumbling across this site, which still ranks high in google, like me. The example (passing a vector/array/single element of numericalT as dataT and then accessing it via [] or directly) is of course somewhat contrived, but should illustrate how you actually can come very close to partially specializing a member function by wrapping it in a partially specialized class. /* The following circumvents the impossible partial specialization of a member function actualClass<dataT,numericalT,1>::access as well as the non-nonsensical full specialisation of the possibly very big actualClass. */ //helper: template <typename dataT, typename numericalT, unsigned int dataDim> class specialised{ public: numericalT& access(dataT& x, const unsigned int index){return x[index];} }; //partial specialisation: template <typename dataT, typename numericalT> class specialised<dataT,numericalT,1>{ public: numericalT& access(dataT& x, const unsigned int index){return x;} }; //your actual class: template <typename dataT, typename numericalT, unsigned int dataDim> class actualClass{ private: dataT x; specialised<dataT,numericalT,dataDim> accessor; public: //... for(int i=0;i<dataDim;++i) ...accessor.access(x,i) ... }; A: If you need to partially specialise a constructor, you might try something like: template <class T, int N> struct thingBase { //Data members and other stuff. }; template <class T, int N> struct thing : thingBase<T, N> {}; template <class T> struct thing<T, 42> : thingBase<T, 42> { thing(T * param1, wchar_t * param2) { //Special construction if N equals 42. } }; Note: this was anonymised from something I'm working on. You can also use this when you have a template class with lots and lots of members and you just want to add a function. A: You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g. template <typename U = T> struct Nested) would work. Or else you can try deriving from another template that partially specializes (works if you use the this->member notation, otherwise you will encounter compiler errors). A: If you're reading this question then you might like to be reminded that although you can't partially specialise methods you can add a non-templated overload, which will be called in preference to the templated function. i.e. struct A { template<typename T> bool foo(T arg) { return true; } bool foo(int arg) { return false; } void bar() { bool test = foo(7); // Returns false } }; A: In C++ 17, I use "if constexpr" to avoid specialize (and rewrite) my method. For example : template <size_t TSize> struct A { void recursiveMethod(); }; template <size_t TSize> void A<TSize>::recursiveMethod() { if constexpr (TSize == 1) { //[...] imple without subA } else { A<TSize - 1> subA; //[...] imple } } That avoid to specialize A<1>::recursiveMethod(). You can also use this method for type like this example : template <typename T> struct A { void foo(); }; template <typename T> void A<T>::foo() { if constexpr (std::is_arithmetic_v<T>) { std::cout << "arithmetic" << std::endl; } else { std::cout << "other" << std::endl; } } int main() { A<char*> a; a.foo(); A<int> b; b.foo(); } output : other arithmetic
{ "language": "en", "url": "https://stackoverflow.com/questions/165101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: What's wrong with Linq to SQL? What's wrong with Linq to SQL? Or - what about Linq to SQL would make it unsuitable for a project, either new or existing? I want to hear about why you would not choose Linq to SQL for a particular project - including what project parameters make it unsuitable. A: For a project that needs to make use of databases other than SQL Server: 1) You are locked in to using SQL Server For a project with complex entity relations and/or relations that change gradually over time: 2) You are locked in to 1-to-1 mapping of tables to classes For a project that must use 1.x versions of .NET 3) Won't work with .NET 1.x A: * *There is no way to mix-n-match lazy loading / eager loading on a datacontext. *True persistance ignorance is very difficult. *Mapping options are limited. For example, there are no many-to-many relationships. *Resyncing the mapping with schema changes is painful. Despite all of the above I think linq-to-sql is an excellent choice for many projects. A: It is difficult to mock while unit testing because of a lack of an interface on the System.Data.Linq.DataContext class. Here's a possible approach: Mocking LINQ to SQL DataContext. A: because you are not using 3.5... is that a valid answer?!?!? A: It is not very adaptable to changes in the database schema. You have to rebuild the dbml layer and regenerate your data contexts. Like any ORM (I am not getting into the debate as to whether it is an ORM or not), you do have to be aware what SQL is being generated, and how that will influence your calls. Inserts are not batched, so can be high cost in performance. It's being sunsetted in favour of Entity Framework Despite the fact it is using a provider model that will allow providers to be built for other DBMS platforms, only SQL Server is supported. [EDIT @ AugustLights - In my experience: ] Lazy loading may take a bit of hacking to get working. That being said, I think it it is very handy if used correctly A: Well, I have developed some applications using LINQ to SQL. One of the main problems that I find is having to layer your application. In LINQ to SQL the entity classes are tied very closely with the data access code. Also, there are some issues with DataContext which means that you can use a DataContext object to retrieve an item but you cannot transfer the item (object) to another DataContext (at least not easily). LINQ to SQL will be useful if you don't care about layering your application properly and also if all you wanted is to create an application in a rapid manner also know as RAPID Application Development. A: A lot of the advantage to LINQ-to-SQL comes from supposedly being able to construct data queries right in your code-behind based on strongly-typed queryable/enumerable data objects from your dbml (which plays the role of a very limited DAL). So a consequence, as has already been mentioned, is that it encourages you somewhat towards playing outside strongly defined and separated layers or tiers to your application. To counter that point, it should mean that you should be able to eliminate most or all of any business logic you were writing into stored procedures on the database, so then at least you only have to go to the code that deals with the data to change non-schema-impacting business rules... However, that breaks down a bit when you realise how complicated it can be to write a query with an outer join with aggregates with grouping, at least when you first approach it. So you'll be tempted to write the sprocs in the SQL you know that is so simple and good at doing those things rather than spend the extra time trying to figure out the LINQ syntax to do the same thing when it's just going to convert it to ugly SQL code anyway... That having been said, I really do love LINQ, and my esteem for it vastly increased when I started ignoring this "query syntax is easier to read" sentiment I've seen floating around and switched to method syntax. Never looked back. A: The only thing I would label as a technical "showstopper" is if you want to use other RDBMSes than SQL Server. (although it can be worked around - see Matt Warren's blog @ http://blogs.msdn.com/mattwar/ ) Besides that, there are some pros and cons already listed in previous answers to your question. However, all of the negatives mentioned so far have workarounds so they are not really showstoppers. A non-technical [potential] showstopper is the risk that MSFT will abandon it in favour of EF... More on that here: http://oakleafblog.blogspot.com/2008/05/is-adonet-team-abandoning-linq-to-sql.html Although (in my opinion, ) the current state of EF is reason enough for them to continue work on L2S. So let's hope they do... A: A true ORM should separate the design of your Business Entities from your persistence medium. That way you can refactor either one of them separately and only have to maintain the mapping between the two. This reduces the amount of application logic code that you need to maintain for database changes. To accomplish this kind of persistence agnostic approach with Linq-to-SQL, you would have to use its generated classes at DTOs and maintain a mapping logic between your DTOs and your Entities. There are much better ORMs for taking this approach (like NHibernate) that greatly reduce the need for DTOs. A: It doesn't appear to have any support for default values on DB columns. A: This question was asked once before over here. But, in essence, LINQ to SQL generates sub-optimal execution plans in your database. For every different length of parameter you search for, it will force the creation of a different execution plan. This will eventually clog up the memory in your database that is being used to cache execution plans and you will start expiring older queries, which will need to be recompiled when they come up again. As I mentioned in the question I linked to, it's a matter of what you're trying to accomplish. If you're willing to trade execution speed for development speed, LINQ to SQL might be a good choice. If you're concerned about execution speed, there are other ORMs/DALs/solutions available that may take longer to work with but will provide you with future proofing against schema changes and better performing solutions at the cost of additional development overhead.
{ "language": "en", "url": "https://stackoverflow.com/questions/165102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to disable Oracle XE component which is listening on 8080? After installing Oracle XE, something in Oracle is listening on port 8080. I am not sure if they have an Apache HTTPD, a Tomcat, or something else. But how can I disable it? A: It is Oracle XML DB HTTP Server; disable it as follows: sqlplus '/ as sysdba' EXEC DBMS_XDB.SETHTTPPORT(0); commit; You might have to restart Oracle XE (not just the listener).
{ "language": "en", "url": "https://stackoverflow.com/questions/165105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: What does the perfect status report look like? I work with a lot of offsite developers and contractors. I ask them daily to send me a quick 5 minute status of their work for the day. I have to sometimes consolidate the status of individuals into teams and sometimes consolidate the status of a week, for end-of-period reporting to my clients. I want to learn: * *Items accomplished and how much time was spent on each *Problems encountered and how much time was spent on each *Items that will be worked on next, their estimates (in man hours) and their target dates *Questions they have on the work I'm looking for a format that will provide this information while: * *Being quick for the developers to complete (5-10 minutes, without thinking too much) *Easy for me to read and browse quickly *Is uniform for each developer What would you suggest? A: you probably do not want to hear this, but here is it anyway - i have been in this situation on both sides of the desk, and come to the conclusion that these kinds of rolled-up status reports are a complete waste of time for you and the developers. Here's why: * *the developers should be working on features/deliverables with specified deadlines *the developers should be asking questions when they occur *communication should flow in both directions as needed if these things are not happening, no amount of passive status reporting is going to fix the problems that will inevitably arise on the developer side of the fence - a "quick five minute status" [i hate that phrase, five minutes is not quick!] interrupts the developer's flow, causing a loss of fifteen minutes (or more) of productivity (joel even blogged about this i think). But even if it really is only five minutes, if you have a dozen developers then you're wasting five man-hours per week on administrivia (and it's probably more like 20) on the manager side of the fence - rolling up the status reports of individuals into teams by project etc. is non-productive busywork that wastes your time also. Chances are that no one even reads the reports. but here's the real problem: this kind of reporting and roll-up may indicate reactive management instead of pro-active management. In other words, it doesn't matter what methodology is being used - scrum, xp, agile, rational, waterfall, home-grown, or whatever - if the project is properly planned and executed then you should already know what everyone is doing because it was planned in advance. And it doesn't matter if it was planned that morning or six months ago. ignoring client requirements for a moment, if you really need this information on a daily basis to manage the projects then there are probably some serious problems with the projects - asking the developer every day what they're going to work on next and how long it will take, for example, hints that no real planning was done in advance... as for the client requirements, if they absolutely insist on this kind of minutia [and i know that, for example, some government agencies do] then the best option is to provide a web interface or other application to automate the tedium that will do the roll-up for you. You'll still be wasting the developers' time, but at least you won't be wasting your time ;-) oh, and to answer your question literally: the perfect status report says "on target with the project plan", and nothing more ;-) A: Use Scrum. Create the sprint backlog, have a spreadsheet with the tasks and a column for each day of the sprint. Ask people to fill out the hours worked on each task every day. Send daily report starting with the burndown chart for the sprint and then short two one liners for each member - last worked on and next working on. Send weekly report with the burndown chart, red/yellow/green status for each major feature (and blocking issues and notes if it's not green) and the remaining items on the sprint backlog. I don't have a link to samples, but here are some drafts: 10/02/2008 - Product A daily status <Burndown chart> Team member A Last 24: feature A Next 24: feature A unit tests Team member B Last 24: bug jail Next 24: feature B Team member C Last 24: feature C Next 24: feature C Blocked on: Dependency D - still waiting on the redist from team D 10/02/2008 - Product A weekly status <Burndown chart> **Feature A** - Green [note: red/yellow/green represents status; use background color as well for better visualisation] On track **Feature B** - Yellow [note: red/yellow/green represents status; use background color as well for better visualisation] Slipping a day due to bug jail Mitigation: will load balance unit tests on team member A **Feature C** - Red [note: red/yellow/green represents status; use background color as well for better visualisation] Feature is blocked on external dependency from team D. No ETA on unblock. Mitigation: consider cutting the feature for this sprint **Milestone schedule:** Planning complete - 9/15 (two weeks of planning) Code complete - 10/15 (four weeks of coding) RC - 10/30 (two weeks stabilization and testing) A: Just give them a template laid out in a format that you expect to see the data returned in. You may also consider increasing the time they are going to devote to this and removing the "not thinking too much" clause if you are requiring estimates for future work. I wouldn't trust an estimate that someone came up with in 5 mins. without thinking. If you are currently using any project management software, it should be trivial for the developers to record and review (or even just remember) what they have done compile it for you. Ideally they would be recording issues or questions throughout the day and not trying to come up with them just to fill in the report. It seems like your "I want to learn" list is an excellent starting point to generate a template from. Only you will know what the perfect format for you is. A: Looks like you want to do Extreme Programming stand up meetings. http://www.extremeprogramming.org/rules/standupmeeting.html You can talk to off site team members using the phone with laudspeaker, or some VOIP. A: Generally I have just relied on e-mail as a means of providing status reports, it provides the simplicity and speed of completion but does not enforce any sort of uniformity. There are a number of options to achieve this but they all risk making the process more complex and time consuming. Some of these could be: An online form with sections for each or a multi sheet spreadsheet, with each sheet being a section. All of these require some effort by yourself to create them, do you need the uniformity for some purpose? e.g. to automate the summary reports. An alternative to this would be to use some project management tool which the contractors filled in whilst they were working and that you could report on at any time. I would recommend Thoughtworks Studio Mingle, but it does rely on an agile-like process.
{ "language": "en", "url": "https://stackoverflow.com/questions/165106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Team Foundation Server Port 8080 ASMX Access Issue How come one user in the local Administrators Group has no problem hitting http://localhost:8080/services/v1.0/Registration.asmx while other users in the local Administrators Group get 403 (access denied) errors (with nothing in the Event log)? A: Have you checked the permissions of all three areas. You need permisssion on server, reporting service and sharepoint for this. I would strongly recommend you download Team Foundation Server Administrator tool to do this as otherwise it can be a right pain. A: rasx, yea, the interface isn't the best on that tool. It basically allows an easy way to set up permissions to the Team Foundation Server, Reporting Services, and Sharepoint. Most of the security problems I've come across always resolve down to one of those three permissions messed up on a particular user. I'm pretty sure that's what you're experiencing. Without the Team Foundation Administrator Tool that dove mentioned, you can still just add permissions to each of those areas manually. It sucks that TFS doesn't come with an easy way to manage all permissions everywhere, but there you have it. A: dove, I’m not sure about how the Team Foundation Server Administrator tool would help here. I installed it on the TF server and got an empty interface that looks like it is expecting pre-exiting Team projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/165127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: GPU-based video cards to accelerate your program calculations, How? I read in this article that a company has created a software capable of using multiple GPU-based video cards in parallel to process hundreds of billions fixed-point calculations per second. The program seems to run in Windows. Is it possible from Windows to assign a thread to a GPU? Do they create their own driver and then interact with it? Any idea of how they do it? A: I imagine that they are using a language like CUDA to program the critical sections of code on the GPUs to accelerate their computation. The main function for the program (and its threads) would still run on the host CPU, but data are shipped off the the GPUs for processing of advanced algorithms. CUDA is an extension to C syntax, so it makes it easier to programmer than having to learn the older shader languages like Cg for programming general purpose calculations on a GPU. A: A good place to start - GPGPU Also, for the record, I don't think there is such a thing as non-GPU based graphic cards. GPU stands for graphics processing unit which is by definition the heart of a graphics card.
{ "language": "en", "url": "https://stackoverflow.com/questions/165133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do i set the dns search suffix for a network adapter in .net? I've written a command line utility that detects which network interface is connected, and sets the staitc ip address and dns servers for it (by calling netsh). However, I can't seem to figure out how to set the dns search suffixes. netsh doesnt appear capable of doing that. How do I do that otherwise (WMI perhaps)? A: I think you have to set the value(s) you want in the DNSDomainSuffixSearchOrder property of the Win32_NetworkAdapterConfiguration WMI object. Here's and example of setting values in WMI, if you need it: Modifying Objects & Running Methods A: The dns search suffixes are valid for the whole machine, not for a single network adapter. You can also get them from registry: string searchList = ""; try { using (var reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(tcpSettingsSubKey)) { searchList = (reg.GetValue("SearchList") as string); } } catch(Exception ex) { // something went wrong } (This is not the default dns suffix when the machine is an AD member)
{ "language": "en", "url": "https://stackoverflow.com/questions/165135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SubSonic SubSonic.SqlQuery & Dates Does SubSonic.SqlQuery have a between/and for date ranges? If not, what would be the best way to get a range. A: Try something like this: SqlQuery query = new SqlQuery().From("Table") .WhereExpression("Column") .IsBetweenAnd("1/1/2008", "12/31/2008"); DataSet dataSet = query.ExecuteDataSet(); // Or whatever output you need A: Another way to query with SubSonic. TableCollection data = new TableCollection(); Query q = Table.CreateQuery() .BETWEEN_AND("Column", "1/1/2008", "12/31/2008"); data.LoadAndCloseReader(q.ExecuteReader()); // loop through collection A: Combined Northwind answer: SqlQuery query = new SqlQuery().From("Orders") .WhereExpression("OrderDate") .IsBetweenAnd("1996-07-02", "1996-07-08"); DataSet dataSet = query.ExecuteDataSet(); // Or whatever output you need #region PresentResultsReplaceResponseWriteWithConsole.WriteLineForConsoleApp DataTable dt = dataSet.Tables[0]; Response.Write("<table>"); foreach ( DataRow dr in dt.Rows ) { Response.Write("<tr>"); for (int i = 0; i < dt.Columns.Count; i++) { Response.Write("<td>"); Response.Write(dr[i].ToString() + " "); Response.Write("<td>"); } //eof for Response.Write("</br>"); Response.Write("</tr>"); } Response.Write("<table>"); #endregion PresentResultsReplaceResponseWriteWithConsole.WriteLineForConsoleApp
{ "language": "en", "url": "https://stackoverflow.com/questions/165140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I create a Routed Event in Silverlight 2? Anyone know how to create a routed event in Silverlight 2? In WPF, the code would be like below. However, there’s no EventManager in Silverlight. public static readonly RoutedEvent ShowVideoEvent = EventManager.RegisterRoutedEvent("ShowVideo", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NavBar)); public event RoutedEventHandler ShowVideo { add { AddHandler(ShowVideoEvent, value); } remove { RemoveHandler(ShowVideoEvent, value); } } A: At least for the time being, there doesn't seem to be a way to create your own. That post was however for Beta2, looking at the document for Beta2->RC0 breaking changes, there doesn't seem to be any mention of anything. But then I guess it could be no breaking change, we can always hope eh ;) There are a number of events which are routed but again I'm not sure this documentation has been updated for RC0.
{ "language": "en", "url": "https://stackoverflow.com/questions/165143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redirect the parent frame inside an UpdatePanel on PostBack This is kind of a weird problem, but I have to create a search box for our site that will be iframed on another site. When the user clicks the search button, it needs to redirect the parent frame to our search results page. At the moment what I've done is to make the search button a postback trigger then registering a client script block to run this: if (window.parent) window.parent.location.href='<url>'; This is ok, but it seems like a hack & it means if the user clicks back on the browser after searching, it redirects them back to the search results page. Is there a better way of doing this? A: OK, since noone else has answered, I'll give this a go. First off, are you testing the code you're using in a real-world way? I am concerned that in a real-world application that your iframed page and the parent page will not reside on the same domain. If so, there is not likely to be any way for your code to direct the parent window to any URL. If you are allowed to control the parent frame's location, your code looks fine to me. If you don't want the new URL in the history, I believe that you can use: if (window.parent) { window.parent.location.replace("<url>"); } See for example: "The Difference Between Javascript Redirect Methods"
{ "language": "en", "url": "https://stackoverflow.com/questions/165149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is Dreamweaver worth getting if I probably won't use its WYSIWYG editor? In the past I've done web application development using Visual Studio. Initially I'd use the design view, editing the page visually. But over time I learned more and more (X)HTML, CSS, and Javascript. I became familiar with the tags for ASP.NET server controls and their common attributes. I got to the point where I'd do all the markup by hand (still in Visual Studio though) and then test the site in an actual browser. Of course I'd also still use Visual Studio for programming server side functionality in C#, but never the WYSIWYG page editor. I was able to get work done faster too, getting the site to look just the way I wanted, and the same across different browsers. Now I'm going to be taking charge of a public facing website (entirely static content - no ASP.NET, PHP, or anything). The website was created and maintained using Dreamweaver, which I don't have and never used before. I'll be working from home, so the organization is looking into getting me a copy of Dreamweaver. Even though it's not money out of my own pocket ... Is it worth using Dreamweaver if I probably won't touch the visual editor? Or should I tell them to save their money and I'll just use Notepad++. Or am I crazy and should relearn to use a WYSIWYG editor? A: You may not know until you see the code. If they were using things like Dreamweaver templates, unless you are going to extricate them, you may end up needing Dreamweaver for sanity sake. A: Dreamweaver is really useful if you maintain a site with templates. If the site is in PHP or ASP, then all you need to do is put the common parts (header, footer etc.) in a separate file and include them in the different pages. If the pages are static then the common parts can't be included. Which means that if you want to change the menu, you have to change it in all pages. With dreamweaver, you can save a page as a template and when you create a new page from a template, dreamweaver stores it in the comments. Next time you update the template, all the pages that use the template are updated. I found this to be the best use of dreamweaver. A: I do 95% of my web dev stuff using Dreamweaver's code editor. But, for the other 5%, the WYSIWYG stuff really comes in handy. Plus, it's not your money anyway. I'd say get it and if the WYSIWYG stuff is too much for you just keep it in source code mode and use it as an editor. A: I haven't used a WYSIWYG HTML editor in years, all the HTML I produce these days is hand-coded, and it's something I would recommend to anyone. WYSIWYG Editors simply make it far too easy to throw in tons of unnecessary markup, and then you end up with unwieldy pages that are tricky to work with and hard to fix browser compatibility problems in. However. If you're taking over a large existing codebase that has been produced this way, I'd say you probably want to make sure you at least have access to Dreamweaver or a similar editor (if they were produced in Dreamweaver, that's probably the best choice). Simply because many pages designed in this way are rather verbose, and can be a nightmare to deal with in a text editor. A: This depends - you mean old school Dreamweaver or CS4 Dreamweaver? With all the new additions (code hinting with some of the newer javascript frameworks, a "preview" that is integrated with webkit so you can see your page in action, being able to test AJAX calls and do a "code freeze") I'm tempted to walk away from jedit and try it out. A: I believe that DreamWeaver gives you intellisense in the code editor for HTML, so I would use it for that, if you're not paying for it. I wouldn't pay for that myself though :) A: If the Visual Studio editor works fine for you, there is no point in switching. And if you don't like WYSIWIG editing, then there's no point in learning it. I stopped using WYSIWIG years ago, and like you, I've found it to be much more flexible and reliable to edit HTML/CSS by hand. If you like DreamWeaver more and the organisation is willing to pay for it, then go for it! A: FWIW, I do a lot of HTML and javascript coding in dreamweaver's code view- the JSF extensions are nice as well. I got it as part of the CS3 bundle, since I needed to get my hands on photoshop and illustrator as well to carve up graphics. If possible, try to get your company to get the whole bundle, since graphics manipulation is always important when you're maintaining a site- and most designers will be giving you photoshop source files. I never ever go in wysiwyg mode, and it's still useful. A: I use dreamweaver, but not for the same reasons as everyone here seem to. I like the syntax highlighting, and I absolutely LOVE the way Dreamweaver handles FTP in the window on the right. If I could find another editor that would offer these two things, I would, but none seem to be that great. I code my pages by hand usually (I do a LOT of PHP, which dreamweaver 8 obviously can't preview) so I do a lot of things like (1) edit page (2) upload changes (3) preview live on testing server. However, I still use the WYSIWIG editor occasionally, especially if I need to throw something together using tables or form elements. I just find it to be a bit quicker that way than doing things by hand. That said, I never use Dreamweaver (8, mind) for CSS, as the implementation is buggy at best. I much prefer to do CSS and more complex HTML by hand. I also do not use the standard method of templating, as I prefer to have one "index.php" that calls in the appropriate template and stuffs data into it that it generated before. All that said though, Dreamweaver offers a nice enough set of tools that I don't really want to leave it, and it certainly won't hurt to learn it, especially if its free. I'd say at least try it out and see if its going to work before making a final decision. It comes down to what you personally prefer to use. A: I hand-code but there are times Dreamweaver is incredibly useful: * *Making visual-tweaks to someone else's complex HTML. It's much quicker to use the WYSIWYG if you're short on time and the code is a mess. *Dreamweaver has got an incredibly good search and replace. The tag-based searching is the best I've seen anywhere for you whilst the regex seach/replace allows back-references, named groups in the replace field etc. The code Dreamweaver produces isn't too horrific and it's fairly good at not breaking your own nice code if you ever dip into the visual editor. A: I use dreamweaver CS5 for code only on a daily basis, and it's a great tool. It is very effective, and its a great tool even for people who already know how to write code. Some of its' features that make it one of the best editors, in my opinion, are: * *Code coloring *Customizable color-schemes *Error highlighting *in-app validation *Autocomplete & Codehinting (works great!) *in-app FTP *New document type dialog (great for quick start) *Search & replace *Code Snippets There are many more features, like setting up a local server and binding it to a database so you can write queries more easily and use dreamweaver's "help" with server-side code, but I haven't really got into it. Bottom line: If you are considering getting Dreamweaver mostly for code editing, then I'd say it's definitely a great deal - even if you aren't going to use some of its' other features. A: Dreamweaver's a tad bloated for something which you really can just do in Notepad (++ or otherwise). No WYSIWYG will give you code to the same quality as hand-crafted code. Especially since it's vanilla HTML, just use an everyday programmer's text editor. Having intellisense isn't that important: I mean, there's only about 10 tags you need to know.
{ "language": "en", "url": "https://stackoverflow.com/questions/165151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Easy mysql question regarding primary keys and an insert In mysql, how do I get the primary key used for an insert operation, when it is autoincrementing. Basically, i want the new autoincremented value to be returned when the statement completes. Thanks! A: MySQL's LAST_INSERT_ID() A: Your clarification comment says that you're interested in making sure that LAST_INSERT_ID() doesn't give the wrong result if another concurrent INSERT happens. Rest assured that it is safe to use LAST_INSERT_ID() regardless of other concurrent activity. LAST_INSERT_ID() returns only the most recent ID generated during the current session. You can try it yourself: * *Open two shell windows, run mysql client in each and connect to database. *Shell 1: INSERT into a table with an AUTO_INCREMENT key. *Shell 1: SELECT LAST_INSERT_ID(), see result. *Shell 2: INSERT into the same table. *Shell 2: SELECT LAST_INSERT_ID(), see result different from shell 1. *Shell 1: SELECT LAST_INSERT_ID() again, see a repeat of earlier result. If you think about it, this is the only way that makes sense. All databases that support auto-incrementing key mechanisms must act this way. If the result depends on a race condition with other clients possibly INSERTing concurrently, then there would be no dependable way to get the last inserted ID value in your current session. A: The MySQL Docs describe the function: LAST_INSERT_ID() A: [select max(primary_key_column_name) from table_name] Ahhh not nessecarily. I am not an MySQL guy but there are specific way to get the last inserted id for the last completed action that are a little more robust than this. What if an insert has happened between you writing to the table and querying it? I know about because it stung me many moons ago (so yeah it does happen). If all else fails read the manual: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
{ "language": "en", "url": "https://stackoverflow.com/questions/165156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: In Ruby on Rails, how do I format a date with the "th" suffix, as in, "Sun Oct 5th"? I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix. For example, the day this question was asked would display "Thu Oct 2nd". I'm using Ruby 1.8.7, and Time.strftime just doesn't seem to do this. I'd prefer a standard library if one exists. A: Create your own %o format. Initializer config/initializers/srtftime.rb module StrftimeOrdinal def self.included( base ) base.class_eval do alias_method :old_strftime, :strftime def strftime( format ) old_strftime format.gsub( "%o", day.ordinalize ) end end end end [ Time, Date, DateTime ].each{ |c| c.send :include, StrftimeOrdinal } Usage Time.new( 2018, 10, 2 ).strftime( "%a %b %o" ) => "Tue Oct 2nd" You can use this with Date and DateTime as well: DateTime.new( 2018, 10, 2 ).strftime( "%a %b %o" ) => "Tue Oct 2nd" Date.new( 2018, 10, 2 ).strftime( "%a %b %o" ) => "Tue Oct 2nd" A: Although Jonathan Tran did say he was looking for the abbreviated day of the week first followed by the abbreviated month, I think it might be useful for people who end up here to know that Rails has out-of-the-box support for the more commonly usable long month, ordinalized day integer, followed by the year, as in June 1st, 2018. It can be easily achieved with: Time.current.to_date.to_s(:long_ordinal) => "January 26th, 2019" Or: Date.current.to_s(:long_ordinal) => "January 26th, 2019" You can stick to a time instance if you wish as well: Time.current.to_s(:long_ordinal) => "January 26th, 2019 04:21" You can find more formats and context on how to create a custom one in the Rails API docs. A: I like Bartosz's answer, but hey, since this is Rails we're talking about, let's take it one step up in devious. (Edit: Although I was going to just monkeypatch the following method, turns out there is a cleaner way.) DateTime instances have a to_formatted_s method supplied by ActiveSupport, which takes a single symbol as a parameter and, if that symbol is recognized as a valid predefined format, returns a String with the appropriate formatting. Those symbols are defined by Time::DATE_FORMATS, which is a hash of symbols to either strings for the standard formatting function... or procs. Bwahaha. d = DateTime.now #Examples were executed on October 3rd 2008 Time::DATE_FORMATS[:weekday_month_ordinal] = lambda { |time| time.strftime("%a %b #{time.day.ordinalize}") } d.to_formatted_s :weekday_month_ordinal #Fri Oct 3rd But hey, if you can't resist the opportunity to monkeypatch, you could always give that a cleaner interface: class DateTime Time::DATE_FORMATS[:weekday_month_ordinal] = lambda { |time| time.strftime("%a %b #{time.day.ordinalize}") } def to_my_special_s to_formatted_s :weekday_month_ordinal end end DateTime.now.to_my_special_s #Fri Oct 3rd A: Taking Patrick McKenzie's answer just a bit further, you could create a new file in your config/initializers directory called date_format.rb (or whatever you want) and put this in it: Time::DATE_FORMATS.merge!( my_date: lambda { |time| time.strftime("%a, %b #{time.day.ordinalize}") } ) Then in your view code you can format any date simply by assigning it your new date format: My Date: <%= h some_date.to_s(:my_date) %> It's simple, it works, and is easy to build on. Just add more format lines in the date_format.rb file for each of your different date formats. Here is a more fleshed out example. Time::DATE_FORMATS.merge!( datetime_military: '%Y-%m-%d %H:%M', datetime: '%Y-%m-%d %I:%M%P', time: '%I:%M%P', time_military: '%H:%M%P', datetime_short: '%m/%d %I:%M', due_date: lambda { |time| time.strftime("%a, %b #{time.day.ordinalize}") } ) A: Use the ordinalize method from 'active_support'. >> time = Time.new => Fri Oct 03 01:24:48 +0100 2008 >> time.strftime("%a %b #{time.day.ordinalize}") => "Fri Oct 3rd" Note, if you are using IRB with Ruby 2.0, you must first run: require 'active_support/core_ext/integer/inflections' A: >> require 'activesupport' => [] >> t = Time.now => Thu Oct 02 17:28:37 -0700 2008 >> formatted = "#{t.strftime("%a %b")} #{t.day.ordinalize}" => "Thu Oct 2nd" A: You can use active_support's ordinalize helper method on numbers. >> 3.ordinalize => "3rd" >> 2.ordinalize => "2nd" >> 1.ordinalize => "1st"
{ "language": "en", "url": "https://stackoverflow.com/questions/165170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "191" }
Q: Confusing return statement I'm failing to understand exactly what the IF statement is doing, from what I can see it is checking if the variable x is equal to the int 0. If this is true the ABSOLUTE value of the variable y is returned... this is when I lose the plot, why would the return statement then go on to include <= ESPILON? Surely this means less than or equal to the value of epsilon? if so how is that working? If it doesn't mean that then what does it mean? (JAVA CODE) final double EPSILON = 1E-14; if (x == 0) return Math.abs(y) <= EPSILON; A: It returns true if the absolute value of y is <= EPSILON, and false otherwise. The <= is evaluated before the return statement. This code is equivalent: if(x == 0) { boolean ret = Math.abs(y) <= EPSILON; return ret; } The code isn't simply read from left to right. A simpler example is int x = 3 + 4 * 5; After evaluating this, x is 23, not 35. The evaluation is 3 + (4*5), not (3+4)*5, because the * has a higher precedence than the +. The return statement in the original example has a very low precedence. All operators like +, -, <, >= are evaluated before it. A: The entire expression Math.abs(y) <= EPSILON should be evaluated first, which means the function is going to return a boolean value (true/false). Having said that, if x != 0 then I'm not sure what will get returned. A: Floating-point math is by its nature inaccurate, so rather than testing for equivalence (which is always a bad idea), instead the developer has chosen a small number (1x10^-14 in this case) as the acceptable tolerance for proximity to zero. The return statement returns a comparison, so what this will do is take the absolute value of y, and return true if and only if it is sufficiently close to zero, where sufficiently close is defined by EPSILON. A: You're right that it is checking if the variable x is equal to (well, maybe int) 0. However, if this is true then it doesn't return the absolute value of y, it returns a boolean, the result of the <= operator. A: It's returning a boolean value. Epsilon is a double, holding the value 1E-14. This is the actual IF statement if (x==0) { return MATH.abs(y) <= EPSILON; } So, what's getting returned is if the absolute value of y is less than or equals to Epsilon. A: I haven't done Java in a long time but it would appear that this is actually returning a boolean (which might be implicitly cast). I would say that if x equals 0, it returns true when the absolute value of y <= Epsilon, otherwise it returns false. However if x doesn't equal 0 then it would return null, as no statement covers the else. A: The "issue" is that this fragment relies heavyly on operator precedence (not bad per se, but sometimes it can be confusing). Here you can find a list of all java operators with their precedence, and here for comparison the same table for C/C++ A: It is equivalent to this return (Math.abs(y) <= EPSILON); which should have been added to the code for clarity. As has been mentioned, it returns a boolean. An alternatives would be if (Math.abs(y) <= EPSILON) return true; else return false;
{ "language": "en", "url": "https://stackoverflow.com/questions/165175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: printf + uint_64 on Solaris 9? I have some c(++) code that uses sprintf to convert a uint_64 to a string. This needs to be portable to both linux and Solaris. On linux we use %ju, but there does not appear to be any equivalent on Solaris. The closest I can find is %lu, but this produces incorrect output. Some sample code: #include <stdio.h> #include <sys/types.h> #ifdef SunOS typedef uint64_t u_int64_t; #endif int main(int argc, char **argv) { u_int64_t val = 123456789123L; #ifdef SunOS printf("%lu\n", val); #else printf("%ju\n", val); #endif } On linux, the output is as expected; on Solaris 9 (don't ask), it's "28" What can I use? A: On a C99 compliant system: #include <inttypes.h> uint64_t big = ...; printf("%" PRIu64 "\n", big); See section 7.8 of the C99 standard. The specifiers are {PRI,SCN}[diouxX]{N,LEASTN,MAX,FASTN,PTR} Where PRI is for the printf() family, SCN is for the scanf() family, d and i for signed integral types; o,u,x,X are for unsigned integral types as octal, decimal, hex, and Hex; N is one of the supported widths; LEAST and FAST correspond to those modifiers; PTR is for intptr_t; and MAX is for intmax_t. A: The answer depends on whether your code is actually C or C++. In C, you should be using an unsigned long long rather than another type (this is conformant to the current standard, and long long is pretty common as far as C99 support goes), appending ULL instead of L to your constant, and using (as has been mentioned) %llu as your specifier. If support for C99 doesn't exist, you may want to check the compiler documentation, as there is no other standard way to do it. long long is guarateed to be 64 bits at least. A: If you have have inttypes.h available you can use the macros it provides: printf( "%" PRIu64 "\n", val); Not pretty (I seem to be saying that a lot recently), but it works. A: You can use %llu for long long. However, this is not very portable either, because long long isn't guaranteed to be 64 bits. :-) A: You can get uint64_t from stdint.h if you want to avoid the SunOS conditional typedef.
{ "language": "en", "url": "https://stackoverflow.com/questions/165188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Anyone use xui? JavaFX? Warning: Java newbie. Been looking at XUI for Java. Its looks quite interesting. Sort of liek a WPF way of designing interfaces. But googling around I don't see much other than articles saying it had been released. So is it used much or a bit niche? Are there other similar frameworks for Java? Was looking at JavaFX but seems to be a general feeling that it has been slow development wise. Are there other frameworks that work in simialr ways? I get the impression Swing/SWT seem to more like WinForms. I'm looking to do something a bit more WPF like. As I said, Java newbie, so I might have this all confused. Seem to be so many UI frameworks its a bit overwhelming working out what to use for a new project. A: If you can't use JavaFx, Take a look http://www.swixml.org. A: JavaFx is a nice framework, it is pretty easy to learn and use. There are also some nice tutorials, doco, API's available, its still only in Preview SDK at the moment, but the next reelase is expected out relativly soon. I would recommend giving it a try official javaFx site suns JavaFX overview openjfx
{ "language": "en", "url": "https://stackoverflow.com/questions/165209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: linux: getting umask of an already running process? How can I check the umask of a program which is currently running? [update: another process, not the current process.] A: From the GNU C Library manual: Here is an example showing how to read the mask with umask without changing it permanently: mode_t read_umask (void) { mode_t mask = umask (0); umask (mask); return mask; } However, it is better to use getumask if you just want to read the mask value, because it is reentrant (at least if you use the GNU operating system). getumask is glibc-specific, though. So if you value portability, then the non-reentrant solution is the only one there is. Edit: I've just grepped for ->umask all through the Linux source code. There is nowhere that will get you the umask of a different process. Also, there is no getumask; apparently that's a Hurd-only thing. A: You can attach gdb to a running process and then call umask in the debugger: (gdb) attach <your pid> ... (gdb) call umask(0) [Switching to Thread -1217489200 (LWP 11037)] $1 = 18 # this is the umask (gdb) call umask(18) # reset umask $2 = 0 (gdb) (note: 18 corresponds to a umask of O22 in this example) This suggests that there may be a really ugly way to get the umask using ptrace. A: If you're the current process, you can write a file to /tmp and check its setting. A better solution is to call umask(3) passing zero - the function returns the setting prior to the call - and then reset it back by passing that value back into umask. The umask for another process doesn't seem to be exposed. A: Beginning with Linux kernel 4.7, the umask is available in /proc/<pid>/status. A: A colleague just showed me this command line pattern for this. I always have emacs running, so that's in the example below. The perl is my contribution: sudo gdb --pid=$(pgrep emacs) --batch -ex 'call/o umask(0)' -ex 'call umask($1)' 2> /dev/null | perl -ne 'print("$1\n")if(/^\$1 = (\d+)$/)'
{ "language": "en", "url": "https://stackoverflow.com/questions/165212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Vim Dvorak keybindings (rebindings :) Although I played with it before, I'm finally starting to use Dvorak (Simplified) regularly. I've been in a steady relationship with Vim for several years now, and I'm trying to figure out the best way to remap the key bindings to suit my newfound Dvorak skills. How do you remap Vim's key bindings to best work with Dvorak? Explanations encouraged! A: I simply use standard qwerty for commands and dvorak for insert mode Here is how to set it up A: My rebindings: noremap h h noremap t j noremap n k noremap s l noremap j t noremap l n noremap k s noremap J T noremap L N noremap K S noremap T J noremap N L noremap S K Notes: * *In qwert, vi has to use 'h', because vi doesn't want to use ';' a non-letter. But in dvroak, we have 's', so why not take this advantage? *vi uses Caps for relative actions. This is a good design philosophy. So I try to conform this. Meanings: n (Next) -> l (Left) -- "What's left?" resembles "What's next?" s (Substitute) -> k (Kill then insert) t (jump Till) -> j (Jump till) N, S, T are similar. J (Join lines) -> T (make lines Together) K (Keyword) -> S (Subject) L[count] (Line count) -> N (line Number) B.T.W. L itself goes to the last line, and N is the last letter of fin. (Thanks for tenzu to point out this.) P.S. I have used these rebindings for a while. Now I does not use it in vim. I just use the default ones. A: I use one of the more common recommended keybindings: Dvorak it! no d h no h j no t k no n l no s : no S : no j d no l n no L N Added benefits no - $ no _ ^ no N <C-w><C-w> no T <C-w><C-r> no H 8<Down> no T 8<Up> no D <C-w><C-r> Movement keys stay in the same location. Other changes: * *Delete 'd' -> Junk 'j' *Next 'n' -> Look 'l' *Previous 'N' -> Look Back 'L' There were also some changes for familiarity, 's'/'S' can be used to access command mode (the old location of the :, which still works). Added Benefits * *End of line '$' -also- '-' *Beginning of line '^' -also- '_' *Move up 8 'T' *Move down 8 'H' *Next window <C-w><C-w> -also- 'N' *Swap windows <C-w><C-r> -also- 'D' -Adam A: I don't find that I need to remap the keys for Dvorak -- I very quickly got used to using the default keybindings when I switched layouts. As a bonus, it means that I don't have to remember two different key combinations when I switch between Dvorak and Qwerty. The difference in keyboard layout is enough that I'm not expecting keys to be in the same location. A: Vim ships with an extensive Dvorak script, but unfortunately it’s not directly source-able, since the file includes a few lines of instructions and another script that undoes its effects. To read it, issue the following command: :e $VIMRUNTIME/macros/dvorak A: A little late, but I use the following: " dvorak remap noremap h h noremap t j noremap n k noremap s l noremap l n noremap L N " easy access to beginning and end of line noremap - $ noremap _ ^ This basically does the following: * *left-down-up-right are all under the default finger positions on the home row (i.e. not moved over by one as in the default QWERTY Vim mappings) *l/L is used for next/previous search result *use -/_ to reach the end/beginning of a line This seems to work for me... A: You can use this to have Vim use Dvorak only in insert mode: :set keymap=dvorak This way all of the commands are still in QWERTY, but everything you type will be in Dvorak. Caveats: Well, almost everything. Insert mode, search mode, and replace mode will all be dvorak, but ex commands will not. This means that you don't have to relearn :wq, but you will need type :%s/foo/bar/gc in QWERTY. This won't help if you only want to move certain commands, but I found that in my head, "move forward one word" was bound to "move left ring finger up," rather than "ask the typing department where the letter 'w' is and then press it," which made this method much easier for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/165231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: How do you force a .net application to display on a particular monitor in a dual monitor setup? I would like to run multiple copies of my application and force the first to open on one monitor and the second instance on a second monitor A: Screen monitor1 = System.Windows.Forms.Screen.AllScreens[0]; Screen monitor2 = System.Windows.Forms.Screen.AllScreens[1]; will give you the size and position information for both monitors. Form f = new Form(); f.Location = monitor2.Location; f.Size = monitor2.Size; f.StartPosition = FormStartPosition.Manual; f.WindowState = FormWindowState.Maximized; f.Show(); should pop a form up in your second monitor.
{ "language": "en", "url": "https://stackoverflow.com/questions/165249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: JavaScript: how to force Image() not to use the browser cache? If I load the nextimg URL manually in the browser, it gives a new picture every time I reload. But this bit of code shows the same image every iteration of draw(). How can I force myimg not to be cached? <html> <head> <script type="text/javascript"> function draw(){ var canvas = document.getElementById('canv'); var ctx = canvas.getContext('2d'); var rx; var ry; var i; myimg = new Image(); myimg.src = 'http://ohm:8080/cgi-bin/nextimg' rx=Math.floor(Math.random()*100)*10 ry=Math.floor(Math.random()*100)*10 ctx.drawImage(myimg,rx,ry); window.setTimeout('draw()',0); } </script> </head> <body onload="draw();"> <canvas id="canv" width="1024" height="1024"></canvas> </body> </html> A: You can't stop it from caching the image altogether within Javascript. But, you can toy with the src/address of the image to force it to cache anew: [Image].src = 'image.png?' + (new Date()).getTime(); You can probably take any of the Ajax cache solutions and apply it here. A: That actually sounds like a bug in the browser -- you could file at http://bugs.webkit.org if it's in Safari or https://bugzilla.mozilla.org/ for Firefox. Why do i say potential browser bug? Because the browser realises it should not be caching on reload, yet it does give you a cached copy of the image when you request it programmatically. That said are you sure you're actually drawing anything? the Canvas.drawImage API will not wait for an image to load, and is spec'd to not draw if the image has not completely loaded when you try to use it. A better practice is something like: var myimg = new Image(); myimg.onload = function() { var rx=Math.floor(Math.random()*100)*10 var ry=Math.floor(Math.random()*100)*10 ctx.drawImage(myimg,rx,ry); window.setTimeout(draw,0); } myimg.src = 'http://ohm:8080/cgi-bin/nextimg' (You can also just pass draw as an argument to setTimeout rather than using a string, which will save reparsing and compiling the same string over and over again.) A: The easiest way is to sling an ever-changing querystring onto the end: var url = 'http://.../?' + escape(new Date()) Some people prefer using Math.random() for that instead of escape(new Date()). But the correct way is probably to alter the headers the web server sends to disallow caching. A: There are actually two caches you need to bypass here: One is the regular HTTP cache, that you can avoid by using the correct HTTP headers on the image. But you've also got to stop the browser from re-using an in-memory copy of the image; if it decides it can do that it will never even get to the point of querying its cache, so HTTP headers won't help. To prevent this, you can use either a changing querystring or a changing fragment identifier. See my post here for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/165253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Flowlayout panel not display the scroll bar after some resizes I have a flowlayout panel and on a resize event, I resize all the controls inside the flowlayout panel so they fit the width of the (flowlayoutpanel - padding - scroll bar width). On some resizes, the scroll bar is not shown, hiding most of the controls outside the area of the flowlayoutpanel while on other resizes the scroll bar is shown.I have set the AutoScroll property on the flowlayoutpanel to true. This is all done using C#, but I have also encountered this problem in VB.net. Is there a way to force the flowlayoutpanel to recalculate how the controls are laid out after I resize the controls in the resize event or some other way to fix this problem? A: Try the .PerformLayout() method, see if that helps. A: By using the Refresh method (inherited from Control) you can force the control to invalidate and redraw itself and its children. Edit: Curiously, are you doing this resize to get the effect of top-bottom stacking?
{ "language": "en", "url": "https://stackoverflow.com/questions/165284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I get my hands on a Dvorak keyboard? I've always assumed that before I can use the Dvorak layout I need to purchase a Dvorak keyboard. But I can't find one on Amazon. Is it simply a matter of popping the keys off a Qwerty keyboard and moving them around? A: If you are a touch typer, you will benefit greatly from the Dvorak layout. The way I taught myself Dvorak as a touch typer was to tape a small copy of the layout to my monitor. Then I practiced typing by looking at the copy instead of the keys. That was six years ago. I still use stardard Qwerty keyboards, but I haven't looked at what the keys says since I first learned to touch type 20 years ago. A: You could go with Das Keyboard Ultimate, which has no letters on the keys. You will become a touch Dvorak typist in no time flat. Or you could wimp out and put labels on the keys. A: I learned Dvorak by changing the layout using the OS. I printed out a keyboard layout and taped it below my monitor so I could refer to it without looking down at the keys. Later, once I learned where the keys were, I printed out stickers and put them on the keys caps. To this day, I just rely on the OS layout switching to get Dvorak. A: I tried to rearrange the letters once, on some keyboards it doesn't work. Since the letters are different in shape based on the row they are in. A: Well if you have a fat wallet then an Optimus Keyboard would give you Dvorak(and qwerty and azerty and any combination!) A: To help you learn your way around the keyboard layout, you can physically rearrange the keys on your Qwerty keyboard. Or you can simply re-label the keys with stickers. I personally learned to type using the Dvorak layout without re-labeling or re-arranging keys, and found that it was not difficult. Most modern OSes allow you to remap any keyboard to the Dvorak layout. * *Windows XP/Vista: you can set your mappings through Control Panel->Regional and Language Options->Languages->Details.... *Mac OSX: System Preferences -> International -> Input Menu (thanks jmah) *Ubuntu: System -> Preferences -> Keyboard, Layouts Tab, Add..., Select the Devorak layout of your choice and optionaly set as default. You can then right-click your panel, select "Add to panel" and choose keyboard indicator. You can then switch between layouts. (Thanks Vagnerr) A: You can just rearrange your keys on your current keyboard and change the layout. Here is the key layout: I'm not seeing the image, so here is the direct link. A: Switchable between qwerty and Dvorak: DvortyBoard Cheap, but you need the OS to remap the keys: Hooleon A: If you're going to rearrange the physical keyboard, go for a Model M with removable key caps. A: Don't get a dvorak keyboard. Non-touch-typing dvorak is as bad for your wrists, and as slow, as non-touch-typing qwerty. There is absolutely no point. You want to get out of that habit. Change the layout in your OS and learn not to rely on looking at the keyboard. If anything, pop off the keycaps and put them back in randomly. If you absolutely must buy new hardware, get a Das Keyboard or any other blank keyboard. A: I got two of these (one for work and one for home), and I love them: http://matias.ca/dvorak/ It's also switchable via a button to Qwerty, as a concession to your colleagues who may need to type on it. My only complaint is a very minor one: after 4 years, some of the labels started to fade or scratch off. If you're just learning Dvorak, good luck. The best thing I did is switch to it 100% of the time. When I was switching back to Qwerty for speed, all I did was scramble my brain. Dvorak will be slower while you're on the learning curve, but it's well worth it. A lot less stress on the fingers in the long run, and after 12 years, I actually type faster on Dvorak than I ever did on Qwerty. Best way to practice: open a book or magazine and copy some paragraphs in Dvorak. If you find a tricky paragraph, type it out two or three times until the patterns start to become muscle memory. Good luck! A: You'll have trouble getting the keys to fit (perhaps you could just draw over them) but yeah, you should be able to switch layout within the OS. A: I don't know how much you are prepared to invest, but I think the Optimus Maximus keyboard from Art Lebedev Studios would be a good choice, since you can switch keyboard layout quite easily and no need for the key pop-up. A: On most PC keyboards the keys have in each row have a different shape. The tops of the keycaps are at a different angle. This provides a slight front-to-back curvature of the top surface of the keys. (You can see this if you peer at the keys from the side). If you go moving keys between rows, the tops of the keys will not line up... the keyboard will look strange and feel "bumpy" and uneven. Not good for touch typing. Solutions: A flat keyboard - a few manufacturers produce keyboards where all the keycaps are the same shape. Apple and Sun keyboards are like this, and I think most Logitech keyboards too... But be careful of the new Apple aluminium keyboard -- it may be harder to remove the keycaps safely. Also, you are best starting with a US QWERTY keyboard. Other national layouts have some different keys, and you won't be able to get standard Dvorak by re-arranging. A: You could try getting a custom keyboard from Unicomp. They offer an IBM buckling spring style keyboard called the "Customizer 104/105" that is available in many different languages, including US-Dvorak if you ask for it. I have purchased a couple of keyboards from this company and the quality is top notch. If you want a new buckling spring keyboard, this is the only company that I am aware of that offers them. This keyboard is hardwired so you don't have any of the issues that you would have if you switch the keyboard layout in the OS - like your log-in key map being different than your account key map, or problems with remoting into another computer. Unicomp Keyboards A: You can just change the layout in your OS. It actually would be better not to get a Dvorak keyboard so you can learn Dvorak without being dependent on looking at the keys. A great typing tutor to help you learn is Stamina Typing Tutor (just google it), which has an on screen keyboard so you don't have to look at your keys. And when you aren't just practicing you can print out the Dvorak layout from Google images and refer to that as you type. If you really want to get a hardwired keyboard search Matias Dvorak on Amazon. That's the only keyboard I could find on Amazon that was Dvorak, and it has a button to switch between Qwerty and Dvorak. I would not rearrange your keys though since most OS's don't switch to Dvorak until the user logs in.
{ "language": "en", "url": "https://stackoverflow.com/questions/165314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: STAThread and multithreading From the MSDN article on STAThread: Indicates that the COM threading model for an application is single-threaded apartment (STA). (For reference, that's the entire article.) Single-threaded apartment... OK, that went over my head. Also, I read somewhere that unless your application uses COM interop, this attribute actually does nothing at all. So what exactly does it do, and how does it affect multithreaded applications? Should multithreaded applications (which includes anything from anyone using Timers to asynchronous method calls, not just threadpools and the like) use MTAThread, even if it's 'just to be safe'? What does STAThread and MTAThread actually do? A: Apartment threading is a COM concept; if you're not using COM, and none of the APIs you call use COM "under the covers", then you don't need to worry about apartments. If you do need to be aware of apartments, then the details can get a little complicated; a probably-oversimplified version is that COM objects tagged as STA must be run on an STAThread, and COM objects marked MTA must be run on an MTA thread. Using these rules, COM can optimize calls between these different objects, avoiding marshaling where it isn't necessary. A: What that does it it ensures that CoInitialize is called specifying COINIT_APARTMENTTHREADED as the parameter. If you do not use any COM components or ActiveX controls it will have no effect on you at all. If you do then it's kind of crucial. Controls that are apartment threaded are effectively single threaded, calls made to them can only be processed in the apartment that they were created in. Some more detail from MSDN: Objects created in a single-threaded apartment (STA) receive method calls only from their apartment's thread, so calls are serialized and arrive only at message-queue boundaries (when the Win32 function PeekMessage or SendMessage is called). Objects created on a COM thread in a multithread apartment (MTA) must be able to receive method calls from other threads at any time. You would typically implement some form of concurrency control in a multithreaded object's code using Win32 synchronization primitives such as critical sections, semaphores, or mutexes to help protect the object's data. When an object that is configured to run in the neutral threaded apartment (NTA) is called by a thread that is in either an STA or the MTA, that thread transfers to the NTA. If this thread subsequently calls CoInitializeEx, the call fails and returns RPC_E_CHANGED_MODE. A: STAThread is written before the Main function of a C# GUI Project. It does nothing but allows the program to create a single thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/165316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "105" }
Q: How to get the asp.net login control to auto authenticate a previously authenticated user? I am trying to to set up the login control to remember the login credentials of a user who has previously entered their user name and password successfully. I set the remember me property to true, but it doesnt seem to triger any events where I could read the cookie and auto login the user. Is there a straightforward mechanism to accomplish this? A: You need to Google for Forms Authentication in ASP.NET 2.0 You will need to set up your application (via web.config) and may also need to alter IIS settings. While it's all quite straightforward, there are heaps of settings that can be used, so best is to read some of the articles. ScottGu has a blog entry that goes into a lot of good detail. There are also many good video's at www.asp.net including these Security Tutorials try How to: Create an ASP.NET Login Page and Walkthrough: Creating a Web Site with Membership and User Login. If I recall, you still have to do the authentication yourself unless you use the Sql Server Membership provider. In that case you still have to set up the database and web.config. Essentially, once you've set up configuration properly, you have a login page. In that login page you tell Forms Authentication to create the authentication ticket for you once you authenticate them: if (VerifyUser(name, password) ) // this is not a framework method FormsAuthentication.RedirectFromLoginPage( userName, false); // no persistent cookie If you want to read the authentication ticket data (from anywhere else). // output just writes to a StringBuilder 'sb' output(sb, "Identity.AuthenticationType", Page.User.Identity.AuthenticationType); FormsIdentity fi = Page.User.Identity as FormsIdentity; if (fi == null) { output(sb, "Identity Type", Page.User.Identity.ToString()); return; } output(sb, "FormsIdentity.Ticket.IssueDate", fi.Ticket.IssueDate); output(sb, "FormsIdentity.Ticket.Expiration", fi.Ticket.Expiration); output(sb, "FormsIdentity.Ticket.Name", fi.Ticket.Name); output(sb, "FormsIdentity.Ticket.CookiePath", fi.Ticket.CookiePath); output(sb, "FormsIdentity.Ticket.UserData", fi.Ticket.UserData); output(sb, "FormsIdentity.Ticket.Version", fi.Ticket.Version); output(sb, "FormsIdentity.Ticket.IsPersistent", fi.Ticket.IsPersistent); The point is, once authenticated, asp.net will only redirect the user to the login page if the authentication ticket has expired and the user is on a protected page. Asp.net doesn't keep asking you to authenticate the user unnecessarily.
{ "language": "en", "url": "https://stackoverflow.com/questions/165331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Relative paths in Visual Studio I'm working in Visual Studio 2005 and have added a text file that needs to be parsed by right-clicking the project in the solution explorer and add --> new item. This places the .txt file to the project folder. The debug .exe file is in the /bin/debug folder. How do I properly point to the txt file from code using relative paths that will properly resolve being two folders back, while also resolving to be in the same folder after the solution is published? A: Check out the Application Class. It has several members that can be used to locate files, etc. relative to the application once it's been installed. For example, Application.ExecutablePath tells you where the running EXE file is located; you could then use a relative path to find the file e.g. ..\..\FileToBeParsed.txt. However, this assumes that the files are deployed in the same folder structure as the project folder structure, which is not usually the case. Consider properties like CommonAppDataPath and LocalUserAppDataPath to locate application-related files once a project has been deployed. A: An alternative to locating the file on disk would be to include the file directly in the compiled assembly as an embedded resource. To do this, right-click on the file and choose "Embedded Resource" as the build action. You can then retrieve the file as a byte stream: Assembly thisAssembly = Assembly.GetExecutingAssembly(); Stream stream = thisAssembly.GetManifestResourceStream("Namespace.Folder.Filename.Ext"); byte[] data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); More information about embedded resources can be found here and here. If you're building an application for your own use, David Krep's suggestion is best: just copy the file to the output directory. If you're building an assembly that will get reused or distributed, then the embedded resource option is preferable because it will package everything in a single .dll. A: I would add a post build step that copies the txt file into the active configuration's output folder: xcopy "$(ProjectDir)*.txt" "$(OutDir)" There are a few macros defined such as "$(ConfigurationName)", $(ProjectDir) A: Go to Project Properties -> Configuration Properties -> Debugging Set "Working Directory" to $(TargetDir) Then you can properly reference your file using a relative path in your code (e.g. "....\foo.xml") A: The Application.ExecutablePath solution don't work for unittests. The path of vstesthost.exe will be returned System.Reflection.Assembly.GetExecutingAssembly().Location will work but gives the path with the assemblyname included. So this works: System.Reflection.Assembly.GetExecutingAssembly().Location + "\..\" + "fileToRead.txt" But just : fileToRead.txt Works also. Seems working directory is the executing assembly directory by default. A: If I understand your question correctly: Select the file in the "Solution Explorer". Under properties --> Copy to Output Directory, select "Copy Always" or "Copy if Newer". For build action, select "Content". This will copy the file to the /bin/debug folder on build. You should be able to reference it from the project root from then on. A: You can add a post-build event to copy the .txt file to the build output folder. Then your code can assume that the file is in the same folder as the executable.
{ "language": "en", "url": "https://stackoverflow.com/questions/165338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Varying Colors in Processing I've been working on porting some of my Processing code over to regular Java in NetBeans. So far so well, most everything works great, except for when I go to use non-grayscale colors. I have a script that draws a spiral pattern, and should vary the colors in the spiral based on a modulus check. The script seems to hang, however, and I can't really explain why. If anyone has some experience with Processing and Java, and you could tell me where my mistake is, I'd really love to know. For the sake of peer-review, here's my little program: package spirals; import processing.core.*; public class Main extends PApplet { float x, y; int i = 1, dia = 1; float angle = 0.0f, orbit = 0f; float speed = 0.05f; //color palette int gray = 0x0444444; int blue = 0x07cb5f7; int pink = 0x0f77cb5; int green = 0x0b5f77c; public Main(){} public static void main( String[] args ) { PApplet.main( new String[] { "spirals.Main" } ); } public void setup() { background( gray ); size( 400, 400 ); noStroke(); smooth(); } public void draw() { if( i % 11 == 0 ) fill( green ); else if( i % 13 == 0 ) fill( blue ); else if( i % 17 == 0 ) fill( pink ); else fill( gray ); orbit += 0.1f; //ever so slightly increase the orbit angle += speed % ( width * height ); float sinval = sin( angle ); float cosval = cos( angle ); //calculate the (x, y) to produce an orbit x = ( width / 2 ) + ( cosval * orbit ); y = ( height / 2 ) + ( sinval * orbit ); dia %= 11; //keep the diameter within bounds. ellipse( x, y, dia, dia ); dia++; i++; } } A: Have you considered adding debugging statements (System.out.println) and looking at the Java Console? There may be a massive amount of output and definitive slowdown, but you can at least see what happens when nothing seems to happen. What I do think is a logic error is the filling if statement; every iteratation you decide the color of that iteration and fill with that color. Only iterations with i == 11, 13, or 17 get filled with a color. And the next iteration that color is overwritten by gray. I would think it tends to flicker, possibly to fast to see. Didn't you want something like public class Main extends PApplet { ... int currentColor = gray; public Main(){} ... public void draw() { if( i % 11 == 0 ) currentColor = green; else if( i % 13 == 0 ) currentColor = blue; else if( i % 17 == 0 ) currentColor = pink; else { // Use current color } fill(currentColor); ... } In that way you start with gray, go to green, blue, pink, green, blue, pink etc. If you also want to see gray at some point you'd have to add something like else if ( i % 19 ) { currentColor = gray; } Hope this helps. A: To see whats happening here add stroke(255); at the beginning of the draw. You'll see all the wanted circles draw, but without color. As the previous poster mentioned: you're using a non gray color only every 11th, 13th and 17th iteration. I think that your color values are the main issue here. As from the reference page From a technical standpoint, colors are 32 bits of information ordered as AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB where the A's contain the alpha value, the R's are the red/hue value, G's are green/saturation, and B's are blue/brightness. If you look at your values you'll see a very low alpha value, which is maybe impossible to distinguish from the background. A: Not sure if you have still an issue. You mention hanging. It is a shot in the dark, but I remember fry repeating that size() call must be the first instruction in setup(). So perhaps moving down the background() call might help. Couldn't hurt anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/165346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why do these two date formats differ? I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the docs, 'd' should produce the day (1-31). string.Format("{0:d }", DateTime.Today); string.Format("{0:d}", DateTime.Today); UPDATE:Adding % is indeed the trick. Appropriate docs here. A: See here d, %d The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns. Otherwise d is interpreted as: d - 'ShortDatePattern' PS. For messing around with format strings, using LinqPad is invaluable. A: From the MSDN documentation for "Custom Date and Time Format Strings": Any string that is not a standard date and time format string is interpreted as a custom date and time format string. {0:d} is interpreted as a standard data and time format string. From "Standard Date and Time Format Strings", the "d" format specifier: Represents a custom date and time format string defined by the current ShortDatePattern property. With the space, {0:d } doesn't match any standard date and time format string, and is interpreted as a custom data and time format string. From "Custom Date and Time Format Strings", the "d" format specifier: Represents the day of the month as a number from 1 through 31. A: The {0:d} format uses the patterns defined in the Standard Date and Time Format Strings document of MSDN. 'd' translates to the short date pattern, 'D' to the long date pattern, and so on and so forth. The format that you want appears to be the Custom Date and Time Format Modifiers, which work when there is no matching specified format (e.g., 'd ' including the space) or when you use ToString(). You could use the following code instead: string.Format("{0}", DateTime.Today.ToString("d ", CultureInfo.InvariantCulture));
{ "language": "en", "url": "https://stackoverflow.com/questions/165355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Double quotes in Oracle Alias I am having fickle of problem in Oracle 9i select 1"FirstColumn" from dual; Oracle throwing error while executing above query. ORA-03001: unimplemented feature in my Production server. The Same query is working fine in my Validation server. Both servers are with Oracle 9i Any one have Idea what's wrong...? Is this something configurable item in Oracle server. A: Try: SELECT 1 AS "'FirstColumn'" FROM dual; There is a similar question: Double Quotes in Oracle Column Aliases A: What is the full Oracle version on both servers? 9i is a marketing label-- are you comparing a 9.0.1.x database to a 9.2.0.x database? A: Does it give the same output if you do? select 1 as "FirstColumn" from dual; To find out the specific versions on yoru Validation and Production servers, do this SQL on each and compare the results: select * from v$version; A: The below are the versions of my server: Oracle9i Enterprise Edition Release 9.2.0.8.0 - Validation Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production 64 bit does make a difference. SELECT 1 AS "'FirstColumn'" FROM dual; is working but will leads me to update nearly hundreds of packages. Configuration change could be handy rather changing the code. Regards, Hanumath A: For what it's worth, I have it working fine with me on 9.2.0.7: select 1"FirstColumn" from dual Feels like a bug to me; have you tried Metalink? A: Hanumath: MetaLink is Oracle's support service. If you're Oracle is licensed, and with a support contract, you would have a MetaLink ID. A: Pretty sure you should have a space between the 1 and the "FirstColumn" SELECT 1 "FirstColumn" from dual; That said, it's more correct to use the AS keyword the previous answerers indicated.
{ "language": "en", "url": "https://stackoverflow.com/questions/165365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Optimal RAID setup for SQL server We have an SQL 2005 database backend for our website, currently about 10GB in size. There are a lot more reads than writes, though I don't have the exact statistics. We're upgrading our database server and I was thinking of getting 4 disks and setting them up in two RAID 1 arrays - one for the data files and the other for the OS and log files. Would this be the optimal set-up or would RAID 5 be better for the data files? RAID 10 gets a bit pricey and is probably overkill for us. At this stage SQL Server should keep much of the database in RAM (8GB), but it will grow, so I don't want to entirely rely on that. Edit: we definitely want redundancy on a production server, so RAID 0 by itself is out. RAID 10 is nice, but might be a bit expensive for us. A: I'd spend a little time making sure your database is efficiently indexed; monitor it for Full Table Scans, make sure the most frequent queries read as little data as possible; I'd take an efficiently designed database on a slow disk setup over a database with improper indexes on SSDs. A: Your concept of using independent RAID 1 mirrors is the correct strategy. We have implemented similar scenarios at my work and they work very well. RAID 1 RAID 1 gives you the speed of 1 disk for writing but 2 disks for reading. When you write data to a RAID 1 array, it has to write that data to both disks, so you do not gain any performance increase, however this is where you get your data security. When reading from a RAID 1 array the controller will read from both disks as they have the same data on them. RAID 5 This is useful for protecting larger amounts of data. The cost of RAID 5 increases a lot slower than RAID 1 (or RAID 0+1 once you are doing capacities beyond the size of the individual disks) for the same amount of data. If you want to protect 600gb in with RAID 5 you can achieve that with 4x200gb drives or 3x300gb drives, requiring 800-900gb of total purchased drive space. RAID 1 would be 2x600gb drives requiring 1,200gb of purchased space (with 600gb drives being quite more expensive) or RAID 0+1 allowing you to use less expensive capacity drives (ie: 4x300gb or 6x200gb) but still requires a total of 1,200gb of purchased space. RAID 0+1 Offers similar advantages as RAID 1 taking it up another notch with the striping across disks. I am assuming that if you are concerned about higher simultaneous reads, you will also be using multi-processors/multi-cores. You will be processing multiple queries at once and so the striping isn't going to help as much. You would see a better advantage on a RAID 0+1 for single applications using large data files, such as video editing. When I was researching this same issue a while ago for a customer I found this article to be very interesting http://blogs.zdnet.com/Ou/?p=484. On the second page he dicusses the change from a RAID 0+1 to independent RAID 1 arrays creating a lot of performance improvements. This was on a much larger scale (a 20 disk and 16 disk SAN) but same concepts. The ability for SQL Server to load balance the data between multiple volumes instead of using just basic uninformed striping of RAID 0+1 is a great concept. A: Given that there are a lot more Reads than Writes, RAID 5 will be faster for your data files. If you possibly can, use a separate RAID 1+0 array for the transaction log files. EDIT: you will need at least 3 Disks to create a RAID 5 array. A: Be aware that the key performance metric will be the seek rate, not the data rate. That is, a typical database that is disk-bound (as yours may become as it grows) will be limited by how many IOs per second the disks can support, rather than the maximum data rate they can support for sequential reads. This means that if you're wondering how to use 4 disks (for example), two RAID1 pairs should give you better performance than one 4-disk RAID5 array. Of course, you won't get as much usable storage out of the two RAID1 pairs. A: Given the small size of the database I would use four 15krpm 2.5" SFF SAS disks, setup as two separate RAID 1 mirrors. I'd run them through something like an Adaptec 5805 PCI-e x 8 SAS controller. I'd put the data on one array and the logs on another for safety. Bar memory-mapping the whole database, a very large/expensive SAN or using SSDs I'm pretty convinced this will be just about the quickest setup for the money. Hope this helps. A: Two things, The theory is RAID 1 gives you two drives for a read, but dont' think that equals two times the performance. As a matter of fact, it doesn't, usually the sequential read spee ends up being exactly the same as one drive. Surprising, but true....do real world tests, don't rely on theory. With that said, I would go with two RAID 1...but not as you said, one for OS, and the other for data. I would have some small OS partition on one of them, but definately give both raids to sql server for data. Give sql server all the sets you can. SQL Server can stripe across the pairs, you absolutely do not want to go with 0+1 despite what anyone here says. They are again looking at theoretical benchmarks, not understand that sql server can stripe all its data across the disks, and can do so in an optimized way. Raid 1 is just for data redundancy...other than that, give as much as you can to sql server, and let it do its thing...its very good at what it does. You have a 0+1 and break it into two raid 1....do real world testing, you'll be surprised at which is faster for sql server work. A: RAID 5 is good if you use a hardware controller with a decent amount of battery-backed cache RAM. Select a chunk size and configure the DB so that the stripe size (data disks * chunk size) is equal to DB write size. Make sure your data partition [is aligned / is a multiple of] the stripe size. Otherwise, RAID 1+0 is always a good choice for DB servers. A: I would also recommend establishing a set of baseline values which allows you to both do some more founded predictions than just putting your finger in the air (or asking StackOverflow, seems vaguely and oddly similar those two concepts). With some baseline values you can also measure the effectiveness of your changes and be a good foundation for future upgrades... (If not known, pick up some literature (or wikipedia) on Performance Engineering. It's a whole branch of stuff that deals with just this type of problems). A: btw, where I work, they have a high end san, that does a tablescan in about 2 minutes. I broke up the drives into simple raid 1 sets, and let sql server handle the striping...not the san. 2 minutes dropped to 45 seconds. there are other articles on the net about this...its very hard to get raid 'true believers' to accept this, thats why I'm so emphatic, about this point. A: I prefer raid 10 which i've already configured on my dell r210-II linux server. Amazing performance...
{ "language": "en", "url": "https://stackoverflow.com/questions/165383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Improve compiling speed in VS project using C++ Boost Libraries I have just started using Boost 1.36. These libraries would be very useful in reducing the amount of code needed in the unmanaged C++ software project that I am working on. However when I tried to used these libraries my compile times increased ten fold. This would pretty much offset the productivity gains I would receive by using the library. I am using a 3GHz Intel Dual Core with 2GB of RAM and VS 2003. There is a snippet of the code that I added. #include "boost/numeric/ublas/matrix.hpp" #include "boost/numeric/ublas/vector.hpp" #include "boost/numeric/ublas/matrix_proxy.hpp" typedef ublas::bounded_matrix <long double,NUM_OF_COLUMNS,NUM_OF_CATEGORIES,ublas::row_major> Matrix; typedef ublas::bounded_vector <long double,NUM_OF_COLUMNS> Vector; void Print(const Matrix& amount) { Vector total; total.clear(); for (int category = 0; category < NUM_OF_CATEGORIES; category++) { PrintLine(ublas::row(amount, category)); total += ublas::row(amount, category); } PrintLine(total); } Is the problem with VS 2003? I know that VS 2008 is faster but upgrading is going to be a hard sell. Is it just that Boost is optimized for fast run times not fast compile times? Am I just using the Boost Library in a sub-optimal manner? Or am I just using the wrong tool for the job? A: Have you tried using precompiled headers? That is including the boost headers in StdAfx.h or whatever header file you use for precompiled headers? A: Did you try Incredibuild? It will allow you to distribute your build on multiple computers. I have seen it used successfully.
{ "language": "en", "url": "https://stackoverflow.com/questions/165386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }