text
stringlengths
8
267k
meta
dict
Q: Simple Frameworks for Displaying Bitmaps and Handling Button Presses We have a set of applications that basically display a bunch of bitmaps and text, then allow user to press "buttons" (certain bitmaps) that cause actions to occur. We currently have these implemented using DirectX and a bunch of code to place the bitmaps and handle the button-presses. But we'd like to have the following features: * *portable to Linux *some sort of "editor" that would allow us to lay out screens without hard-coding locations of elements in code *animation *we need to be able to overlay video *not resource intensive (these terminals don't have a lot of memory or CPU) *we're currently using C++, so management would prefer that, but other languages would be considered *We'd prefer a free, open-source solution, but would be willing to buy something if it is not too expensive. (We have a couple dozen developers, and tens of thousands of terminals deployed.) We don't like the common GUI toolkits or widgets. We want something that has more of the look of a game than of a dialog box. Any suggestions for off-the-shelf stuff we could use? A: Maybe the way to go is something like Clutter or Allegro. If you check in this article at ArsTechnica what they are using Clutter for, you might get an idea how to use it. I don't know for sure if it works on Windows, but I'm pretty sure it does, considering it only depends on libraries that are supported under Windows. A: You could try wxWidgets (it has wxBitmapButton) or try to implement your own solution using SDL for all of the graphics. A: "We don't like the common GUI toolkits or widgets. We want something that has more of the look of a game than of a dialog box." You realize that Trolltech's QT has a style sheet language for widgets? Take a look at their white paper, specifically page 60 http://trolltech.com/pdf/qt43-whitepaper-us.pdf Going over your other requirements: * *portable to Linux Yes. Also supports Windows, Mac, and embedded environments. * *some sort of "editor" that would allow us to lay out screens without hard-coding locations of elements in code Qt's Designer is a very nice tool. I use it all the time. * *animation Qt supports this. * *we need to be able to overlay video Qt supports this. * *not resource intensive (these terminals don't have a lot of memory or CPU) This might be the fly in the ointment. You could check out Qt's embedded option. I've never used that myself. * *we're currently using C++, so management would prefer that, but other languages would be considered Qt is for C++ and works with all major compilers. * *We'd prefer a free, open-source solution, but would be willing to buy something if it is not too expensive. (We have a couple dozen developers, and tens of thousands of terminals deployed.) Qt has both open-source and closed source options.
{ "language": "en", "url": "https://stackoverflow.com/questions/24196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the fastest way to bulk insert a lot of data in SQL Server (C# client) I am hitting some performance bottlenecks with my C# client inserting bulk data into a SQL Server 2005 database and I'm looking for ways in which to speed up the process. I am already using the SqlClient.SqlBulkCopy (which is based on TDS) to speed up the data transfer across the wire which helped a lot, but I'm still looking for more. I have a simple table that looks like this: CREATE TABLE [BulkData]( [ContainerId] [int] NOT NULL, [BinId] [smallint] NOT NULL, [Sequence] [smallint] NOT NULL, [ItemId] [int] NOT NULL, [Left] [smallint] NOT NULL, [Top] [smallint] NOT NULL, [Right] [smallint] NOT NULL, [Bottom] [smallint] NOT NULL, CONSTRAINT [PKBulkData] PRIMARY KEY CLUSTERED ( [ContainerIdId] ASC, [BinId] ASC, [Sequence] ASC )) I'm inserting data in chunks that average about 300 rows where ContainerId and BinId are constant in each chunk and the Sequence value is 0-n and the values are pre-sorted based on the primary key. The %Disk time performance counter spends a lot of time at 100% so it is clear that disk IO is the main issue but the speeds I'm getting are several orders of magnitude below a raw file copy. Does it help any if I: * *Drop the Primary key while I am doing the inserting and recreate it later *Do inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening small *Anything else? -- Based on the responses I have gotten, let me clarify a little bit: Portman: I'm using a clustered index because when the data is all imported I will need to access data sequentially in that order. I don't particularly need the index to be there while importing the data. Is there any advantage to having a nonclustered PK index while doing the inserts as opposed to dropping the constraint entirely for import? Chopeen: The data is being generated remotely on many other machines (my SQL server can only handle about 10 currently, but I would love to be able to add more). It's not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the output. Jason: I am not doing any concurrent queries against the table during the import process, I will try dropping the primary key and see if that helps. A: Have you tried using transactions? From what you describe, having the server committing 100% of the time to disk, it seems you are sending each row of data in an atomic SQL sentence thus forcing the server to commit (write to disk) every single row. If you used transactions instead, the server would only commit once at the end of the transaction. For further help: What method are you using for inserting data to the server? Updating a DataTable using a DataAdapter, or executing each sentence using a string? A: BCP - it's a pain to set up, but it's been around since the dawn of DBs and it's very very quick. Unless you're inserting data in that order the 3-part index will really slow things. Applying it later will really slow things too, but will be in a second step. Compound keys in Sql are always quite slow, the bigger the key the slower. A: I'm not really a bright guy and I don't have a lot of experience with the SqlClient.SqlBulkCopy method but here's my 2 cents for what it's worth. I hope it helps you and others (or at least causes people to call out my ignorance ;). You will never match a raw file copy speed unless your database data file (mdf) is on a separate physical disk from your transaction log file (ldf). Additionally, any clustered indexes would also need to be on a separate physical disk for a fairer comparison. Your raw copy is not logging or maintaining a sort order of select fields (columns) for indexing purposes. I agree with Portman on creating a nonclustered identity seed and changing your existing nonclustered index to a clustered index. As far as what construct you're using on the clients...(data adapter, dataset, datatable, etc). If your disk io on the server is at 100%, I don't think your time is best spent analyzing client constructs as they appear to be faster than the server can currently handle. If you follow Portman's links about minimal logging, I wouldn't think surrounding your bulk copies in transactions would help a lot if any but I've been wrong many times in my life ;) This won't necessarily help you right now but if you figure out your current issue, this next comment might help with the next bottleneck (network throughput) - especially if it's over the Internet... Chopeen asked an interesting question too. How did you determine to use 300 record count chunks to insert? SQL Server has a default packet size (I believe it is 4096 bytes) and it would make sense to me to derive the size of your records and ensure that you are making efficient use of the packets transmitting between client and server. (Note, you can change your packet size on your client code as opposed to the server option which would obviously change it for all server communications - probably not a good idea.) For instance, if your record size results in 300 record batches requiring 4500 bytes, you will send 2 packets with the second packet being mostly wasted. If batch record count was arbitrarily assigned, it might make sense to do some quick easy math. From what I can tell (and remember about data type sizes) you have exactly 20 bytes for each record (if int=4 bytes and smallint=2 bytes). If you are using 300 record count batches, then you are trying to send 300 x 20 = 6,000 bytes (plus I'm guessing a little overhead for the connection, etc). You might be more efficient to send these up in 200 record count batches (200 x 20 = 4,000 + room for overhead) = 1 packet. Then again, your bottleneck still appears to be the server's disk io. I realize you're comparing a raw data transfer to the SqlBulkCopy with the same hardware/configuration but here's where I would go also if the challenge was mine: This post probably won't help you anymore as it's rather old but I would next ask what your disk's RAID configuration is and what speed of disk are you using? Try putting the log file on a drive that uses RAID 10 with a RAID 5 (ideally 1) on your data file. This can help reduce a lot of spindle movement to different sectors on the disk and result in more time reading/writing instead of the unproductive "moving" state. If you already separate your data and log files, do you have your index on a different physical disk drive from your data file (you can only do this with clustered indexes). That would allow for not only concurrently updating logging information with data inserting but would allow index inserting (and any costly index page operations) to occur concurrently. A: Here's how you can disable/enable indexes in SQL Server: --Disable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users DISABLE GO --Enable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users REBUILD Here are some resources to help you find a solution: Some bulk loading speed comparisons Use SqlBulkCopy to Quickly Load Data from your Client to SQL Server Optimizing Bulk Copy Performance Definitely look into NOCHECK and TABLOCK options: Table Hints (Transact-SQL) INSERT (Transact-SQL) A: You're already using SqlBulkCopy, which is a good start. However, just using the SqlBulkCopy class does not necessarily mean that SQL will perform a bulk copy. In particular, there are a few requirements that must be met for SQL Server to perform an efficient bulk insert. Further reading: * *Prerequisites for Minimal Logging in Bulk Import *Optimizing Bulk Import Performance Out of curiosity, why is your index set up like that? It seems like ContainerId/BinId/Sequence is much better suited to be a nonclustered index. Is there a particular reason you wanted this index to be clustered? A: My guess is that you'll see a dramatic improvement if you change that index to be nonclustered. This leaves you with two options: * *Change the index to nonclustered, and leave it as a heap table, without a clustered index *Change the index to nonclustered, but then add a surrogate key (like "id") and make it an identity, primary key, and clustered index Either one will speed up your inserts without noticeably slowing down your reads. Think about it this way -- right now, you're telling SQL to do a bulk insert, but then you're asking SQL to reorder the entire table every table you add anything. With a nonclustered index, you'll add the records in whatever order they come in, and then build a separate index indicating their desired order. A: I think that it sounds like this could be done using SSIS packages. They're similar to SQL 2000's DTS packages. I've used them to successfully transform everything from plain text CSV files, from existing SQL tables, and even from XLS files with 6-digit rows spanned across multiple worksheets. You could use C# to transform the data into an importable format (CSV, XLS, etc), then have your SQL server run a scheduled SSIS job to import the data. It's pretty easy to create an SSIS package, there's a wizard built-into SQL Server's Enterprise Manager tool (labeled "Import Data" I think), and at the end of the wizard it gives you the option of saving it as an SSIS package. There's a bunch more info on Technet as well. A: Still facing the issue? Try this one too. * *Check the database configuration( Memory & Processor ). *For bulky data's , I would suggest the Memory of at least 16GB and Processor of 16 A: Yes your ideas will help. Lean on option 1 if there are no reads happening while your loading. Lean on option 2 if you destination table is being queried during your processing. @Andrew Question. Your inserting in chunks of 300. What is the total amount your inserting? SQL server should be able to handle 300 plain old inserts very fast.
{ "language": "en", "url": "https://stackoverflow.com/questions/24200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: “rusage” statistics I'm trying to use “rusage” statistics in my program to get data similar to that of the time tool. However, I'm pretty sure that I'm doing something wrong. The values seem about right but can be a bit weird at times. I didn't find good resources online. Does somebody know how to do it better? Sorry for the long code. class StopWatch { public: void start() { getrusage(RUSAGE_SELF, &m_begin); gettimeofday(&m_tmbegin, 0); } void stop() { getrusage(RUSAGE_SELF, &m_end); gettimeofday(&m_tmend, 0); timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime); timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime); timeval_sub(m_tmend, m_tmbegin, m_tmdiff); } void printf(std::ostream& out) const { using namespace std; timeval const& utime = m_diff.ru_utime; timeval const& stime = m_diff.ru_stime; format_time(out, utime); out << "u "; format_time(out, stime); out << "s "; format_time(out, m_tmdiff); } private: rusage m_begin; rusage m_end; rusage m_diff; timeval m_tmbegin; timeval m_tmend; timeval m_tmdiff; static void timeval_add(timeval const& a, timeval const& b, timeval& ret) { ret.tv_usec = a.tv_usec + b.tv_usec; ret.tv_sec = a.tv_sec + b.tv_sec; if (ret.tv_usec > 999999) { ret.tv_usec -= 1000000; ++ret.tv_sec; } } static void timeval_sub(timeval const& a, timeval const& b, timeval& ret) { ret.tv_usec = a.tv_usec - b.tv_usec; ret.tv_sec = a.tv_sec - b.tv_sec; if (a.tv_usec < b.tv_usec) { ret.tv_usec += 1000000; --ret.tv_sec; } } static void format_time(std::ostream& out, timeval const& tv) { using namespace std; long usec = tv.tv_usec; while (usec >= 1000) usec /= 10; out << tv.tv_sec << '.' << setw(3) << setfill('0') << usec; } }; // class StopWatch A: What is the purpose of: while (usec >= 1000) usec /= 10; I gather that you want the most significant three digits of the usec; in that case, the most straightforward way I can think of is to divide usec by 1000, and be done with that. Test cases: * *999999 ⇒ 999 *99999 ⇒ 999 (should be 099) *9999 ⇒ 999 (should be 009) *999 ⇒ 999 (should be 000) A: I think there's probably a bug somewhere in your composition of sec and usec. I can't really say what exactly without knowing the kinds of errors you're seeing. A rough guess would be that usec can never be > 999999, so you're relying on overflow to know when to adjust sec. It could also just be a problem with your duration output format. Anyway. Why not store the utime and stime components as float seconds rather than trying to build your own rusage on output? I'm pretty sure the following will give you proper seconds. static int timeval_diff_ms(timeval const& end, timeval const& start) { int micro_seconds = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec; return micro_seconds; } static float timeval_diff(timeval const& end, timeval const& start) { return (timeval_diff_ms(end, start)/1000000.0f); } If you want to decompose this back into an rusage, you can always int-div and modulo.
{ "language": "en", "url": "https://stackoverflow.com/questions/24207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use QItemDelegate to show image thumbnails What's the best way to use QT4's QItemDelegate to show thumbnails for images in a view? Specifically, how do you stop the item delegate from blocking when generating pixmaps from very large image files (> 500MB)? Can anyone link to some example code that achieves this? Then again, perhaps this isn't the place to look for Qt-specific code. A: You're doing it wrong if you are generating pixmaps inside any of the delegate methods (paint, draw...). Try to generate the thumbnails only once (on worker thread or maybe not even at runtime, if possible) and have the delegate just display them for the appropriate role. If you do it at runtime display a default picture until you have the thumbnail generated (like web browsers do with pictures that are not yet downloaded).
{ "language": "en", "url": "https://stackoverflow.com/questions/24212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java Annotations What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time? What are their typical usages? Are they unique to Java? Is there a C++ equivalent? A: Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as JUnit and Hibernate use annotations to minimize the amount of code you need to write yourself to use the frameworks. Oracle has a good explanation of the concept and its meaning in Java on their site. A: Java also has the Annotation Processing Tool (apt) where not only you create annotations, but decide also how do these annotations work on the source code. Here is an introduction. A: To see some cool stuff you can do with Annotations, check out my JavaBean annotations and annotation processor. They're great for generating code, adding extra validations during your build, and I've also been using them for an error message framework (not yet published -- need to clear with the bosses...). A: The first thing a newcomer to annotations will ask about annotations is: "What is an annotation?" It turns out that there is no answer to this question, in the sense that there is no common behavior which is present in all of the various kinds of java annotations. There is, in other words, nothing that binds them together into an abstract conceptual group other than the fact that they all start with an "@" symbol. For example, there is the @Override annotation, which tells the compiler to check that this member function overrides one in the parent class. There is the @Target annotation, which is used to specify what kinds of objects a user defined annotation (a third type of construct with nothing in common with other kinds of annotation) can be attached to. These have nothing to do with one another except for starting with an @ symbol. Basically, what appears to have happened is that some committee responsible for maintaining the java language definition is gatekeeping the addition of new keywords to the java language, and therefore other developers are doing an end run around that by calling new keywords "annotations". And that's why it is hard to understand, in general what an annotation is: because there is no common feature linking all annotations that could be used to put them in a conceptual group. In other words, annotations as a concept do not exist. Therefore I would recommend studying the behavior of every different kind of annotation individually, and do not expect understanding one kind of annotation to tell you anything about the others. Many of the other answers to this question assume the user is asking about user defined annotations specifically, which are one kind of annotation that defines a set of integers or strings or other data, static to the class or method or variable they are attached to, that can be queried at compile time or run time. Sadly, there is no marker that distinguishes this kind of annotation from other kinds like @interface that do different things. A: Also, are they unique to Java, is there a C++ equivalent? No, but VB and C# have attributes which are the same thing. Their use is quite diverse. One typical Java example, @Override has no effect on the code but it can be used by the compiler to generate a warning (or error) if the decorated method doesn't actually override another method. Similarly, methods can be marked obsolete. Then there's reflection. When you reflect a type of a class in your code, you can access the attributes and act according to the information found there. I don't know any examples in Java but in .NET this is used by the compiler to generate (de)serialization information for classes, determine the memory layout of structures and declare function imports from legacy libraries (among others). They also control how the IDE form designer works. /EDIT: Attributes on classes are comparable to tag interfaces (like Serializable in Java). However, the .NET coding guidelines say not to use tag interfaces. Also, they only work on class level, not on method level. A: Anders gives a good summary, and here's an example of a JUnit annotation @Test(expected=IOException.class) public void flatfileMissing() throws IOException { readFlatFile("testfiles"+separator+"flatfile_doesnotexist.dat"); } Here the @Test annotation is telling JUnit that the flatfileMissing method is a test that should be executed and that the expected result is a thrown IOException. Thus, when you run your tests, this method will be called and the test will pass or fail based on whether an IOException is thrown. A: By literal definition an annotation adds notes to an element. Likewise, Java annotations are tags that we insert into source code for providing more information about the code. Java annotations associate information with the annotated program element. Beside Java annotations Java programs have copious amounts of informal documentation that typically is contained within comments in the source code file. But, Java annotations are different from comments they annotate the program elements directly using annotation types to describe the form of the annotations. Java Annotations present the information in a standard and structured way so that it could be used amenably by processing tools. A: When do you use Java's @Override annotation and why? The link refers to a question on when one should use the override annotation(@override).. This might help understand the concept of annotation better.Check out. A: Annotations when it comes to EJB is known as choosing Implicit middle-ware approach over an explicit middle-ware approach , when you use annotation you're customizing what you exactly need from the API for example you need to call transaction method for a bank transfer : without using annotation : the code will be transfer(Account account1, Account account2, long amount) { // 1: Call middleware API to perform a security check // 2: Call middleware API to start a transaction // 3: Call middleware API to load rows from the database // 4: Subtract the balance from one account, add to the other // 5: Call middleware API to store rows in the database // 6: Call middleware API to end the transaction } while using Annotation your code contains no cumbersome API calls to use the middle- ware services. The code is clean and focused on business logic transfer(Account account1, Account account2, long amount) { // 1: Subtract the balance from one account, add to the other }
{ "language": "en", "url": "https://stackoverflow.com/questions/24221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "120" }
Q: Code Injection With C# Can you use windows hooks or other methods to do code injection with c#? I've seen lots of things about code injection but all of them are done in C/C++. I don't know either of those languages and have a really hard time translating. Does anyone have any ideas on how to do this? A: Kevin, it is possible. You can create library with window hook proc using managed C++. All you need to do is to inject this hook into some application using standard WinAPI (SetWindowsHookEx etc.). Inside this hook you can call System::AppDomain::CurrentDomain->Load method to load your assembly into target application's AppDomain. Then you can call methods defined in your assembly using reflection. For example, Snoop uses this method. A: Mike Stall has this sample, that uses CreateRemoteThread. It has the advantage of not requiring any C++. A: EDIT: I seem to have misinterpreted the question .... I was under the impression that the question was about code injection into the current process. I am joining the party rather late, but I have just used exactly this a few weeks ago: A delegate contains the private fields IntPtr _methodPtr and IntPtr _methodPtrAux, which represent the body's memory address. By setting the field (via reflection) to specific values, one can alter the memory address, to which the EIP will be pointing. Using this information, one can do the following: * *Create an array with assembly bytes, which are to be executed *Move the delegate's method pointer to the bytes in question *Call the delegate *Profit ??? (Of course, you can change the _methodPtr-value to any memory address -- even in the kernel space, but this might require appropriate execution privileges). I have a working code example here, if you want: public static unsafe int? InjectAndRunX86ASM(this Func<int> del, byte[] asm) { if (del != null) fixed (byte* ptr = &asm[0]) { FieldInfo _methodPtr = typeof(Delegate).GetField("_methodPtr", BindingFlags.NonPublic | BindingFlags.Instance); FieldInfo _methodPtrAux = typeof(Delegate).GetField("_methodPtrAux", BindingFlags.NonPublic | BindingFlags.Instance); _methodPtr.SetValue(del, ptr); _methodPtrAux.SetValue(del, ptr); return del(); } else return null; } Which can be used as follows: Func<int> del = () => 0; byte[] asm_bytes = new byte[] { 0xb8, 0x15, 0x03, 0x00, 0x00, 0xbb, 0x42, 0x00, 0x00, 0x00, 0x03, 0xc3 }; // mov eax, 315h // mov ebx, 42h // add eax, ebx // ret int res = del.InjectAndRunX86ASM(asm_bytes); // should be 789 + 66 = 855 Of course, on could also write the following method: public static unsafe int RunX86ASM(byte[] asm) { Func<int> del = () => 0; // create a delegate variable Array.Resize(ref asm, asm.Length + 1); // add a return instruction at the end to prevent any memory leaks asm[asm.Length - 1] = 0xC3; fixed (byte* ptr = &asm[0]) { FieldInfo _methodPtr = typeof(Delegate).GetField("_methodPtr", BindingFlags.NonPublic | BindingFlags.Instance); FieldInfo _methodPtrAux = typeof(Delegate).GetField("_methodPtrAux", BindingFlags.NonPublic | BindingFlags.Instance); _methodPtr.SetValue(del, ptr); _methodPtrAux.SetValue(del, ptr); return del(); } } The same could probably be done to existing methods (not delegates) via reflection: // UNTESTED // Action new_method_body = () => { }; MethodInfo nfo = typeof(MyType).GetMethod( ..... ); IntPtr ptr = nfo.MethodHandle.Value; // ptr is a pointer to the method in question InjectX86ASM(new_method_body, new byte[] { ......., 0xC3 }); // assembly bytes to be injected int target = new_method_body.Method.MethodHandle.Value.ToInt32(); byte[] redirector = new byte[] { 0xE8, // CALL INSTRUCTION + TARGET ADDRESS IN LITTLE ENDIAN (byte)(target & 0xff), (byte)((target >> 8) & 0xff), (byte)((target >> 16) & 0xff), (byte)((target >> 24) & 0xff), 0xC3, // RETURN INSTRUCTION }; Marshal.Copy(redirector, 0, ptr, redirector.Length); Use any code at your own risk. The code examples must be compiled with the /unsafe-compiler switch. A: You can check out CInject for code injection into .NET assemblies at CodePlex site http://codeinject.codeplex.com/. You don't need to have any knowledge about code injection to inject any code when you are using CInject.
{ "language": "en", "url": "https://stackoverflow.com/questions/24241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Select existing data from database to create test data I have a SqlServer database that I've manually filled with some test data. Now I'd like to extract this test data as insert statements and check it in to source control. The idea is that other team members should be able to create the same database, run the created insert scripts and have the same data to test and develop on. Is there a good tool out there to do this? I'm not looking for a tool to generate data as discussed here. A: If you want a light-weight solution, I would recommend sp_generate_inserts. It is a store procedure you can create on your DB and pass in a variety of arguments to generate insert statements of all the data in the target table. A: EMS DB Extract for SQL Server (http://www.sqlmanager.net/en/products/mssql/extract) seems to do what you want, and it seems to be free. Hope this helps, Robin A: Red-Gate SQL Data Compare will do this. Just create a blank data base with the same schema, and run a compare against the original and the blank database. It will generate scripts to insert all of your test data. A: This works http://www.sqlscripter.com/ New version of SQL Scripter (V2.1) was released last month.
{ "language": "en", "url": "https://stackoverflow.com/questions/24243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: About File permissions in C# While creating a file synchronization program in C# I tried to make a method copy in LocalFileItem class that uses System.IO.File.Copy(destination.Path, Path, true) method where Path is a string. After executing this code with destination. Path = "C:\\Test2" and this.Path = "C:\\Test\\F1.txt" I get an exception saying that I do not have the required file permissions to do this operation on C:\Test, but C:\Test is owned by myself (the current user). Does anybody knows what is going on, or how to get around this? Here is the original code complete. using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Diones.Util.IO { /// <summary> /// An object representation of a file or directory. /// </summary> public abstract class FileItem : IComparable { protected String path; public String Path { set { this.path = value; } get { return this.path; } } protected bool isDirectory; public bool IsDirectory { set { this.isDirectory = value; } get { return this.isDirectory; } } /// <summary> /// Delete this fileItem. /// </summary> public abstract void delete(); /// <summary> /// Delete this directory and all of its elements. /// </summary> protected abstract void deleteRecursive(); /// <summary> /// Copy this fileItem to the destination directory. /// </summary> public abstract void copy(FileItem fileD); /// <summary> /// Copy this directory and all of its elements /// to the destination directory. /// </summary> protected abstract void copyRecursive(FileItem fileD); /// <summary> /// Creates a FileItem from a string path. /// </summary> /// <param name="path"></param> public FileItem(String path) { Path = path; if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true; else IsDirectory = false; } /// <summary> /// Creates a FileItem from a FileSource directory. /// </summary> /// <param name="directory"></param> public FileItem(FileSource directory) { Path = directory.Path; } public override String ToString() { return Path; } public abstract int CompareTo(object b); } /// <summary> /// A file or directory on the hard disk /// </summary> public class LocalFileItem : FileItem { public override void delete() { if (!IsDirectory) File.Delete(this.Path); else deleteRecursive(); } protected override void deleteRecursive() { Directory.Delete(Path, true); } public override void copy(FileItem destination) { if (!IsDirectory) File.Copy(destination.Path, Path, true); else copyRecursive(destination); } protected override void copyRecursive(FileItem destination) { Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory( Path, destination.Path, true); } /// <summary> /// Create's a LocalFileItem from a string path /// </summary> /// <param name="path"></param> public LocalFileItem(String path) : base(path) { } /// <summary> /// Creates a LocalFileItem from a FileSource path /// </summary> /// <param name="path"></param> public LocalFileItem(FileSource path) : base(path) { } public override int CompareTo(object obj) { if (obj is FileItem) { FileItem fi = (FileItem)obj; if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) > 0) return 1; else if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) < 0) return -1; else { if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) < 0) return -1; else if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) > 0) return 1; else return 0; } } else throw new ArgumentException("obj isn't a FileItem"); } } } A: It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destination). Also is "C:\Test2" a directory? You can't copy file to a directory. Use something like that instead: File.Copy( sourceFile, Path.Combine(destinationDir,Path.GetFileName(sourceFile)) ); A: I'm kinda guessing here, but could it be because: * *You are trying to perform file operations in C: root? (there may be protection on this by Vista if you are using it - not sure?) *You are trying to copy to a non-existant directory? *The file already exists and may be locked? (i.e you have not closed another application instance)? Sorry I cant be of more help, I have rarely experienced problems with File.Copy. A: I was able to solve the problem, Michal pointed me to the right direction. The problem was that I tried to use File.Copy to copy a file from one location to another, while the Copy method does only copy all the contents from one file to another(creating the destination file if it does not already exists). The solution was to append the file name to the destination directory. Thanks for all the help!
{ "language": "en", "url": "https://stackoverflow.com/questions/24262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What's the point of OOP? As far as I can tell, in spite of the countless millions or billions spent on OOP education, languages, and tools, OOP has not improved developer productivity or software reliability, nor has it reduced development costs. Few people use OOP in any rigorous sense (few people adhere to or understand principles such as LSP); there seems to be little uniformity or consistency to the approaches that people take to modelling problem domains. All too often, the class is used simply for its syntactic sugar; it puts the functions for a record type into their own little namespace. I've written a large amount of code for a wide variety of applications. Although there have been places where true substitutable subtyping played a valuable role in the application, these have been pretty exceptional. In general, though much lip service is given to talk of "re-use" the reality is that unless a piece of code does exactly what you want it to do, there's very little cost-effective "re-use". It's extremely hard to design classes to be extensible in the right way, and so the cost of extension is normally so great that "re-use" simply isn't worthwhile. In many regards, this doesn't surprise me. The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed (I can sit on a table, a tree stump, a car bonnet, someone's lap--but not one of those is-a chair). Even if we move to more abstract domains, OO modelling is often difficult, counterintuitive, and ultimately unhelpful (consider the classic examples of circles/ellipses or squares/rectangles). So what am I missing here? Where's the value of OOP, and why has all the time and money failed to make software any better? A: Maybe a bonnet, lap or a tree is not a chair but they all are ISittable. A: I think those real world things are objects You do? What methods does an invoice have? Oh, wait. It can't pay itself, it can't send itself, it can't compare itself with the items that the vendor actually delivered. It doesn't have any methods at all; it's totally inert and non-functional. It's a record type (a struct, if you prefer), not an object. Likewise the other things you mention. Just because something is real does not make it an object in the OO sense of the word. OO objects are a peculiar coupling of state and behaviour that can act of their own accord. That isn't something that's abundant in the real world. A: I have been writing OO code for the last 9 years or so. Other than using messaging, it's hard for me to imagine other approach. The main benefit I see totally in line with what CodingTheWheel said: modularisation. OO naturally leads me to construct my applications from modular components that have clean interfaces and clear responsibilities (i.e. loosely coupled, highly cohesive code with a clear separation of concerns). I think where OO breaks down is when people create deeply nested class heirarchies. This can lead to complexity. However, factoring out common finctionality into a base class, then reusing that in other descendant classes is a deeply elegant thing, IMHO! A: In the first place, the observations are somewhat sloppy. I don't have any figures on software productivity, and have no good reason to believe it's not going up. Further, since there are many people who abuse OO, good use of OO would not necessarily cause a productivity improvement even if OO was the greatest thing since peanut butter. After all, an incompetent brain surgeon is likely to be worse than none at all, but a competent one can be invaluable. That being said, OO is a different way of arranging things, attaching procedural code to data rather than having procedural code operate on data. This should be at least a small win by itself, since there are cases where the OO approach is more natural. There's nothing stopping anybody from writing a procedural API in C++, after all, and so the option of providing objects instead makes the language more versatile. Further, there's something OO does very well: it allows old code to call new code automatically, with no changes. If I have code that manages things procedurally, and I add a new sort of thing that's similar but not identical to an earlier one, I have to change the procedural code. In an OO system, I inherit the functionality, change what I like, and the new code is automatically used due to polymorphism. This increases the locality of changes, and that is a Good Thing. The downside is that good OO isn't free: it requires time and effort to learn it properly. Since it's a major buzzword, there's lots of people and products who do it badly, just for the sake of doing it. It's not easier to design a good class interface than a good procedural API, and there's all sorts of easy-to-make errors (like deep class hierarchies). Think of it as a different sort of tool, not necessarily generally better. A hammer in addition to a screwdriver, say. Perhaps we will eventually get out of the practice of software engineering as knowing which wrench to use to hammer the screw in. A: @Sean However, factoring out common finctionality into a base class, then reusing that in other descendant classes is a deeply elegant thing, IMHO! But "procedural" developers have been doing that for decades anyway. The syntax and terminology might differ, but the effect is identical. There is more to OOP than "reusing common functionality in a base class", and I might even go so far as to say that that is hard to describe as OOP at all; calling the same function from different bits of code is a technique as old as the subprocedure itself. A: @Konrad OOP may be flawed and it certainly is no silver bullet but it makes large-scale applications much simpler because it's a great way to reduce dependencies That is the dogma. I am not seeing what makes OOP significantly better in this regard than procedural programming of old. Whenever I make a procedure call I am isolating myself from the specifics of the implementation. A: To me, there is a lot of value in the OOP syntax itself. Using objects that attempt to represent real things or data structures is often much more useful than trying to use a bunch of different flat (or "floating") functions to do the same thing with the same data. There is a certain natural "flow" to things with good OOP that just makes more sense to read, write, and maintain long term. It doesn't necessarily matter that an Invoice isn't really an "object" with functions that it can perform itself - the object instance can exist just to perform functions on the data without having to know what type of data is actually there. The function "invoice.toJson()" can be called successfully without having to know what kind of data "invoice" is - the result will be Json, no matter it if comes from a database, XML, CSV, or even another JSON object. With procedural functions, you all the sudden have to know more about your data, and end up with functions like "xmlToJson()", "csvToJson()", "dbToJson()", etc. It eventually becomes a complete mess and a HUGE headache if you ever change the underlying data type. The point of OOP is to hide the actual implementation by abstracting it away. To achieve that goal, you must create a public interface. To make your job easier while creating that public interface and keep things DRY, you must use concepts like abstract classes, inheritance, polymorphism, and design patterns. So to me, the real overriding goal of OOP is to make future code maintenance and changes easier. But even beyond that, it can really simplify things a lot when done correctly in ways that procedural code never could. It doesn't matter if it doesn't match the "real world" - programming with code is not interacting with real world objects anyways. OOP is just a tool that makes my job easier and faster - I'll go for that any day. A: @CodingTheWheel But to the extent that OOP has been a waste of time, I'd say it's because of lack of programmer training, compounded by the steep learning curve of learning a language specific OOP mapping. Some people "get" OOP and others never will. I dunno if that's really surprising, though. I think that technically sound approaches (LSP being the obvious thing) make hard to use, but if we don't use such approaches it makes the code brittle and inextensible anyway (because we can no longer reason about it). And I think the counterintuitive results that OOP leads us to makes it unsurprising that people don't pick it up. More significantly, since software is already fundamentally too hard for normal humans to write reliably and accurately, should we really be extolling a technique that is consistently taught poorly and appears hard to learn? If the benefits were clear-cut then it might be worth persevering in spite of the difficulty, but that doesn't seem to be the case. A: @Jeff Relative to straight procedural programming, the first fundamental tenet of OOP is the notion of information hiding and encapsulation. This idea leads to the notion of the class that seperates the interface from implementation. Which has the more hidden implementation: C++'s iostreams, or C's FILE*s? I think the use of opaque context objects (HANDLEs in Win32, FILE*s in C, to name two well-known examples--hell, HANDLEs live on the other side of the kernel-mode barrier, and it really doesn't get much more encapsulated than that) is found in procedural code too; I'm struggling to see how this is something particular to OOP. I suppose that may be a part of why I'm struggling to see the benefits: the parts that are obviously good are not specific to OOP, whereas the parts that are specific to OOP are not obviously good! (this is not to say that they are necessarily bad, but rather that I have not seen the evidence that they are widely-applicable and consistently beneficial). A: In the only dev blog I read, by that Joel-On-Software-Founder-of-SO guy, I read a long time ago that OO does not lead to productivity increases. Automatic memory management does. Cool. Who can deny the data? I still believe that OO is to non-OO what programming with functions is to programming everything inline. (And I should know, as I started with GWBasic.) When you refactor code to use functions, variable2654 becomes variable3 of the method you're in. Or, better yet, it's got a name that you can understand, and if the function is short, it's called value and that's sufficient for full comprehension. When code with no functions becomes code with methods, you get to delete miles of code. When you refactor code to be truly OO, b, c, q, and Z become this, this, this and this. And since I don't believe in using the this keyword, you get to delete miles of code. Actually, you get to do that even if you use this. I do not think OO is natural metaphor. I don't think language is a natural metaphor either, nor do I think that Fowler's "smells" are better than saying "this code tastes bad." That said, I think that OO is not about natural metaphors and people who think the objects just pop out at you are basically missing the point. You define the object universe, and better object universes result in code that is shorter, easier to understand, works better, or all of these (and some criteria I am forgetting). I think that people who use the customers/domain's natural objects as programming objects are missing the power to redefine the universe. For instance, when you do an airline reservation system, what you call a reservation might not correspond to a legal/business reservation at all. Some of the basic concepts are really cool tools I think that most people exaggerate with that whole "when you have a hammer, they're all nails" thing. I think that the other side of the coin/mirror is just as true: when you have a gadget like polymorphism/inheritance, you begin to find uses where it fits like a glove/sock/contact-lens. The tools of OO are very powerful. Single-inheritance is, I think, absolutely necessary for people not to get carried away, my own multi-inheritance software not withstanding. What's the point of OOP? I think it's a great way to handle an absolutely massive code base. I think it lets you organize and reorganize you code and gives you a language to do that in (beyond the programming language you're working in), and modularizes code in a pretty natural and easy-to-understand way. OOP is destined to be misunderstood by the majority of developers This is because it's an eye-opening process like life: you understand OO more and more with experience, and start avoiding certain patterns and employing others as you get wiser. One of the best examples is that you stop using inheritance for classes that you do not control, and prefer the Facade pattern instead. Regarding your mini-essay/question I did want to mention that you're right. Reusability is a pipe-dream, for the most part. Here's a quote from Anders Hejilsberg about that topic (brilliant) from here: If you ask beginning programmers to write a calendar control, they often think to themselves, "Oh, I'm going to write the world's best calendar control! It's going to be polymorphic with respect to the kind of calendar. It will have displayers, and mungers, and this, that, and the other." They need to ship a calendar application in two months. They put all this infrastructure into place in the control, and then spend two days writing a crappy calendar application on top of it. They'll think, "In the next version of the application, I'm going to do so much more." Once they start thinking about how they're actually going to implement all of these other concretizations of their abstract design, however, it turns out that their design is completely wrong. And now they've painted themself into a corner, and they have to throw the whole thing out. I have seen that over and over. I'm a strong believer in being minimalistic. Unless you actually are going to solve the general problem, don't try and put in place a framework for solving a specific one, because you don't know what that framework should look like. A: OOP isn't about creating re-usable classes, its about creating Usable classes. A: All too often, the class is used simply for its syntactic sugar; it puts the functions for a record type into their own little namespace. Yes, I find this to be too prevalent as well. This is not Object Oriented Programming. It's Object Based Programming and data centric programing. In my 10 years of working with OO Languages, I see people mostly doing Object Based Programming. OBP breaks down very quickly IMHO since you are essentially getting the worst of both words: 1) Procedural programming without adhering to proven structured programming methodology and 2) OOP without adhering to to proven OOP methodology. OOP done right is a beautiful thing. It makes very difficult problems easy to solve, and to the uninitiated (not trying to sound pompous there), it can almost seem like magic. That being said, OOP is just one tool in the toolbox of programming methodologies. It is not the be all end all methodology. It just happens to suit large business applications well. Most developers who work in OOP languages are utilizing examples of OOP done right in the frameworks and types that they use day-to-day, but they just aren't aware of it. Here are some very simple examples: ADO.NET, Hibernate/NHibernate, Logging Frameworks, various language collection types, the ASP.NET stack, The JSP stack etc... These are all things that heavily rely on OOP in their codebases. A: Have you ever created a window using WinAPI? More times than I care to remember. Then you should know that you define a class (RegisterClass), create an instance of it (CreateWindow), call virtual methods (WndProc) and base-class methods (DefWindowProc) and so on. WinAPI even takes the nomenclature from SmallTalk OOP, calling the methods “messages” (Window Messages). Then you'll also know that it does no message dispatch of its own, which is a big gaping void. It also has crappy subclassing. Handles may not be inheritable but then, there's final in Java. They don't lack a class, they are a placeholder for the class: That's what the word “handle” means. Looking at architectures like MFC or .NET WinForms it's immediately obvious that except for the syntax, nothing much is different from the WinAPI. They're not inheritable either in interface or implementation, minimally substitutable, and they're not substantially different from what procedural coders have been doing since forever. Is this really it? The best bits of OOP are just... traditional procedural code? That's the big deal? A: I agree completely with InSciTek Jeff's answer, I'll just add the following refinements: * *Information hiding and encapsulation: Critical for any maintainable code. Can be done by being careful in any programming language, doesn't require OO features, but doing it will make your code slightly OO-like. *Inheritance: There is one important application domain for which all those OO is-a-kind-of and contains-a relationships are a perfect fit: Graphical User Interfaces. If you try to build GUIs without OO language support, you will end up building OO-like features anyway, and it's harder and more error-prone without language support. Glade (recently) and X11 Xt (historically) for example. Using OO features (especially deeply nested abstract hierarchies), when there is no point, is pointless. But for some application domains, there really is a point. A: I believe the most beneficial quality of OOP is data hiding/managing. However, there are a LOT of examples where OOP is misused and I think this is where the confusion comes in. Just because you can make something into an object does not mean you should. However, if doing so will make your code more organized/easier to read then you definitely should. A great practical example where OOP is very helpful is with a "product" class and objects that I use on our website. Since every page is a product, and every product has references to other products, it can get very confusing as to which product the data you have refers to. Is this "strURL" variable the link to the current page, or to the home page, or to the statistics page? Sure you could make all kinds of different variable that refer to the same information, but proCurrentPage->strURL, is much easier to understand (for a developer). In addition, attaching functions to those pages is much cleaner. I can do proCurrentPage->CleanCache(); Followed by proDisplayItem->RenderPromo(); If I just called those functions and had it assume the current data was available, who knows what kind of evil would occur. Also, if I had to pass the correct variables into those functions, I am back to the problem of having all kinds of variables for the different products laying around. Instead, using objects, all my product data and functions are nice and clean and easy to understand. However. The big problem with OOP is when somebody believes that EVERYTHING should be OOP. This creates a lot of problems. I have 88 tables in my database. I only have about 6 classes, and maybe I should have about 10. I definitely don't need 88 classes. Most of the time directly accessing those tables is perfectly understandable in the circumstances I use it, and OOP would actually make it more difficult/tedious to get to the core functionality of what is occurring. I believe a hybrid model of objects where useful and procedural where practical is the most effective method of coding. It's a shame we have all these religious wars where people advocate using one method at the expense of the others. They are both good, and they both have their place. Most of the time, there are uses for both methods in every larger project (In some smaller projects, a single object, or a few procedures may be all that you need). A: Reuse shouldn't be a goal of OOP - or any other paradigm for that matter. Reuse is a side-effect of an good design and proper level of abstraction. Code achieves reuse by doing something useful, but not doing so much as to make it inflexible. It does not matter whether the code is OO or not - we reuse what works and is not trivial to do ourselves. That's pragmatism. The thought of OO as a new way to get to reuse through inheritance is fundamentally flawed. As you note the LSP violations abound. Instead, OO is properly thought of as a method of managing the complexity of a problem domain. The goal is maintainability of a system over time. The primary tool for achieving this is the separation of public interface from a private implementation. This allows us to have rules like "This should only be modified using ..." enforced by the compiler, rather than code review. Using this, I'm sure you will agree, allows us to create and maintain hugely complex systems. There is lots of value in that, and it is not easy to do in other paradigms. A: I don't care for reuse as much as I do for readability. The latter means your code is easier to change. That alone is worth in gold in the craft of building software. And OO is a pretty damn effective way to make your programs readable. Reuse or no reuse. A: Verging on religious but I would say that you're painting an overly grim picture of the state of modern OOP. I would argue that it actually has reduced costs, made large software projects manageable, and so forth. That doesn't mean it's solved the fundamental problem of software messiness, and it doesn't mean the average developer is an OOP expert. But the modularization of function into object-components has certainly reduced the amount of spaghetti code out there in the world. I can think of dozens of libraries off the top of my head which are beautifully reusable and which have saved time and money that can never be calculated. But to the extent that OOP has been a waste of time, I'd say it's because of lack of programmer training, compounded by the steep learning curve of learning a language specific OOP mapping. Some people "get" OOP and others never will. A: There's no empirical evidence that suggests that object orientation is a more natural way for people to think about the world. There's some work in the field of psychology of programming that shows that OO is not somehow more fitting than other approaches. Object-oriented representations do not appear to be universally more usable or less usable. It is not enough to simply adopt OO methods and require developers to use such methods, because that might have a negative impact on developer productivity, as well as the quality of systems developed. Which is from "On the Usability of OO Representations" from Communications of the ACM Oct. 2000. The articles mainly compares OO against theprocess-oriented approach. There's lots of study of how people who work with the OO method "think" (Int. J. of Human-Computer Studies 2001, issue 54, or Human-Computer Interaction 1995, vol. 10 has a whole theme on OO studies), and from what I read, there's nothing to indicate some kind of naturalness to the OO approach that makes it better suited than a more traditional procedural approach. A: I think the use of opaque context objects (HANDLEs in Win32, FILE*s in C, to name two well-known examples--hell, HANDLEs live on the other side of the kernel-mode barrier, and it really doesn't get much more encapsulated than that) is found in procedural code too; I'm struggling to see how this is something particular to OOP. HANDLEs (and the rest of the WinAPI) is OOP! C doesn't support OOP very well so there's no special syntax but that doesn't mean it doesn't use the same concepts. WinAPI is in every sense of the word an object-oriented framework. See, this is the trouble with every single discussion involving OOP or alternative techniques: nobody is clear about the definition, everyone is talking about something else and thus no consensus can be reached. Seems like a waste of time to me. A: "The real world isn't "OO"," Really? My world is full of objects. I'm using one now. I think that having software "objects" model the real objects might not be such a bad thing. OO designs for conceptual things (like Windows, not real world windows, but the display panels on my computer monitor) often leave a lot to be desired. But for real world things like invoices, shipping orders, insurance claims and what-not, I think those real world things are objects. I have a stack on my desk, so they must be real. A: The point of OOP is to give the programmer another means for describing and communicating a solution to a problem in code to machines and people. The most important part of that is the communication to people. OOP allows the programmer to declare what they mean in the code through rules that are enforced in the OO language. Contrary to many arguments on this topic, OOP and OO concepts are pervasive throughout all code including code in non-OOP languages such as C. Many advanced non-OO programmers will approximate the features of objects even in non-OO languages. Having OO built into the language merely gives the programmer another means of expression. The biggest part to writing code is not communication with the machine, that part is easy, the biggest part is communication with human programmers. A: It's the only language-portable methodology for keeping variables grouped together with the functions/methods/subroutines that interact with them. A: From my experience which started in C/Unix (non OOP) in the mid 1980s then moving onto C++ (OOP) in 1990 and then into Java around 1996 (OOP) I have found OOP to give a massive boost to productivity, maintainability and robustness compared with the large non OOP programs I was working on earlier. The main thing I have observed is that in non OOP applications I have worked on the complexity seemed to grow at an exponential rate with respect to the sophistication of the application whereas in the OOP applications I worked on the complexity seemed to have a much more linear relationship with repect to the sophistication of the application. In other words - with well designed OOP applications you never get that "OMG the source code for this app is getting waaaaay out of control" feeling that you get with large non OOP applications. The other things I can't do without as an OOP developer is the way I can write code that models the real world entities that exist in the application's problem domain. Objects take on a life of their own - way beyond what any structs (C) or Records (Pascal) did back in the bad old =] non OOP days. The one stipulation is that the chief architect of an OOP project must know what he's doing and he has to usually put more thinking time into getting the design right than in actually implementing it but the payback for 'thinking things through up front' is truly amazing. Opportunities for reuse or awesomely cool design optimizations come to light that have you punching the air and doing touchdowns in the office... ok, that might look a bit strange to the others in the office but that kind of enthusiasm never happened in the non OOP days :) I've seen some pretty badly written OOP code and maybe that's what you've experienced which may have lead you to ask the question. As a contractor in the mid 90s I often found that the 'OO' design had already been started by someone who knew what a class was but not much more. It was a very painful experience and I often found that my first few months in a job involved educating the team in the very different way of 'OO' thinking. It was only after everyone's brain had been rewired that we could all proceed as a team to create something awesome. Many people find the 'brain rewiring' process too hard, painful or just too much effort and so spend their life dissin' OOP and so you'll find a lot of OO haters out there but I'm happy about that because it's those people that make people like me look good: "What, you can do it for $X and it will be ready in 2 months and you will give us a maintainable code base!!! Wow, can you start today?" A: Its a programming paradigm.. Designed to make it easier for us mere mortals to break down a problem into smaller, workable pieces.. If you dont find it useful.. Don't use it, don't pay for training and be happy. I on the other hand do find it useful, so I will :) A: Relative to straight procedural programming, the first fundamental tenet of OOP is the notion of information hiding and encapsulation. This idea leads to the notion of the class that seperates the interface from implementation. These are hugely important concepts and the basis for putting a framework in place to think about program design in a different way and better (I think) way. You can't really argue against those properties - there is no trade-off made and it is always a cleaner way to modulize things. Other aspects of OOP including inheritance and polymorphism are important too, but as others have alluded to, those are commonly over used. ie: Sometimes people use inheritance and/or polymorphism because they can, not because they should have. They are powerful concepts and very useful, but need to be used wisely and are not automatic winning advantages of OOP. Relative to re-use. I agree re-use is over sold for OOP. It is a possible side effect of well defined objects, typically of more primitive/generic classes and is a direct result of the encapsulation and information hiding concepts. It is potentially easier to be re-used because the interfaces of well defined classes are just simply clearer and somewhat self documenting. A: The problem with OOP is that it was oversold. As Alan Kay originally conceived it, it was a great alternative to the prior practice of having raw data and all-global routines. Then some management-consultant types latched onto it and sold it as the messiah of software, and lemming-like, academia and industry tumbled along after it. Now they are lemming-like tumbling after other good ideas being oversold, such as functional programming. So what would I do differently? Plenty, and I wrote a book on this. (It's out of print - I don't get a cent, but you can still get copies.)Amazon My constructive answer is to look at programming not as a way of modeling things in the real world, but as a way of encoding requirements. That is very different, and is based on information theory (at a level that anyone can understand). It says that programming can be looked at as a process of defining languages, and skill in doing so is essential for good programming. It elevates the concept of domain-specific-languages (DSLs). It agrees emphatically with DRY (don't repeat yourself). It gives a big thumbs-up to code generation. It results in software with massively less data structure than is typical for modern applications. It seeks to re-invigorate the idea that the way forward lies in inventiveness, and that even well-accepted ideas should be questioned. A: The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed While this is true and has been observed by other people (take Stepanov, inventor of the STL), the rest is nonsense. OOP may be flawed and it certainly is no silver bullet but it makes large-scale applications much simpler because it's a great way to reduce dependencies. Of course, this is only true for “good” OOP design. Sloppy design won't give any advantage. But good, decoupled design can be modelled very well using OOP and not well using other techniques. There are much better, more universal models (Haskell's type model comes to mind) but these are also often more complicated and/or difficult to implement efficiently. OOP is a good trade-off between extremes. A: HANDLEs (and the rest of the WinAPI) is OOP! Are they, though? They're not inheritable, they're certainly not substitutable, they lack well-defined classes... I think they fall a long way short of "OOP". Have you ever created a window using WinAPI? Then you should know that you define a class (RegisterClass), create an instance of it (CreateWindow), call virtual methods (WndProc) and base-class methods (DefWindowProc) and so on. WinAPI even takes the nomenclature from SmallTalk OOP, calling the methods “messages” (Window Messages). Handles may not be inheritable but then, there's final in Java. They don't lack a class, they are a placeholder for the class: That's what the word “handle” means. Looking at architectures like MFC or .NET WinForms it's immediately obvious that except for the syntax, nothing much is different from the WinAPI. A: Yes OOP did not solve all our problems, sorry about that. We are, however working on SOA which will solve all those problems. A: In my experience of reviewing code and design of projects I have been through, the value of OOP is not fully realised because alot of developers have not properly conceptualised the object-oriented model in their minds. Thus they do not program with OO design, very often continuing to write top-down procedural code making the classes a pretty flat design. (if you can even call that "design" in the first place) It is pretty scary to observe how little colleagues know about what an abstract class or interface are, let alone properly design an inheritance hierarchy to suit the business needs. However, when good OO design is present, it is just sheer joy reading the code and seeing the code naturally fall into place into intuitive components/classes. I have always perceived system architecture and design like designing the various departments and staff jobs in a company - all are there to accomplish a certain piece of work in the grand scheme of things, emitting the synergy required to propel the organisation/system forward. That, of course, is quite rare unfortunately. Like the ratio of beautifully-designed versus horrendously-designed physical objects in the world, the same can pretty much be said about software engineering and design. Having the good tools at one's disposal does not necessarily confer good practices and results. A: OOP lends itself well to programming internal computer structures like GUI "widgets", where for example SelectList and TextBox may be subtypes of Item, which has common methods such as "move" and "resize". The trouble is, 90% of us work in the world of business where we are working with business concepts such as Invoice, Employee, Job, Order. These do not lend themselves so well to OOP because the "objects" are more nebulous, subject to change according to business re-engineering and so on. The worst case is where OO is enthusiastically applied to databases, including the egregious OO "enhancements" to SQL databases - which are rightly ignored except by database noobs who assume they must be the right way to do things because they are newer. A: "Even if there is no actual [information architecture], it doesn’t mean we don’t experience or perceive it as such. Zen Buddhists say there is no actual “self” but they still name their kids."-Andrew Hinton A: HANDLEs (and the rest of the WinAPI) is OOP! Are they, though? They're not inheritable, they're certainly not substitutable, they lack well-defined classes... I think they fall a long way short of "OOP". A: Maybe a bonnet, lap or a tree is not a chair but they all are ISittable. Yes, but only ex post facto. They're ISittable because someone sat on them. A: I know I find OOP useful pretty much solely on a syntactical sugar basis (encapsulation, operator overloading, typechecking). As to the benefits of OOP... I don't know. I don't think it's worse than procedural stuff. On the lighter side, my OOP lecturer said that OOP is important because otherwise the "code would have too many loops". Yeah. Sometimes it's depressing that I pay $500 per paper. :( A: To me, the value of OOP is to reduce the scope and to separate state from behavior. With smaller scope, code is easier to understand. It can be done in most languages, all is needed to achieve this is a way for a state to delegate a method call to a behavior, and a way for a behavior to further delegate the call to a parent behavior. As to have a set of classes model a domain in an effective way, there is no magic method. Like a piano, we have to practice. OOP is an abstract tool, it can help you build code in a simpler way, but it can't think and analyze the domain of your app for you. What works for me is to stay close to the domain as long as possible, while still avoiding most code duplications. A: OOP helps separate interface from implementation. You do not need OOP support in the language to benefit from OO design. One small example where OOP has helped tremendously: The UNIX Virtual File System (VFS) layer presents a uniform interface (open/read/write) using tables of function pointers -- much like the C++ virtual table dispatch. Clients use the same set of calls regardless of whether they are talking to a local file system, a remote Network File System (NFS) or (today) fake file systems (e.g. /proc). See the original Sun paper: Vnodes: An Architecture for Multiple File System Types in Sun UNIX A: Will we say the same things ten years from now about functional programming? A: The real world isn't "OO". The real world is not largely structured from sensible pieces. Instead it's made from chaotically moving particles. The earth is a particle soup. Still people see birds, trees, sky, ground, forests, ponds. OO is about abstraction of program components. It's fundamentally flawed to think about OO for modelling something else than programs. All the money and time failed to make software any better, because it failed to make programmers smarter, also because it failed to change the way how people think about software. "OOP" in the sense you use it is a buzzword used to get the money out from idiots. Yes, people who have put money on "OOP" education and tools are idiots. People who tend to fall on hoaxes tend to be idiots. The value of "OOP" is the abstraction and the code reuse inside the same program. OOP is meant to be used with imperative programs. If you get up from assembly routines. Assembly is an ordered sequences of pairs composed from labels and instructions. Assembly code is similar to the 'particle soup'. Now you can move to the subroutine. Subroutine picks a label from that label:instruction -soup, and hides the rest of labels inside the subroutine. As the effect code becomes more abstract and your namespace stays cleaner. Now, if you think what subroutines do... Few of decades ago people were thinking that subroutines are at their best when they work on the arguments. That made them to give each object it's own protocol. Protocol would contain label:procedure -pairs. Now called selector:method -pairs. Procedures weren't bound directly to the other procedures anymore, explaining the 'late binding' -term. Along with keeping the history from the protocols (inheritance), this formed the 'object orientation' in the smalltalk. You've been incapacitated the late binding mechanism and forgotten what inheritance means. And you yet wonder what you are missing there. "Where's the value of OOP, and why has all the time and money failed to make software any better?" - I think you stuffed them into your arse. When you attempt to colonoscopy you will find them. A: There are already a lot of answers on this as this is an old post but i thought i'd chime in. You mention "class taxonomy" a bit which gets into subtyping and polymorphism. This all revolves around inheritance which in it heyday was considered the silver bullet of OOP. Nowadays, inheritance and large class hierarchies are actually discouraged, even among shops that do a lot of OOP. This is because the other pricinples of OOP, such as encapsulation, loose coupling, cohesion and so forth have been found to be far more useful than inheritance. I would even go so far to say that loose coupling is the reason for OO, not code reuse. Code reuse usually happens at the method/function level. I do sometimes reuse classes under different circumstances, but not that often. Loose coupling though helps organize a system quite a bit. Each object has its own scope, the data in the object isn't or should not be manipulated except by accessor methods or properties, each object should do one simple thing and should talk to other objects thru simple interfaces. This handful of principles helps code readability, helps isolate bugs and prevent you from having to make many changes in lots of different places to change one thing. When objects are not closely intertwined, you can change one without affecting others. This has been a huge benefit to me. Inheritance is useful only now and then. Code reuse is still important and if you are copying and pasting or rewriting the same code, thats a bad practice even under plain old procedural, structured or functional programming. That actually increases costs due to duplicated effort, increased maintenance and more bugs. A: OOP has reduced costs, and increased efficiency. When I made the jump from classic ASP/VBScript to C# I noticed a HUGE increase in productivity thanks to OOP. A: I agree with InSciTek Jeff. Even if you don't use OO in its purest sense, Encapsulation Theory can help reduce potential structural complexity: http://www.edmundkirwan.com @ DrPizza If procedureal programming uses the benefits of encapsulation to the same degree then good on it! A: Real world may not be OO but people tend to learn or think better with analogy (abstraction) rather than logic. OOP is not for computer but it's for programmer who is poor at figuring out a complex system without analogy. I believe main purpose of OOP is better organization of code using abstraction so without knowledge of other parts, a programmer can easily understand what specific part of or whole system does in a level she/he want to be in. To organize the code with abstraction, you will need encapsulation, inheritance, and polymorphism as well in your language. And SOLID OOP principles and design patterns come in to do better job at this organization. But I think whole point of OOP is abstraction because human thinks better in that way. A: OOP is about instancing... you want to reinstance the same thing over and over again, with a slightly different classification of its activity. shared activity means a shared class. If you dont want to think in that way, dont do OOP. it definitely twists the mind to start thinking about it after say pascal, hence the pissed off programmers. You detail your instancing robot to the every last difference, and you dont repeat yourself once. You only have 1 label/class for every classification difference (not every different thing!), thats the power of OOP... and thats how its similar to some super nueral network for ai, that never runs out of names for different things, because it relies apon the total distribution, to name it. -Magnus W.
{ "language": "en", "url": "https://stackoverflow.com/questions/24270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "126" }
Q: Functional programming and non-functional programming In my second year of University we were "taught" Haskell, I know almost nothing about it and even less about functional programming. What is functional programming, why and/xor where would I want to use it instead of non-functional programming and am I correct in thinking that C is a non-functional programming language? A: One key feature in a functional language is the concept of first-class functions. The idea is that you can pass functions as parameters to other functions and return them as values. Functional programming involves writing code that does not change state. The primary reason for doing so is so that successive calls to a function will yield the same result. You can write functional code in any language that supports first-class functions, but there are some languages, like Haskell, which do not allow you to change state. In fact, you're not supposed to make any side effects (like printing out text) at all - which sounds like it could be completely useless. Haskell instead employs a different approach to IO: monads. These are objects that contain the desired IO operation to be executed by your interpreter's toplevel. At any other level they are simply objects in the system. What advantages does functional programming provide? Functional programming allows coding with fewer potentials for bugs because each component is completely isolated. Also, using recursion and first-class functions allows for simple proofs of correctness which typically mirror the structure of the code. A: May be worth checking out this article on F# "101" on CoDe Mag recently posted. Also, Dustin Campbell has a great blog where he has posted many articles on his adventures on getting up to speed with F#.. I hope you find these useful :) EDIT: Also, just to add, my understanding of functional programming is that everything is a function, or parameters to a function, rather than instances/stateful objects.. But I could be wrong F# is something I am dying to get in to but just dont have the time! :) A: John the Statistician's example code does not show functional programming, because when you're doing functional programming, the key is that the code does NO ASSIGNMENTS ( record = thingConstructor(t) is an assignment), and it has NO SIDE EFFECTS (localMap.put(record) is a statement with a side effect). As a result of these two constraints, everything that a function does is fully captured by its arguments and its return value. Rewriting the Statistician's code the way it would have to look, if you wanted to emulate a functional language using C++: RT getOrCreate(const T thing, const Function<RT<T>> thingConstructor, const Map<T,RT<T>> localMap) { return localMap.contains(t) ? localMap.get(t) : localMap.put(t,thingConstructor(t)); } As a result of the no side-effects rule, every statement is part of the return value (hence return comes first), and every statement is an expression. In languages that enforce functional programming, the return keyword is implied, and the if statement behaves like C++'s ?: operator. Also, everything is immutable, so localMap.put has to create a new copy of localMap and return it, instead of modifying the original localMap, the way a normal C++ or Java program would. Depending on the structure of localMap, the copy could re-use pointers into the original, reducing the amount of data that has to be copied. Some of the advantages of functional programming include the fact that functional programs are shorter, and it is easier to modify a functional program (because there are no hidden global effects to take into account), and it is easier to get the program right in the first place. However, functional programs tend to run slowly (because of all the copying they have to do), and they don't tend to interact well with other programs, operating system processes, or operating systems, which deal in memory addresses, little-endian blocks of bytes, and other machine-specific, non-functional bits. The degree of noninteroperability tends to be inversely correlated with the degree of functional purity, and the strictness of the type system. The more popular functional languages have really, really strict type systems. In OCAML, you can't even mix integer and floating-point math, or use the same operators (+ is for adding integers, +. is for adding floats). This can be either an advantage or a disadvantage, depending on how highly you value the ability of a type checker to catch certain kinds of bugs. Functional languages also tend to have really big runtime environments. Haskell is an exception (GHC executables are almost as small as C programs, both at compile-time and runtime), but SML, Common Lisp, and Scheme programs always require tons of memory. A: Yes you are correct in thinking that C is a non-functional language. C is a procedural language. A: I prefer to use functional programming to save myself repeated work, by making a more abstract version and then using that instead. Let me give an example. In Java, I often find myself creating maps to record structures, and thus writing getOrCreate structures. SomeKindOfRecord<T> getOrCreate(T thing) { if(localMap.contains(thing)) { return localMap.get(thing); } SomeKindOfRecord<T> record = new SomeKindOfRecord<T>(thing); localMap = localMap.put(thing, record); return record; } This happens very often. Now, in a functional language I could write RT<T> getOrCreate(T thing, Function<RT<T>> thingConstructor, Map<T,RT<T>> localMap) { if(localMap.contains(thing)) { return localMap.get(thing); } RT<T> record = thingConstructor(thing); localMap = localMap.put(thing,record); return record; } and I would never have to write a new one of these again, I could inherit it. But I could do one better than inheriting, I could say in the constructor of this thing getOrCreate = myLib.getOrCreate(*, SomeKindOfRecord<T>.constructor(<T>), localMap); (where * is a kind of "leave this parameter open" notation, which is a sort of currying) and then the local getOrCreate is exactly the same as it would have been if I wrote out the whole thing, in one line, with no inheritance dependencies. A: What is functional programming There are two different definitions of "functional programming" in common use today: The older definition (originating from Lisp) is that functional programming is about programming using first-class functions, i.e. where functions are treated like any other value so you can pass functions as arguments to other functions and function can return functions among their return values. This culminates in the use of higher-order functions such as map and reduce (you may have heard of mapReduce as a single operation used heavily by Google and, unsurprisingly, it is a close relative!). The .NET types System.Func and System.Action make higher-order functions available in C#. Although currying is impractical in C#, functions that accept other functions as arguments are common, e.g. the Parallel.For function. The younger definition (popularized by Haskell) is that functional programming is also about minimizing and controlling side effects including mutation, i.e. writing programs that solve problems by composing expressions. This is more commonly called "purely functional programming". This is made possible by wildly different approaches to data structures called "purely functional data structures". One problem is that translating traditional imperative algorithms to use purely functional data structures typically makes performance 10x worse. Haskell is the only surviving purely functional programming language but the concepts have crept into mainstream programming with libraries like Linq on .NET. where would I want to use it instead of non-functional programming Everywhere. Lambdas in C# have now demonstrated major benefits. C++11 has lambdas. There's no excuse not to use higher-order functions now. If you can use a language like F# you'll also benefit from type inference, automatic generalization, currying and partial application (as well as lots of other language features!). am I correct in thinking that C is a non-functional programming language? Yes. C is a procedural language. However, you can get some of the benefit of functional programming by using function pointers and void * in C. A: If you are looking for a good text on F# Expert F# is co-written by Don Syme. Creator of F#. He worked on generics in .NET specifically so he could create F#. F# is modeled after OCaml so any OCaml text would help you learn F# as well. A: I find What Is Functional Programming? to be useful Functional programming is about writing pure functions, about removing hidden inputs and outputs as far as we can, so that as much of our code as possible just describes a relationship between inputs and outputs. Prefer explicit when param public Program getProgramAt(TVGuide guide, int channel, Date when) { Schedule schedule = guide.getSchedule(channel); Program program = schedule.programAt(when); return program; } over public Program getCurrentProgram(TVGuide guide, int channel) { Schedule schedule = guide.getSchedule(channel); Program current = schedule.programAt(new Date()); return current; } A functional language is actively hostile to side-effects. Side-effects are complexity and complexity is bugs and bugs are the devil. A functional language will help you be hostile to side-effects too.
{ "language": "en", "url": "https://stackoverflow.com/questions/24279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "74" }
Q: Best Solution For Authentication in Ruby on Rails I'm looking for a pre-built solution I can use in my RoR application. I'm ideally looking for something similar to the ASP.NET Forms authentication that provides email validation, sign-up controls, and allows users to reset their passwords. Oh yeah, and easily allows me to pull the user that is currently logged into the application. I've started to look into the already written pieces, but I've found it to be really confusing. I've looked at LoginGenerator, RestfulAuthentication, SaltedLoginGenerator, but there doesn't seem to be one place that has great tutorials or provide a comparison of them. If there's a site I just haven't discovered yet, or if there is a de-facto standard that most people use, I'd appreciate the helping hand. A: AuthLogic appears to be the new kid on the block and seems to be the next evolution of restful_authentication, easier to use, etc http://github.com/binarylogic/authlogic/tree/master Edit: now that Rails 3 is out, Devise seems to be the new, new kid on the block https://github.com/plataformatec/devise or I have been rolling my own authentication now with the has_secure_password built in to Rails http://railscasts.com/episodes/250-authentication-from-scratch-revised Side note: Ruby Toolbox is a great site for finding the current best solution in various categories (based on the number of GitHub watchers): http://ruby-toolbox.com/categories/rails_authentication.html A: There's also RestfulOpenIDAuthentication if you want OpenID support in addition to password support. A: Just a note, LoginGenerator and SaltedLoginGenerator have been superseded by Restful Authentication and are unsupported on newer Rails releases -- dont waste any time on them, though they were great at the time. A: I'd also like to point out an excellent tutorial/discussion on extending the core functionality of Restful Authentication, in case you're looking for something a bit more robust. A: AuthLogic seems to be what you want for this. It's very configurable, and although it doesn't generate the code for you, it's quite easy to use. For email validation and password recovery you probably want to use the :perishable_token column. AuthLogic takes care of it, you only need to reset it when it's used. For information on how to set up a basic app, you can take a look at Ryan Bates' Railscast on AuthLogic, and the "official" example app. Ben Johnson, the creator of AuthLogic has also written a blog post on how to RESTfully reset passwords. Unfortunately I can't post more than one link, but the links to the railscast, the password reset blog post and the example app are all in the README (see the AuthLogic repo for the README) Update: Now I can post more links, so I linked some more. Thank you marinatime for adding the link in the meanwhile A: I'm really liking thoughtbot's clearance. Very simple and has a few good hooks and is testable. A: I would really recommend Restful Authentication. I think it's pretty much the de-facto standard. A: restful_authentication is a powerful tool which is very flexible and provides most of what you are looking for out of the box. However, a couple of caveats: * *Don't think in terms of 'controls'. In Rails the Model, View and Controller are much more independent than in 'Webforms-style' ASP.NET. Work out what you want from each layer independently, write tests/specs to match and make sure each layer is doing what you expect. *Even if you are using a plugin there is no substitute for reading (at least some) of the code generated. If you have a big-picture idea of what is going on under the hood, you will find debugging and customising much easier. A: The plugin restful_authentication and other plugins that extend it, answer your needs perfectly. A quick search on github.com will reveal a lot of tutorials, examples, and extensitons. Just go here: - http://github.com/search?q=restful_authentication There are several projects that use restful_authentication just to provide examples of a bare-bones Rails app with just the authentication parts. * *http://github.com/fudgestudios/bort -- A base rails app featuring: RESTful Authentication *http://github.com/mrflip/restful_authentication_example -- Another project with a great examlpe of how to use restful_authentication *http://github.com/activefx/restful_authentication_tutorial -- Same as above, with some other plugins bundled. *http://railscasts.com/episodes/67-restful-authentication -- a great screencast explaining restful_authentication This information should be enough to get you started finding heads and tails ... good luck. A: Just updating this: Ryan Bates' Railscast #250 shows building an authentication system from scratch.... A: For a really simple solution go with Clearance. If you are looking for more options Devise is a great solution. It uses Warden which is a rack based authentication system. A: Another vote for Clearance - perhaps not as customisable or as 'in' as authlogic, but in terms of just being able to drop it in place and go, it's definitely worth having a look at.
{ "language": "en", "url": "https://stackoverflow.com/questions/24298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "84" }
Q: Programming a simple IRC (Internet-Relay-Chat) Client I started using IRC at a young age, and I have always been fascinated with it. As a language exercise, I was thinking about programming a simple IRC client in Ruby with Shoes as a graphical front-end. My question to you, kind-sirs, what do I need to become familiar with to start on this great adventure (besides shoes and Ruby of course)? I imagine there is some-sort of specification on IRC Protocol. Any pointers? A: I found this gem on Wikipedia. Sounds intimidating. It's actually not. Telnet onto an IRC Server and witness the simplicity of the protocol first hand. The hardest part is the handshake, after that its very simple. A: An earlier post mentioned RFC1459. While it is a very good introduction to IRC, it has actually been superseded by RFCs 2810-2813. Here is a more complete list of documentation you need to program anything IRC-related: * *RFC1459 (original RFC; superseded, but still useful) *RFC2810 (IRC architecture) *RFC2811 (IRC channel management) *RFC2812 (IRC client protocol) *RFC2813 (IRC server protocol) *CTCP specification *DCC specification *Updated CTCP specification (not all clients support this) *ISupport (response code 005) draft (almost all servers support this nowadays) *Client capabilities (CAP command) draft (supported by some servers/clients) *IRCv3 standards and proposals (the future features of IRC, some of which are already widely supported) A: I once implemented a client and a server with 2 more guys (as part of a course). I can tell you that the RFC you were already linked to is great. I'd also try simply sniffing a connection with an existing client to see for yourself how stuff work. A: The IRC Specification is laid out in RFC 1459 http://www.irchelp.org/irchelp/rfc/rfc.html A: Not exactly an answer to your question, but it may be helpful. If you are using Ruby, I have found the Autumn Leaves project to be a great way to build an IRC bot using Ruby: http://github.com/RISCfuture/autumn/tree/master It is pretty much the Jibble of the Ruby world.
{ "language": "en", "url": "https://stackoverflow.com/questions/24310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Is It Possible To Raise An Event When A File Becomes Accessible? In C# I can use the FileSystemWatcher object to watch for a specific file and raise an event when it is created, modified, etc. The problem I have with this class is that it raises the event the moment the file becomes created, even if the process which created the file is still in the process of writing. I have found this to be very problematic, especially if I'm trying to read something like an XML document where the file must have some structure to it which won't exist until it is completed being written. Does .NET (preferably 2.0) have any way to raise an event after the file becomes accessible, or do I have to constantly try reading the file until it doesn't throw an exception to know it is available? A: You can use a file system watcher to check when the file has been changed. It only becomes "changed" after whichever program had the file previously closes the file. I know you asked for C#, but my VB.Net is much better. Hope you or someone else can translate. It tries to open the file, if it isn't available, it adds a watcher, and waits for the file to be changed. After the file is changed, it tries to open again. It throws an exception if it waits more than 120 seconds, because you may get caught in a situation where the file is never released. Also, I decided to add a timeout of waiting for the file change of 5 seconds, in case of the small possibility that the file was closed prior to the actual file watcher being created. Public Sub WriteToFile(ByVal FilePath As String, ByVal FileName As String, ByVal Data() As Byte) Dim FileOpen As Boolean Dim File As System.IO.FileStream = Nothing Dim StartTime As DateTime Dim MaxWaitSeconds As Integer = 120 StartTime = DateTime.Now FileOpen = False Do Try File = New System.IO.FileStream(FilePath & FileName, IO.FileMode.Append) FileOpen = True Catch ex As Exception If DateTime.Now.Subtract(StartTime).TotalSeconds > MaxWaitSeconds Then Throw New Exception("Waited more than " & MaxWaitSeconds & " To Open File.") Else Dim FileWatch As System.IO.FileSystemWatcher FileWatch = New System.IO.FileSystemWatcher(FilePath, FileName) FileWatch.WaitForChanged(IO.WatcherChangeTypes.Changed,5000) End If FileOpen = False End Try Loop While Not FileOpen If FileOpen Then File.Write(Data, 0, Data.Length) File.Close() End If End Sub A: Not sure if there is a way of an event actually being raised by the standard class, but I eas experiencing similar problems on some recent work I was doing. In short, I was trying to write to a file that was locked at the time. I ended up wrapping the write method up so it would automatically try the write again in a few ms after.. Thinking out loud, Can you probe the file for a ReadOnly status? May be worth then having a wrapper for file IO which can stack up delegates for pending file operations or something.. Thoughts? A: Use CreateFile in a loop with OPEN_ EXISTING flag and FILE_ ALL_ ACCESS (or you might need only a subset, see http://msdn.microsoft.com/en-us/library/aa364399(VS.85).aspx Examine the handle returned against -1 (INVALID_ HANDLE_ VALUE) for failure. It's still polling, but this will save the cost of an exception throw. EDIT: this editor/markup can't handle underscores! bah! A: Kibbe answer seems right but didn't worked for me. It seems that the FileSystemWatcher has a bug. So I wrote my own WaitForChanged: using (var watcher = new FileSystemWatcher(MatlabPath, fileName)) { var wait = new EventWaitHandle(false, EventResetMode.AutoReset); watcher.EnableRaisingEvents = true; watcher.Changed += delegate(object sender, FileSystemEventArgs e) { wait.Set(); }; if (!wait.WaitOne(MillissecondsTimeout)) { throw new TimeoutException(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/24315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Database query representation impersonating file on Windows share? Is there any way to have something that looks just like a file on a Windows file share, but is really a resource served up over HTTP? For context, I'm working with an old app that can only deal with files on a Windows file share, I want to create a simple HTTP-based service to serve the content of the files dynamically to pick up real time changes to the underlying data on request. A: WebDAV (basically) takes an existing directory, and shares it over HTTP - which sounds like the opposite of what you want. You need something that speaks SMB/CIFS on one end, and your own code on the other. The easiest way to do that is with a userspace file system. To that end, here's a couple of links: * *WinFUSE, which is kind of a barebones CIFS/SMB server that can host your own filesystem. I've done a couple of small samples with it - and the docs are terrible, but it more or less worked. *Dokan, a userspace file driver with .NET bindings. I haven't used this one, but it looks promising. It has both .NET and Ruby bindings, so you should be able to get a POC up pretty quickly. *Callback File System - yet another userspace file system. Again, I have no experience with this one. *A Linux box with SAMBA and FUSE that shares the drive out to the Windows box. A: This won't answer your question in any meaningful way, but maybe it will get you pointed in the right direction. Look into serving the "file(s)" via WebDAV--SharePoint uses this and its files can be accessed exactly as you want, as a file share where the transport mechanism is HTTP. Unfortunately I can't give any more detailed info, as I've only worked on the client end of WebDAV and not the server side of things. A: I think serving up files from WebDAV might be what you're looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/24408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I capture Windows Mobile PIE keyboard events? Anyone know of a way to capture keyboard events (keyup / keydown) in Portable IE under Window mobile? I noticed that key events are not supported in JS, and would like to come up with a solution that works without any client side additions. A: Without any client side additions? As per IEMobile Team Blog, the only way for that would be wait for the next release :(
{ "language": "en", "url": "https://stackoverflow.com/questions/24414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IE 7+ Favorites Is it possible to develop a plug-in for Internet Explorer that can replace the existing favorites functionality? A: Absolutely, however, it does depend somewhat on what you expect "replacing" to mean. You can develop an extension to provide a new set of menus or dropdown toolbar of some kind like the Google Bookmarks toolbar for example, or like the Delicious toolbar & sidebar. These IMO are much better designs for managing bookmarks than the built-in IE menu anyway. However, you could build a top level menu structure that worked the exact same way as the IE favorites menu if you wanted as well. There are many libraries out there that you could use to even handle the IE integration as well. I don't know what language you develop in, but some example libraries to make the IE addons a breeze are (for .NET, there are plenty others out there for other languages as well): http://www.add-in-express.com/programming-internet-explorer/ http://www.ssware.com/ezshell/ezshell.htm also some articles to create your own from scratch: http://www.codeproject.com/kb/applications/codeprojectsearchbar.aspx http://www.codeproject.com/KB/atl/rbdeskband.aspx That should get you going.
{ "language": "en", "url": "https://stackoverflow.com/questions/24439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Are there any legitimate use-cases for "goto" in a language that supports loops and functions? I've long been under the impression that goto should never be used if possible. However, while perusing libavcodec (which is written in C) the other day, I was surprised to notice multiple uses of it. Is it ever advantageous to use goto in a language that supports loops and functions? If so, why? Please provide a concrete example that clearly justifies the use of a goto. A: Everybody who is anti-goto cites, directly or indirectly, Edsger Dijkstra's GoTo Considered Harmful article to substantiate their position. Too bad Dijkstra's article has virtually nothing to do with the way goto statements are used these days and thus what the article says has little to no applicability to the modern programming scene. The goto-less meme verges now on a religion, right down to its scriptures dictated from on high, its high priests and the shunning (or worse) of perceived heretics. Let's put Dijkstra's paper into context to shed a little light on the subject. When Dijkstra wrote his paper the popular languages of the time were unstructured procedural ones like BASIC, FORTRAN (the earlier dialects) and various assembly languages. It was quite common for people using the higher-level languages to jump all over their code base in twisted, contorted threads of execution that gave rise to the term "spaghetti code". You can see this by hopping on over to the classic Trek game written by Mike Mayfield and trying to figure out how things work. Take a few moments to look that over. THIS is "the unbridled use of the go to statement" that Dijkstra was railing against in his paper in 1968. THIS is the environment he lived in that led him to write that paper. The ability to jump anywhere you like in your code at any point you liked was what he was criticising and demanding be stopped. Comparing that to the anaemic powers of goto in C or other such more modern languages is simply risible. I can already hear the raised chants of the cultists as they face the heretic. "But," they will chant, "you can make code very difficult to read with goto in C." Oh yeah? You can make code very difficult to read without goto as well. Like this one: #define _ -F<00||--F-OO--; int F=00,OO=00;main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO() { _-_-_-_ _-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_ _-_-_-_ } Not a goto in sight, so it must be easy to read, right? Or how about this one: a[900]; b;c;d=1 ;e=1;f; g;h;O; main(k, l)char* *l;{g= atoi(* ++l); for(k= 0;k*k< g;b=k ++>>1) ;for(h= 0;h*h<= g;++h); --h;c=( (h+=g>h *(h+1)) -1)>>1; while(d <=g){ ++O;for (f=0;f< O&&d<=g ;++f)a[ b<<5|c] =d++,b+= e;for( f=0;f<O &&d<=g; ++f)a[b <<5|c]= d++,c+= e;e= -e ;}for(c =0;c<h; ++c){ for(b=0 ;b<k;++ b){if(b <k/2)a[ b<<5|c] ^=a[(k -(b+1)) <<5|c]^= a[b<<5 |c]^=a[ (k-(b+1 ))<<5|c] ;printf( a[b<<5|c ]?"%-4d" :" " ,a[b<<5 |c]);} putchar( '\n');}} /*Mike Laman*/ No goto there either. It must therefore be readable. What's my point with these examples? It's not language features that make unreadable, unmaintainable code. It's not syntax that does it. It's bad programmers that cause this. And bad programmers, as you can see in that above item, can make any language feature unreadable and unusable. Like the for loops up there. (You can see them, right?) Now to be fair, some language constructs are easier to abuse than others. If you're a C programmer, however, I'd peer far more closely at about 50% of the uses of #define long before I'd go on a crusade against goto! So, for those who've bothered to read this far, there are several key points to note. * *Dijkstra's paper on goto statements was written for a programming environment where goto was a lot more potentially damaging than it is in most modern languages that aren't an assembler. *Automatically throwing away all uses of goto because of this is about as rational as saying "I tried to have fun once but didn't like it so now I'm against it". *There are legitimate uses of the modern (anaemic) goto statements in code that cannot be adequately replaced by other constructs. *There are, of course, illegitimate uses of the same statements. *There are, too, illegitimate uses of the modern control statements like the "godo" abomination where an always-false do loop is broken out of using break in place of a goto. These are often worse than judicious use of goto. A: The rule with goto that we use is that goto is okay to for jumping forward to a single exit cleanup point in a function. In really complex functions we relax that rule to allow other jump forwards. In both cases we are avoiding deeply nested if statements that often occur with error code checking, which helps readability and maintance. A: I find it funny that some people will go as far as to give a list of cases where goto is acceptable, saying that all other uses are unacceptable. Do you really think that you know every case where goto is the best choice for expressing an algorithm? To illustrate, I'll give you an example that no one here has shown yet: Today I was writing code for inserting an element in a hash table. The hash table is a cache of previous calculations which can be overwritten at will (affecting performance but not correctness). Each bucket of the hash table has 4 slots, and I have a bunch of criteria to decide which element to overwrite when a bucket is full. Right now this means making up to three passes through a bucket, like this: // Overwrite an element with same hash key if it exists for (add_index=0; add_index < ELEMENTS_PER_BUCKET; add_index++) if (slot_p[add_index].hash_key == hash_key) goto add; // Otherwise, find first empty element for (add_index=0; add_index < ELEMENTS_PER_BUCKET; add_index++) if ((slot_p[add_index].type == TT_ELEMENT_EMPTY) goto add; // Additional passes go here... add: // element is written to the hash table here Now if I didn't use goto, what would this code look like? Something like this: // Overwrite an element with same hash key if it exists for (add_index=0; add_index < ELEMENTS_PER_BUCKET; add_index++) if (slot_p[add_index].hash_key == hash_key) break; if (add_index >= ELEMENTS_PER_BUCKET) { // Otherwise, find first empty element for (add_index=0; add_index < ELEMENTS_PER_BUCKET; add_index++) if ((slot_p[add_index].type == TT_ELEMENT_EMPTY) break; if (add_index >= ELEMENTS_PER_BUCKET) // Additional passes go here (nested further)... } // element is written to the hash table here It would look worse and worse if more passes are added, while the version with goto keeps the same indentation level at all times and avoids the use of spurious if statements whose result is implied by the execution of the previous loop. So there's another case where goto makes the code cleaner and easier to write and understand... I'm sure there are many more, so don't pretend to know all the cases where goto is useful, dissing any good ones that you couldn't think of. A: The most thoughtful and thorough discussion of goto statements, their legitimate uses, and alternative constructs that can be used in place of "virtuous goto statements" but can be abused as easily as goto statements, is Donald Knuth's article "Structured Programming with goto Statements", in the December 1974 Computing Surveys (volume 6, no. 4. pp. 261 - 301). Not surprisingly, some aspects of this 39-year old paper are dated: Orders-of-magnitude increases in processing power make some of Knuth's performance improvements unnoticeable for moderately sized problems, and new programming-language constructs have been invented since then. (For example, try-catch blocks subsume Zahn's Construct, although they are rarely used in that way.) But Knuth covers all sides of the argument, and should be required reading before anyone rehashes the issue yet again. A: One of the reasons goto is bad, besides coding style is that you can use it to create overlapping, but non-nested loops: loop1: a loop2: b if(cond1) goto loop1 c if(cond2) goto loop2 This would create the bizarre, but possibly legal flow-of-control structure where a sequence like (a, b, c, b, a, b, a, b, ...) is possible, which makes compiler hackers unhappy. Apparently there are a number of clever optimization tricks that rely on this type of structure not occuring. (I should check my copy of the dragon book...) The result of this might (using some compilers) be that other optimizations aren't done for code that contains gotos. It might be useful if you know it just, "oh, by the way", happens to persuade the compiler to emit faster code. Personally, I'd prefer to try to explain to the compiler about what's probable and what's not before using a trick like goto, but arguably, I might also try goto before hacking assembler. A: Some say there is no reason for goto in C++. Some say that in 99% cases there are better alternatives. This is not reasoning, just irrational impressions. Here's a solid example where goto leads to a nice code, something like enhanced do-while loop: int i; PROMPT_INSERT_NUMBER: std::cout << "insert number: "; std::cin >> i; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(1000,'\n'); goto PROMPT_INSERT_NUMBER; } std::cout << "your number is " << i; Compare it to goto-free code: int i; bool loop; do { loop = false; std::cout << "insert number: "; std::cin >> i; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(1000,'\n'); loop = true; } } while(loop); std::cout << "your number is " << i; I see these differences: * *nested {} block is needed (albeit do {...} while looks more familiar) *extra loop variable is needed, used in four places *it takes longer time to read and understand the work with the loop *the loop does not hold any data, it just controls the flow of the execution, which is less comprehensible than simple label There is another example void sort(int* array, int length) { SORT: for(int i=0; i<length-1; ++i) if(array[i]>array[i+1]) { swap(data[i], data[i+1]); goto SORT; // it is very easy to understand this code, right? } } Now let's get rid of the "evil" goto: void sort(int* array, int length) { bool seemslegit; do { seemslegit = true; for(int i=0; i<length-1; ++i) if(array[i]>array[i+1]) { swap(data[i], data[i+1]); seemslegit = false; } } while(!seemslegit); } You see it is the same type of using goto, it is well structured pattern and it is not forward goto as many promote as the only recommended way. Surely you want to avoid "smart" code like this: void sort(int* array, int length) { for(int i=0; i<length-1; ++i) if(array[i]>array[i+1]) { swap(data[i], data[i+1]); i = -1; // it works, but WTF on the first glance } } The point is that goto can be easily misused, but goto itself is not to blame. Note that label has function scope in C++, so it does not pollute global scope like in pure assembly, in which overlapping loops have its place and are very common - like in the following code for 8051, where 7segment display is connected to P1. The program loops lightning segment around: ; P1 states loops ; 11111110 <- ; 11111101 | ; 11111011 | ; 11110111 | ; 11101111 | ; 11011111 | ; |_________| init_roll_state: MOV P1,#11111110b ACALL delay next_roll_state: MOV A,P1 RL A MOV P1,A ACALL delay JNB P1.5, init_roll_state SJMP next_roll_state There is another advantage: goto can serve as named loops, conditions and other flows: if(valid) { do { // while(loop) // more than one page of code here // so it is better to comment the meaning // of the corresponding curly bracket } while(loop); } // if(valid) Or you can use equivalent goto with indentation, so you don't need comment if you choose the label name wisely: if(!valid) goto NOTVALID; LOOPBACK: // more than one page of code here if(loop) goto LOOPBACK; NOTVALID:; A: I have come across a situation where a goto was a good solution, and I have not seen this example here or anywhere. I had a switch case with a few cases which all needed to call the same function in the end. I had other cases which all needed to call a different function in the end. This looked a bit like this: switch( x ) { case 1: case1() ; doStuffFor123() ; break ; case 2: case2() ; doStuffFor123() ; break ; case 3: case3() ; doStuffFor123() ; break ; case 4: case4() ; doStuffFor456() ; break ; case 5: case5() ; doStuffFor456() ; break ; case 6: case6() ; doStuffFor456() ; break ; case 7: case7() ; doStuffFor789() ; break ; case 8: case8() ; doStuffFor789() ; break ; case 9: case9() ; doStuffFor789() ; break ; } Instead of giving every case a function call, I replaced the break by a goto. The goto jumps to a label which is also inside the switch case. switch( x ) { case 1: case1() ; goto stuff123 ; case 2: case2() ; goto stuff123 ; case 3: case3() ; goto stuff123 ; case 4: case4() ; goto stuff456 ; case 5: case5() ; goto stuff456 ; case 6: case6() ; goto stuff456 ; case 7: case7() ; goto stuff789 ; case 8: case8() ; goto stuff789 ; case 9: case9() ; goto stuff789 ; stuff123: doStuffFor123() ; break ; stuff456: doStuffFor456() ; break ; stuff789: doStuffFor789() ; break ; } cases 1 through 3 all must call doStuffFor123() and similarly cases 4 through 6 had to call doStuffFor456() etc. In my opinion, gotos are perfectly fine if you use them correctly. In the end, any code is as clear as people write it. With gotos one can make spaghetti code, but that does not mean that gotos are the cause of the spaghetti code. That cause is us; programmers. I can also create spaghetti code with functions if I want to. The same goes for macros as well. A: Well, there's one thing that's always worse than goto's; strange use of other programflow operators to avoid a goto: Examples: // 1 try{ ... throw NoErrorException; ... } catch (const NoErrorException& noe){ // This is the worst } // 2 do { ...break; ...break; } while (false); // 3 for(int i = 0;...) { bool restartOuter = false; for (int j = 0;...) { if (...) restartOuter = true; if (restartOuter) { i = -1; } } etc etc A: In a Perl module, you occasionally want to create subroutines or closures on the fly. The thing is, that once you have created the subroutine, how do you get to it. You could just call it, but then if the subroutine uses caller() it won't be as helpful as it could be. That is where the goto &subroutine variation can be helpful. Here is a quick example: sub AUTOLOAD{ my($self) = @_; my $name = $AUTOLOAD; $name =~ s/.*:://; *{$name} = my($sub) = sub{ # the body of the closure } goto $sub; # nothing after the goto will ever be executed. } You can also use this form of goto to provide a rudimentary form of tail-call optimization. sub factorial($){ my($n,$tally) = (@_,1); return $tally if $n <= 1; $tally *= $n--; @_ = ($n,$tally); goto &factorial; } ( In Perl 5 version 16 that would be better written as goto __SUB__; ) There is a module that will import a tail modifier and one that will import recur if you don't like using this form of goto. use Sub::Call::Tail; sub AUTOLOAD { ... tail &$sub( @_ ); } use Sub::Call::Recur; sub factorial($){ my($n,$tally) = (@_,1); return $tally if $n <= 1; recur( $n-1, $tally * $n ); } Most of the other reasons to use goto are better done with other keywords. Like redoing a bit of code: LABEL: ; ... goto LABEL if $x; { ... redo if $x; } Or going to the last of a bit of code from multiple places: goto LABEL if $x; ... goto LABEL if $y; ... LABEL: ; { last if $x; ... last if $y ... } A: 1) The most common use of goto that I know of is emulating exception handling in languages that don't offer it, namely in C. (The code given by Nuclear above is just that.) Look at the Linux source code and you'll see a bazillion gotos used that way; there were about 100,000 gotos in Linux code according to a quick survey conducted in 2013: http://blog.regehr.org/archives/894. Goto usage is even mentioned in the Linux coding style guide: https://www.kernel.org/doc/Documentation/CodingStyle. Just like object-oriented programming is emulated using structs populated with function pointers, goto has its place in C programming. So who is right: Dijkstra or Linus (and all Linux kernel coders)? It's theory vs. practice basically. There is however the usual gotcha for not having compiler-level support and checks for common constructs/patterns: it's easier to use them wrong and introduce bugs without compile-time checks. Windows and Visual C++ but in C mode offer exception handling via SEH/VEH for this very reason: exceptions are useful even outside OOP languages, i.e. in a procedural language. But the compiler can't always save your bacon, even if it offers syntactic support for exceptions in the language. Consider as example of the latter case the famous Apple SSL "goto fail" bug, which just duplicated one goto with disastrous consequences (https://www.imperialviolet.org/2014/02/22/applebug.html): if (something()) goto fail; goto fail; // copypasta bug printf("Never reached\n"); fail: // control jumps here You can have exactly the same bug using compiler-supported exceptions, e.g. in C++: struct Fail {}; try { if (something()) throw Fail(); throw Fail(); // copypasta bug printf("Never reached\n"); } catch (Fail&) { // control jumps here } But both variants of the bug can be avoided if the compiler analyzes and warns you about unreachable code. For example compiling with Visual C++ at the /W4 warning level finds the bug in both cases. Java for instance forbids unreachable code (where it can find it!) for a pretty good reason: it's likely to be a bug in the average Joe's code. As long as the goto construct doesn't allow targets that the compiler can't easily figure out, like gotos to computed addresses(**), it's not any harder for the compiler to find unreachable code inside a function with gotos than using Dijkstra-approved code. (**) Footnote: Gotos to computed line numbers are possible in some versions of Basic, e.g. GOTO 10*x where x is a variable. Rather confusingly, in Fortran "computed goto" refers to a construct that is equivalent to a switch statement in C. Standard C doesn't allow computed gotos in the language, but only gotos to statically/syntactically declared labels. GNU C however has an extension to get the address of a label (the unary, prefix && operator) and also allows a goto to a variable of type void*. See https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html for more on this obscure sub-topic. The rest of this post ins't concerned with that obscure GNU C feature. Standard C (i.e. not computed) gotos are not usually the reason why unreachable code can't be found at compile time. The usual reason is logic code like the following. Given int computation1() { return 1; } int computation2() { return computation1(); } It's just as hard for a compiler to find unreachable code in any of the following 3 constructs: void tough1() { if (computation1() != computation2()) printf("Unreachable\n"); } void tough2() { if (computation1() == computation2()) goto out; printf("Unreachable\n"); out:; } struct Out{}; void tough3() { try { if (computation1() == computation2()) throw Out(); printf("Unreachable\n"); } catch (Out&) { } } (Excuse my brace-related coding style, but I tried to keep the examples as compact as possible.) Visual C++ /W4 (even with /Ox) fails to find unreachable code in any of these, and as you probably know the problem of finding unreachable code is undecidable in general. (If you don't believe me about that: https://www.cl.cam.ac.uk/teaching/2006/OptComp/slides/lecture02.pdf) As a related issue, the C goto can be used to emulate exceptions only inside the body of a function. The standard C library offers a setjmp() and longjmp() pair of functions for emulating non-local exits/exceptions, but those have some serious drawbacks compared to what other languages offer. The Wikipedia article http://en.wikipedia.org/wiki/Setjmp.h explains fairly well this latter issue. This function pair also works on Windows (http://msdn.microsoft.com/en-us/library/yz2ez4as.aspx), but hardly anyone uses them there because SEH/VEH is superior. Even on Unix, I think setjmp and longjmp are very seldom used. 2) I think the second most common use of goto in C is implementing multi-level break or multi-level continue, which is also a fairly uncontroversial use case. Recall that Java doesn't allow goto label, but allows break label or continue label. According to http://www.oracle.com/technetwork/java/simple-142616.html, this is actually the most common use case of gotos in C (90% they say), but in my subjective experience, system code tends to use gotos for error handling more often. Perhaps in scientific code or where the OS offers exception handling (Windows) then multi-level exits are the dominant use case. They don't really give any details as to the context of their survey. Edited to add: it turns out these two use patterns are found in the C book of Kernighan and Ritchie, around page 60 (depending on edition). Another thing of note is that both use cases involve only forward gotos. And it turns out that MISRA C 2012 edition (unlike the 2004 edition) now permits gotos, as long as they are only forward ones. A: Since goto makes reasoning about program flow hard1 (aka. “spaghetti code”), goto is generally only used to compensate for missing features: The use of goto may actually be acceptable, but only if the language doesn't offer a more structured variant to obtain the same goal. Take Doubt's example: The rule with goto that we use is that goto is okay to for jumping forward to a single exit cleanup point in a function. This is true – but only if the language doesn't allow structured exception handling with cleanup code (such as RAII or finally), which does the same job better (as it is specially built for doing it), or when there's a good reason not to employ structured exception handling (but you will never have this case except at a very low level). In most other languages, the only acceptable use of goto is to exit nested loops. And even there it is almost always better to lift the outer loop into an own method and use return instead. Other than that, goto is a sign that not enough thought has gone into the particular piece of code. 1 Modern languages which support goto implement some restrictions (e.g. goto may not jump into or out of functions) but the problem fundamentally remains the same. Incidentally, the same is of course also true for other language features, most notably exceptions. And there are usually strict rules in place to only use these features where indicated, such as the rule not to use exceptions to control non-exceptional program flow. A: In C# switch statement doest not allow fall-through. So goto is used to transfer control to a specific switch-case label or the default label. For example: switch(value) { case 0: Console.WriteLine("In case 0"); goto case 1; case 1: Console.WriteLine("In case 1"); goto case 2; case 2: Console.WriteLine("In case 2"); goto default; default: Console.WriteLine("In default"); break; } Edit: There is one exception on "no fall-through" rule. Fall-through is allowed if a case statement has no code. A: If so, why? C has no multi-level/labelled break, and not all control flows can be easily modelled with C's iteration and decision primitives. gotos go a long way towards redressing these flaws. Sometimes it's clearer to use a flag variable of some kind to effect a kind of pseudo-multi-level break, but it's not always superior to the goto (at least a goto allows one to easily determine where control goes to, unlike a flag variable), and sometimes you simply don't want to pay the performance price of flags/other contortions to avoid the goto. libavcodec is a performance-sensitive piece of code. Direct expression of the control flow is probably a priority, because it'll tend to run better. A: There are a few reasons for using the "goto" statement that I'm aware of (some have spoken to this already): Cleanly exiting a function Often in a function, you may allocate resources and need to exit in multiple places. Programmers can simplify their code by putting the resource cleanup code at the end of the function, and all "exit points" of the function would goto the cleanup label. This way, you don't have to write cleanup code at every "exit point" of the function. Exiting nested loops If you're in a nested loop and need to break out of all loops, a goto can make this much cleaner and simpler than break statements and if-checks. Low-level performance improvements This is only valid in perf-critical code, but goto statements execute very quickly and can give you a boost when moving through a function. This is a double-edged sword, however, because a compiler typically cannot optimize code that contains gotos. Note that in all these examples, gotos are restricted to the scope of a single function. A: I find the do{} while(false) usage utterly revolting. It is conceivable might convince me it is necessary in some odd case, but never that it is clean sensible code. If you must do some such loop, why not make the dependence on the flag variable explicit? for (stepfailed=0 ; ! stepfailed ; /*empty*/) A: The GOTO can be used, of course, but there is one more important thing than the code style, or if the code is or not readable that you must have in mind when you use it: the code inside may not be as robust as you think. For instance, look at the following two code snippets: If A <> 0 Then A = 0 EndIf Write("Value of A:" + A) An equivalent code with GOTO If A == 0 Then GOTO FINAL EndIf A = 0 FINAL: Write("Value of A:" + A) The first thing we think is that the result of both bits of code will be that "Value of A: 0" (we suppose an execution without parallelism, of course) That's not correct: in the first sample, A will always be 0, but in the second sample (with the GOTO statement) A might not be 0. Why? The reason is because from another point of the program I can insert a GOTO FINAL without controlling the value of A. This example is very obvious, but as programs get more complicated, the difficulty of seeing those kind of things increases. Related material can be found into the famous article from Mr. Dijkstra "A case against the GO TO statement" A: It comes in handy for character-wise string processing from time to time. Imagine something like this printf-esque example: for cur_char, next_char in sliding_window(input_string) { if cur_char == '%' { if next_char == '%' { cur_char_index += 1 goto handle_literal } # Some additional logic if chars_should_be_handled_literally() { goto handle_literal } # Handle the format } # some other control characters else { handle_literal: # Complicated logic here # Maybe it's writing to an array for some OpenGL calls later or something, # all while modifying a bunch of local variables declared outside the loop } } You could refactor that goto handle_literal to a function call, but if it's modifying several different local variables, you'd have to pass references to each unless your language supports mutable closures. You'd still have to use a continue statement (which is arguably a form of goto) after the call to get the same semantics if your logic makes an else case not work. I have also used gotos judiciously in lexers, typically for similar cases. You don't need them most of the time, but they're nice to have for those weird cases. A: Obeying best practices blindly is not a best practice. The idea of avoiding goto statements as one's primary form of flow control is to avoid producing unreadable spaghetti code. If used sparingly in the right places, they can sometimes be the simplest, clearest way of expressing an idea. Walter Bright, the creator of the Zortech C++ compiler and the D programming language, uses them frequently, but judiciously. Even with the goto statements, his code is still perfectly readable. Bottom line: Avoiding goto for the sake of avoiding goto is pointless. What you really want to avoid is producing unreadable code. If your goto-laden code is readable, then there's nothing wrong with it. A: I've written more than a few lines of assembly language over the years. Ultimately, every high level language compiles down to gotos. Okay, call them "branches" or "jumps" or whatever else, but they're gotos. Can anyone write goto-less assembler? Now sure, you can point out to a Fortran, C or BASIC programmer that to run riot with gotos is a recipe for spaghetti bolognaise. The answer however is not to avoid them, but to use them carefully. A knife can be used to prepare food, free someone, or kill someone. Do we do without knives through fear of the latter? Similarly the goto: used carelessly it hinders, used carefully it helps. A: #ifdef TONGUE_IN_CHEEK Perl has a goto that allows you to implement poor-man's tail calls. :-P sub factorial { my ($n, $acc) = (@_, 1); return $acc if $n < 1; @_ = ($n - 1, $acc * $n); goto &factorial; } #endif Okay, so that has nothing to do with C's goto. More seriously, I agree with the other comments about using goto for cleanups, or for implementing Duff's device, or the like. It's all about using, not abusing. (The same comment can apply to longjmp, exceptions, call/cc, and the like---they have legitimate uses, but can easily be abused. For example, throwing an exception purely to escape a deeply-nested control structure, under completely non-exceptional circumstances.) A: Take a look at When To Use Goto When Programming in C: Although the use of goto is almost always bad programming practice (surely you can find a better way of doing XYZ), there are times when it really isn't a bad choice. Some might even argue that, when it is useful, it's the best choice. Most of what I have to say about goto really only applies to C. If you're using C++, there's no sound reason to use goto in place of exceptions. In C, however, you don't have the power of an exception handling mechanism, so if you want to separate out error handling from the rest of your program logic, and you want to avoid rewriting clean up code multiple times throughout your code, then goto can be a good choice. What do I mean? You might have some code that looks like this: int big_function() { /* do some work */ if([error]) { /* clean up*/ return [error]; } /* do some more work */ if([error]) { /* clean up*/ return [error]; } /* do some more work */ if([error]) { /* clean up*/ return [error]; } /* do some more work */ if([error]) { /* clean up*/ return [error]; } /* clean up*/ return [success]; } This is fine until you realize that you need to change your cleanup code. Then you have to go through and make 4 changes. Now, you might decide that you can just encapsulate all of the cleanup into a single function; that's not a bad idea. But it does mean that you'll need to be careful with pointers -- if you plan to free a pointer in your cleanup function, there's no way to set it to then point to NULL unless you pass in a pointer to a pointer. In a lot of cases, you won't be using that pointer again anyway, so that may not be a major concern. On the other hand, if you add in a new pointer, file handle, or other thing that needs cleanup, then you'll need to change your cleanup function again; and then you'll need to change the arguments to that function. By using goto, it will be int big_function() { int ret_val = [success]; /* do some work */ if([error]) { ret_val = [error]; goto end; } /* do some more work */ if([error]) { ret_val = [error]; goto end; } /* do some more work */ if([error]) { ret_val = [error]; goto end; } /* do some more work */ if([error]) { ret_val = [error]; goto end; } end: /* clean up*/ return ret_val; } The benefit here is that your code following end has access to everything it will need to perform cleanup, and you've managed to reduce the number of change points considerably. Another benefit is that you've gone from having multiple exit points for your function to just one; there's no chance you'll accidentally return from the function without cleaning up. Moreover, since goto is only being used to jump to a single point, it's not as though you're creating a mass of spaghetti code jumping back and forth in an attempt to simulate function calls. Rather, goto actually helps write more structured code. In a word, goto should always be used sparingly, and as a last resort -- but there is a time and a place for it. The question should be not "do you have to use it" but "is it the best choice" to use it. A: In Perl, use of a label to "goto" from a loop - using a "last" statement, which is similar to break. This allows better control over nested loops. The traditional goto label is supported too, but I'm not sure there are too many instances where this is the only way to achieve what you want - subroutines and loops should suffice for most cases. A: I use goto in the following case: when needed to return from funcions at different places, and before return some uninitialization needs to be done: non-goto version: int doSomething (struct my_complicated_stuff *ctx) { db_conn *conn; RSA *key; char *temp_data; conn = db_connect(); if (ctx->smth->needs_alloc) { temp_data=malloc(ctx->some_size); if (!temp_data) { db_disconnect(conn); return -1; } } ... if (!ctx->smth->needs_to_be_processed) { free(temp_data); db_disconnect(conn); return -2; } pthread_mutex_lock(ctx->mutex); if (ctx->some_other_thing->error) { pthread_mutex_unlock(ctx->mutex); free(temp_data); db_disconnect(conn); return -3; } ... key=rsa_load_key(....); ... if (ctx->something_else->error) { rsa_free(key); pthread_mutex_unlock(ctx->mutex); free(temp_data); db_disconnect(conn); return -4; } if (ctx->something_else->additional_check) { rsa_free(key); pthread_mutex_unlock(ctx->mutex); free(temp_data); db_disconnect(conn); return -5; } pthread_mutex_unlock(ctx->mutex); free(temp_data); db_disconnect(conn); return 0; } goto version: int doSomething_goto (struct my_complicated_stuff *ctx) { int ret=0; db_conn *conn; RSA *key; char *temp_data; conn = db_connect(); if (ctx->smth->needs_alloc) { temp_data=malloc(ctx->some_size); if (!temp_data) { ret=-1; goto exit_db; } } ... if (!ctx->smth->needs_to_be_processed) { ret=-2; goto exit_freetmp; } pthread_mutex_lock(ctx->mutex); if (ctx->some_other_thing->error) { ret=-3; goto exit; } ... key=rsa_load_key(....); ... if (ctx->something_else->error) { ret=-4; goto exit_freekey; } if (ctx->something_else->additional_check) { ret=-5; goto exit_freekey; } exit_freekey: rsa_free(key); exit: pthread_mutex_unlock(ctx->mutex); exit_freetmp: free(temp_data); exit_db: db_disconnect(conn); return ret; } The second version makes it easier, when you need to change something in the deallocation statements (each is used once in the code), and reduces the chance to skip any of them, when adding a new branch. Moving them in a function will not help here, because the deallocation can be done at different "levels". A: Use "goto" wherever it makes your code more readable or run faster. Just don't let it turn your code into spaghetti. A: The problem with 'goto' and the most important argument of the 'goto-less programming' movement is, that if you use it too frequently your code, although it might behave correctly, becomes unreadable, unmaintainable, unreviewable etc. In 99.99% of the cases 'goto' leads to spaghetti code. Personally, I cannot think of any good reason as to why I would use 'goto'. A: Edsger Dijkstra, a computer scientist that had major contributions on the field, was also famous for criticizing the use of GoTo. There's a short article about his argument on Wikipedia.
{ "language": "en", "url": "https://stackoverflow.com/questions/24451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "220" }
Q: Embedding IPTC image data with PHP GD I'm trying to embed a IPTC data onto a JPEG image using iptcembed() but am having a bit of trouble. I have verified it is in the end product: // Embed the IPTC data $content = iptcembed($data, $path); // Verify IPTC data is in the end image $iptc = iptcparse($content); var_dump($iptc); Which returns the tags entered. However when I save and reload the image the tags are non existant: // Save the edited image $im = imagecreatefromstring($content); imagejpeg($im, 'phplogo-edited.jpg'); imagedestroy($im); // Get data from the saved image $image = getimagesize('./phplogo-edited.jpg'); // If APP13/IPTC data exists output it if(isset($image['APP13'])) { $iptc = iptcparse($image['APP13']); print_r($iptc); } else { // Otherwise tell us what the image *does* contain // SO: This is what's happening print_r($image); } So why aren't the tags in the saved image? The PHP source is avaliable here, and the respective outputs are: * *Image output *Data output A: getimagesize has an optional second parameter Imageinfo which contains the info you need. From the manual: This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed » IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable. so you could use it like this: <?php $size = getimagesize('./phplogo-edited.jpg', $info); if(isset($info['APP13'])) { $iptc = iptcparse($info['APP13']); var_dump($iptc); } ?> Hope this helps...
{ "language": "en", "url": "https://stackoverflow.com/questions/24456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: (N)Hibernate Auto-Join I'm developing a web- application using NHibernate. Can you tell me how to write a NHibernate Query for the following SQL query: SELECT v1.Id FROM VIEW v1 LEFT JOIN VIEW v2 ON v1.SourceView = v2.Id ORDER BY v1.Position It's basically a auto-join but I don't know how to write this in Nhibernate. Lets say the property names are the same as the table column names. A: You could just perform the select on the original entity and make the association between the two objects "lazy = false". As long as the entities are mapped then both will be returned and you wont get a lazyloadingexception when trying to access the object. If you don't want to map "lazy=false" then you can also iterate through the results and perform some sort of operation (such as asking if it is null; if(v1.AssocatedObject == null){}) to ensure the data is loaded while the session is open. Update: I think there is actually a better one than that in, NHibernateUtil.Initialise() that can initialise a collection without having to wander through it.
{ "language": "en", "url": "https://stackoverflow.com/questions/24467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Running "partially trusted" .NET assemblies from a network share When I try to run a .NET assembly (boo.exe) from a network share (mapped to a drive), it fails since it's only partially trusted: Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers. at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) at BooCommandLine..ctor() at Program..ctor() at ProgramModule.Main(String[] argv) The action that failed was: LinkDemand The assembly or AppDomain that failed was: boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67 The Zone of the assembly that failed was: Intranet The Url of the assembly that failed was: file:///H:/boo-svn/bin/boo.exe With instructions from a blog post, I added a policy to the .NET Configuration fully trusting all assemblies with file:///H:/* as their URL. I verified this by entering the URL file:///H:/boo-svn/bin/boo.exe into the Evaluate Assembly tool in the .NET Configuration and noting that boo.exe had the Unrestricted permission (which it didn't have before the policy). Even with the permission, boo.exe does not run. I still get the same error message. What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run? A: With .NET 3.5 SP1, .NET assemblies running from UNC shares have full permissions. See Brad Abrams's Allow .exes to be run off a network shares for workaround and discussions, and finally the follow up .NET 3.5 SP1 allows managed code to be launched from a network share. A: I resolved the problem by using caspol as instructed in Johnny Hughes' blog post Running a .Net application from a network share: caspol -addgroup 1.2 -url file:///H:/* FullTrust It seems the .NET Configuration GUI for managing the policies simply doesn't work. A: Take a look at the 'caspol.exe' program (provided with .NET runtimes). You will have to do this on the machine you are trying to run the application from. I wasn't able to 'mark' and assembly (probably just me). However, using caspol and setting up the proper permission for my app, LocalIntranet_Zone, fix my similar issue. I have heard (but haven't tried it yet), that .NET 3.5 sp1 removed this tighten security requirement (not allowing .NET assemblies to reside on a share by default). A: I think you want to add the AllowPartiallyTrustedCallers attribute to your assembly. The error message implies that something that's calling into your boo.exe assembly is not fully trusted, and boo.exe doesn't have this attribute allowing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/24468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: SQL Server: Examples of PIVOTing String data Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following. Action1 VIEW Action1 EDIT Action2 VIEW Action3 VIEW Action3 EDIT I would like to use PIVOT (if even possible) to make the results like so: Action1 VIEW EDIT Action2 VIEW NULL Action3 VIEW EDIT Is this even possible with the PIVOT functionality? A: From http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/: SELECT CUST, PRODUCT, QTY FROM Product) up PIVOT ( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p UNPIVOT (QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS) ) AS Unpvt GO A: Well, for your sample and any with a limited number of unique columns, this should do it. select distinct a, (select distinct t2.b from t t2 where t1.a=t2.a and t2.b='VIEW'), (select distinct t2.b from t t2 where t1.a=t2.a and t2.b='EDIT') from t t1 A: Table setup: CREATE TABLE dbo.tbl ( action VARCHAR(20) NOT NULL, view_edit VARCHAR(20) NOT NULL ); INSERT INTO dbo.tbl (action, view_edit) VALUES ('Action1', 'VIEW'), ('Action1', 'EDIT'), ('Action2', 'VIEW'), ('Action3', 'VIEW'), ('Action3', 'EDIT'); Your table: SELECT action, view_edit FROM dbo.tbl Query without using PIVOT: SELECT Action, [View] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'VIEW'), [Edit] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'EDIT') FROM tbl t GROUP BY Action Query using PIVOT: SELECT [Action], [View], [Edit] FROM (SELECT [Action], view_edit FROM tbl) AS t1 PIVOT (MAX(view_edit) FOR view_edit IN ([View], [Edit]) ) AS t2 Both queries result: A: If you specifically want to use the SQL Server PIVOT function, then this should work, assuming your two original columns are called act and cmd. (Not that pretty to look at though.) SELECT act AS 'Action', [View] as 'View', [Edit] as 'Edit' FROM ( SELECT act, cmd FROM data ) AS src PIVOT ( MAX(cmd) FOR cmd IN ([View], [Edit]) ) AS pvt A: With pivot_data as ( select action, -- grouping column view_edit -- spreading column from tbl ) select action, [view], [edit] from pivot_data pivot ( max(view_edit) for view_edit in ([view], [edit]) ) as p; A: Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once. SELECT Action, MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol, MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol FROM t GROUP BY Action A: I had a situation where I was parsing strings and the first two positions of the string in question would be the field names of a healthcare claims coding standard. So I would strip out the strings and get values for F4, UR and UQ or whatnot. This was great on one record or a few records for one user. But when I wanted to see hundreds of records and the values for all usersz it needed to be a PIVOT. This was wonderful especially for exporting lots of records to excel. The specific reporting request I had received was "every time someone submitted a claim for Benadryl, what value did they submit in fields F4, UR, and UQ. I had an OUTER APPLY that created the ColTitle and the value fields below PIVOT( min(value) FOR ColTitle in([F4], [UR], [UQ]) )
{ "language": "en", "url": "https://stackoverflow.com/questions/24470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "131" }
Q: What is the "best" way to store international addresses in a database? What is the "best" way to store international addresses in a database? Answer in the form of a schema and an explanation of the reasons why you chose to normalize (or not) the way you did. Also explain why you chose the type and length of each field. Note: You decide what fields you think are necessary. A: In the past I've modeled forms that needed to be international after the ups/fedex shipping address forms on their websites (I figured if they don't know how to handle an international order we are all hosed). The fields they use can be used as reference for setting up your schema. A: In general, you need to understand why you want an address. Is it for shipping/mailing? Then there is really only one requirement, have the country separate. The other lines are freeform, to be filled in by the user. The reason for this is the common forwarding strategy for mail : any incoming mail for a foreign country is forwarded without looking at the other address lines. Hence, the detailed information is parsed only by the mail sorter located in the country itself. Like the receiver, they'll be familiar with national conventions. (UPS may bunch together some small European countries, e.. all the Low Countries are probably served from Belgium - the idea still holds.) A: Plain freeform text. Validating all the world's post/zip codes is too hard; a fixed list of countries is too politically sensitive; mandatory state/region/other administrative subdivision is just plain inappropriate (all too often I'm asked which county I live in--when I don't, because Greater London is not a county at all). More to the point, it's simply unnecessary. Your application is highly unlikely to be modelling addresses in any serious way. If you want a postal address, ask for the postal address. Most people aren't so stupid as to put in something other than a postal address, and if they do, they can kiss their newly purchased item bye-bye. The exception to this is if you're doing something that's naturally constrained to one country anyway. In this situation, you should ask for, say, the { postcode, house number } pair, which is enough to identify a postal address. I imagine you could achieve similar things with the extended zip code in the US. A: I think adding country/city and address text will be fine. country and city should be separate for reporting. Managers always ask for these kind of reports which you do not expect and I dont prefer running a LIKE query through a large database. A: Not to give Facebook undue respect. However, the overall structure of the database seems to be overlooked in many web applications launching every day. Obviously I don't think there is a perfect solution that covers all the potential variables with address structure without some hard work. That said, combined with autocomplete Facebook manages to take location input data and eliminate a majority of their redundant entries. They do this by organizing their database well enough to provide autocomplete information in a low cost, low error way to the client in real time allowing them to more or less choose the correct location from an existing list. I think the best solution is to access a third party database which contains your desired geographic scope and use it to initially seed your user location information. This will allow you to avoid doing the groudwork of creating your own. With any luck you can reduce the load on your server by allowing your new users to receive the correct autocomplete information directly off your third party supplier. Eventually you will be able to fill most autocomplete for location information such as city, country, etc. from information contained in your own database from user input data. A: You need to provide a bit more details about how you are planning to use the data. For example, fields like City, State, Country can either be text in the single table, or be codes which are linked to a separate table with a Foreign Key. Simplest would be Address_Line_01 (Required, Non blank) Address_Line_02 Address_Line_03 Landmark City (Required) Pin (Required) Province_District State (Required) Country (Required) All the above can be Text/Unicode with appropriate field lengths. Phone Numbers as applicable.
{ "language": "en", "url": "https://stackoverflow.com/questions/24481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Reading model objects mapped in Velocity Templates I have a Struts + Velocity structure like for example, a Person class, whose one property is a Car object (with its own getter/setter methods) and it is mapped to a Velocity form that submits to an Action, using ModelDriven and getModel structure. I what to put a button on the form that shows "View Car" if car property is not null or car.id != 0 or show another button "Choose Car" if car is null or car.id = 0. How do I code this. I tried something like that in the template file: #if($car != null) #ssubmit("name=view" "value=View Car") #else #ssubmit("name=new" "value=Choose Car") #end But I keep getting error about Null value in the #if line. I also created a boolean method hasCar() in Person to try, but I can't access it and I don't know why. And Velocity + Struts tutorials are difficult to find or have good information. Thanks A: You should change the #if line to: #if($car) A: In the upcoming Velocity 1.6 release, you will be able to do #if( $car == $null ) without error messages. This will allow you to distinguish easily between when $car is null and when it is false. To do that now requires #if( $car && $car != false ), which just isn't as friendly.
{ "language": "en", "url": "https://stackoverflow.com/questions/24495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What Alternatives Are There to Model-View-Controller? While going through university and from following the development of SO, I've heard a lot about the Model-View-Controller architectural design pattern. I inadvertently used the MVC pattern even before I knew what it was, and still use it in my everyday job. From what I've seen, it's probably the most popular pattern used today. What I haven't heard much about though, are the alternative patterns you can use instead of MVC. What options are there, and for what reasons would you decide to use them over MVC? I'm also interested in knowing the types of systems they are typical of being used for. Finally, what are the pros and cons that come along with using them? A: Some other architectural patterns including MVC. Layered Systems TCP/IP Object-Oriented Organization Model-View-Controller, Presentation-abstraction-control, Model View Presenter and Model View ViewModel. Examples would be ASP.NET's MVC, Ruby on Rails, and bunch of others. Event Based, Implicit invocation Browser environment (DOM) Pipe and filter architecture Unix pipes Repositories Table Driven Interpreters You may also find this paper by Garlan & Shaw on Software Architecture a nice read. Another noteworthy link would be the article on architectural patterns at Wikipedia. A: I've occasionally seen MVC without the C, where the view listens for changes in the model's data and alters rendering accordingly, and where the methods in the model are bound to event handlers for the view. For projects where the view is by necessity tightly couple with the data (such as when there are visual components that directly relate to the model or attributes of the model), this can be rather useful, as it cuts out the "middle man." I think many would argue, though, that this is still MVC, just a hybridized version, and that the bindings established between the view and model are controller logic. A: Well, there's Model-View-Presenter, but I think you'll find that the most common "alternative" to MVC is really a lack of proper separation. As an extreme example, consider classic ASP pages where HTML, VBScript and SQL are found side-by-side in the same file. (That's not a bash of ASP — you'll find plenty of such examples in other languages.) A: Although the above answers are quite correct, I think it's much more important to note that the words "design pattern" are completely unknown to 90% of all people who create software. They just start writing code. The challenge is not selecting the best design approach, it's convincing others that design has value. A: * *Passive View - http://martinfowler.com/eaaDev/PassiveScreen.html *Supervising Controller - http://martinfowler.com/eaaDev/SupervisingPresenter.html *Model-View-Presenter - http://martinfowler.com/eaaDev/ModelViewPresenter.html My personal favorite is the Passive View. More testable than others I've seen including MVC. A: Well it is quite old now. I would like to mention one more (in the interest of info for additional knowledge) is PresenterFirst patrern Here is more information on the same: http://en.wikipedia.org/wiki/Presenter_First http://www.atomicobject.com/pages/Presenter+First HTH A: The Presentation-Abstraction-Control (PAC) family of patterns, where interface/interaction is handled by a hierarchy of agents. The wikipedia article is not great http://en.m.wikipedia.org/wiki/Presentation-abstraction-control A: In the Lift web framework we use a View First approach. Basically a view is composed of one or more snippets (somewhat similar to controllers) and snippets can be nested. This works very well with HTML and Scala's built-in XML processing capabilities. A: You can roll your own MVC with the current ASP.NET framework and still keep the postback model. http://www.codeproject.com/KB/aspnet/RollingYourOwnMVCwithASP.aspx A: What about the Observer pattern. If I am not mistaken , MVC was introduced in Smalltalk and thereafter several publish/ subscribe patterns have come into picture. The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. Ex : The Save button gets enabled in an editior, only when there is data to be saved. Another example of the observer pattern is Document View architecture in MFC, where in the view gets updated when the document changes .
{ "language": "en", "url": "https://stackoverflow.com/questions/24496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: What is the purpose of the AppManifest.xaml file in Silverlight applications? In opening up the .xap file that is generated as output from a Silverlight application I've been tinkering with lately, I noticed a file called AppManifest.xaml. I've also noticed an option in the property pages for the Silverlight project that appears to allow you to optionally not output AppManifest.xaml for the project. When unchecking that option, however, I get errors when running the application: Invalid or malformed application: Check manifest. What is the purpose of the AppManifest.xaml file? A: Maybe this blog post will help: http://blogs.msdn.com/katriend/archive/2008/03/16/silverlight-2-structure-of-the-new-xap-file-silverlight-packaged-application.aspx. It discusses the .xap file and its parts including the AppManifest. To save people a link click, in short, it defines the application for deployment, its entry point, and references all the assemblies needed to run.
{ "language": "en", "url": "https://stackoverflow.com/questions/24506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: "bad words" filter Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I found this one, and it's a start, but nothing more. Yes, I know that this kind of filters are easily escaped... but the client will is the client will !!! :-) The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce" :-) - an email will do. Thanks for any help. A: If anyone needs an API, google currently provide a bad word indicator. http://www.wdyl.com/profanity?q=naughtyword { response: "false" } Update: Google has now removed this service. A: Beware of clbuttic mistakes. "Apple made the clbuttic mistake of forcing out their visionary - I mean, look at what NeXT has been up to!" Hmm. "clbuttic". Google "clbuttic" - thousands of hits! There's someone who call his car 'clbuttic'. There are "Clbuttic Steam Engine" message boards. Webster's dictionary - no help. Hmm. What can this be? HINT: People who make buttumptions about their regex scripts, will be embarbutted when they repeat this mbuttive mistake. A: I would say to just remove posts as you become aware of them, and block users who are overly explicit with their postings. You can say very offensive things without using any swear words. If you block the word ass (aka donkey), then people will just type a$$ or /\55, or whatever else they need to type to get past the filter. A: +1 on the Clbuttic mistake, I think it is important for "bad word" filters to scan for both leading and trailing spaces (e.g., " ass ") as opposed for just the exact string so that we won't have words like clbuttic, clbuttes, buttert, buttess, etc. A: I didn't see any language specified but you can use this for PHP it will generate a RegEx for each instered work so that even intentional mis-spellings (i.e. @ss, i3itch ) will also be caught. <?php /** * @author [email protected] **/ if($_GET['act'] == 'do') { $pattern['a'] = '/[a]/'; $replace['a'] = '[a A @]'; $pattern['b'] = '/[b]/'; $replace['b'] = '[b B I3 l3 i3]'; $pattern['c'] = '/[c]/'; $replace['c'] = '(?:[c C (]|[k K])'; $pattern['d'] = '/[d]/'; $replace['d'] = '[d D]'; $pattern['e'] = '/[e]/'; $replace['e'] = '[e E 3]'; $pattern['f'] = '/[f]/'; $replace['f'] = '(?:[f F]|[ph pH Ph PH])'; $pattern['g'] = '/[g]/'; $replace['g'] = '[g G 6]'; $pattern['h'] = '/[h]/'; $replace['h'] = '[h H]'; $pattern['i'] = '/[i]/'; $replace['i'] = '[i I l ! 1]'; $pattern['j'] = '/[j]/'; $replace['j'] = '[j J]'; $pattern['k'] = '/[k]/'; $replace['k'] = '(?:[c C (]|[k K])'; $pattern['l'] = '/[l]/'; $replace['l'] = '[l L 1 ! i]'; $pattern['m'] = '/[m]/'; $replace['m'] = '[m M]'; $pattern['n'] = '/[n]/'; $replace['n'] = '[n N]'; $pattern['o'] = '/[o]/'; $replace['o'] = '[o O 0]'; $pattern['p'] = '/[p]/'; $replace['p'] = '[p P]'; $pattern['q'] = '/[q]/'; $replace['q'] = '[q Q 9]'; $pattern['r'] = '/[r]/'; $replace['r'] = '[r R]'; $pattern['s'] = '/[s]/'; $replace['s'] = '[s S $ 5]'; $pattern['t'] = '/[t]/'; $replace['t'] = '[t T 7]'; $pattern['u'] = '/[u]/'; $replace['u'] = '[u U v V]'; $pattern['v'] = '/[v]/'; $replace['v'] = '[v V u U]'; $pattern['w'] = '/[w]/'; $replace['w'] = '[w W vv VV]'; $pattern['x'] = '/[x]/'; $replace['x'] = '[x X]'; $pattern['y'] = '/[y]/'; $replace['y'] = '[y Y]'; $pattern['z'] = '/[z]/'; $replace['z'] = '[z Z 2]'; $word = str_split(strtolower($_POST['word'])); $i=0; while($i < count($word)) { if(!is_numeric($word[$i])) { if($word[$i] != ' ' || count($word[$i]) < '1') { $word[$i] = preg_replace($pattern[$word[$i]], $replace[$word[$i]], $word[$i]); } } $i++; } //$word = "/" . implode('', $word) . "/"; echo implode('', $word); } if($_GET['act'] == 'list') { $link = mysql_connect('localhost', 'username', 'password', '1'); mysql_select_db('peoples'); $sql = "SELECT word FROM filters"; $result = mysql_query($sql, $link); $i=0; while($i < mysql_num_rows($result)) { echo mysql_result($result, $i, 'word') . "<br />"; $i++; } echo '<hr>'; } ?> <html> <head> <title>RegEx Generator</title> </head> <body> <form action='badword.php?act=do' method='post'> Word: <input type='text' name='word' /><br /> <input type='submit' value='Generate' /> </form> <a href="badword.php?act=list">List Words</a> </body> </html> A: Shutterstock has a Github repo with a list of bad words used for filtering. You can check it out here: https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words A: Wikipedia ClueBot has a bad word filter, read its source. http://en.wikipedia.org/wiki/User:ClueBot/Source#Score_list A: You could always convince the client to have a session of users just constantly posting expletives and make an easy solution to add them to the system. It is a lot of work but it will probably be more representative of the community. A: In researching this topic I determined that what was needed was more than just a list that does arbitrary replacements. I have built a web service that allows you to identify the level of 'cleanliness' you desire. It also makes an effort to identify false positives - i.e. where a word may be bad in one context but not in others. Take a look at http://filterlanguage.com
{ "language": "en", "url": "https://stackoverflow.com/questions/24515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: Resolving reduce/reduce conflict in yacc/ocamlyacc I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using: %token <int> INT %token <string> ID %token MINUS %start expr %type <expr> expr %nonassoc INT ID %left MINUS %left APPLY %% expr: INT { ExprInt $1 } | ID { ExprId $1 } | expr MINUS expr { ExprSub($1, $3) } | MINUS expr { ExprNeg $2 } | expr expr %prec APPLY { ExprApply($1, $2) }; The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule? A: Unfortunately, the only answer I can come up with means increasing the complexity of the grammar. * *split expr into simple_expr and expr_with_prefix *allow only simple_expr or (expr_with_prefix) in an APPLY The first step turns your reduce/reduce conflict into a shift/reduce conflict, but the parentheses resolve that. You're going to have the same problem with 'a b c': is it a(b(c)) or (a(b))(c)? You'll need to also break off applied_expression and required (applied_expression) in the grammar. I think this will do it, but I'm not sure: expr := INT | parenthesized_expr | expr MINUS expr parenthesized_expr := ( expr ) | ( applied_expr ) | ( expr_with_prefix ) applied_expr := expr expr expr_with_prefix := MINUS expr A: Well, this simplest answer is to just ignore it and let the default reduce/reduce resolution handle it -- reduce the rule that appears first in the grammar. In this case, that means reducing expr MINUS expr in preference to MINUS expr, which is exactly what you want. After seeing a-b, you want to parse it as a binary minus, rather than a unary minus and then an apply.
{ "language": "en", "url": "https://stackoverflow.com/questions/24516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: What are your experiences running SVN on Windows? I'm curious to hear the experiences of those who are currently running their SVN server on Windows. Jeff Atwood has a post on how to setup SVN as a Windows service. It's a great first step, but it doesn't touch on other topics, such as: * *What to use for a web-based repository browser? WebSVN can work on Windows, but it ain't pretty. *How to manage the passwd file? *Is it possible to integrate with Active Directory without running Apache? *Strategies for backing up the repository. *Useful global ignore patterns for Visual Studio development (suggestions here, here, and here for example). Our company switched from SourceGear Vault to Subversion about one month ago. We've got the basics down pat, but would love to discover people's tips and tricks for running SVN in a MSFT world. A: VisualSVN is the way to go. The built-in Active Directory support is very easy to use. A: I have found that VisualSVN is about 50% slower than running SVN as a native service. I always assumed that was because of accessing via http:// with Apache, which seems like it would have to be slower than accessing via svn://, which is native TCP/IP. The Experiment In the last 30 minutes, here's what I did: * *Installed VisualSVN on port 8080, side-by-side with my existing SVN install *Imported three existing repos into VisualSVN *Kicked everyone else off the server *Did side-by-side comparisons of a full svn checkout Results Repo 1: 652 files, 273 directories, 60.1MB 23 seconds for VisualSVN over http:// 16 seconds for SVN over svn:// Repo 2: 4623 files, 964 directories, 127.9MB 2 minutes, 18 seconds for VisualSVN over http:// 1 minute, 30 seconds for SVN over svn:// This is on identical hardware, with the exact same repository. I like how easy VisualSVN is, but AD integration and GUI aren't worth a 50% performance hit. Anyone else seen this difference? Am I doing something wrong just following along with the default installation options? A: Use VisualSVN Server. It integrates with Windows authentication and it handles all the apache setup. It's as painless as SVN can be on Windows. A: I have a fairly indepth tutorials on my blog http://tv.inner-rhythm.co.uk/ on how to set SVN up with Apache and Trac which we use at my company which works for us. A: I use a combo of VisualSVN and Tortoise. It doesn't integrate well with visual studio but you can use other plugins/apps for that. A: Trac is certainly the best web based project management software I use, it integrates with subversion so you can see timelines of commits and diffs of each versions, it allows tickets and bug reports, and has a built in wiki. http://trac.edgewall.org/wiki/TracOnWindows A little knowledge of python and it is easy to get up and running (if your on windows though, use the tracd server: http://trac.edgewall.org/wiki/TracStandalone (this link will show you how to install it as a windows service). A: I recommend TortoiseSVN. It adds SVN capabilities into Windows Explorer. In addition TortoiseSVN check to see if the IDE you are using has support for SVN. A: Rich Strahl just posted a blog entry on Running VisualSVN Server for Subversion Source Control. Worth a read: http://west-wind.com/weblog/posts/480534.aspx A: For backing up, I wrote a combination of a batch file and a VBScript that runs once a week as a scheduled task. It: * *Scans through a particular folder on the file system recursively looking for SVN repositories (we have a multitude of small repositories, as we found that one uber-repository quickly became difficult to maintain and intolerably slow when used with TortoiseSVN); *Uses svnadmin hotcopy on each repository found to create a backup; *7zips all of the backups into a single archive; *Mounts a share on a SAN and copies the archive over; *Deletes all of the temp files; *Emails a "success" notification. A: VisualSVN Server + Trac + TortoiseSVN + Ankhsvn. Done. Smooth as silk. What Visual SourceSafe should have been. A: I think you are seeing the difference betweeen the svn protocol and hosting the svn protocol on another. Similar performance decreases when using svn+ssh compared to svn. The ease of setup, has made it a no brainer for my team, we just threw it on a vm and ran. A: Running SVN under apache really isn't that hard. And you can use mod_auth_sspi to integrate with active directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/24528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Create a database from another database? Is there an automatic way in SQL Server 2005 to create a database from several tables in another database? I need to work on a project and I only need a few tables to run it locally, and I don't want to make a backup of a 50 gig DB. UPDATE I tried the Tasks -> Export Data in Management studio, and while it created a new sub database with the tables I wanted, it did not copy over any table metadata, ie...no PK/FK constraints and no Identity data (Even with Preserve Identity checked). I obviously need these for it to work, so I'm open to other suggestions. I'll try that database publishing tool. I don't have Integration Services available, and the two SQL Servers cannot directly connect to each other, so those are out. Update of the Update The Database Publishing Tool worked, the SQL it generated was slightly buggy, so a little hand editing was needed (Tried to reference nonexistent triggers), but once I did that I was good to go. A: You can use the Database Publishing Wizard for this. It will let you select a set of tables with or without the data and export it into a .sql script file that you can then run against your other db to recreate the tables and/or the data. A: Create your new database first. Then right-click on it and go to the Tasks sub-menu in the context menu. You should have some kind of import/export functionality in there. I can't remember exactly since I'm not at work right now! :) From there, you will get to choose your origin and destination data sources and which tables you want to transfer. When you select your tables, click on the advanced (or options) button and select the check box called "preserve primary keys". Otherwise, new primary key values will be created for you. A: I know this method can hardly be called automatic but why don't you use a few simple SELECT INTO statements? Because I'd have to reconstruct the schema, constraints and indexes first. Thats the part I want to automate...Getting the data is the easy part. Thanks for your suggestions everyone, looks like this is easy. A: Integration Services can help accomplish this task. This tool provids advanced data transformation capabilities so you will be able to get exact subset of data that you need from large database. Assuming that such data is needed for testing/debugging you may consider applying Row Sampling to reduce amount of data exported. A: * *Create new database *Right click on it, *Tasks -> Import Data *Follow instructions
{ "language": "en", "url": "https://stackoverflow.com/questions/24541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Using bitwise operators for Booleans in C++ Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++? I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful. I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this? A: || and && are boolean operators and the built-in ones are guaranteed to return either true or false. Nothing else. |, & and ^ are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn't want. For instance: BOOL two = 2; BOOL one = 1; BOOL and = two & one; //and = 0 BOOL cand = two && one; //cand = 1 In C++, however, the bool type is guaranteed to be only either a true or a false (which convert implicitly to respectively 1 and 0), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say b = b && x and be done with it. A: Two main reasons. In short, consider carefully; there could be a good reason for it, but if there is be VERY explicit in your comments because it can be brittle and, as you say yourself, people aren't generally used to seeing code like this. Bitwise xor != Logical xor (except for 0 and 1) Firstly, if you are operating on values other than false and true (or 0 and 1, as integers), the ^ operator can introduce behavior not equivalent to a logical xor. For example: int one = 1; int two = 2; // bitwise xor if (one ^ two) { // executes because expression = 3 and any non-zero integer evaluates to true } // logical xor; more correctly would be coded as // if (bool(one) != bool(two)) // but spelled out to be explicit in the context of the problem if ((one && !two) || (!one && two)) { // does not execute b/c expression = ((true && false) || (false && true)) // which evaluates to false } Credit to user @Patrick for expressing this first. Order of operations Second, |, &, and ^, as bitwise operators, do not short-circuit. In addition, multiple bitwise operators chained together in a single statement -- even with explicit parentheses -- can be reordered by optimizing compilers, because all 3 operations are normally commutative. This is important if the order of the operations matters. In other words bool result = true; result = result && a() && b(); // will not call a() if result false, will not call b() if result or a() false will not always give the same result (or end state) as bool result = true; result &= (a() & b()); // a() and b() both will be called, but not necessarily in that order in an // optimizing compiler This is especially important because you may not control methods a() and b(), or somebody else may come along and change them later not understanding the dependency, and cause a nasty (and often release-build only) bug. A: Contrary to Patrick's answer, C++ has no ^^ operator for performing a short-circuiting exclusive or. If you think about it for a second, having a ^^ operator wouldn't make sense anyway: with exclusive or, the result always depends on both operands. However, Patrick's warning about non-bool "Boolean" types holds equally well when comparing 1 & 2 to 1 && 2. One classic example of this is the Windows GetMessage() function, which returns a tri-state BOOL: nonzero, 0, or -1. Using & instead of && and | instead of || is not an uncommon typo, so if you are deliberately doing it, it deserves a comment saying why. A: Patrick made good points, and I'm not going to repeat them. However might I suggest reducing 'if' statements to readable english wherever possible by using well-named boolean vars.For example, and this is using boolean operators but you could equally use bitwise and name the bools appropriately: bool onlyAIsTrue = (a && !b); // you could use bitwise XOR here bool onlyBIsTrue = (b && !a); // and not need this second line if (onlyAIsTrue || onlyBIsTrue) { .. stuff .. } You might think that using a boolean seems unnecessary, but it helps with two main things: * *Your code is easier to understand because the intermediate boolean for the 'if' condition makes the intention of the condition more explicit. *If you are using non-standard or unexpected code, such as bitwise operators on boolean values, people can much more easily see why you've done this. EDIT: You didnt explicitly say you wanted the conditionals for 'if' statements (although this seems most likely), that was my assumption. But my suggestion of an intermediate boolean value still stands. A: Using bitwise operations for bool helps save unnecessary branch prediction logic by the processor, resulting from a 'cmp' instruction brought in by logical operations. Replacing the logical with bitwise operations (where all operands are bool) generates more efficient code offering the same result. The efficiency ideally should outweigh all the short-circuit benefits that can be leveraged in the ordering using logical operations. This can make code a bit un-readable albeit the programmer should comment it with reasons why it was done so. A: The raised eyebrows should tell you enough to stop doing it. You don't write the code for the compiler, you write it for your fellow programmers first and then for the compiler. Even if the compilers work, surprising other people is not what you want - bitwise operators are for bit operations not for bools. I suppose you also eat apples with a fork? It works but it surprises people so it's better not to do it. A: I think a != b is what you want A: Disadvantages of the bitlevel operators. You ask: “Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++? ” Yes, the logical operators, that is the built-in high level boolean operators !, && and ||, offer the following advantages: * *Guaranteed conversion of arguments to bool, i.e. to 0 and 1 ordinal value. *Guaranteed short circuit evaluation where expression evaluation stops as soon as the final result is known. This can be interpreted as a tree-value logic, with True, False and Indeterminate. *Readable textual equivalents not, and and or, even if I don't use them myself. As reader Antimony notes in a comment also the bitlevel operators have alternative tokens, namely bitand, bitor, xor and compl, but in my opinion these are less readable than and, or and not. Simply put, each such advantage of the high level operators is a disadvantage of the bitlevel operators. In particular, since the bitwise operators lack argument conversion to 0/1 you get e.g. 1 & 2 → 0, while 1 && 2 → true. Also ^, bitwise exclusive or, can misbehave in this way. Regarded as boolean values 1 and 2 are the same, namely true, but regarded as bitpatterns they're different. How to express logical either/or in C++. You then provide a bit of background for the question, “I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression.” Well, the bitwise operators have higher precedence than the logical operators. This means in particular that in a mixed expression such as a && b ^ c you get the perhaps unexpected result a && (b ^ c). Instead write just (a && b) != c expressing more concisely what you mean. For the multiple argument either/or there is no C++ operator that does the job. For example, if you write a ^ b ^ c than that is not an expression that says “either a, b or c is true“. Instead it says, “An odd number of a, b and c are true“, which might be 1 of them or all 3… To express the general either/or when a, b and c are of type bool, just write (a + b + c) == 1 or, with non-bool arguments, convert them to bool: (!!a + !!b + !!c) == 1 Using &= to accumulate boolean results. You further elaborate, “I also need to accumulate Boolean values sometimes, and &= and |=? can be quite useful.” Well, this corresponds to checking whether respectively all or any condition is satisfied, and de Morgan’s law tells you how to go from one to the other. I.e. you only need one of them. You could in principle use *= as a &&=-operator (for as good old George Boole discovered, logical AND can very easily be expressed as multiplication), but I think that that would perplex and perhaps mislead maintainers of the code. Consider also: struct Bool { bool value; void operator&=( bool const v ) { value = value && v; } operator bool() const { return value; } }; #include <iostream> int main() { using namespace std; Bool a = {true}; a &= true || false; a &= 1234; cout << boolalpha << a << endl; bool b = {true}; b &= true || false; b &= 1234; cout << boolalpha << b << endl; } Output with Visual C++ 11.0 and g++ 4.7.1: true false The reason for the difference in results is that the bitlevel &= does not provide a conversion to bool of its right hand side argument. So, which of these results do you desire for your use of &=? If the former, true, then better define an operator (e.g. as above) or named function, or use an explicit conversion of the right hand side expression, or write the update in full. A: IIRC, many C++ compilers will warn when attempting to cast the result of a bitwise operation as a bool. You would have to use a type cast to make the compiler happy. Using a bitwise operation in an if expression would serve the same criticism, though perhaps not by the compiler. Any non-zero value is considered true, so something like "if (7 & 3)" will be true. This behavior may be acceptable in Perl, but C/C++ are very explicit languages. I think the Spock eyebrow is due diligence. :) I would append "== 0" or "!= 0" to make it perfectly clear what your objective was. But anyway, it sounds like a personal preference. I would run the code through lint or similar tool and see if it also thinks it's an unwise strategy. Personally, it reads like a coding mistake.
{ "language": "en", "url": "https://stackoverflow.com/questions/24542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "99" }
Q: Why can't I fetch wikipedia pages with LWP::Simple? I'm trying to fetch Wikipedia pages using LWP::Simple, but they're not coming back. This code: #!/usr/bin/perl use strict; use LWP::Simple; print get("http://en.wikipedia.org/wiki/Stack_overflow"); doesn't print anything. But if I use some other webpage, say http://www.google.com, it works fine. Is there some other name that I should be using to refer to Wikipedia pages? What could be going on here? A: I solved this problem using LWP:RobotUA instead of LWP::UserAgent. You can read the document below. There are not much differences you should modify. http://lwp.interglacial.com/ch12_02.htm A: Because Wikipedia is blocking the HTTP user-agent string used by LWP::Simple. You will get a "403 Forbidden"-response if you try using it. Try the LWP::UserAgent module to work around this, setting the agent-attribute. A: Also see the Mediawiki related CPAN modules - these are designed to hit Mediawiki sites (of which wikipedia is one) and might give you more bells and whistles than simple LWP. http://cpan.uwinnipeg.ca/search?query=Mediawiki&mode=dist A: Apparently Wikipedia blocks LWP::Simple requests: http://www.perlmonks.org/?node_id=695886 The following works instead: #!/usr/bin/perl use strict; use LWP::UserAgent; my $url = "http://en.wikipedia.org/wiki/Stack_overflow"; my $ua = LWP::UserAgent->new(); my $res = $ua->get($url); print $res->content; A: You can also just set the UA on the LWP::Simple module - just import the $ua variable, and it'll allow you to modify the underlying UserAgent: use LWP::Simple qw/get $ua/; $ua->agent("WikiBot/0.1"); print get("http://en.wikipedia.org/wiki/Stack_overflow");
{ "language": "en", "url": "https://stackoverflow.com/questions/24546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Initialize class fields in constructor or at declaration? I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields. Should I do it at declaration?: public class Dice { private int topFace = 1; private Random myRand = new Random(); public void Roll() { // ...... } } or in a constructor?: public class Dice { private int topFace; private Random myRand; public Dice() { topFace = 1; myRand = new Random(); } public void Roll() { // ..... } } I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach. A: Assuming the type in your example, definitely prefer to initialize fields in the constructor. The exceptional cases are: * *Fields in static classes/methods *Fields typed as static/final/et al I always think of the field listing at the top of a class as the table of contents (what is contained herein, not how it is used), and the constructor as the introduction. Methods of course are chapters. A: In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has in all cases, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same. A: There are many and various situations. I just need an empty list The situation is clear. I just need to prepare my list and prevent an exception from being thrown when someone adds an item to the list. public class CsvFile { private List<CsvRow> lines = new List<CsvRow>(); public CsvFile() { } } I know the values I exactly know what values I want to have by default or I need to use some other logic. public class AdminTeam { private List<string> usernames; public AdminTeam() { usernames = new List<string>() {"usernameA", "usernameB"}; } } or public class AdminTeam { private List<string> usernames; public AdminTeam() { usernames = GetDefaultUsers(2); } } Empty list with possible values Sometimes I expect an empty list by default with a possibility of adding values through another constructor. public class AdminTeam { private List<string> usernames = new List<string>(); public AdminTeam() { } public AdminTeam(List<string> admins) { admins.ForEach(x => usernames.Add(x)); } } A: What if I told you, it depends? I in general initialize everything and do it in a consistent way. Yes it's overly explicit but it's also a little easier to maintain. If we are worried about performance, well then I initialize only what has to be done and place it in the areas it gives the most bang for the buck. In a real time system, I question if I even need the variable or constant at all. And in C++ I often do next to no initialization in either place and move it into an Init() function. Why? Well, in C++ if you're initializing something that can throw an exception during object construction you open yourself to memory leaks. A: My rules: * *Don't initialize with the default values in declaration (null, false, 0, 0.0…). *Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field. *If the value of the field changes because of a constructor parameter put the initialization in the constructors. *Be consistent in your practice (the most important rule). A: The design of C# suggests that inline initialization is preferred, or it wouldn't be in the language. Any time you can avoid a cross-reference between different places in the code, you're generally better off. There is also the matter of consistency with static field initialization, which needs to be inline for best performance. The Framework Design Guidelines for Constructor Design say this: ✓ CONSIDER initializing static fields inline rather than explicitly using static constructors, because the runtime is able to optimize the performance of types that don’t have an explicitly defined static constructor. "Consider" in this context means to do so unless there's a good reason not to. In the case of static initializer fields, a good reason would be if initialization is too complex to be coded inline. A: Being consistent is important, but this is the question to ask yourself: "Do I have a constructor for anything else?" Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables. In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration. So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to. A: Consider the situation where you have more than one constructor. Will the initialization be different for the different constructors? If they will be the same, then why repeat for each constructor? This is in line with kokos statement, but may not be related to parameters. Let's say, for example, you want to keep a flag which shows how the object was created. Then that flag would be initialized differently for different constructors regardless of the constructor parameters. On the other hand, if you repeat the same initialization for each constructor you leave the possibility that you (unintentionally) change the initialization parameter in some of the constructors but not in others. So, the basic concept here is that common code should have a common location and not be potentially repeated in different locations. So I would say always put it in the declaration until you have a specific situation where that no longer works for you. A: I think there is one caveat. I once committed such an error: Inside of a derived class, I tried to "initialize at declaration" the fields inherited from an abstract base class. The result was that there existed two sets of fields, one is "base" and another is the newly declared ones, and it cost me quite some time to debug. The lesson: to initialize inherited fields, you'd do it inside of the constructor. A: The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match. If you can, make the fields final. A: In C# it doesn't matter. The two code samples you give are utterly equivalent. In the first example the C# compiler (or is it the CLR?) will construct an empty constructor and initialise the variables as if they were in the constructor (there's a slight nuance to this that Jon Skeet explains in the comments below). If there is already a constructor then any initialisation "above" will be moved into the top of it. In terms of best practice the former is less error prone than the latter as someone could easily add another constructor and forget to chain it. A: There is a slight performance benefit to setting the value in the declaration. If you set it in the constructor it is actually being set twice (first to the default value, then reset in the ctor). A: When you don't need some logic or error handling: * *Initialize class fields at declaration When you need some logic or error handling: * *Initialize class fields in constructor This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. From https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html . A: I normally try the constructor to do nothing but getting the dependencies and initializing the related instance members with them. This will make you life easier if you want to unit test your classes. If the value you are going to assign to an instance variable does not get influenced by any of the parameters you are going to pass to you constructor then assign it at declaration time. A: Not a direct answer to your question about the best practice but an important and related refresher point is that in the case of a generic class definition, either leave it on compiler to initialize with default values or we have to use a special method to initialize fields to their default values (if that is absolute necessary for code readability). class MyGeneric<T> { T data; //T data = ""; // <-- ERROR //T data = 0; // <-- ERROR //T data = null; // <-- ERROR public MyGeneric() { // All of the above errors would be errors here in constructor as well } } And the special method to initialize a generic field to its default value is the following: class MyGeneric<T> { T data = default(T); public MyGeneric() { // The same method can be used here in constructor } } A: "Prefer initialization in declaration", seems like a good general practice. Here is an example which cannot be initialized in the declaration so it has to be done in the constructor. "Error CS0236 A field initializer cannot reference the non-static field, method, or property" class UserViewModel { // Cannot be set here public ICommand UpdateCommad { get; private set; } public UserViewModel() { UpdateCommad = new GenericCommand(Update_Method); // <== THIS WORKS } void Update_Method(object? parameter) { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/24551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "461" }
Q: Attaching entities to data contexts In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it? A little context if it helps... I have this code in my global.asax as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the Member object in the same unit of work where it was created. private void CheckCurrentUser() { if (!HttpContext.Current.User.Identity.IsAuthenticated) { AppHelper.CurrentMember = null; return; } IUserService userService = new UserService(); if (AppHelper.CurrentMember != null) userService.AttachExisting(AppHelper.CurrentMember); else AppHelper.CurrentMember = userService.GetMember( HttpContext.Current.User.Identity.Name, AppHelper.CurrentLocation); } A: I believe there are two methods to do this. DataContext.TableName.Contains(Item) or we use the id field. If the item is inserted in the Database, then it will be assigned a row. if(Item.id == 0) DataContext.Insert(Item) else DataContext.Update(Item) A: Rather than attaching to a new data context why not just requery the object in the new datacontext? It believe it is a more reliable and stateless strategy.
{ "language": "en", "url": "https://stackoverflow.com/questions/24556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WYSIWYG editor gem for Rails? Is there a good ruby gem for a WYSIWYG editor that will easily work with a rails app? A: While I know this has been answered I wanted to add regarding the use of textile... I completely agree, but I'd recommend processing it in a before_save filter. Let's say you have a database field called "details" - just add one called "details_html". Then do something like this... before_save :convert_details def convert_details return if self.details.nil? self.details_html = RedCloth.new(self.details).to_html end RedCloth can get a little process heavy and if you are constantly processing the stuff on each render you're going to run into some memory issues... this will just help lower some of your needed resources. A: Update for 2010. I just implemented TinyMCE in a Rails app using the tinyMCE gem. You can find it here: http://github.com/kete/tiny_mce It took less than 5 minutes and in my basic testing, it's working perfectly. There was a commit in June 2010, so it looks like this is an actively developed gem. Hope that helps some googlers. A: I'm not sure about a Ruby Gem, but TinyMCE is a customizable, generally stable WYSIWYG editor that is fairly simple to integrate w/ any project. I've used it a number of times. A: A similar question: What is the best WYSIWYG for Rails - Ruby on Rails Blog I just pasted my same solution here too. I strongly suggest you give WYSIHAT a try. The biggest problem with the editors mentioned above is its bulky size and "hard-to-customize"(ability). The bad code in most of these editors is a big turn-off. WYSIHAT is more like a framework for a WYSIWYG editor. Extremely easy to customize. Easy to configure. And what more.. Its backed by 37signals. What i would appreiciate about TinyMCE is its paste from word feature which preserves the layout. But if not for that one feature i find the rest really bulky. Please do read this article: http://37signals.com/svn/posts/1330-introducing-wysihat-an-eventually-better-open-source-wysiwyg-editor Tutorial on using WYSIHAT: Part 1: http://jrmehle.com/2009/01/25/wysiwhat-wysihat-part-1/ Part 2: http://jrmehle.com/2009/02/13/wysiwhat-wysihat-part-2/ And to make your life even easier theres an awesome rails-engine developed by Jeff Kreeftmeijer (80beans.com) for the 37signals WYSIHAT editor: http://github.com/80beans/wysihat-engine And heres an article by Jeff Kreeftmeijer: http://www.80beans.com/2009/10/01/wysihat-engine/ A: I use FCKEditorOnRails plugin: http://github.com/UnderpantsGnome/fckeditor_on_rails/tree/master Note that you can generally drop in the latest version of FCKEditor without much tweaking if you're running into bugs in the older version. A: Have a look at http://livepipe.net/control/textarea for a WYSIWYG markdown editor with the AJAXY preview mentioned in the chosen answer. A: Though it's certainly not a direct answer, in the past I've found I prefer to use RedCloth (or a Markdown parser if you don't enjoy Textile) and use a simple textarea with an AJAXy preview. Generally speaking, WYSIWYG editors have a long history of creating redundant tags and similar, leading to potentially broken pieces of HTML. A: There is a plugin to use TinyMCE with rails, lots of information on the rails wiki. A: +1 for FCKEditor - there is a great Rails plugin that includes helpers. However it is often overkill as it features everything. In many cases something a little simpler such as jQuery's WYSIWYG editor is great for wrapping a text area input. A: I'm really loving CKeditor gem. It's much, much more elegant than TinyMCE, especially if you deal with raw HTML. CKeditor displays on page--TinyMCE gives a popup. CKeditor allows access to things like all headings right out of the box, too. TinyMCE requires hacking. RedCloth's inability to support ALL HTML was a dealbreaker for me. (Among other things, you can't support giving an image a description OR a caption!!!!) I didn't mind the markup so much as the complete lack of flexibility. Plus, it was like learning a new language--a lot of the markup was the opposite of intuitive (like image alignment), and I couldn't possibly imagine asking contributors to learn all that. For comments, I will use something much lighter weight, though. A: I had bad experiences with CKEditor (gem "ckeditor") .. I managed to get it to work on local maschine but had a lot problems when trying to deploy it to Heroku .. It seems like code is too heavy to automatically precompile the code on Heroku ... That means it is quite useless ... EDIT: Solution: make sure that you precompile javascript before deploying it on Heroku. A: I would use Tiny MCE it is a Java Script solution I have integrated with Web Applications to edit HTML. http://www.tinymce.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/24579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How do you automate a Visual Studio build? How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line? A: Simplest way: navigate to the directory containing the solution or project file, and run msbuild (assuming you have Visual Studio 2005 or newer). More flexible ways: * *Read up on the MSBuild reference. There are tons of customization, especially once you've installed the MSBuild Community Tasks Project. *Use NAnt. It has existed for longer than MSBuild and has more community support, but requires you to start a project file from scratch, rather than extending the existing, Visual Studio-created one. A: NAnt and MSBuild are the most popular tools to automate your build in .NET, and you can find a discussion on there of the pros/cons of each in the Stack Overflow question Best .NET build tool. A: Here is the script I'm using to completely automate the command line build of x86 AND x64 configurations for the same solution through batch scripts. This is based on DevEnv.exe as it works if you have a Setup project in your build (msbuild doesn't support building Setup projects). I'm assuming your setup is 32bit Windows 7 with Visual Studio 2010 setup using the x86 native compiler and x64 cross compiler. If you're running 64bit windows you may need to change x86_amd64 to amd64 in the batch script depending on your setup. This is assuming Visual Studio is installed in Program Files and your solution is located in D:\MySoln Create a file called buildall.bat and add this to it: D: cd "D:\MySoln" if "%1" == "" goto all if %1 == x86 goto x86 if %1 == x64 goto x64 :x86 %comspec% /k ""C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" x86 < crosscompilex86.bat goto eof :x64 %comspec% /k ""C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" x86_amd64 < crosscompilex64.bat goto eof :all %comspec% /k ""C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" x86 < crosscompilex86.bat if %ERRORLEVEL% NEQ 0 goto eof %comspec% /k ""C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" x86_amd64 < crosscompilex64.bat goto eof :eof pause Now create 2 more batch scripts: crosscompilex86.bat to build the Release version of a x86 build and include this devenv MySoln.sln /clean "Release|x86" IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL% devenv MySoln.sln /rebuild "Release|x86" IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL% crosscompilex64.bat to build the Release version of the x64 build and include this devenv MySoln.sln /clean "Release|x64" IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL% devenv MySoln.sln /rebuild "Release|x64" IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL% Now place all 3 batch files along in your solution folder along with MySoln.sln. You can build both x86 and x64 Release versions by creating a Shortcut on your desktop which run the following commands: * *Build All -> D:\MySoln\buildall.bat *Build x86 Release Only -> D:\MySoln\buildall.bat x86 *Build x64 Release Only -> D:\MySoln\buildall.bat x64 If you're using another configuration like AnyCPU etc you would need to customize the above scripts accordingly. A: With VS2008 you can do this: devenv solution.sln /build configuration A: \Windows\Microsoft.NET\Framework\[YOUR .NET VERSION]\msbuild.exe Lots of command line parameters, but the simplest is just: msbuild.exe yoursln.sln A: Look into build tool NAnt or MSBuild. I believe MSBuild is the build tool for Visual Studio 2005 and later. I am, however, a fan of NAnt... A: As of Visual Studio 2005, all of the project files (at least for .NET based projects) are actual MSBuild files, so you can call MSBuild on the command line and pass it the project file. The bottom line is that you need to use a "build scripting language" like NAnt or MSBuild (there are others, but these are the mainstream ones right now) if you want to have any real control over your build process. A: Take a look at UppercuT. It has a lot of bang for your buck and it does what you are looking for and much more. UppercuT uses NAnt to build and it is the insanely easy to use Build Framework. Automated Builds as easy as (1) solution name, (2) source control path, (3) company name for most projects! http://projectuppercut.org/ Some good explanations here: UppercuT A: Here is my batch file using msbuild for VS 2010 Debug configuration: "C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" iTegra.Web.sln /p:Configuration=Debug /clp:Summary /nologo A: I had to do this for a C++ project in Visual Studio 2003 so I don't know how relevant this is to later version of visual studio: In the directory where your executable is created there will be a BuildLog.htm file. Open that file in your browser and then for each section such as: Creating temporary file "c:\some\path\RSP00003C.rsp" with contents [ /D "WIN32" /D "_WINDOWS" /D "STRICT" /D "NDEBUG" ..... (lots of other switches) .\Project.cpp .\Another.cpp .\AndAnother.cpp ".\And Yet Another.cpp" ] Creating command line "cl.exe @c:\some\path\RSP00003C.rsp /nologo" create a .rsp file with the content between the square brackets (but not including the square brackets) and call it whatever you like. I seem to remember having problems with absolute paths so you may have to make sure all the paths are relative. Then in your build script add the command line from the BuildLog.htm file but with your .rsp filename: cl.exe @autobuild01.rsp /nologo (note there will also be a link.exe section as well as cl.exe) A: A more simple way is to change VS 2015 Projects & Solutions configuration: Go to the Tools tab -> Options -> Projects and Solutions -> Build and Run -> On Run, when projects are out of date (choose Always build). VOILA! Now your IDE will automatically build your project when you run (F5) it. Hope this helps, any feedback are welcome.
{ "language": "en", "url": "https://stackoverflow.com/questions/24580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: Code Classic ASP in Linux What should i use to code Classic ASP under Linux. I have really tried to use Emacs and Vim but I don't have the time to learn them. What i'm looking for is: * *Syntax highlighting *Code Browser (Ctags) *Preferably som sort of code insight Something like Ultra Edit or E-texteditor. A: I'm not sure what you're asking here, but if you are simply looking for a text-editor, my recommendations would be: Console-based: * *jed (simple, with a DOS Edit-like menubar, supports syntax-highlighing) *nano / pico (even simpler) X-based: * *Kate (KDE, syntax-highlighing) *Mousepad (like notepad) *SciTE (syntax-highlighing) There are of course likely to be a gazillion other text-editors better than the ones listed above, but these are the ones I tend to use. A: I played with BlueFish for a while when I was contemplating switching over completely and I liked it better than Kate. But, you will have to add the code to enable ASP highlighting. Its floating around numerous places - I found it in short order with a quick trip to the trusty ole Google. ;) But that is just my personal preference. Your mileage may vary.
{ "language": "en", "url": "https://stackoverflow.com/questions/24595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are the pros and cons of the assorted Java web frameworks? I am considering creating my own website using Java and am trying to decide what framework to use. However, doing a quick search for Java frameworks returns more than 50 to choose from! My website is just going to be for my own enjoyment of building it in the beginning, but if it becomes popular, it would be good for it to have some scalability, or to at least be able to redesign for that. What are the main differences between the more popular frameworks? Are there instances where one significantly outperforms the others? For example, high-traffic enterprise applications versus low-traffic small applications. I'm also wondering if some are much easier to learn and use than others. Is there anyone who has experience with some of these frameworks and can make a recommendation? Does the sheer number of choices just serve as an early warning to avoid Java-based web development where possible? A: Disclamer: I work at Vaadin (previously IT Mill) If you are doing something RIAish, you might want to take look at Vaadin. It's an open source UI-oriented AJAX framework that, to me, is nice to use (I come from a PHP background myself). There's a case study that compares doing the same application (i.e. two applications with the same set of features) in Icefaces and Vaadin. In a nutshell, it states that the UI development was considerably faster. Even though the study is hosted at the company's wiki, I can assure that it's objective, genuine and truthful, although I can't force you in believing me. A: After a long while of testing various solutions, for me it turned out to be: * *Spring MVC for the presentation and controller layer (NO Spring Webflow though, because my flows are based on ajax) *jQuery for all the client side stuff *Spring Security for the, well, security aspect *Hibernate / JPA2 *Jetty for the sake of continuations (comet) One month of an extraordinarily steep learning curve, but now I am happy. I would also like to mention that I was just a little step away from skipping all that Java stuff and learing Scala/LIFT instead. As far as I am concerned, everything in Java that is related with cutting edge web development (comet, async communication, security (yes, even with Spring Security!)) still is a bit of a hack (proove me wrong by evidence, pleeease!). To me, Scala/LIFT seems to be a more out-of-the-box and all-in-one solution. The reason why I finally decided not to go with Scala is * *as a project leader I must consider human resources and Java developers are much easier to find than Scala developers *for most developers in my team, Scala's funcional concept, as excellent as it is, is hard to understand Cheers Er A: I've used Tapestry 3, Wicket, Echo, and JSF fairly extensively. I'd really recommend you look those over and pick the one that appears the easiest for you, and to most closely fit the way you prefer to work. Of them, the most comfortable for me to work with was Wicket, due to the lightweight nature of component building and simplicity of page templating. That goes doubly so if you are using your own db code instead of Hibernate or some other framework (I was never completely happy with Wicket Hibernate or Spring Integration). Echo is great if you don't mind writing all of your layout in Java. I know that is different now, but I still think that product serves a fairly narrow niche. They change the development model with every major release as well it seems. Tapestry is a great product, but it is obviously very different from the others in terms of development model as it is led mainly by one dude. Howard Lewis Ship is no doubt quite smart, but I am disappointed with their decision to basically forget backwards compatibility with each release. Again, though, for your needs this may not matter, and I've always found the Tapestry products pleasurable to work against. JSF has been out for years, and still feels like something that a Struts guy built to fix all of the problems of Struts. Without really understanding all of the problems with Struts. It still has an unfinished feel to it, although the product is obviously very flexible. I use it and have some fondness for it, with great hopes for its future. I think the next release (2.0) to be delivered in JEE6 will really bring it into its own, with a new template syntax (similar to Facelets) and a simplified component model (custom components in only 1 file... finally). And, of course, there are a million smaller frameworks and tools that get their own following (Velocity for basic needs, raw JSPs, Struts, etc). I generally prefer component oriented frameworks myself, though. In the end, I'd recommend just taking a look at Tapestry, Wicket, and JSF and just picking the one that feels the best to you. You'll probably find one that just fits the way you like to work very quickly. A: I've heard good things about the Spring Framework too. In general, though, I've been underwhelmed by most Java web frameworks I've looked at (esp Struts). For a simple app I'd definitely consider using "raw" servlets and JSPs and not worry about adopting a framework. If the servlets are well written, it should be straightforward in the future to port to a framework if necessary when the app grows in complexity. A: My pick is Wicket!! A: All of them - that's the problem ;-) A: My favorite is the Spring Framework. With 2.5 Spring MVC is soooo kick ass, with new annotations, convention over configuration features, etc. If you're just doing something super simple you could also just try using the regular Servlet API and not bother with a framework. A: I think for your modest requirements, you just need to code up servlets or simple jsp pages that you can serve from Tomcat server. I dont think you need any kind of web-framework (like struts) for personal web-site data A: Saying "use JSF" is a little to simple. When you decide to use JSF, you have to choose a component library on top of it. Will you use MyFaces Tomahawk, Trinidad, Tobago (http://myfaces.apache.org/)? Or maybe ICEfaces (http://www.icefaces.org/)? Oh, and if you use ICEfaces, will you use JSPs or Facelets for your views? In my opinion it is to hard to tell. Nobody has the time to evaluate all the promising alternatives, at least in the projects I work on, because they are not big enough to do three month evaluation phases. However, you should look around for some that has a big and active community and isn't gone in a year. JSF is around for some time, and since it gets pushed by sun, it will be around for some more. I can't say if it's the best choice, but it will be a good one. A: http://zkoss.org - the good one A: For high traffic sites I'd use a framework that doesn't manage client state on the server - Wicket, JSF and Tapestry are managing client state on the server. I'd only use those frameworks (Wicket is my favourite) if the application should be more like a desktop application. But I'd try to use a more scalable and simple REST+AJAX approach though. Spring MVC would be a candidate, but since Spring MVC 3 it has a strange annotation overloaded programming model which doesn't use the benefits of static typing. There ore other ugly things like output parameters in methods combined with a usual return, so there are two output channels of one method. Spring MVC also tends to reeinvent the wheel and you'll have more to configure compared to other frameworks. I cannot really recommend Spring MVC though it has some nice ideas. Grails is a convenient way to use Spring MVC and other established frameworks like Hibernate. Coding is fun and you'll quickly see results. And don't forget that the Servlet API with a few little helpers like FreeMarker for templating is very powerful. A: I have evaluated quite a few frameworks and Vaadin (http://vaadin.com/home) has percolated all the way to the top. You should at least give it a short evaluation. Cheers! A: I recommend the component oriented Wicket framework. It allows you to write your web application in plain old Java code, you can use POJOs as the model for all components and don't need to mess around with huge XML configuration files. I had successfully developed an online banking application with Struts when I discovered Wicket and saw how easy web application development can be! A: My pick would be Wicket (for large projects and a predictable user base), GWT (for large projects that are mostly public facing) or just a service framework (like Jersey/ JAXRS) together with a JavaScript toolkit (for small to medium projects). A: I recommend Seam, especially if you need persistence. A: I've recently started using the Stripes Framework. If you're looking for a request based framework that's really easy to use, but doesn't impose any limits on what you are doing I'd highly recommend it. It's similar to struts, but it goes way beyond it. There are even some plugin projects that enable you to do use hibernate or jpa with very little configuration. There are a lot of good frameworks out there though I've heard wicket is a good one as well, but I haven't used it. A: Haven't tried it myself, but I think http://www.playframework.org/ has a lot of potential... coming from php and classic asp, it's the first java web framework that sound promising to me.... A: UPDATE: Tapestry 5.2 is out, so it's not abandoned, as it previously appeared to be. My experience is with Tapestry 4, not 5, so your mileage may vary. My opinion of Tapestry has changed over the years; I have modified this post to reflect it. I can no longer recommend Tapestry as I did previously. Tapestry 5 appears to be a significant improvement, but my main issue with Tapestry is not with platform itself; it's with the people behind it. Historically, every major version update of Tapestry has broken backwards compatibility with extreme prejudice, far more than one might expect. This seems to be due to the incorporation of new coding techniques or technologies that require significant rewrites. Howard Lewis Ship (the principal author of Tapestry) is certainly a brilliant developer, but I can't say I care for his management of the Tapestry project. Development of Tapestry 5 began almost immediately after Tapestry 4 shipped. From what I can tell, Ship pretty much devoted himself to that, leaving Tapestry 4 in the hands of other contributors, who I feel are not nearly as capable as Ship. After having made the painful switch from Tapestry 3 to Tapestry 4, I felt that I had been abandoned almost immediately. Of course, with the release of Tapestry 5, Tapestry 4 became a legacy product. I wouldn't have a problem with this if the upgrade path wasn't so brutal again. So now our development team is in the rather unenviable position: We could continue to use an essentially abandoned web platform (Tapestry 4), make the heinous upgrade to Tapestry 5, or give up on Tapestry entirely and rewrite our application using another platform. None of these options is very attractive. Tapestry 5 is supposedly written so as to reduce the likelihood of update breakage from this point forward. A good example is in the page classes: in previous incarnations, page classes descended from a base class provided by Tapestry; incompatible API changes in this class were the cause of a large number of backward compatibility problems. In Tapestry 5, pages are POJOs which are enhanced at runtime with the "magic Tapestry fairy dust" via annotations. So as long as the contract for the annotations is maintained, changes to Tapestry won't affect your page classes. If this is right, then writing a new application using Tapestry 5 could turn out well. But personally, I don't feel like putting my hand on the burner again. A: See a few comments on some Java application Frameworks (second paragraph): http://swiss-knife.blogspot.com/2009/11/some-java-application-servers.html A: For quick and fancy GUI you can use JSF with Richfaces library. Richfaces UI components are easy to use and handy references available with code demonstration in the demo site. Probably later when your site has more data to handle and lot of information has to be transacted in database you can plug any database access framework (ORM) with it. A: Can't believe no one has mentioned GWT A: My favorite way to go for really simple apps is Apache VelocityTools (VelocityLayoutServlet) with Velosurf (http://velosurf.sourceforge.net). For more complex apps, Spring MVC or Struts 2. A: Try HybridJava - that is much simpler than anything else. A: I would say vaadin or wicket
{ "language": "en", "url": "https://stackoverflow.com/questions/24596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "85" }
Q: Stylus/tablet input device I need to make a WebCast presentation soon and need to do some "whiteboarding" during that WebCast. Does anyone have any stylus/tablet input device recommendations? Anyone ever used such an input device with WebEx's whiteboard feature? rp A: Wacom http://www.wacom.com/index2.cfm makes by far the best tablets I have ever used. They come in a variety of prices with associated features. If you want to be able to draw 'on-screen' they have the Cintiq, which is the most expensive, starting at $999 but definitely worth it. For a cheaper more 'traditional' tablet there is Bambo and Intuos which start at $79, however with the Bambo and the Intuos there is quite a learning curve if your not already used to using tablets. A: A lot of people recommend Wacom. I've tried one, and it is really nice to use. To some extent, it really depends if you want only a tablet (no video feedback on the device), or a 'screen' (having video feedback, which I find nice but is also a bit pricey...).
{ "language": "en", "url": "https://stackoverflow.com/questions/24599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Vi editing for Visual Studio I'm used to the Vi(m) editor and am using MS Visual Studio 2005 at work. I couldn't find a free Vi add-in (there's only one for the 2003 version). I googled a bit, saw that there was a 'Google summer of code' project this year to write such an add-in, and am eagerly awaiting the result. I've also heard of ViEmu (not free, and I can't test it at work). Has anyone in my situation has found a solution (and/or tested ViEmu)? Edit: I can't test ViEmu at work because they are paranoid about what we install on our boxes: it has to go through required channels, and for 30 days I don't reckon it's worth it (and I have no Windows box at home). Edit: Since both answers were equivalent, I ended up accepting the first one that came in. A: ViEmu works great with Visual Studio. I used Vi(m) strictly in Linux, but I was turned on to bringing the Vi(m) editing process into the Windows world by JP Boodhoo. JP praises about it also. A: ViEmu works great. I've been using it for about a year now and couldn't imagine coding in Visual Studio without it. Why can't you test it at work? It has a 30 day free trial.
{ "language": "en", "url": "https://stackoverflow.com/questions/24610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Why should you prevent a class from being subclassed? What can be reasons to prevent a class from being inherited? (e.g. using sealed on a c# class) Right now I can't think of any. A: How about if you are not sure about the interface yet and don't want any other code depending on the present interface? [That's off the top of my head, but I'd be interested in other reasons as well!] Edit: A bit of googling gave the following: http://codebetter.com/blogs/patricksmacchia/archive/2008/01/05/rambling-on-the-sealed-keyword.aspx Quoting: There are three reasons why a sealed class is better than an unsealed class: * *Versioning: When a class is originally sealed, it can change to unsealed in the future without breaking compatibility. (…) *Performance: (…) if the JIT compiler sees a call to a virtual method using a sealed types, the JIT compiler can produce more efficient code by calling the method non-virtually.(…) *Security and Predictability: A class must protect its own state and not allow itself to ever become corrupted. When a class is unsealed, a derived class can access and manipulate the base class’s state if any data fields or methods that internally manipulate fields are accessible and not private.(…) A: I want to give you this message from "Code Complete": Inheritance - subclasses - tends to work against the primary technical imperative you have as a programmer, which is to manage complexity.For the sake of controlling complexity, you should maintain a heavy bias against inheritance. A: Because writing classes to be substitutably extended is damn hard and requires you to make accurate predictions of how future users will want to extend what you've written. Sealing your class forces them to use composition, which is much more robust. A: The only legitimate use of inheritance is to define a particular case of a base class like, for example, when inherit from Shape to derive Circle. To check this look at the relation in opposite direction: is a Shape a generalization of Circle? If the answer is yes then it is ok to use inheritance. So if you have a class for which there can not be any particular cases that specialize its behavior it should be sealed. Also due to LSP (Liskov Substitution Principle) one can use derived class where base class is expected and this is actually imposes the greatest impact from use of inheritance: code using base class may be given an inherited class and it still has to work as expected. In order to protect external code when there is no obvious need for subclasses you seal the class and its clients can rely that its behavior will not be changed. Otherwise external code needs to be explicitly designed to expect possible changes in behavior in subclasses. A more concrete example would be Singleton pattern. You need to seal singleton to ensure one can not break the "singletonness". A: This may not apply to your code, but a lot of classes within the .NET framework are sealed purposely so that no one tries to create a sub-class. There are certain situations where the internals are complex and require certain things to be controlled very specifically so the designer decided no one should inherit the class so that no one accidentally breaks functionality by using something in the wrong way. A: @jjnguy Another user may want to re-use your code by sub-classing your class. I don't see a reason to stop this. If they want to use the functionality of my class they can achieve that with containment, and they will have much less brittle code as a result. Composition seems to be often overlooked; all too often people want to jump on the inheritance bandwagon. They should not! Substitutability is difficult. Default to composition; you'll thank me in the long run. A: I am in agreement with jjnguy... I think the reasons to seal a class are few and far between. Quite the contrary, I have been in the situation more than once where I want to extend a class, but couldn't because it was sealed. As a perfect example, I was recently creating a small package (Java, not C#, but same principles) to wrap functionality around the memcached tool. I wanted an interface so in tests I could mock away the memcached client API I was using, and also so we could switch clients if the need arose (there are 2 clients listed on the memcached homepage). Additionally, I wanted to have the opportunity to replace the functionality altogether if the need or desire arose (such as if the memcached servers are down for some reason, we could potentially hot swap with a local cache implementation instead). I exposed a minimal interface to interact with the client API, and it would have been awesome to extend the client API class and then just add an implements clause with my new interface. The methods that I had in the interface that matched the actual interface would then need no further details and so I wouldn't have to explicitly implement them. However, the class was sealed, so I had to instead proxy calls to an internal reference to this class. The result: more work and a lot more code for no real good reason. That said, I think there are potential times when you might want to make a class sealed... and the best thing I can think of is an API that you will invoke directly, but allow clients to implement. For example, a game where you can program against the game... if your classes were not sealed, then the players who are adding features could potentially exploit the API to their advantage. This is a very narrow case though, and I think any time you have full control over the codebase, there really is little if any reason to make a class sealed. This is one reason I really like the Ruby programming language... even the core classes are open, not just to extend but to ADD AND CHANGE functionality dynamically, TO THE CLASS ITSELF! It's called monkeypatching and can be a nightmare if abused, but it's damn fun to play with! A: From an object-oriented perspective, sealing a class clearly documents the author's intent without the need for comments. When I seal a class I am trying to say that this class was designed to encapsulate some specific piece of knowledge or some specific service. It was not meant to be enhanced or subclassed further. This goes well with the Template Method design pattern. I have an interface that says "I perform this service." I then have a class that implements that interface. But, what if performing that service relies on context that the base class doesn't know about (and shouldn't know about)? What happens is that the base class provides virtual methods, which are either protected or private, and these virtual methods are the hooks for subclasses to provide the piece of information or action that the base class does not know and cannot know. Meanwhile, the base class can contain code that is common for all the child classes. These subclasses would be sealed because they are meant to accomplish that one and only one concrete implementation of the service. Can you make the argument that these subclasses should be further subclassed to enhance them? I would say no because if that subclass couldn't get the job done in the first place then it should never have derived from the base class. If you don't like it then you have the original interface, go write your own implementation class. Sealing these subclasses also discourages deep levels of inheritence, which works well for GUI frameworks but works poorly for business logic layers. A: Because you always want to be handed a reference to the class and not to a derived one for various reasons: i. invariants that you have in some other part of your code ii. security etc Also, because it's a safe bet with regards to backward compatibility - you'll never be able to close that class for inheritance if it's release unsealed. Or maybe you didn't have enough time to test the interface that the class exposes to be sure that you can allow others to inherit from it. Or maybe there's no point (that you see now) in having a subclass. Or you don't want bug reports when people try to subclass and don't manage to get all the nitty-gritty details - cut support costs. A: Sometimes your class interface just isn't meant to be inheirited. The public interface just isn't virtual and while someone could override the functionality that's in place it would just be wrong. Yes in general they shouldn't override the public interface, but you can insure that they don't by making the class non-inheritable. The example I can think of right now are customized contained classes with deep clones in .Net. If you inherit from them you lose the deep clone ability.[I'm kind of fuzzy on this example, it's been a while since I worked with IClonable] If you have a true singelton class, you probably don't want inherited forms of it around, and a data persistence layer is not normally place you want a lot of inheritance. A: Not everything that's important in a class is asserted easily in code. There can be semantics and relationships present that are easily broken by inheriting and overriding methods. Overriding one method at a time is an easy way to do this. You design a class/object as a single meaningful entity and then someone comes along and thinks if a method or two were 'better' it would do no harm. That may or may not be true. Maybe you can correctly separate all methods between private and not private or virtual and not virtual but that still may not be enough. Demanding inheritance of all classes also puts a huge additional burden on the original developer to foresee all the ways an inheriting class could screw things up. I don't know of a perfect solution. I'm sympathetic to preventing inheritance but that's also a problem because it hinders unit testing. A: I exposed a minimal interface to interact with the client API, and it would have been awesome to extend the client API class and then just add an implements clause with my new interface. The methods that I had in the interface that matched the actual interface would then need no further details and so I wouldn't have to explicitly implement them. However, the class was sealed, so I had to instead proxy calls to an internal reference to this class. The result: more work and a lot more code for no real good reason. Well, there is a reason: your code is now somewhat insulated from changes to the memcached interface. A: Performance: (…) if the JIT compiler sees a call to a virtual method using a sealed types, the JIT compiler can produce more efficient code by calling the method non-virtually.(…) That's a great reason indeed. Thus, for performance-critical classes, sealed and friends make sense. All the other reasons I've seen mentioned so far boil down to "nobody touches my class!". If you're worried someone might misunderstand its internals, you did a poor job documenting it. You can't possibly know that there's nothing useful to add to your class, or that you already know every imaginable use case for it. Even if you're right and the other developer shouldn't have used your class to solve their problem, using a keyword isn't a great way of preventing such a mistake. Documentation is. If they ignore the documentation, their loss. A: Most of answers (when abstracted) state that sealed/finalized classes are tool to protect other programmers against potential mistakes. There is a blurry line between meaningful protection and pointless restriction. But as long as programmer is the one who is expected to understand the program, I see no hardly any reasons to restrict him from reusing parts of a class. Most of you talk about classes. But it's all about objects! In his first post, DrPizza claims that designing inheritable class means anticipating possible extensions. Do I get it right that you think that class should be inheritable only if it's likely to be extended well? Looks as if you were used to design software from the most abstract classes. Allow me a brief explanation of how do I think when designing: Starting from the very concrete objects, I find characteristics and [thus] functionality that they have in common and I abstract it to superclass of those particular objects. This is a way to reduce code duplicity. Unless developing some specific product such as a framework, I should care about my code, not others (virtual) code. The fact that others might find it useful to reuse my code is a nice bonus, not my primary goal. If they decide to do so, it's their responsibility to ensure validity of extensions. This applies team-wide. Up-front design is crucial to productivity. Getting back to my idea: Your objects should primarily serve your purposes, not some possible shoulda/woulda/coulda functionality of their subtypes. Your goal is to solve given problem. Object oriented languages uses fact that many problems (or more likely their subproblems) are similar and therefore existing code can be used to accelerate further development. Sealing a class forces people who could possibly take advantage of existing code WITHOUT ACTUALLY MODIFYING YOUR PRODUCT to reinvent the wheel. (This is a crucial idea of my thesis: Inheriting a class doesn't modify it! Which seems quite pedestrian and obvious, but it's being commonly ignored). People are often scared that their "open" classes will be twisted to something that can not substitute its ascendants. So what? Why should you care? No tool can prevent bad programmer from creating bad software! I'm not trying to denote inheritable classes as the ultimately correct way of designing, consider this more like an explanation of my inclination to inheritable classes. That's the beauty of programming - virtually infinite set of correct solutions, each with its own cons and pros. Your comments and arguments are welcome. And finally, my answer to the original question: I'd finalize a class to let others know that I consider the class a leaf of the hierarchical class tree and I see absolutely no possibility that it could become a parent node. (And if anyone thinks that it actually could, then either I was wrong or they don't get me).
{ "language": "en", "url": "https://stackoverflow.com/questions/24620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Setting PHP Include Path on a per site basis? I can set the PHP include path in the php.ini: include_path = /path/to/site/includes/ But then other websites are affected so that is no good. I can set the PHP include in the start of every file: $path = '/path/to/site/includes/'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); But that seems like bad practice and clutters things up. So I can make an include of that and then include it into every file: include 'includes/config.php'; or include '../includes/config.php'; This is what I'm doing right now, but the include path of config.php will change depending on what is including it. Is there a better way? Does it matter? A: Erik Van Brakel gave, IMHO, one of the best answers. More, if you're using Apache & Virtual hosts, you can set up includes directly in them. Using this method, you won't have to remember to leave php_admin commands in your .htaccess. A: Use a php.ini file in website root, if your setup uses PHP as CGI (the most frequent case on shared hosts) with the same syntax as the server-wide php.ini; put it into .htaccess if you have PHP as an Apache module (do a phpinfo() if unsure): php_value include_path "wherever" Note that per-folder php.ini does not affects subfolders. A: Why do you think append to include path is bad practice? This code near top of root script shouldn't be that bad... $path = '/path/to/site/includes/'; set_include_path($path . PATH_SEPARATOR . get_include_path()); IMHO the main advantage is that it's portable and compatible not only with Apache EDIT: I saw a drawback of this method: small performance impact. see http://www.geeksengine.com/article/php-include-path.html A: If you're using apache as a webserver you can override (if you allow it) settings using .htaccess files. See the PHP manual for details. Basically you put a file called .htaccess in your website root, which contains some PHP ini values. Provided you configured Apache to allow overrides, this site will use all values in your PHP config, + the values you specify in the .htaccess file. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives as stated in the page I linked. If you click through to the full listing, you see that the include path is a PHP_INI_ALL directive. A: Depending on how your host is set up, you may be permitted to place a php.ini file in the root of your home directory with extra configuration directives. A: Your application should have a config file written in PHP. Then include that with a relative page into every page in the program. That config file will have a variable for the path to the includes dir, templates dir, images dir, etc. A: You can set include_path in your php.ini file too. I'm a perl guy, so I expect to be able to load includes and have include do the right thing. I have all my includes in a specific directory, which is added to include_path. I can do things like require_once "ClassName.php"; I don't need to worry about relative paths or locations of files. I've also written my own CustomRequire to do things like function CustomRequire ($file) { if(defined('MYINCLUDEPATH')) { require_once MYINCLUDEPATH . "/$file"; } else { require_once $file; } } That way I can change how I do includes at a later date. Of course, you still need to find a way to include your include code :)
{ "language": "en", "url": "https://stackoverflow.com/questions/24622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Java EE - DAO DVO I have seen two ways of implementing DAO-DVO design. 1) DVO are objects and DAOs are instantiated using factories i.e DAOs are also objects 2) DVOs are again objects but in this case, DAOs are classes which contain only static methods which accept DVOs to perform tasks. I was wondering which way is better and more scalable. A: Try the Spring Framework. DAOs are initialized via Dependency Injection and are just plain 'ole Java objects. Then, the methods on the DAO should just use Domain Objects that are used at all layers of the Application. A: With regards to testability, I'd advise against the second approach. Static methods prevent you from adjusting the class's behaviour by overriding collaborators with mocks and such. As Miško Hevery puts it: "Static Methods are Death to Testability". A: I would strongly recommend not using that many layers unless they are really layered physically. eg if you have something like a rich client where you need to send detached objects to update the GUI, otherwise, its a world of pain. A: How to download DAO Factory to create Database Connectivity?
{ "language": "en", "url": "https://stackoverflow.com/questions/24623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Abstraction VS Information Hiding VS Encapsulation Can you tell me what is the difference between abstraction and information hiding in software development? I am confused. Abstraction hides detail implementation and information hiding abstracts whole details of something. Update: I found a good answer for these three concepts. See the separate answer below for several citations taken from there. A: The OP updated his question with several citations that he had found, namely in an article by Edward V. Berard titled, "Abstraction, Encapsulation, and Information Hiding". I am re-posting a slightly expanded and reformatted version of the OP's update, since it should be an answer in its own right. (All citations are taken from the article mentioned above.) Abstraction: "One point of confusion regarding abstraction is its use as both process and an entity. Abstraction, as a process, denotes the extracting of the essential details about an item, or a group of items, while ignoring the inessential details. Abstraction, as an entity, denotes a model, a view, or some other focused representation for an actual item." Information Hiding: "Its interface or definition was chosen to reveal as little as possible about its inner workings." — [Parnas, 1972b] "Abstraction can be […] used as a technique for identifying which information should be hidden." "Confusion can occur when people fail to distinguish between the hiding of information, and a technique (e.g., abstraction) that is used to help identify which information is to be hidden." Encapsulation: "It […] refers to building a capsule, in the case a conceptual barrier, around some collection of things." — [Wirfs-Brock et al, 1990] "As a process, encapsulation means the act of enclosing one or more items within a […] container. Encapsulation, as an entity, refers to a package or an enclosure that holds (contains, encloses) one or more items." "If encapsulation was 'the same thing as information hiding,' then one might make the argument that 'everything that was encapsulated was also hidden.' This is obviously not true." Conclusion: "Abstraction, information hiding, and encapsulation are very different, but highly-related, concepts. One could argue that abstraction is a technique that help us identify which specific information should be visible, and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible." A: The meaning of abstraction given by the Oxford English Dictionary (OED) closest to the meaning intended here is 'The act of separating in thought'. A better definition might be 'Representing the essential features of something without including background or inessential detail.' Information hiding is the principle that users of a software component (such as a class) need to know only the essential details of how to initialize and access the component, and do not need to know the details of the implementation. Edit: I seems to me that abstraction is the process of deciding which parts of the implementation that should be hidden. So its not abstraction VERSUS information hiding. It's information hiding VIA abstraction. A: Abstraction is hiding the implementation details by providing a layer over the basic functionality. Information Hiding is hiding the data which is being affected by that implementation. Use of private and public comes under this. For example, hiding the variables of the classes. Encapsulation is just putting all similar data and functions into a group e.g Class in programming; Packet in networking. Through the use of Classes, we implement all three concepts - Abstraction, Information Hiding and Encapsulation A: Abstraction Abstraction is an act of representing essentail details without including the background details. A abstract class have only method signatures and implementing class can have its own implementation, in this way the complex details will be hidden from the user. Abstraction focuses on the outside view. In otherwords, Abstraction is sepration of interfaces from the actual implementation. Encapsulation Encapsulation explains binding the data members and methods into a single unit. Information hiding is the main purpose of encapsulation. Encapsulation is acheived by using access specifiers like private, public, protected. Class member variables are made private so that they cann't be accessible directly to outside world. Encapsulation focuses on the inner view. In otherwords, Encapsulation is a technique used to protect the information in an object from the other object. A: Please don't complicate simple concepts. Encapsulation : Wrapping up of data and methods into a single unit is Encapsulation (e.g. Class) Abstraction : It is an act of representing only the essential things without including background details. (e.g. Interface) FOR EXAMPLES AND MORE INFO GOTO : http://thecodekey.com/C_VB_Codes/Encapsulation.aspx http://thecodekey.com/C_VB_Codes/Abstraction.aspx Approved definitions here P.S.: I also remember the definition from a book named C++ by Sumita Arora which we read in 11th class ;) A: Abstraction is hiding details of implementation as you put it. You abstract something to a high enough point that you'll only have to do something very simple to perform an action. Information hiding is hiding implementation details. Programming is hard. You can have a lot of things to deal with and handle. There can be variables you want/need to keep very close track of. Hiding information ensures that no one accidentally breaks something by using a variable or method you exposed publicly. These 2 concepts are very closely tied together in object-oriented programming. A: Abstraction - It is the process of identifying the essential characteristics of an object without including the irrelevant and tedious details. Encapsulation - It is the process of enclosing data and functions manipulating this data into a single unit. Abstraction and Encapsulation are related but complementary concepts. * *Abstraction is the process. Encapsulation is the mechanism by which Abstraction is implemented. *Abstraction focuses on the observable behavior of an object. Encapsulation focuses upon the implementation that give rise to this behavior. Information Hiding - It is the process of hiding the implementation details of an object. It is a result of Encapsulation. A: Abstraction : Abstraction is the concept/technique used to identify what should be the external view of an object. Making only the required interface available. Information Hiding : It is complementary to Abstraction, as through information hiding Abstraction is achieved. Hiding everything else but the external view. Encapsulation : Is binding of data and related functions into a unit. It facilitates Abstraction and information hiding. Allowing features like member access to be applied on the unit to achieve Abstraction and Information hiding A: In very short Encapsulation:– Information hiding Abstraction :– Implementation hiding Abstraction lets you focus on what the object does while Encapsulation means how an object works A: See Joel's post on the Law of Leaky Abstractions JoelOnsoftware Basically, abstracting gives you the freedom of thinking of higher level concepts. A non-programming analogy is that most of us do not know where our food comes from, or how it is produced, but the fact that we (usually) don't have to worry about it frees us up to do other things, like programming. As for information hiding, I agree with jamting. A: Encapsulation: binding the data members and member functions together is called encapsulation. encapsulation is done through class. abstraction: hiding the implementation details form usage or from view is called abstraction. ex: int x; we don't know how int will internally work. but we know int will work. that is abstraction. A: It's worth noting these terms have standardized, IEEE definitions, which can be searched at https://pascal.computer.org/. abstraction * *view of an object that focuses on the information relevant to a particular purpose and ignores the remainder of the information *process of formulating a view *process of suppressing irrelevant detail to establish a simplified model, or the result of that process information hiding * *software development technique in which each module's interfaces reveal as little as possible about the module's inner workings and other modules are prevented from using information about the module that is not in the module's interface specification *containment of a design or implementation decision in a single module so that the decision is hidden from other modules encapsulation * *software development technique that consists of isolating a system function or a set of data and operations on those data within a module and providing precise specifications for the module *concept that access to the names, meanings, and values of the responsibilities of a class is entirely separated from access to their realization *idea that a module has an outside that is distinct from its inside, that it has an external interface and an internal implementation A: Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition): Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object... encapsulation focuses upon the implementation that gives rise to this behavior... encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics. In other words: abstraction = the object externally; encapsulation (achieved through information hiding) = the object internally, Example: In the .NET Framework, the System.Text.StringBuilder class provides an abstraction over a string buffer. This buffer abstraction lets you work with the buffer without regard for its implementation. Thus, you're able to append strings to the buffer without regard for how the StringBuilder internally keeps track of things such the pointer to the buffer and managing memory when the buffer gets full (which it does with encapsulation via information hiding). rp A: Abstraction allows you to treat a complex process as a simple process. For example, the standard "file" abstraction treats files as a contiguous array of bytes. The user/developer does not even have to think about issues of clusters and fragmentation. (Abstraction normally appears as classes or subroutines.) Information hiding is about protecting your abstractions from malicious/incompetent users. By restricting control of some state (hard drive allocations, for example) to the original developer, huge amounts of error handling becomes redundant. If nobody else besides the file system driver can write to the hard drive, then the file system driver knows exactly what has been written to the hard drive and where. (The usual manifestation of this concept is private and protected keywords in OO languages.) A: To abstract something we need to hide the detail or to hide the detail of something we need to abstract it. But, both of them can be achieved by encapsulation. So, information hiding is a goal, abstraction is a process, and encapsulation is a technique. A: Abstraction simply means the technique in which only essential details of software is made visible to the user to help the user to use or operate with software, thus implementation details of that software are not shown(are made invisible). Encapsulation is the technique that have package that hold one or more items and hence some of information (particularly program details) became visible and some not visible to the user, so encapsulation is achieved through information hiding. In summary. Abstraction is for observable behavior (externally) and encapsulation is for invisibility (internally) but these two are really complementary. A: Just adding on more details around InformationHiding, found This link is really good source with examples InformationHiding is the idea that a design decision should be hidden from the rest of the system to prevent unintended coupling. InformationHiding is a design principle. InformationHiding should inform the way you encapsulate things, but of course it doesn't have to. Encapsulation is a programming language feature. A: Both Abstraction and Encapsulation are two of the four basic OOP concepts which allow you to model real-world things into objects so that you can implement them in your program and code. Many beginners get confused between Abstraction and Encapsulation because they both look very similar. If you ask someone what is Abstraction, he will tell that it's an OOP concept which focuses on relevant information by hiding unnecessary detail, and when you ask about Encapsulation, many will tell that it's another OOP concept which hides data from outside world. The definitions are not wrong as both Abstraction and Encapsulation does hide something, but the key difference is on intent. Abstraction hides complexity by giving you a more abstract picture, a sort of 10,000 feet view, while Encapsulation hides internal working so that you can change it later. In other words, Abstraction hides details at the design level, while Encapsulation hides details at the implementation level. A: After reading all the above answers one by one I cant stop myself from posting that abstraction involves the facility to define objects that represent abstract "actors" that can perform work, report on and change their state, and "communicate" with other objects in the system. Encapsulation is quite clear from above however -> The term encapsulation refers to the hiding of state details, but extending the concept of data type from earlier programming languages to associate behavior most strongly with the data, and standardizing the way that different data types interact, is the beginning of abstraction. reference wiki A: I too was very confused about the two concepts of Abstraction and Encapsulation. But when I saw the abstraction article on myjavatrainer.com, It became clear to me that Abstraction and Encapsulation are Apples and Oranges, you can't really compare them because both are required. Encapsulation is how the object is created, and abstraction is how the object is viewed in the outside world. A: Encapsulation: binding data and the methods that act on it. this allows the hiding of data from all other methods in other classes. example: MyList class that can add an item, remove an item, and remove all items the methods add, remove, and removeAll act on the list(a private array) that can not be accessed directly from the outside. Abstraction: is hiding the non relevant behavior and data. How the items are actually stored, added, or deleted is hidden (abstracted). My data may be held in simple array, ArrayList, LinkedList, and so on. Also, how the methods are implemented is hidden from the outside. A: Encapsulation- enforcing access to the internal data in a controlled manner or preventing members from being accessed directly. Abstraction- Hiding the implementation details of certain methods is known as abstraction Let's understand with the help of an example:- class Rectangle { private int length; private int breadth;// see the word private that means they cant be accesed from outside world. //now to make them accessed indirectly define getters and setters methods void setLength(int length) { // we are adding this condition to prevent users to make any irrelevent changes that is why we have made length private so that they should be set according to certain restrictions if(length!=0) { this.length=length } void getLength() { return length; } // same do for breadth } now for abstraction define a method that can only be accessed and user doesnt know what is the body of the method and how it is working Let's consider the above example, we can define a method area which calculates the area of the rectangle. public int area() { return length*breadth; } Now, whenever a user uses the above method he will just get the area not the way how it is calculated. We can consider an example of println() method we just know that it is used for printing and we don't know how it prints the data. I have written a blog in detail you can see the below link for more info abstraction vs encapsulation
{ "language": "en", "url": "https://stackoverflow.com/questions/24626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "183" }
Q: Hooking my program with windows explorer's rename event Is there any way, in any language, to hook my program when a user renames a file? For example: A user renames a file and presses enter (or clicks away) to confirm the rename action. BEFORE the file is actually renamed, my program "listens" to this event and pops up a message saying "Are you sure you want to rename C:\test\file.txt to C:\test\test.txt?". I'm thinking/hoping this is possible with C++, C# or .NET.. But I don't have any clue where to look for. A: You can probably solve this by using the FileSystemWatcher class in .NET framework. From the class remarks: You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the Filter property to "*.txt" and call the WaitForChanged method with a Renamed specified for its parameter. A: My guess is that this is not possible, I did find this which is for monitoring operations (including rename) on a folder, but there does not appear to be a similar method for files. @Richard, FileSystemWatcher is good if you only need to monitor changes, but he needs to interrupt them which it cannot do. A: IFileOperationProgressSink.PreRenameItem is the closest supported thing I know of. Unfortunately, it's not a hook into Explorer - so you can only use it for your own IFileOperation actions. Depending on your needs, you can write a shell extension to do your own ConfirmRename (or something), and branch from there. Otherwise, you're looking at hooking SHFileOperation, I think. This would have to be done in unmanaged code, as you'll be loaded into Explorer.exe. For Vista, this has been changed to IFileOperation - which probably means you'll have to hook the creation of it and pass out your mock. Personally, I think since you're talking a rename, wilhelmtell's idea of confirming after the change, and undoing it if necessary is the best idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/24644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What's the best way to get to know linux or BSD kernel internals? I'd like to gain better knowledge of operating system internals. Process management, memory management, and stuff like that. I was thinking of learning by getting to know either linux or BSD kernel. Which one kernel is better for learning purposes? What's the best place to start? Can you recommend any good books? A: As a Linux user I'd say Linux has a great community for people to learn about the kernel. http://kernelnewbies.org is a great place to start asking questions and learning about how the kernel works. I can't make a book reccomendation, but once you've read the starting material on kernelnewbies the source is very well documented. A: Aside from the good books already mentioned (Opeating System Design & Implementation is particularly good), get a hold of a 1.x release Linux Kernel, load it into VMWare or VirtualBox and start playing around from there. You will need to spend a lot of time browsing source code. For this, check out http://lxr.linux.no/ which is a browsable linked version of the source and makes life a lot easier. For the very first version of Linux (0.01) check out http://lxr.linux.no/linux-old+v0.01/. The fun begins at http://lxr.linux.no/linux-old+v0.01/boot/boot.s. As you progress from version to version, check out the ChangeLog and dig into those parts that have changed to save you re-reading the whole thing again. Once you've gotten a hold of the concepts, look at 2.0, then 2.2, etc. Be prepared to sink A LOT of time into the process. A: * *Linux Device Drivers *Linux Core Kernel Commentary *Operating Systems Design and Implementation I had previously bought these books on recommendation for the same purpose but I never got to studying them myself so only take them as second-hand advice. A: Noting the lack of BSDs here, I figured I'd chip in: * *The Design and Implementation of the FreeBSD Operating System (dead-tree book) *Unix and BSD Courses (courses and videos) *FreeBSD Architecture Handbook (online book) I haven't taken any of the courses myself, but I've heard Marshall Kirk McKusick speak on other occasions, and he is really good at what he does. And of course the BSD man pages, which are an excellent resource as they are maintained to a far greater extent than your average Linux man-page. Take for instance the uvm(9) man-page, describing the virtual memory interface in OpenBSD. Not quite related, but I'll also recommend the video History of the Berkeley Software Distributions as it gives a nice introduction to the BSD parts of the UNIX history and culture as well as plenty of hilarious anectodes from back when. A: I recommend you the BSD kernels! BSD kernels have far fewer hackers so following their evolution is easier. Either BSD and Linux kernels have great hackers, but some people argue that BSD lower fame filters out novice ones. Also taking design decisions is easier when the sources are not being updated 100 times a day. Among the BSD choices, my favorite one is NetBSD. It might not be the pain-free choice you want for your desktop, but because it has a strong focus on portability, the quality is quite good. I think this part say it all: Some systems seem to have the philosophy of “If it works, it's right”. In that light NetBSD's philosophy could be described as “It doesn't work unless it's right” If you have been working long enough, you will know that NetBSD is a quite joy for learning good coding. Although professionally you will find more chances with Linux Whichever choice you take, start joining their mail lists, follow the discussions. Study some patches and finally try to do your own bug-fixing. Regarding books, search for Diomidis Spinellis articles and his book. It is not exactly a kernel book, but has NetBSD examples and helps a lot to tackle large software. A: In college, I had an operating systems class where we used a book by Tanenbaum. In the class, we implemented a device driver in the Minix operating system. It was a lot of fun, and we learned a lot. One thing to note though, if you pick Minix, it is designed for learning. It is a microkernel, while Linux and BSD are a monolithic kernel, so what you learn may not be 100% translatable to be able to work with Linux or BSD, but you can still gain a lot out of it, without having to process quite as much information. As a side note, if you've read Just for Fun, Linus actually was playing with Minix before he wrote Linux, but it just wasn't enough for his purposes. A: There's no substitute for diving into the code. Try to find a driver or subsystem that you're interested in and poke around with it. With tools like VMware Workstation it's super easy to make whatever changes you want, snapshot the VM, and run your modified kernel. If the kernel panics on boot, who cares? Just jump back to the snapshot and fix the problem. For books, I strongly recommend Linux Kernel Development by Robert Love. It's a wonderfully written book -- lots of information, organized sanely, and humorous... not dry reading at all. A: Take Mike Stone's advice and start with Minix. That's what Linus did! The textbook is really well written, and Tannenbaum does a great job of showing how the various features are implemented in a real system. A: Nobody seems to have mentioned that code-wise BSD is much cleaner and more consistent. The documentation's way better too (as already mentioned). But since there's a whole lot of fiddling with whatever system you choose - I'd pick the one you use more often. A: Linux and Minix are fun to learn. If you also want to learn how a modern micro-kernel operating system looks like, you can look at QNX. The complete documentation is available online and it is very accessible. For example, this online book. A: When I was at uni I spent a semester studying operating systems, and as part of this had an assignment where we had to implement a RAM-based filesystem in Linux. It was a fantastic way to get to understand the internals of the Linux keurnel and to get a grasp on how everything fits together - And a heck of a lot of fun playing around with how it interacts with standard tools too. A: I haven't tried it myself, but you can go to Linux From Scratch and start building your own Linux distribution. Sounds like something that'll take a junkload of time, but will result in an intimate knowledge of the guts of the Linux kernel and how each part works. Of course, you can supplement this learning by following any of the other tips here.
{ "language": "en", "url": "https://stackoverflow.com/questions/24648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Tactics for using PHP in a high-load site Before you answer this I have never developed anything popular enough to attain high server loads. Treat me as (sigh) an alien that has just landed on the planet, albeit one that knows PHP and a few optimisation techniques. I'm developing a tool in PHP that could attain quite a lot of users, if it works out right. However while I'm fully capable of developing the program I'm pretty much clueless when it comes to making something that can deal with huge traffic. So here's a few questions on it (feel free to turn this question into a resource thread as well). Databases At the moment I plan to use the MySQLi features in PHP5. However how should I setup the databases in relation to users and content? Do I actually need multiple databases? At the moment everything's jumbled into one database - although I've been considering spreading user data to one, actual content to another and finally core site content (template masters etc.) to another. My reasoning behind this is that sending queries to different databases will ease up the load on them as one database = 3 load sources. Also would this still be effective if they were all on the same server? Caching I have a template system that is used to build the pages and swap out variables. Master templates are stored in the database and each time a template is called it's cached copy (a html document) is called. At the moment I have two types of variable in these templates - a static var and a dynamic var. Static vars are usually things like page names, the name of the site - things that don't change often; dynamic vars are things that change on each page load. My question on this: Say I have comments on different articles. Which is a better solution: store the simple comment template and render comments (from a DB call) each time the page is loaded or store a cached copy of the comments page as a html page - each time a comment is added/edited/deleted the page is recached. Finally Does anyone have any tips/pointers for running a high load site on PHP. I'm pretty sure it's a workable language to use - Facebook and Yahoo! give it great precedence - but are there any experiences I should watch out for? A: No two sites are alike. You really need to get a tool like jmeter and benchmark to see where your problem points will be. You can spend a lot of time guessing and improving, but you won't see real results until you measure and compare your changes. For example, for many years, the MySQL query cache was the solution to all of our performance problems. If your site was slow, MySQL experts suggested turning the query cache on. It turns out that if you have a high write load, the cache is actually crippling. If you turned it on without testing, you'd never know. And don't forget that you are never done scaling. A site that handles 10req/s will need changes to support 1000req/s. And if you're lucking enough to need to support 10,000req/s, your architecture will probably look completely different as well. Databases * *Don't use MySQLi -- PDO is the 'modern' OO database access layer. The most important feature to use is placeholders in your queries. It's smart enough to use server side prepares and other optimizations for you as well. *You probably don't want to break your database up at this point. If you do find that one database isn't cutting, there are several techniques to scale up, depending on your app. Replicating to additional servers typically works well if you have more reads than writes. Sharding is a technique to split your data over many machines. Caching * *You probably don't want to cache in your database. The database is typically your bottleneck, so adding more IO's to it is typically a bad thing. There are several PHP caches out there that accomplish similar things like APC and Zend. *Measure your system with caching on and off. I bet your cache is heavier than serving the pages straight. *If it takes a long time to build your comments and article data from the db, integrate memcache into your system. You can cache the query results and store them in a memcached instance. It's important to remember that retrieving the data from memcache must be faster than assembling it from the database to see any benefit. *If your articles aren't dynamic, or you have simple dynamic changes after it's generated, consider writing out html or php to the disk. You could have an index.php page that looks on disk for the article, if it's there, it streams it to the client. If it isn't, it generates the article, writes it to the disk and sends it to the client. Deleting files from the disk would cause pages to be re-written. If a comment is added to an article, delete the cached copy -- it would be regenerated. A: APC is an absolute must. Not only does it make for a great caching system, but the gain from the auto-cached PHP files is a godsend. As for the multiple database idea, I don't think you would get much out of having different databases on the same server. It may give you a bit of a gain in speed during query time, but I doubt the effort it would take to deploy and maintain the code for all three while making sure they are in sync would be worth it. I also highly recommend running Xdebug to find bottlenecks in your program. It made optimization a breeze for me. A: Firstly, as I think Knuth said, "Premature optimization is the root of all evil". If you don't have to deal with these issues right now then don't, focus on delivering something that works correctly first. That being said, if the optimizations can't wait. Try profiling your database queries, figure out what's slow and what happens alot and come up with an optimization strategy from that. I would investigate Memcached as it's what a lot of the higher load sites use for efficiently caching content of all types, and the PHP object interface to it is quite nice. Splitting up databases among servers and using some sort of load balancing technique (e.g. generate a random number between 1 and # redundant databases with necessary data - and use that number to determine which database server to connect to) can also be an excellent way to increase efficiency. These have all worked out pretty well in the past for some fairly high load sites. Hope this helps to get you started :-) A: I'm a lead developer on a site with over 15M users. We have had very little scaling problems because we planned for it EARLY and scaled thoughtfully. Here are some of the strategies I can suggest from my experience. SCHEMA First off, denormalize your schemas. This means that rather than to have multiple relational tables, you should instead opt to have one big table. In general, joins are a waste of precious DB resources because doing multiple prepares and collation burns disk I/O's. Avoid them when you can. The trade-off here is that you will be storing/pulling redundant data, but this is acceptable because data and intra-cage bandwidth is very cheap (bigger disks) whereas multiple prepare I/O's are orders of magnitude more expensive (more servers). INDEXING Make sure that your queries utilize at least one index. Beware though, that indexes will cost you if you write or update frequently. There are some experimental tricks to avoid this. You can try adding additional columns that aren't indexed which run parallel to your columns that are indexed. Then you can have an offline process that writes the non-indexed columns over the indexed columns in batches. This way, you can control better when mySQL will need to recompute the index. Avoid computed queries like a plague. If you must compute a query, try to do this once at write time. CACHING I highly recommend Memcached. It has been proven by the biggest players on the PHP stack (Facebook) and is very flexible. There are two methods to doing this, one is caching in your DB layer, the other is caching in your business logic layer. The DB layer option would require caching the result of queries retrieved from the DB. You can hash your SQL query using md5() and use that as a lookup key before going to database. The upside to this is that it is pretty easy to implement. The downside (depending on implementation) is that you lose flexibility because you're treating all caching the same with regard to cache expiration. In the shop I work in, we use business layer caching, which means each concrete class in our system controls its own caching schema and cache timeouts. This has worked pretty well for us, but be aware that items retrieved from DB may not be the same as items from cache, so you will have to update cache and DB together. DATA SHARDING Replication only gets you so far. Sooner than you expect, your writes will become a bottleneck. To compensate, make sure to support data sharding early as possible. You will likely want to shoot yourself later if you don't. It is pretty simple to implement. Basically, you want to separate the key authority from the data storage. Use a global DB to store a mapping between primary keys and cluster ids. You query this mapping to get a cluster, and then query the cluster to get the data. You can cache the hell out of this lookup operation which will make it a negligible operation. The downside to this is that it may be difficult to piece together data from multiple shards. But, you can engineer your way around that as well. OFFLINE PROCESSING Don't make the user wait for your backend if they don't have to. Build a job queue and move any processing that you can offline, doing it separate from the user's request. A: Profiling your app with something like Xdebug (like tj9991 recommended) is definitely going to be a must. It doesn't make a whole lot of sense to just go around optimizing things blindly. Xdebug will help you find the real bottlenecks in your code so you can spend your optimization time wisely and fix chunks of code that are actually causing slow downs. If you're using Apache, another utility that can help in testing is Siege. It will help you anticipate how your server and application will react to high loads by really putting it through its paces. Any kind of opcode cache for PHP (like APC or one of the many others) will help a lot as well. A: I run a website with 7-8 million page views a month. Not terribly much, but enough that our server felt the load. The solution we chose was simple: Memcache at the database level. This solution works well if the database load is your main problem. We started out using Memcache to cache entire objects and the database results that were most frequently used. It did work, but it also introduced bugs (we might have avoided some of those if we had been more careful). So we changed our approach. We built a database wrapper (with the exact same methods as our old database, so it was easy to switch), and then we subclassed it to provide memcached database access methods. Now all you have to do is decide whether a query can use cached (and possibly out of date) results or not. Most of the queries run by the users are now fetched directly from Memcache. The exceptions are updates and inserts, which for the main website only happens because of logging. This rather simple measure reduced our server load by about 80%. A: For what it's worth, caching is DIRT SIMPLE in PHP even without an extension/helper package like memcached. All you need to do is create an output buffer using ob_start(). Create a global cache function. Call ob_start, pass the function as a callback. In the function, look for a cached version of the page. If exists, serve it and end. If it doesn't exist, the script will continue processing. When it reaches the matching ob_end() it will call the function you specified. At that time, you just get the contents of the output buffer, drop them in a file, save the file, and end. Add in some expiration/garbage collection. And many people don't realize you can nest ob_start()/ob_end() calls. So if you're already using an output buffer to, say, parse in advertisements or do syntax highlighting or whatever, you can just nest another ob_start/ob_end call. A: Thanks for the advice on PHP's caching extensions - could you explain reasons for using one over another? I've heard great things about memcached through IRC but have never heard of APC - what are your opinions on them? I assume using multiple caching systems is pretty counter-effective. Actually, many do use APC and memcached together... A: I've worked on a few sites that get millions/hits/month backed by PHP & MySQL. Here are some basics: * *Cache, cache, cache. Caching is one of the simplest and most effective ways to reduce load on your webserver and database. Cache page content, queries, expensive computation, anything that is I/O bound. Memcache is dead simple and effective. *Use multiple servers once you are maxed out. You can have multiple web servers and multiple database servers (with replication). *Reduce overall # of request to your webservers. This entails caching JS, CSS and images using expires headers. You can also move your static content to a CDN, which will speed up your user's experience. *Measure & benchmark. Run Nagios on your production machines and load test on your dev/qa server. You need to know when your server will catch on fire so you can prevent it. I'd recommend reading Building Scalable Websites, it was written by one of the Flickr engineers and is a great reference. Check out my blog post about scalability too, it has a lot of links to presentations about scaling with multiple languages and platforms: http://www.ryandoherty.net/2008/07/13/unicorns-and-scalability/ A: Re: PDO / MySQLi / MySQLND @gary You cannot just say "don't use MySQLi" as they have different goals. PDO is almost like an abstraction layer (although it is not actually) and is designed to make it easy to use multiple database products whereas MySQLi is specific to MySQL conections. It is wrong to say that PDO is the modern access layer in the context of comparing it to MySQLi because your statement implies that the progression has been mysql -> mysqli -> PDO which is not the case. The choice between MySQLi and PDO is simple - if you need to support multiple database products then you use PDO. If you're just using MySQL then you can choose between PDO and MySQLi. So why would you choose MySQLi over PDO? See below... @ross You are correct about MySQLnd which is the newest MySQL core language level library, however it is not a replacement for MySQLi. MySQLi (as with PDO) remains the way you would interact with MySQL through your PHP code. Both of these use libmysql as the C client behind the PHP code. The problem is that libmysql is outside of the core PHP engine and that is where mysqlnd comes in i.e. it is a Native Driver which makes use of the core PHP internals to maximise efficiency, specifically where memory usage is concerned. MySQLnd is being developed by MySQL themselves and has recently landed onto the PHP 5.3 branch which is in RC testing, ready for a release later this year. You will then be able to use MySQLnd with MySQLi...but not with PDO. This will give MySQLi a performance boost in many areas (not all) and will make it the best choice for MySQL interaction if you do not need the abstraction like capabilities of PDO. That said, MySQLnd is now available in PHP 5.3 for PDO and so you can get the advantages of the performance enhancements from ND into PDO, however, PDO is still a generic database layer and so will be unlikely to be able to benefit as much from the enhancements in ND as MySQLi can. Some useful benchmarks can be found here although they are from 2006. You also need to be aware of things like this option. There are a lot of considerations that need to be taken into account when deciding between MySQLi and PDO. It reality it is not going to matter until you get to rediculously high request numbers and in that case, it makes more sense to be using an extension that has been specifically designed for MySQL rather than one which abstracts things and happens to provide a MySQL driver. It is not a simple matter of which is best because each has advantages and disadvantages. You need to read the links I've provided and come up with your own decision, then test it and find out. I have used PDO in past projects and it is a good extension but my choice for pure performance would be MySQLi with the new MySQLND option compiled (when PHP 5.3 is released). A: It looks like I was wrong. MySQLi is still being developed. But according to the article, PDO_MySQL is now being contributed to by the MySQL team. From the article: The MySQL Improved Extension - mysqli - is the flagship. It supports all features of the MySQL Server including Charsets, Prepared Statements and Stored Procedures. The driver offers a hybrid API: you can use a procedural or object-oriented programming style based on your preference. mysqli comes with PHP 5 and up. Note that the End of life for PHP 4 is 2008-08-08. The PHP Data Objects (PDO) are a database access abstraction layer. PDO allows you to use the same API calls for various databases. PDO does not offer any degree of SQL abstraction. PDO_MYSQL is a MySQL driver for PDO. PDO_MYSQL comes with PHP 5. As of PHP 5.3 MySQL developers actively contribute to it. The PDO benefit of a unified API comes at the price that MySQL specific features, for example multiple statements, are not fully supported through the unified API. Please stop using the first MySQL driver for PHP ever published: ext/mysql. Since the introduction of the MySQL Improved Extension - mysqli - in 2004 with PHP 5 there is no reason to still use the oldest driver around. ext/mysql does not support Charsets, Prepared Statements and Stored Procedures. It is limited to the feature set of MySQL 4.0. Note that the Extended Support for MySQL 4.0 ends at 2008-12-31. Don't limit yourself to the feature set of such old software! Upgrade to mysqli, see also Converting_to_MySQLi. mysql is in maintenance only mode from our point of view. To me, it seems the article is biased towards MySQLi. I suppose I'm biased towards PDO. I really like PDO over MySQLi. It's straight forward to me. The API is a lot closer to other languages I've programmed in. OO Database interfaces seem to work better. I haven't come across any specific MySQL features that weren't available through PDO. I would be surprised if I ever did. A: PDO is also very slow and its API is pretty complicated. No one in their sane mind should use it if portability is not a concern. And let's face it, in 99% of all webapps it is not. You just stick with MySQL or PostrgreSQL, or whatever it is you are working with. As for the PHP question and what to take into account. I think premature optimization is the root of all evil. ;) Get your application done first, try to keep it clean when it comes to programming, do a little documentation and write unit tests. With all of the above you will have no issues refactoring code when the time comes. But first you want to be done and push it out to see how people react to it. A: General * *Do not try to optimize before you start to see real world load. You might guess right, but if you don't, you've wasted your time. *Use jmeter, xdebug or another tool to benchmark the site. *If load starts to be an issue, either object or data caching will likely be involved, so generally read up on caching options (memcached, MySQL caching options) Code * *Profile your code so that you know where the bottleneck is, and whether it's in code or the database Databases * *Use MYSQLi if portability to other databases is not vital, PDO otherwise *If benchmarks reveal the database is the issue, check the queries before you start caching. Use EXPLAIN to see where your queries are slowing down. *After the queries are optimized and the database is cached in some way, you may want to use multiple databases. Either replicating to multiple servers or sharding (splitting the data over multiple databases/servers) may be appropriate, depending on the data, the queries, and the kind of read/write behavior. Caching * *Plenty of writing has been done on caching code, objects, and data. Look up articles on APC, Zend Optimizer, memcached, QuickCache, JPCache. Do some of this before you really need to, and you'll be less concerned about starting off unoptimized. *APC and Zend Optimizer are opcode caches, they speed up PHP code by avoiding reparsing and recompilation of code. Generally simple to install, worth doing early. *Memcached is a generic cache, that you can use to cache queries, PHP functions or objects, or entire pages. Code must be specifically written to use it, which can be an involved process if there are no central points to handle creation, update and deletion of cached objects. *QuickCache and JPCache are file caches, otherwise similar to Memcached. The basic concept is simple, but also requires code and is easier with central points of creation, update and deletion. Miscellaneous * *Consider alternative web servers for high load. Servers like lighthttp and nginx can handle large amounts of traffic in much less memory than Apache, if you can sacrifice Apache's power and flexibility (or if you just don't need those things, which often, you don't). *Remember that hardware is surprisingly cheap these days, so be sure to cost out the effort to optimize a large block of code versus "let's buy a monster server." *Consider adding the "MySQL" and "scaling" tags to this question A: Sure pdo is nice, but there has been some controversy about it's performance versus mysql and mysqli, although it seems fixed now. You should use pdo if you envision portability, but if not, mysqli should be the way. It has an OO interface, prepared statements, and most of what pdo offers (except, well, portability). Plus, if performance is really needed, prepare for the (native mysql) MysqLnd driver in PHP 5.3, who will be much more tightly integrated with php, with better performance and improved memory usage (and statistics for performance tuning). Memcache is nice if you have clustered servers (and YouTube-like load), but i'd try out APC first too. A: A lot of good answers were given already, but I would like to point you to an alternate opcode cache called XCache. It is created by a lighty contributor. Also, if you may need load balancing your database server in future, MySQL Proxy could very well help you to achieve this. Both of those tools should plug into an existing application quite easily, so this optimization can be done when you need it, without too much hassle. A: First question is how big do you really expect it to be? And how much do you plan on investing in your infrastructure. Since you feel the need to ask the question here, I'm guessing that you expect to start small on a limited budget. Performance is irrelevant if the site is not available. And for availability you need horizontal scaling. The minimum you can sensibly get away with is 2 servers, both running apache, php and mysql. Set up one DBMS as a slave to the other. Do all the writes on the master, and all the reads on the local database (whatever that is) - unless for some reason you need to read back the data you've just read (use master). Make sure you've got the machinery in place to automatically promote the slave and fence the master. Use round-robin DNS for the webserver addresses to give more affinity for the slave node. Partitioning your data across different database nodes at this stage is a very bad idea - however you might want to consider splitting it across different databases on the same server (which will facilitate partitioning across nodes when you overtake facebook). Do make sure you've got the monitoring and data analysis tools in place to measure your sites performance and identify bottlenecks. Most performance problems can be fixed by writing better SQL / fixing the database schema. Keeping your template cache on the database is a dumb idea - the database should be a central common repository for structured data. Keep your template cache on the local filesystem of your webservers - it will be available faster and won't slow down your database access. Do use a op-code cache. Spend plenty of time studying your site and its logs to understand why its going so slow. Push as much caching as possible onto the client. Use mod_gzip to compress everything you can. C. A: My first piece of advice is to think about this issue and keep it in mind when designing the site but don't go overboard. It's often difficult to predict the success of a new site and I your time will be better spent getting up finished early and optimising it later. In general, Simple is fast. Templates slow you down. Databases slow you down. Complex libraries slow you down. Layering templates over each other retrieving them from databases and parsing it in a complex library --> the time delays multiply with each other. Once you have the basic site up and running do tests to show you where to spend your efforts. It's difficult to see where to target. Often to speed things up you will have to unravel the complexity of the code, this makes it larger and harder to maintain, so you only want to do it where necessary. In my experience establishing the database connection was relatively expensive. If you can get away with it, don't connect to the database for general visitors on the most trafficed pages like the front page to the site. Creating multiple database connections is madness with very little benefit. A: @Gary Don't use MySQLi -- PDO is the 'modern' OO database access layer. The most important feature to use is placeholders in your queries. It's smart enough to use server side prepares and other optimizations for you as well. I'm loking over PDO at the moment and it looks like you're right - however I know that MySQL are developing the MySQLd extension for PHP - I think to succeed either MySQL or MySQLi - what do you think about that? @Ryan, Eric, tj9991 Thanks for the advice on PHP's caching extensions - could you explain reasons for using one over another? I've heard great things about memcached through IRC but have never heard of APC - what are your opinions on them? I assume using multiple caching systems is pretty counter-effective. I will definitely be sorting out some profiling testers - thank you very much for your recommendations on those. A: I don't see myself switching from MySQL anytime soon - so I guess I don't need the abstraction capabilities of PDO. Thanks for those articles DavidM, they've helped me a lot. A: Look into mod_cache, an output cache for the Apache web server, simillar to the output caching in ASP.NET. Yes, I can see that it's still experimental but it will be final someday. A: I can't believe no-one has already mentioned this: Modularisation and Abstraction. If you think your site is going to have to grow to lots of machines, you must design it so it can! That means stupid things like don't assume the database is on localhost. It also means things that are going to be a bother at first, like writing a database abstraction layer (like PDO, but much much lighter because it only does what you need it to do). And it means things like working with a framework. You will need layers to your code so that you can later gain performance by refactoring the data-abstraction layer, for example, by teaching it that some objects are in a different database -- and the code doesn't have to know or care. Finally, be careful of memory-intensive operations, for example, unnecessary string copying. If you can keep PHP's memory usage down, then you will get more performance out of your webserver and this is something that will scale when you go to a load-balanced solution. A: If you are working with large amounts of data, and caching isn't cutting it, look into Sphinx. We've had great results with using SphinxSearch not only for better text searching, but also as a data retrieval replacement for MySQL when dealing larger tables. If you use SphinxSE (MySQL plugin), it surpassed our performance gains we had from caching several times over, and application-implementation is a sinch. A: The points made about cache are spot-on; it is the least complicated and most important part of building an efficient application. I'd like to add that while memcached is great, APC is about five times faster if your application lives on a single server. The "Cache Performance Comparison" post at the MySQL performance blog has some interesting benchmarks on the subject - http://www.mysqlperformanceblog.com/2006/08/09/cache-performance-comparison/.
{ "language": "en", "url": "https://stackoverflow.com/questions/24675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "253" }
Q: JavaScript editor within Eclipse I'm looking for the best JavaScript editor available as an Eclipse plugin. I've been using Spket which is good. But, is there more better one? A: Ganymede's version of WTP includes a revamped Javascript editor that's worth a try. The key version numbers are Eclipse 3.4 and WTP 3.0. See http://live.eclipse.org/node/569 A: Eclipse HTML Editor Plugin I too have struggled with this totally obvious question. It seemed crazy that this wasn't an extremely easy-to-find feature with all the web development happening in Eclipse these days. I was very turned off by Aptana because of how bloated it is, and the fact that it starts up a local web server (by default on port 8000) everytime you start Eclipse and you can't disable this functionality. Adobe's port of JSEclipse is now a 400Mb plugin, which is equally insane. However, I just found a super-lightweight JavaScript editor called Eclipse HTML Editor Plugin, made by Amateras, which was exactly what I was looking for. A: There once existed a plugin called JSEclipse that Adobe has subsequently sucked up and killed by making it available only by purchasing and installing FlexBuilder 3 (please someone prove me wrong). I found it to worked excellent but have since lost it since "upgrading" from Eclipse 3.4 to 3.4.1. The feature I liked most was Content Outline. In the Outline window of your Eclipse Screen, JSEclipse lists all classes in the currently opened file. It provides an overview of the class hierarchy and also method and property names. The outline makes heavy use of the code completion engine to find out more about how the code is structured. By clicking on the function entry in the list the cursor will be taken to the function declaration helping you navigate faster in long files with lots of class and method definitions A: The new release of Eclipse (Helios) has an especific package for javascript web development. I haven't tried it yet, but it certainly worth a look. A: Disclaimer, I work at Aptana. I would point out there are some nice features for JS that you might not get so easily elsewhere. One is plugin-level integration of JS libraries that provide CodeAssist, samples, snippets and easy inclusion of the libraries files into your project; we provide the plugins for many of the more commonly used libraries, including YUI, jQuery, Prototype, dojo and EXT JS. Second, we have a server-side JavaScript engine called Jaxer that not only lets you run any of your JS code on the server but adds file, database and networking functionality so that you don't have to use a scripting language but can write the entire app in JS. A: Try the Vjet Javascript IDE from ebay (installation) A: Didn't use eclipse for a while, but there are ATF and Aptana. A: Oracle Workshop for WebLogic (formally BEA Workshop) has excellent support for JavaScript and for visually editing HTMLs. It support many servers, not only WebLogic, including Tomcat, JBoss, Resin, Jetty, and WebSphere. It recently became free, check out my post about it. Given that it was an expensive product not long ago, I guess it's worth checking out.
{ "language": "en", "url": "https://stackoverflow.com/questions/24678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "133" }
Q: Using Subversion with Visual Basic 6 My team is moving from Visual SourceSafe to Subversion soon, while developing/supporting a legacy project in Visual Basic 6.0, so I have a couple of questions: * *What's the best tool for Subversion IDE integration in Visual Studio 6? (or is it not worth the trouble...) *Are there any best practices for using Subversion with Visual Basic 6.0? (file types to ignore, etc.) A: Depending how much you're planning to do on these legacy projects I would consider not switching. I would really advise you to switch to SVN. I know of a few projects that lost source code because the VSS database became corrupted. I think there are tools that perform the migration from SourceSafe to SVN. (Yes-- a quick Google search confirmed it.) That way you wouldn't be losing the revision history. A: File types to ignore: *.vbw Workspace file that is automatically generated when you close a project, and contains which files you have open etc. MSSCCPRJ.SCC The source control status file generated by the VB6 IDE (if you go with the solution of controlling SVN in Windows Explorer, you should disable the source control plugin in VB6 and this will not be generated). *.log This is files generated if something goes wrong in loading a form GUI. The file is located in the same place as the form file with name equal to the form file. Example: MyForm.frm generates MyForm.log. You should of course only do this if you don't have log files that you need in source control... A: My guess would be to not bother with integration and just use Tortoise SVN in Windows Explorer. As for file types to ignore, give it a test, checkout, build, and see if any files changed (for modern Visual Studio I tend to ignore the .suo files) A: I would agree that Tortoise SVN in Windows Explorer would be the best way to use SVN with VB6. The biggest change you will find migrating to SVN is the idea of "Check out" and "Check in" aren't exactly the same as "Update" and "Commit". . . thus, any IDE integration with VB6 is limited because VB6 supports MSSCCI, a check-out/check-in mechanism. I once used TamTam SVN (http://www.daveswebsite.com/software/tamtamsvn/index.shtml) with Visual Studio 2003, but stopped since I found it limiting. Merging/branching/blaming, etc. are very powerful features Tortoise SVN provides that weren't in TamTam. Tigris also has http://svnvb6.tigris.org/, but I have not tried it. Again, while you quite possibly get an IDE to work with VB6, I would not recommend it since the greatest strength of migrating to SVN is to break the Source Safe philosophy of check-in/check-out. A: Since Subversion uses an update/edit/commit cycle (rather than checkin/checkout), you will need to be especially careful with binary files. Most forms in VB6 consist of two files: MyForm.frm and MyForm.frx. The *.frx files are binary, and thus cannot be merged. Given that, I would set up Subversion to require "locking" on .frx files. This means that only one person can check the file out at a time. By doing so, you will enforce that only one developer can modify these files at a time, and it is always clear who that person currently is. If you don't do this, you are setting yourself up for some major headaches. A: For the server side, VisualSVN Server, is a super simple solution, we are running it in a vmware virtual, and its humming along. If you are a command line guy, I really like the command line interface for svn, I find it less confusing to get to certain actions than tortoise, such as status of the folder. But if you are an explorer fan, tortoise is more than adequate, coming from a source safe world. The main things to ignore are: * *Reproducable artifacts (dll, pdb, exe) *Environment specific settings (i.e. the settings file for vs, csproj.user file, .suo files) A: Depending how much you're planning to do on these legacy projects I would consider not switching. When digging through legacy code it really helps to have all the history and blame. SVN is miles better than VSS, but you'll be losing the history when you switch. If you're going to be a lot of ongoing development in VB6 then it may well be worth switching to SVN, but if you're going to be doing that much going forward is it also worth reviewing the project? I have a similar problem, only the legacy projects are in Delphi. Were they in VB6 I think I would consider 'upgrading' them to VB.Net, just for maintainability.
{ "language": "en", "url": "https://stackoverflow.com/questions/24680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Where do I find information about Blog APIs and how to use them? I'm thinking of creating a small offline blog editor for personal use and I don't know how do the APIs work. Where can I find this information? I'm particularly looking for the most common providers: Blogger, Wordpress, MovableType, Live Spaces (not sure if this has an API) etc. A: See the following links: Blogger Wordpress Live Spaces A: The Blogger API link you provided says: This documentation is provided for historical interest only. The Blogger 1.0 API is no longer supported and must not be used for new client development. Please use our GData API instead. So the correct one probably is: http://code.google.com/apis/blogger/ Also, if more APIs are answered in this question, would you be kind enough to edit your answer to include them. Since I'm gonna vote it as the correct one. Thank you. A: MovableType API : http://www.sixapart.com/developers/xmlrpc/movable_type_api/ MetaWeblog API : http://www.xmlrpc.com/metaWeblogApi
{ "language": "en", "url": "https://stackoverflow.com/questions/24708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SQL many-to-many matching I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag. I'm looking to write a query to find the objects that match a given set of tags. Suppose I had the following data (in [object] -> [tags]* format) apple -> fruit red food banana -> fruit yellow food cheese -> yellow food firetruck -> vehicle red If I want to match (red), I should get apple and firetruck. If I want to match (fruit, food) I should get (apple, banana). How do I write a SQL query do do what I want? @Jeremy Ruten, Thanks for your answer. The notation used was used to give some sample data - my database does have a table with 1 object id and 1 tag per record. Second, my problem is that I need to get all objects that match all tags. Substituting your OR for an AND like so: SELECT object WHERE tag = 'fruit' AND tag = 'food'; Yields no results when run. A: Given: * *object table (primary key id) *objecttags table (foreign keys objectId, tagid) *tags table (primary key id) SELECT distinct o.* from object o join objecttags ot on o.Id = ot.objectid join tags t on ot.tagid = t.id where t.Name = 'fruit' or t.name = 'food'; This seems backwards, since you want and, but the issue is, 2 tags aren't on the same row, and therefore, an and yields nothing, since 1 single row cannot be both a fruit and a food. This query will yield duplicates usually, because you will get 1 row of each object, per tag. If you wish to really do an and in this case, you will need a group by, and a having count = <number of ors> in your query for example. SELECT distinct o.name, count(*) as count from object o join objecttags ot on o.Id = ot.objectid join tags t on ot.tagid = t.id where t.Name = 'fruit' or t.name = 'food' group by o.name having count = 2; A: Oh gosh I may have mis-interpreted your original comment. The easiest way to do this in SQL would be to have three tables: 1) Tags ( tag_id, name ) 2) Objects (whatever that is) 3) Object_Tag( tag_id, object_id ) Then you can ask virtually any question you want of the data quickly, easily, and efficiently (provided you index appropriately). If you want to get fancy, you can allow multi-word tags, too (there's an elegant way, and a less elegant way, I can think of). I assume that's what you've got, so this SQL below will work: The literal way: SELECT obj FROM object WHERE EXISTS( SELECT * FROM tags WHERE tag = 'fruit' AND oid = object_id ) AND EXISTS( SELECT * FROM tags WHERE tag = 'Apple' AND oid = object_id ) There are also other ways you can do it, such as: SELECT oid FROM tags WHERE tag = 'Apple' INTERSECT SELECT oid FROM tags WHERE tag = 'Fruit' A: @Kyle: Your query should be more like: SELECT object WHERE tag IN ('fruit', 'food'); Your query was looking for rows where the tag was both fruit AND food, which is impossible seeing as the field can only have one value, not both at the same time. A: Combine Steve M.'s suggestion with Jeremy's you'll get a single record with what you are looking for: select object from tblTags where tag = @firstMatch and ( @secondMatch is null or (object in (select object from tblTags where tag = @secondMatch) ) Now, that doesn't scale very well but it will get what you are looking for. I think there is a better way to go about doing this so you can easily have N number of matching items without a great deal of impact to the code but it currently escapes me. A: I recommend the following schema. Objects: objectID, objectName Tags: tagID, tagName ObjectTag: objectID,tagID With the following query. select distinct objectName from ObjectTab ot join object o on o.objectID = ot.objectID join tabs t on t.tagID = ot.tagID where tagName in ('red','fruit') A: I'd suggest making your table have 1 tag per record, like this: apple -> fruit apple -> red apple -> food banana -> fruit banana -> yellow banana -> food Then you could just SELECT object WHERE tag = 'fruit' OR tag = 'food'; If you really want to do it your way though, you could do it like this: SELECT object WHERE tag LIKE 'red' OR tag LIKE '% red' OR tag LIKE 'red %' OR tag LIKE '% red %';
{ "language": "en", "url": "https://stackoverflow.com/questions/24715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best regex to catch XSS (Cross-site Scripting) attack (in Java)? Jeff actually posted about this in Sanitize HTML. But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java? [Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is! (*) In fact, I think it was still in closed beta A: Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily. For example, see this list of obfuscated XSS attacks. Are you prepared to tailor a regex to prevent this real world attack on Yahoo and Hotmail on IE6/7/8? <HTML><BODY> <?xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time"> <?import namespace="t" implementation="#default#time2"> <t:set attributeName="innerHTML" to="XSS&lt;SCRIPT DEFER&gt;alert(&quot;XSS&quot;)&lt;/SCRIPT&gt;"> </BODY></HTML> How about this attack that works on IE6? <TABLE BACKGROUND="javascript:alert('XSS')"> How about attacks that are not listed on this site? The problem with Jeff's approach is that it's not a whitelist, as claimed. As someone on that page adeptly notes: The problem with it, is that the html must be clean. There are cases where you can pass in hacked html, and it won't match it, in which case it'll return the hacked html string as it won't match anything to replace. This isn't strictly whitelisting. I would suggest a purpose built tool like AntiSamy. It works by actually parsing the HTML, and then traversing the DOM and removing anything that's not in the configurable whitelist. The major difference is the ability to gracefully handle malformed HTML. The best part is that it actually unit tests for all the XSS attacks on the above site. Besides, what could be easier than this API call: public String toSafeHtml(String html) throws ScanException, PolicyException { Policy policy = Policy.getInstance(POLICY_FILE); AntiSamy antiSamy = new AntiSamy(); CleanResults cleanResults = antiSamy.scan(html, policy); return cleanResults.getCleanHTML().trim(); } A: I extracted from NoScript best Anti-XSS addon, here is its Regex: Work flawless: <[^\w<>]*(?:[^<>"'\s]*:)?[^\w<>]*(?:\W*s\W*c\W*r\W*i\W*p\W*t|\W*f\W*o\W*r\W*m|\W*s\W*t\W*y\W*l\W*e|\W*s\W*v\W*g|\W*m\W*a\W*r\W*q\W*u\W*e\W*e|(?:\W*l\W*i\W*n\W*k|\W*o\W*b\W*j\W*e\W*c\W*t|\W*e\W*m\W*b\W*e\W*d|\W*a\W*p\W*p\W*l\W*e\W*t|\W*p\W*a\W*r\W*a\W*m|\W*i?\W*f\W*r\W*a\W*m\W*e|\W*b\W*a\W*s\W*e|\W*b\W*o\W*d\W*y|\W*m\W*e\W*t\W*a|\W*i\W*m\W*a?\W*g\W*e?|\W*v\W*i\W*d\W*e\W*o|\W*a\W*u\W*d\W*i\W*o|\W*b\W*i\W*n\W*d\W*i\W*n\W*g\W*s|\W*s\W*e\W*t|\W*i\W*s\W*i\W*n\W*d\W*e\W*x|\W*a\W*n\W*i\W*m\W*a\W*t\W*e)[^>\w])|(?:<\w[\s\S]*[\s\0\/]|['"])(?:formaction|style|background|src|lowsrc|ping|on(?:d(?:e(?:vice(?:(?:orienta|mo)tion|proximity|found|light)|livery(?:success|error)|activate)|r(?:ag(?:e(?:n(?:ter|d)|xit)|(?:gestur|leav)e|start|drop|over)?|op)|i(?:s(?:c(?:hargingtimechange|onnect(?:ing|ed))|abled)|aling)|ata(?:setc(?:omplete|hanged)|(?:availabl|chang)e|error)|urationchange|ownloading|blclick)|Moz(?:M(?:agnifyGesture(?:Update|Start)?|ouse(?:PixelScroll|Hittest))|S(?:wipeGesture(?:Update|Start|End)?|crolledAreaChanged)|(?:(?:Press)?TapGestur|BeforeResiz)e|EdgeUI(?:C(?:omplet|ancel)|Start)ed|RotateGesture(?:Update|Start)?|A(?:udioAvailable|fterPaint))|c(?:o(?:m(?:p(?:osition(?:update|start|end)|lete)|mand(?:update)?)|n(?:t(?:rolselect|extmenu)|nect(?:ing|ed))|py)|a(?:(?:llschang|ch)ed|nplay(?:through)?|rdstatechange)|h(?:(?:arging(?:time)?ch)?ange|ecking)|(?:fstate|ell)change|u(?:echange|t)|l(?:ick|ose))|m(?:o(?:z(?:pointerlock(?:change|error)|(?:orientation|time)change|fullscreen(?:change|error)|network(?:down|up)load)|use(?:(?:lea|mo)ve|o(?:ver|ut)|enter|wheel|down|up)|ve(?:start|end)?)|essage|ark)|s(?:t(?:a(?:t(?:uschanged|echange)|lled|rt)|k(?:sessione|comma)nd|op)|e(?:ek(?:complete|ing|ed)|(?:lec(?:tstar)?)?t|n(?:ding|t))|u(?:ccess|spend|bmit)|peech(?:start|end)|ound(?:start|end)|croll|how)|b(?:e(?:for(?:e(?:(?:scriptexecu|activa)te|u(?:nload|pdate)|p(?:aste|rint)|c(?:opy|ut)|editfocus)|deactivate)|gin(?:Event)?)|oun(?:dary|ce)|l(?:ocked|ur)|roadcast|usy)|a(?:n(?:imation(?:iteration|start|end)|tennastatechange)|fter(?:(?:scriptexecu|upda)te|print)|udio(?:process|start|end)|d(?:apteradded|dtrack)|ctivate|lerting|bort)|DOM(?:Node(?:Inserted(?:IntoDocument)?|Removed(?:FromDocument)?)|(?:CharacterData|Subtree)Modified|A(?:ttrModified|ctivate)|Focus(?:Out|In)|MouseScroll)|r(?:e(?:s(?:u(?:m(?:ing|e)|lt)|ize|et)|adystatechange|pea(?:tEven)?t|movetrack|trieving|ceived)|ow(?:s(?:inserted|delete)|e(?:nter|xit))|atechange)|p(?:op(?:up(?:hid(?:den|ing)|show(?:ing|n))|state)|a(?:ge(?:hide|show)|(?:st|us)e|int)|ro(?:pertychange|gress)|lay(?:ing)?)|t(?:ouch(?:(?:lea|mo)ve|en(?:ter|d)|cancel|start)|ime(?:update|out)|ransitionend|ext)|u(?:s(?:erproximity|sdreceived)|p(?:gradeneeded|dateready)|n(?:derflow|load))|f(?:o(?:rm(?:change|input)|cus(?:out|in)?)|i(?:lterchange|nish)|ailed)|l(?:o(?:ad(?:e(?:d(?:meta)?data|nd)|start)?|secapture)|evelchange|y)|g(?:amepad(?:(?:dis)?connected|button(?:down|up)|axismove)|et)|e(?:n(?:d(?:Event|ed)?|abled|ter)|rror(?:update)?|mptied|xit)|i(?:cc(?:cardlockerror|infochange)|n(?:coming|valid|put))|o(?:(?:(?:ff|n)lin|bsolet)e|verflow(?:changed)?|pen)|SVG(?:(?:Unl|L)oad|Resize|Scroll|Abort|Error|Zoom)|h(?:e(?:adphoneschange|l[dp])|ashchange|olding)|v(?:o(?:lum|ic)e|ersion)change|w(?:a(?:it|rn)ing|heel)|key(?:press|down|up)|(?:AppComman|Loa)d|no(?:update|match)|Request|zoom))[\s\0]*= Test: http://regex101.com/r/rV7zK8 I think it block 99% XSS because it is a part of NoScript, a addon that get updated regularly A: I'm not to convinced that using a regular expression is the best way for finding all suspect code. Regular expressions are quite easy to trick specially when dealing with broken HTML. For example, the regular expression listed in the Sanitize HTML link will fail to remove all 'a' elements that have an attribute between the element name and the attribute 'href': < a alt="xss injection" href="http://www.malicous.com/bad.php" > A more robust way of removing malicious code is to rely on a XML Parser that can handle all kind of HTML documents (Tidy, TagSoup, etc) and to select the elements to remove with an XPath expression. Once the HTML document is parsed into a DOM document the elements to revome can be found easily and safely. This is even easy to do with XSLT. A: ^(\s|\w|\d|<br>)*?$ This will validate characters, digits, whitespaces and also the <br> tag. If you want more risk you can add more tags like ^(\s|\w|\d|<br>|<ul>|<\ul>)*?$ A: This question perfectly illustrates a great application of the study of Theory of Computation. Theory of Computation is a field that focuses on producing and studying mathematical representations for computation. Some of the most profound research in computation theory includes the proofs that illustrate the relationships of various languages. Some of the language relationships that computation theorists have proven include: This shows that context free languages are strictly more powerful than regular languages. Thus if a language is explicitly context-free (context-free and not regular), then it is impossible for any regular expression to recognize it. JavaScript is at the very least context-free, thus we know with one-hundred percent certainty that designing a regular expression (regex) capable of catching all XSS is a mathematically impossible task. A: The biggest problem by using jeffs code is the @ which currently isnt available. I would probably just take the "raw" regexp from jeffs code if i needed it and paste it into http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html and see the things needing escape get escaped and then use it. Taking the usage of this regex in mind I would personally make sure I understood exactly what I was doing, why and what consequences would be if I didnt succeed, before copy/pasting anything, like the other answers try to help you with. (Thats propbably pretty sound advice for any copy/paste) A: [\s\w\.]*. If it doesn't match, you've got XSS. Maybe. Take note that this expression only allows letters, numbers, and periods. It avoids all symbols, even useful ones, out of fear of XSS. Once you allow &, you've got worries. And merely replacing all instances of & with &amp; is not sufficient. Too complicated to trust :P. Obviously this will disallow a lot of legitimate text (You can just replace all nonmatching characters with a ! or something), but I think it will kill XSS. The idea to just parse it as html and generate new html is probably better. A: An old thread but maybe this will be useful for other users. There is a maintained security layer tool for php: https://github.com/PHPIDS/ It is based on a set of regex which you can find here: https://github.com/PHPIDS/PHPIDS/blob/master/lib/IDS/default_filter.xml A: For java, I used the following regular expression with replaceAll, and worked for me value.replaceAll("(?i)(\\b)(on\\S+)(\\s*)=|javascript:|(<\\s*)(\\/*)script|style(\\s*)=|(<\\s*)meta", ""); Added (?i) to ignore case for alphabets. A: public String validate(String value) { // Avoid anything between script tags Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything in a src='...' type of expression scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything in a src="..." type of expression scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything in a src=... type of expression added because quotes are not necessary scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*(.*?)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Remove any lonesome </script> tag scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Remove any lonesome <script ...> tag scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid eval(...) expressions scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid expression(...) expressions scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid javascript:... expressions scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid vbscript:... expressions scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid onload= expressions scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything between script tags added - paranoid regex. note: if testing local PREP this must be commented scriptPattern = Pattern.compile("<(.*?)[\r\n]*(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything between script tags added - paranoid regex scriptPattern = Pattern.compile("<script(.*?)[\r\n]*(.*?)/script>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything between * tags like *(alert)* added scriptPattern = Pattern.compile("\\*(.*?)[\r\n]*(.*?)\\*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything between + tags like +(alert)+ added scriptPattern = Pattern.compile("\\+(.*?)[\r\n]*(.*?)\\+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Prohibit lines containing = (...) added scriptPattern = Pattern.compile("=(.*?)\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // removing href link scriptPattern = Pattern.compile("(?i)<[\\s]*[/]?[\\s]*a[^>]*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); //Avoid alert scriptPattern = Pattern.compile("alert", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("[^\\dA-Za-z ]", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); return value; }
{ "language": "en", "url": "https://stackoverflow.com/questions/24723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: What is this 'Multiple-step OLE DB' error? I'm doing a little bit of work on a horrid piece of software built by Bangalores best. It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages :( I'm getting this message when it tries to connect to my local database: Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. Line 38: MasterConn = New ADODB.Connection() Line 39: MasterConn.connectiontimeout = 10000 Line 40: MasterConn.Open(strDB) Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string: PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true Which is the connection string that it was initially using, I just repointed it at my database. UPDATE: The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine. A: I ran into this a long time ago with working in ASP. I found this knowledge base article and it helped me out. I hope it solves your problem. http://support.microsoft.com/kb/269495 If this doesn't work and everything checks out, then it is probably your connection string. I would try these steps next: Remove: DRIVER={SQL Server}; Edit the Provider to this: Provider=SQLOLEDB; A: As a side note, connectionstrings.com is a great site so you don't have to remember all that connection string syntax. A: I came across this problem when trying to connect to an MySQL database via the wonderful Classic ASP. The solutions above didn't fix it directly, but I resolved it in the end by updating the ODBC Driver (from the long standing 3.51) to the latest version. I was then able to leave the driver line in (and not add the Provider bit), but I did have to update the connection string accordingly to: Driver={MySQL ODBC 5.1 Driver}; That worked fine. Happy chappy.
{ "language": "en", "url": "https://stackoverflow.com/questions/24730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Displaying version of underlying software in footer of web app? I am thinking about providing a version of say, the database schema and the dlls for business logic in the footer of my web application. Is this advised? Are there any pitfalls, or pointers of how to do this best? Usability concerns? I already have a version scheme, for both schema and dlls, used in my CI solution. A: I quite like what is done e.g. here. If you look towards the bottom of the page, there's a piece of text "powered by eve community". If you click that text you get a small chunk of technical information. To me, this is a nice tradeoff between having the (useful) information readily available (for bug reports, etc.) and having to have (unpleasant) technical jargon visible to users of the site. A: IMO, the only reasons to show version numbers are: * *To show progress is being made *To help bug reports be localized to the version they were discovered in So if these things are important for your bug reports, then expose them. If not, then don't. A: Don't do this. It gives away free information to a potential attacker and makes their job easier. If there are exploits known for your given version of the software, there's no need to tell them that. There are actually search engines built on top of Google who use this information incontinence to power massive exploits (e.g. cDc's Goolag scanner). Although this may sound like security by obscurity (because it is) it is still advisable to make an attacker's job as hard as possible. Not divulging implementation details is an important step. Of course, this can only ever be part of the effort to make a website securer.
{ "language": "en", "url": "https://stackoverflow.com/questions/24731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SelectNodes not working on stackoverflow feed I'm trying to add support for stackoverflow feeds in my rss reader but SelectNodes and SelectSingleNode have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet. I have gotten it to work by removing all attributes from the feed tag, but that's a hack and I would like to do it properly. So, how do you use SelectNodes with atom feeds? Here's a snippet of the feed. <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0"> <title type="html">StackOverflow.com - Questions tagged: c</title> <link rel="self" href="http://stackoverflow.com/feeds/tag/c" type="application/atom+xml" /> <subtitle>Check out the latest from StackOverflow.com</subtitle> <updated>2008-08-24T12:25:30Z</updated> <id>http://stackoverflow.com/feeds/tag/c</id> <creativeCommons:license>http://www.creativecommons.org/licenses/by-nc/2.5/rdf</creativeCommons:license> <entry> <id>http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server</id> <title type="html">What is the best way to communicate with a SQL server?</title> <category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c++" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="sql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="mysql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="database" /> <author><name>Ed</name></author> <link rel="alternate" href="http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server" /> <published>2008-08-22T05:09:04Z</published> <updated>2008-08-23T04:52:39Z</updated> <summary type="html">&lt;p&gt;I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?&lt;/p&gt;</summary> <link rel="replies" type="application/atom+xml" href="http://stackoverflow.com/feeds/question/22901/answers" thr:count="2"/> <thr:total>2</thr:total> </entry> </feed> The Solution XmlDocument doc = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom"); doc.Load(feed); // successful XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr); A: Don't confuse the namespace names in the XML file with the namespace names for your namespace manager. They're both shortcuts, and they don't necessarily have to match. So you can register "http://www.w3.org/2005/Atom" as "atom", and then do a SelectNodes for "atom:entry". A: You might need to add a XmlNamespaceManager. XmlDocument document = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); nsmgr.AddNamespace("creativeCommons", "http://backend.userland.com/creativeCommonsRssModule"); // AddNamespace for other namespaces too. document.Load(feed); It is needed if you want to call SelectNodes on a document that uses them. What error are you seeing? A: You've guessed correctly: you're asking for nodes not in a namespace, but these nodes are in a namespace. Description of the problem and solution: http://weblogs.asp.net/wallen/archive/2003/04/02/4725.aspx A: I just want to use.. XmlNodeList itemList = xmlDoc.DocumentElement.SelectNodes("entry"); but, what namespace do the entry tags fall under? I would assume xmlns="http://www.w3.org/2005/Atom", but it has no title so how would I add that namespace? XmlDocument document = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); nsmgr.AddNamespace("", "http://www.w3.org/2005/Atom"); document.Load(feed); Something like that?
{ "language": "en", "url": "https://stackoverflow.com/questions/24734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How do I write a Firefox Addon? What are some resources for getting started writing a Firefox Addon? Is there an API guide somewhere? Is there a getting started tutorial somewhere? Is there a developer discussion board somewhere? A: We tried to make https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions answer all those questions. The first three links in the documentation section are about getting started (that includes something like Adam's link, before it became stale). The newsgroup and the irc channel in the Community section are the official discussion boards. Mozilla is very complex, so any kind of API guide would be overwhelming and hard to write. So your best bet is to check the code snippets page (also linked from the MDC Extensions page), then search MDC/google, then ask in the forums. A: This is a great resource to start learning how to build a FireFox extension: How to create Firefox extensions This is an awesome tutorial and will covers most type of extensions. Edit: Updated link to use archived copy since original page no longer exists A: The official page listed above is good, but this is the most useful page I have found to get started: http://blog.mozilla.com/addons/2009/01/28/how-to-develop-a-firefox-extension/ More recent official post And I found starting with an extension generated from the Add-on Builder to be a great start also. You go right to tweaking JavaScript and seeing what happens: https://addons.mozilla.org/en-US/developers/tools/builder You are also really going to want to be able to debug, you have two choices for that: ChromeBug - Which gives you FireBug for Firefox Extensions. WebStorm, but you need to use the early-access version and it currently requires a patch I wrote. A: Here's the official starter page from Mozilla for writing your first extension. https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension A: This has the best solutions: https://developer.mozilla.org/en/Extensions but you can try greasemonkey script compiler A: I found greasemonkey to be a great starting point... I used it to create some functionality for a site, then I used this script compiler to turn my script into a working add-on. Of course it's machine generated... but it's very few files and pretty easy to understand. Just unzip the .xpi and tinker away.
{ "language": "en", "url": "https://stackoverflow.com/questions/24772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "145" }
Q: Effectively Converting dates between UTC and Local (ie. PST) time in SQL 2005 What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is. CLR integration isn't an option for me either. The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup) A: FOR READ-ONLY Use this(inspired by Bob Albright's incorrect solution ): SELECT date1, dateadd(hh, -- The schedule through 2006 in the United States was that DST began on the first Sunday in April -- (April 2, 2006), and changed back to standard time on the last Sunday in October (October 29, 2006). -- The time is adjusted at 02:00 local time (which, for edt, is 07:00 UTC at the start, and 06:00 GMT at the end). CASE WHEN YEAR(date1) <= 2006 THEN CASE WHEN date1 >= '4/' + CAST((8-DATEPART(dw,'4/1/' + CAST(YEAR(date1) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 7:00' AND date1 < '10/' + CAST(32-DATEPART(dw,'10/31/' + CAST(YEAR(date1) as varchar)) as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 6:00' THEN -4 ELSE -5 END ELSE -- By the Energy Policy Act of 2005, daylight saving time (DST) was extended in the United States in 2007. -- DST starts on the second Sunday of March, which is three weeks earlier than in the past, and it ends on -- the first Sunday of November, one week later than in years past. This change resulted in a new DST period -- that is four weeks (five in years when March has five Sundays) longer than in previous years. In 2008 -- daylight saving time ended at 02:00 edt (06:00 UTC) on Sunday, November 2, and in 2009 it began at 02:00 edt (07:00 UTC) on Sunday, March 8 CASE WHEN date1 >= '3/' + CAST((8-DATEPART(dw,'3/1/' + CAST(YEAR(date1) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 7:00' AND date1 < '11/' + CAST((8-DATEPART(dw,'11/1/' + CAST(YEAR(date1) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 6:00' THEN -4 ELSE -5 END END , date1) as date1Edt from MyTbl I posted this answer after I tried to edit Bob Albright's wrong answer. I corrected the times and removed superfluous abs(), but my edits were rejected multiple times. I tried explaining, but was dismissed as a noob. His is a GREAT approach to the problem! It got me started in the right direction. I hate to create this separate answer when his just needs a minor tweak, but I tried ¯\_(ツ)_/¯ A: A much simpler and generic solution that considers daylight savings. Given an UTC date in "YourDateHere": --Use Minutes ("MI") here instead of hours because sometimes -- the UTC offset may be half an hour (e.g. 9.5 hours). SELECT DATEADD(MI, DATEDIFF(MI, SYSUTCDATETIME(),SYSDATETIME()), YourUtcDateHere)[LocalDateTime] A: If either of these issues affects you, you should never store local times in the database: * *With DST is that there is an "hour of uncertainty" around the falling back period where a local time cannot be unambiguously converted. If exact dates & times are required, then store in UTC. *If you want to show users the date & time in their own timezone, rather than the timezone in which the action took place, store in UTC. A: In Eric Z Beard's answer, the following SQL inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId left join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone and x.TheDateToConvert between ds.BeginDst and ds.EndDst might more accurately be: inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId left join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone and x.TheDateToConvert >= ds.BeginDst and x.TheDateToConvert < ds.EndDst (above code not tested) The reason for this is that the sql "between" statement is inclusive. On the back-end of DST, this would result in a 2AM time NOT being converted to 1AM. Of course the likelihood of the time being 2AM precisely is small, but it can happen, and it would result in an invalid conversion. A: Create two tables and then join to them to convert stored GMT dates to local time: TimeZones e.g. --------- ---- TimeZoneId 19 Name Eastern (GMT -5) Offset -5 Create the daylight savings table and populate it with as much information as you can (local laws change all the time so there's no way to predict what the data will look like years in the future) DaylightSavings --------------- TimeZoneId 19 BeginDst 3/9/2008 2:00 AM EndDst 11/2/2008 2:00 AM Join them like this: inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId left join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone and x.TheDateToConvert between ds.BeginDst and ds.EndDst Convert dates like this: dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, TheDateToConvert) A: If you're in the US and only interested in going from UTC/GMT to a fixed time zone (such as EDT) this code should suffice. I whipped it up today and believe it's correct but use at your own risk. Adds a computed column to a table 'myTable' assuming your dates are on the 'date' column. Hope someone else finds this useful. ALTER TABLE myTable ADD date_edt AS dateadd(hh, -- The schedule through 2006 in the United States was that DST began on the first Sunday in April -- (April 2, 2006), and changed back to standard time on the last Sunday in October (October 29, 2006). -- The time is adjusted at 02:00 local time. CASE WHEN YEAR(date) <= 2006 THEN CASE WHEN date >= '4/' + CAST(abs(8-DATEPART(dw,'4/1/' + CAST(YEAR(date) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' AND date < '10/' + CAST(32-DATEPART(dw,'10/31/' + CAST(YEAR(date) as varchar)) as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' THEN -4 ELSE -5 END ELSE -- By the Energy Policy Act of 2005, daylight saving time (DST) was extended in the United States in 2007. -- DST starts on the second Sunday of March, which is three weeks earlier than in the past, and it ends on -- the first Sunday of November, one week later than in years past. This change resulted in a new DST period -- that is four weeks (five in years when March has five Sundays) longer than in previous years.[35] In 2008 -- daylight saving time ended at 02:00 on Sunday, November 2, and in 2009 it began at 02:00 on Sunday, March 8.[36] CASE WHEN date >= '3/' + CAST(abs(8-DATEPART(dw,'3/1/' + CAST(YEAR(date) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' AND date < '11/' + CAST(abs(8-DATEPART(dw,'11/1/' + CAST(YEAR(date) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' THEN -4 ELSE -5 END END ,date) A: Maintain a TimeZone table, or shell out with an extended stored proc (xp_cmdshell or a COM component, or your own) and ask the OS to do it. If you go the xp route, you'd probably want to cache the offset for a day. A: I like the answer @Eric Z Beard provided. However, to avoid performing a join everytime, what about this? TimeZoneOffsets --------------- TimeZoneId 19 Begin 1/4/2008 2:00 AM End 1/9/2008 2:00 AM Offset -5 TimeZoneId 19 Begin 1/9/2008 2:00 AM End 1/4/2009 2:00 AM Offset -6 TimeZoneId 20 --Hong Kong for example - no DST Begin 1/1/1900 End 31/12/9999 Offset +8 Then Declare @offset INT = (Select IsNull(tz.Offset,0) from YourTable ds join TimeZoneOffsets tz on tz.TimeZoneId=ds.LocalTimeZoneId and x.TheDateToConvert >= ds.Begin and x.TheDateToConvert < ds.End) finally becoming dateadd(hh, @offset, TheDateToConvert) A: I've read through a lot of StackOverflow posts in regards to this issue and found many methods. Some "sort of" ok. I also found this MS reference (https://msdn.microsoft.com/en-us/library/mt612795.aspx) which I tried to utilize in my script. I have managed to achieve the required result BUT I am not sure if this will run on 2005 version. Either way, I hope this helps. Fnc to return PST from the system UTC default CREATE FUNCTION dbo.GetPst() RETURNS DATETIME AS BEGIN RETURN SYSDATETIMEOFFSET() AT TIME ZONE 'Pacific Standard Time' END SELECT dbo.GetPst() Fnc to return PST from the provided timestamp CREATE FUNCTION dbo.ConvertUtcToPst(@utcTime DATETIME) RETURNS DATETIME AS BEGIN RETURN DATEADD(HOUR, 0 - DATEDIFF(HOUR, CAST(SYSDATETIMEOFFSET() AT TIME ZONE 'Pacific Standard Time' AS DATETIME), SYSDATETIME()), @utcTime) END SELECT dbo.ConvertUtcToPst('2016-04-25 22:50:01.900') A: I am using this because all of my dates are from now forward. DATEADD(HH,(DATEPART(HOUR, GETUTCDATE())-DATEPART(HOUR, GETDATE()))*-1, GETDATE()) For historical dates (or to handle future changes in DST, I'm guessing Bob Albright's solution would be the way to go. The modification I make to my code is to use the target column: DATEADD(HH,(DATEPART(HOUR, GETUTCDATE())-DATEPART(HOUR, GETDATE()))*-1, [MySourceColumn]) So far, this seems to work, but I'm happy to receive feedback. A: Here is the code I use to make my timezone table. It's a bit naive, but is usually good enough. Assumptions: * *It assumes US only rules (DST is 2AM on some pre-defined Sunday, etc). *It assumes you don't have dates prior to 1970 *It assumes you know the local timezone offsets (i.e.: EST=-05:00, EDT=-04:00, etc.) Here's the SQL: -- make a table (#dst) of years 1970-2101. Note that DST could change in the future and -- everything was all custom and jacked before 1970 in the US. declare @first_year varchar(4) = '1970' declare @last_year varchar(4) = '2101' -- make a table of all the years desired if object_id('tempdb..#years') is not null drop table #years ;with cte as ( select cast(@first_year as int) as int_year ,@first_year as str_year ,cast(@first_year + '-01-01' as datetime) as start_of_year union all select int_year + 1 ,cast(int_year + 1 as varchar(4)) ,dateadd(year, 1, start_of_year) from cte where int_year + 1 <= @last_year ) select * into #years from cte option (maxrecursion 500); -- make a staging table of all the important DST dates each year if object_id('tempdb..#dst_stage') is not null drop table #dst_stage select dst_date ,time_period ,int_year ,row_number() over (order by dst_date) as ordinal into #dst_stage from ( -- start of year select y.start_of_year as dst_date ,'start of year' as time_period ,int_year from #years y union all select dateadd(year, 1, y.start_of_year) ,'start of year' as time_period ,int_year from #years y where y.str_year = @last_year -- start of dst union all select case when y.int_year >= 2007 then -- second sunday in march dateadd(day, ((7 - datepart(weekday, y.str_year + '-03-08')) + 1) % 7, y.str_year + '-03-08') when y.int_year between 1987 and 2006 then -- first sunday in april dateadd(day, ((7 - datepart(weekday, y.str_year + '-04-01')) + 1) % 7, y.str_year + '-04-01') when y.int_year = 1974 then -- special case cast('1974-01-06' as datetime) when y.int_year = 1975 then -- special case cast('1975-02-23' as datetime) else -- last sunday in april dateadd(day, ((7 - datepart(weekday, y.str_year + '-04-24')) + 1) % 7, y.str_year + '-04-24') end ,'start of dst' as time_period ,int_year from #years y -- end of dst union all select case when y.int_year >= 2007 then -- first sunday in november dateadd(day, ((7 - datepart(weekday, y.str_year + '-11-01')) + 1) % 7, y.str_year + '-11-01') else -- last sunday in october dateadd(day, ((7 - datepart(weekday, y.str_year + '-10-25')) + 1) % 7, y.str_year + '-10-25') end ,'end of dst' as time_period ,int_year from #years y ) y order by 1 -- assemble a final table if object_id('tempdb..#dst') is not null drop table #dst select a.dst_date + case when a.time_period = 'start of dst' then ' 03:00' when a.time_period = 'end of dst' then ' 02:00' else ' 00:00' end as start_date ,b.dst_date + case when b.time_period = 'start of dst' then ' 02:00' when b.time_period = 'end of dst' then ' 01:00' else ' 00:00' end as end_date ,cast(case when a.time_period = 'start of dst' then 1 else 0 end as bit) as is_dst ,cast(0 as bit) as is_ambiguous ,cast(0 as bit) as is_invalid into #dst from #dst_stage a join #dst_stage b on a.ordinal + 1 = b.ordinal union all select a.dst_date + ' 02:00' as start_date ,a.dst_date + ' 03:00' as end_date ,cast(1 as bit) as is_dst ,cast(0 as bit) as is_ambiguous ,cast(1 as bit) as is_invalid from #dst_stage a where a.time_period = 'start of dst' union all select a.dst_date + ' 01:00' as start_date ,a.dst_date + ' 02:00' as end_date ,cast(0 as bit) as is_dst ,cast(1 as bit) as is_ambiguous ,cast(0 as bit) as is_invalid from #dst_stage a where a.time_period = 'end of dst' order by 1 ------------------------------------------------------------------------------- -- Test Eastern select the_date as eastern_local ,todatetimeoffset(the_date, case when b.is_dst = 1 then '-04:00' else '-05:00' end) as eastern_local_tz ,switchoffset(todatetimeoffset(the_date, case when b.is_dst = 1 then '-04:00' else '-05:00' end), '+00:00') as utc_tz --,b.* from ( select cast('2015-03-08' as datetime) as the_date union all select cast('2015-03-08 02:30' as datetime) as the_date union all select cast('2015-03-08 13:00' as datetime) as the_date union all select cast('2015-11-01 01:30' as datetime) as the_date union all select cast('2015-11-01 03:00' as datetime) as the_date ) a left join #dst b on b.start_date <= a.the_date and a.the_date < b.end_date A: --Adapted Bob Albright and WillDeStijl suggestions for SQL server 2014 -- --In this instance I had no dates prior to 2006, therefore I simplified the case example --I had to add the variables for the assignment to allow trimming the timestamp from my resultset DECLARE @MARCH_DST as DATETIME SET @MARCH_DST='3/' + CAST((8-DATEPART(dw,'3/1/' + CAST(YEAR(getdate()) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(getdate()) as varchar) + ' 7:00' DECLARE @NOV_DST as DATETIME SET @NOV_DST='11/' + CAST((8-DATEPART(dw,'11/1/' + CAST(YEAR(getdate()) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(getdate()) as varchar) + ' 6:00' select cast(dateadd(HOUR, -- By the Energy Policy Act of 2005, daylight saving time (DST) was extended in the United States in 2007. -- DST starts on the second Sunday of March, which is three weeks earlier than in the past, and it ends on -- the first Sunday of November, one week later than in years past. This change resulted in a new DST period -- that is four weeks (five in years when March has five Sundays) longer than in previous years. In 2008 -- daylight saving time ended at 02:00 edt (06:00 UTC) on Sunday, November 2, and in 2009 it began at 02:00 edt (07:00 UTC) on Sunday, March 8 CASE WHEN date1 >=@MARCH_DST AND date1< @NOV_DST THEN -4 ELSE -5 END , date1) as DATE) as date1_edited A: I found Simple Way to convert any date to any timezone. Currently i have changed date to India Standard Time DECLARE @SqlServerTimeZone VARCHAR(50) DECLARE @LocalTimeZone VARCHAR(50)='India Standard Time' EXEC MASTER.dbo.xp_regread 'HKEY_LOCAL_MACHINE', 'SYSTEM\CurrentControlSet\Control\TimeZoneInformation', 'TimeZoneKeyName',@SqlServerTimeZone OUT DECLARE @DateToConvert datetime= GetDate() SELECT LocalDate = @DateToConvert AT TIME ZONE @SqlServerTimeZone AT TIME ZONE @LocalTimeZone
{ "language": "en", "url": "https://stackoverflow.com/questions/24797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Recommendations needed for good AI references I've been asked to help out on an XNA project with the AI. I'm not totally new to the concepts (pathfinding, flocking, etc.) but this would be the first "real" code. I'd be very thankful for any resources (links or books); I want to make sure I do this right. A: These links might be useful to check out, for a beginning (even if most are mostly game-oriented): http://www.a-i.com http://www.kynogon.com http://openai.sourceforge.net http://www.botspot.com http://aigamedev.com http://www.aiwisdom.com http://igda.org/ai/ http://gamedev.net and http://www.gameai.com, who has already been mentioned.. A: I was surprised not to find in the above answers any of the books I though of so here goes, the books that any development team in a game studio will always have: * *Game Programming Gems (there are 7 books by now). *AI programming Wisdom (I think 4 are out). Both series are combined of many very useful articles and browsing through the first two of each series (the game programming gems have AI chapters which includes several very good articles) will give you nice understanding of both basic and advanced techniques used currently in the game industry. BTW - you can also gain understanding in other areas like data structures, effects, 3D and sound. Enjoy the reading, A: I have to comment that AI: A modern approach is a pretty dry read. If you're actually interested in AI, and want to stay interested, you are much better off going with Norvig's gift to the world: Paradigms of Artificial Intelligence Programming. Not only is this a great intro to AI, it's a great intro to beautiful programming. A: I second "Artificial Intelligence: A modern Approach". It is really good at explaining the items in a basic, understandable manner. It's also a book that is used in many universities to teach students the basics of artificial intelligence. Maybe it is not such a bad idea to take also take a look at the slides they use in the courses, to get a basic idea on the topics at hand. A: There's an XNA specific tutorial on flocking. A: You might find the blog, wiki and forums on AiGameDev.com useful. A: Russel and Norvig's Artificial Intelligence: A Modern Approach. Be warned, this book is a bit of a door step. Very detailed and generally very good. I would probably recommend some of the online sites first to get a flavour for the types of algorithms you might need and then selectivly dive into Russel and Norvig to get a more in depth view of the implementation. Dont forget the usefulness of online forurms such as this or aigamedev.com as I used these extensivly throughout my own AI degree. You might also find that you need to buy a specific game AI book to help with some game logic as this can be substantially different from AI 'application' logic. In game scenarios I think you're generally lucky if you get ~5-10% of the processing time whereas in an application the AI is generally the only thing running and this allows for much more advanced and processor heavy techniques. This is also something that you might need to consider and Im not entirely sure that Russel & Norvig is the best place. Good luck with the project, I wish I was in your shoes! A: Two references of interest should be * *Artificial Intelligence for games (Ian Millington) *Programming Game AI by example (Matt Buckland) I second the reference to the AI forum at gamedev.net. particularly because some of the key posters on that forum work in the industry (including the writer of AiGameDev.com), or use AI & related techniques like planning and optimisation in practical domains. A: Amit's A* Pages are extremely helpful in writing pathfinding code. Lots of meaty theoretical and practical info there. A: The standard textbook and a great place to start is Russel and Norvig's Artificial Intelligence: A Modern Approach. You can also get MIT's Intro AI course via OpenCourseWare A: I've always found Steve Woodcock's Game AI site to be a great reference. It includes discussion, source code, and pointers to books, conferences, etc. A: I would second: Programming Game AI by example (Matt Buckland) This book gives great algorithms that should easly port to XNA. A: I just read some excerpts from AI a modern approach, mostly because I'm interested in the matter, not because I could actually use it. AI a modern approach is quite good, it's well written and really interesting, however I don't know if you can use it, maybe not if you are more looking for code samples..
{ "language": "en", "url": "https://stackoverflow.com/questions/24812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Automating MSI Build Process Does anyone have a good way to build MSI (vdproj) projects using MsBuild or Nant? I know one answer was to install Visual Studio on the build server and just use devenv.exe to build the project, but, I prefer not to install Visual Studio on our build servers. A: Short of the method you mentioned above (devenv), there is no way to do this with the current version of MSBuild. The method the Visual Studio team uses to run their MSI builds is with Windows Installer XML. You can learn more about using WiX to deploy setup packages here. Please note WiX doesn't support vdproj files so it means you'll be recreating your installer projects. Edit: Looks like I was beat to the chase when grabbing my references :) A: We use Wix to automate MSI builds for IronPython and IronRuby. EDIT: to clarify, this probably means starting over from scratch when building your installer. While Wix has a mechanism to create a configuration directly from a preexisting MSI file, I've never gotten a satisfactory result from using this tool
{ "language": "en", "url": "https://stackoverflow.com/questions/24813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Escaping HTML strings with jQuery Does anyone know of an easy way to escape HTML from strings in jQuery? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this. A: There is also the solution from mustache.js var entityMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '/': '&#x2F;', '`': '&#x60;', '=': '&#x3D;' }; function escapeHtml (string) { return String(string).replace(/[&<>"'`=\/]/g, function (s) { return entityMap[s]; }); } A: If you're escaping for HTML, there are only three that I can think of that would be really necessary: html.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); Depending on your use case, you might also need to do things like " to &quot;. If the list got big enough, I'd just use an array: var escaped = html; var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]] for(var item in findReplace) escaped = escaped.replace(findReplace[item][0], findReplace[item][1]); encodeURIComponent() will only escape it for URLs, not for HTML. A: If your're going the regex route, there's an error in tghw's example above. <!-- WON'T WORK - item[0] is an index, not an item --> var escaped = html; var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g,"&gt;"], [/"/g, "&quot;"]] for(var item in findReplace) { escaped = escaped.replace(item[0], item[1]); } <!-- WORKS - findReplace[item[]] correctly references contents --> var escaped = html; var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]] for(var item in findReplace) { escaped = escaped.replace(findReplace[item[0]], findReplace[item[1]]); } A: This is a nice safe example... function escapeHtml(str) { if (typeof(str) == "string"){ try{ var newStr = ""; var nextCode = 0; for (var i = 0;i < str.length;i++){ nextCode = str.charCodeAt(i); if (nextCode > 0 && nextCode < 128){ newStr += "&#"+nextCode+";"; } else{ newStr += "?"; } } return newStr; } catch(err){ } } else{ return str; } } A: Since you're using jQuery, you can just set the element's text property: // before: // <div class="someClass">text</div> var someHtmlString = "<script>alert('hi!');</script>"; // set a DIV's text: $("div.someClass").text(someHtmlString); // after: // <div class="someClass">&lt;script&gt;alert('hi!');&lt;/script&gt;</div> // get the text in a string: var escaped = $("<div>").text(someHtmlString).html(); // value: // &lt;script&gt;alert('hi!');&lt;/script&gt; A: Easy enough to use underscore: _.escape(string) Underscore is a utility library that provides a lot of features that native js doesn't provide. There's also lodash which is the same API as underscore but was rewritten to be more performant. A: I wrote a tiny little function which does this. It only escapes ", &, < and > (but usually that's all you need anyway). It is slightly more elegant then the earlier proposed solutions in that it only uses one .replace() to do all the conversion. (EDIT 2: Reduced code complexity making the function even smaller and neater, if you're curious about the original code see end of this answer.) function escapeHtml(text) { 'use strict'; return text.replace(/[\"&<>]/g, function (a) { return { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' }[a]; }); } This is plain Javascript, no jQuery used. Escaping / and ' too Edit in response to mklement's comment. The above function can easily be expanded to include any character. To specify more characters to escape, simply insert them both in the character class in the regular expression (i.e. inside the /[...]/g) and as an entry in the chr object. (EDIT 2: Shortened this function too, in the same way.) function escapeHtml(text) { 'use strict'; return text.replace(/[\"&'\/<>]/g, function (a) { return { '"': '&quot;', '&': '&amp;', "'": '&#39;', '/': '&#47;', '<': '&lt;', '>': '&gt;' }[a]; }); } Note the above use of &#39; for apostrophe (the symbolic entity &apos; might have been used instead – it is defined in XML, but was originally not included in the HTML spec and might therefore not be supported by all browsers. See: Wikipedia article on HTML character encodings). I also recall reading somewhere that using decimal entities is more widely supported than using hexadecimal, but I can't seem to find the source for that now though. (And there cannot be many browsers out there which does not support the hexadecimal entities.) Note: Adding / and ' to the list of escaped characters isn't all that useful, since they do not have any special meaning in HTML and do not need to be escaped. Original escapeHtml Function EDIT 2: The original function used a variable (chr) to store the object needed for the .replace() callback. This variable also needed an extra anonymous function to scope it, making the function (needlessly) a little bit bigger and more complex. var escapeHtml = (function () { 'use strict'; var chr = { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' }; return function (text) { return text.replace(/[\"&<>]/g, function (a) { return chr[a]; }); }; }()); I haven't tested which of the two versions are faster. If you do, feel free to add info and links about it here. A: I realize how late I am to this party, but I have a very easy solution that does not require jQuery. escaped = new Option(unescaped).innerHTML; Edit: This does not escape quotes. The only case where quotes would need to be escaped is if the content is going to be pasted inline to an attribute within an HTML string. It is hard for me to imagine a case where doing this would be good design. Edit 3: For the fastest solution, check the answer above from Saram. This one is the shortest. A: Here is a clean, clear JavaScript function. It will escape text such as "a few < many" into "a few &lt; many". function escapeHtmlEntities (str) { if (typeof jQuery !== 'undefined') { // Create an empty div to use as a container, // then put the raw text in and get the HTML // equivalent out. return jQuery('<div/>').text(str).html(); } // No jQuery, so use string replace. return str .replace(/&/g, '&amp;') .replace(/>/g, '&gt;') .replace(/</g, '&lt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); } A: After last tests I can recommend fastest and completely cross browser compatible native javaScript (DOM) solution: function HTMLescape(html){ return document.createElement('div') .appendChild(document.createTextNode(html)) .parentNode .innerHTML } If you repeat it many times you can do it with once prepared variables: //prepare variables var DOMtext = document.createTextNode("test"); var DOMnative = document.createElement("span"); DOMnative.appendChild(DOMtext); //main work for each case function HTMLescape(html){ DOMtext.nodeValue = html; return DOMnative.innerHTML } Look at my final performance comparison (stack question). A: You can easily do it with vanilla js. Simply add a text node the document. It will be escaped by the browser. var escaped = document.createTextNode("<HTML TO/ESCAPE/>") document.getElementById("[PARENT_NODE]").appendChild(escaped) A: 2 simple methods that require NO JQUERY... You can encode all characters in your string like this: function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})} Or just target the main characters to worry about &, line breaks, <, >, " and ' like: function encode(r){ return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"}) } var myString='Encode HTML entities!\n"Safe" escape <script></'+'script> & other tags!'; test.value=encode(myString); testing.innerHTML=encode(myString); /************* * \x26 is &ampersand (it has to be first), * \x0A is newline, *************/ <p><b>What JavaScript Generated:</b></p> <textarea id=test rows="3" cols="55"></textarea> <p><b>What It Renders Too In HTML:</b></p> <div id="testing">www.WHAK.com</div> A: Plain JavaScript escaping example: function escapeHtml(text) { var div = document.createElement('div'); div.innerText = text; return div.innerHTML; } escapeHtml("<script>alert('hi!');</script>") // "&lt;script&gt;alert('hi!');&lt;/script&gt;" A: Try Underscore.string lib, it works with jQuery. _.str.escapeHTML('<div>Blah blah blah</div>') output: '&lt;div&gt;Blah blah blah&lt;/div&gt;' A: (function(undefined){ var charsToReplace = { '&': '&amp;', '<': '&lt;', '>': '&gt;' }; var replaceReg = new RegExp("[" + Object.keys(charsToReplace).join("") + "]", "g"); var replaceFn = function(tag){ return charsToReplace[tag] || tag; }; var replaceRegF = function(replaceMap) { return (new RegExp("[" + Object.keys(charsToReplace).concat(Object.keys(replaceMap)).join("") + "]", "gi")); }; var replaceFnF = function(replaceMap) { return function(tag){ return replaceMap[tag] || charsToReplace[tag] || tag; }; }; String.prototype.htmlEscape = function(replaceMap) { if (replaceMap === undefined) return this.replace(replaceReg, replaceFn); return this.replace(replaceRegF(replaceMap), replaceFnF(replaceMap)); }; })(); No global variables, some memory optimization. Usage: "some<tag>and&symbol©".htmlEscape({'©': '&copy;'}) result is: "some&lt;tag&gt;and&amp;symbol&copy;" A: ES6 one liner for the solution from mustache.js const escapeHTML = str => (str+'').replace(/[&<>"'`=\/]/g, s => ({'&': '&amp;','<': '&lt;','>': '&gt;','"': '&quot;',"'": '&#39;','/': '&#x2F;','`': '&#x60;','=': '&#x3D;'})[s]); A: $('<div/>').text('This is fun & stuff').html(); // "This is fun &amp; stuff" Source: http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb A: escape() and unescape() are intended to encode / decode strings for URLs, not HTML. Actually, I use the following snippet to do the trick that doesn't require any framework: var escapedHtml = html.replace(/&/g, '&amp;') .replace(/>/g, '&gt;') .replace(/</g, '&lt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); A: I've enhanced the mustache.js example adding the escapeHTML() method to the string object. var __entityMap = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': '&quot;', "'": '&#39;', "/": '&#x2F;' }; String.prototype.escapeHTML = function() { return String(this).replace(/[&<>"'\/]/g, function (s) { return __entityMap[s]; }); } That way it is quite easy to use "Some <text>, more Text&Text".escapeHTML() A: If you have underscore.js, use _.escape (more efficient than the jQuery method posted above): _.escape('Curly, Larry & Moe'); // returns: Curly, Larry &amp; Moe A: function htmlEscape(str) { var stringval=""; $.each(str, function (i, element) { alert(element); stringval += element .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(' ', '-') .replace('?', '-') .replace(':', '-') .replace('|', '-') .replace('.', '-'); }); alert(stringval); return String(stringval); } A: function htmlDecode(t){ if (t) return $('<div />').html(t).text(); } works like a charm A: A speed-optimized version: function escapeHtml(s) { let out = ""; let p2 = 0; for (let p = 0; p < s.length; p++) { let r; switch (s.charCodeAt(p)) { case 34: r = "&quot;"; break; // " case 38: r = "&amp;" ; break; // & case 39: r = "&#39;" ; break; // ' case 60: r = '&lt;' ; break; // < case 62: r = '&gt;' ; break; // > default: continue; } if (p2 < p) { out += s.substring(p2, p); } out += r; p2 = p + 1; } if (p2 == 0) { return s; } if (p2 < s.length) { out += s.substring(p2); } return out; } const s = "Hello <World>!"; document.write(escapeHtml(s)); console.log(escapeHtml(s)); A: For escape html specials (UTF-8) function htmlEscape(str) { return str .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/\//g, '&#x2F;') .replace(/=/g, '&#x3D;') .replace(/`/g, '&#x60;'); } For unescape html specials (UTF-8) function htmlUnescape(str) { return str .replace(/&amp;/g, '&') .replace(/&quot;/g, '"') .replace(/&#39;/g, "'") .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&#x2F/g, '/') .replace(/&#x3D;/g, '=') .replace(/&#x60;/g, '`'); } A: If you are saving this information in a database, its wrong to escape HTML using a client-side script, this should be done in the server. Otherwise its easy to bypass your XSS protection. To make my point clear, here is a exemple using one of the answers: Lets say you are using the function escapeHtml to escape the Html from a comment in your blog and then posting it to your server. var entityMap = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': '&quot;', "'": '&#39;', "/": '&#x2F;' }; function escapeHtml(string) { return String(string).replace(/[&<>"'\/]/g, function (s) { return entityMap[s]; }); } The user could: * *Edit the POST request parameters and replace the comment with javascript code. *Overwrite the escapeHtml function using the browser console. If the user paste this snippet in the console it would bypass the XSS validation: function escapeHtml(string){ return string } A: This answer provides the jQuery and normal JS methods, but this is shortest without using the DOM: unescape(escape("It's > 20% less complicated this way.")) Escaped string: It%27s%20%3E%2020%25%20less%20complicated%20this%20way. If the escaped spaces bother you, try: unescape(escape("It's > 20% less complicated this way.").replace(/%20/g, " ")) Escaped string: It%27s %3E 20%25 less complicated this way. Unfortunately, the escape() function was deprecated in JavaScript version 1.5. encodeURI() or encodeURIComponent() are alternatives, but they ignore ', so the last line of code would turn into this: decodeURI(encodeURI("It's > 20% less complicated this way.").replace(/%20/g, " ").replace("'", '%27')) All major browsers still support the short code, and given the number of old websites, i doubt that will change soon. A: All solutions are useless if you dont prevent re-escape, e.g. most solutions would keep escaping & to &amp;. escapeHtml = function (s) { return s ? s.replace( /[&<>'"]/g, function (c, offset, str) { if (c === "&") { var substr = str.substring(offset, offset + 6); if (/&(amp|lt|gt|apos|quot);/.test(substr)) { // already escaped, do not re-escape return c; } } return "&" + { "&": "amp", "<": "lt", ">": "gt", "'": "apos", '"': "quot" }[c] + ";"; } ) : ""; };
{ "language": "en", "url": "https://stackoverflow.com/questions/24816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "652" }
Q: Why is Response.BufferOutput = False, not working? This problem started on a different board, but Dave Ward, who was very prompt and helpful there is also here, so I'd like to pick up here for hopefully the last remaining piece of the puzzle.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ Basically, I was looking for a way to do constant updates to a web page from a long process. I thought AJAX was the way to go, but Dave has a nice article about using JavaScript. I integrated it into my application and it worked great on my client, but NOT my server WebHost4Life. I have another server @ Brinkster and decided to try it there and it DOES work. All the code is the same on my client, WebHost4Life, and Brinkster, so there's obviously something going on with WebHost4Life. I'm planning to write an email to them or request technical support, but I'd like to be proactive and try to figure out what could be going on with their end to cause this difference. I did everything I could with my code to turn off Buffering like Page.Response.BufferOutput = False. What server settings could they have implemented to cause this difference? Is there any way I could circumvent it on my own without their help? If not, what would they need to do? For reference, a link to the working version of a simpler version of my application is located @ http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx and the same version that isn't working is located @ http://www.tabroom.org/Ajaxfun/Default.aspx. You'll notice in the working version, you get updates with each step, but in the one that doesn't, it sits there for a long time until everything is done and then does all the updates to the client at once ... and that makes me sad. A: Hey, Jason. Sorry you're still having trouble with this. What I would do is set up a simple page like: protected void Page_Load(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { Response.Write(i + "<br />"); Response.Flush(); Thread.Sleep(1000); } } As we discussed before, make sure the .aspx file is empty of any markup other than the @Page declaration. That can sometimes trigger page buffering when it wouldn't have normally happened. Then, point the tech support guys to that file and describe the desired behavior (10 updates, 1 per second). I've found that giving them a simple test case goes a long way toward getting these things resolved. Definitely let us know what it ends up being. I'm guessing some sort of inline caching or reverse proxy, but I'm curious. A: I don't know that you can force buffering - but a reverse proxy server between you and the server would affect buffering (since the buffer then affects the proxy's connection - not your browser's). A: I've done some fruitless research on this one, but i'll share my line of thinking in the dim hope that it helps. IIS is one of the things sitting between client and server in this case, so it might be useful to know what version of IIS is involved in each case -- and to investigate if there's some way that IIS can perform its own buffering on an open connection. Though it's not quite on the money, this article about IIS6 v IIS 5 is the kind of thing I'm thinking of. A: You should make sure that neither IIS nor any other filter is trying to compress your response. It is very possible that your production server has IIS compression enabled for dynamic pages such as those with the .aspx suffix, and your development server does not. If this is the case, IIS may be waiting for the entire response (or a sizeable chunk) before it attempts to compress and send any result back to the client. I suggest using Fiddler to monitor the response from your production server and figure out if responses are being gzip'd. If response compression does turn out to be the problem, you can instruct IIS to ignore compression for specific responses via the Content-Encoding:Identity header. A: The issue is that IIS will further buffer output (beyond ASP.NET's buffering) if you have dynamic gzip compression turned on (it is by default these days). Therefore to stop IIS buffering your response there's a little hack you can do to fool IIS into thinking that the client can't handle compression by overwriting the Request.Headers["Accept-Encoding"] header (yes, Request.Headers, trust me): Response.BufferOutput = false; Request.Headers["Accept-Encoding"] = ""; // suppresses gzip compression on output As it's sending the response, the IIS compression filter checks the request headers for Accept-Encoding: gzip ... and if it's not there, doesn't compress (and therefore further buffer the output).
{ "language": "en", "url": "https://stackoverflow.com/questions/24821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Implementing a custom Windows Workflow activity that executes an asynchronous operation I'm having some conceptual trouble on figuring out how to best implement this... I want to create a custom Activity class for Windows Workflow. The activity has to call out to a third party library method that itself runs another process asynchronously and may take anywhere from seconds to many hours to complete. This library offers the ability for me to either poll for the method result or to subscribe to an event that indicates its completion. In my non-workflow apps, I typically just subscribe to that event, but that doesn't seem to be reasonable in the workflow case. I'm also not sure exactly how to best implement a polling scheme. Can someone recommend some pointers to similar problems? A: Kirk Allen Evans wrote an interesting blog about this with some pretty good code examples.
{ "language": "en", "url": "https://stackoverflow.com/questions/24823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does .net managed memory handle value types inside objects? public class MyClass { public int Age; public int ID; } public void MyMethod() { MyClass m = new MyClass(); int newID; } To my understanding, the following is true: * *The reference m lives on the stack and goes out of scope when MyMethod() exits. *The value type newID lives on the stack and goes out of scope when MyMethod() exits. *The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists. Here is my question: * *Do value types within objects live on the stack or the heap? *Is boxing/unboxing value types in an object a concern? *Are there any detailed, yet understandable, resources on this topic? Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there. Edit: Suggested reading for this topic: * *CLR Via C# by Jeffrey Richter *Essential .NET by Don Box A: Value-type values for a class have to live together with the object instance in the managed heap. The thread's stack for a method only lives for the duration of a method; how can the value persist if it only exists within that stack? A class' object size in the managed heap is the sum of its value-type fields, reference-type pointers, and additional CLR overhead variables like the Sync block index. When one assigns a value to an object's value-type field, the CLR copies the value to the space allocated within the object for that particluar field. Take for example, a simple class with a single field. public class EmbeddedValues { public int NumberField; } And with it, a simple testing class. public class EmbeddedTest { public void TestEmbeddedValues() { EmbeddedValues valueContainer = new EmbeddedValues(); valueContainer.NumberField = 20; int publicField = valueContainer.NumberField; } } If you use the MSIL Disassembler provided by the .NET Framework SDK to peek at the IL code for EmbeddedTest.TestEmbeddedValues() .method public hidebysig instance void TestEmbeddedValues() cil managed { // Code size 23 (0x17) .maxstack 2 .locals init ([0] class soapextensions.EmbeddedValues valueContainer, [1] int32 publicField) IL_0000: nop IL_0001: newobj instance void soapextensions.EmbeddedValues::.ctor() IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.s 20 IL_000a: stfld int32 soapextensions.EmbeddedValues::NumberField IL_000f: ldloc.0 IL_0010: ldfld int32 soapextensions.EmbeddedValues::NumberField IL_0015: stloc.1 IL_0016: ret } // end of method EmbeddedTest::TestEmbeddedValues Notice the CLR is being told to stfld the loaded value of "20" in the stack to the loaded EmbeddValues' NumberField field location, directly into the managed heap. Similarly, when retrieving the value, it uses ldfld instruction to directly copy the value out of that managed heap location into the thread stack. No box/unboxing happens with these types of operations. A: * *Any references or value types that an object own live in the heap. *Only if you're casting ints to Objects. A: The best resource I've seen for this is the book CLR via C# by Jeffrey Richter. It's well worth reading if you do any .NET development. Based on that text, my understanding is that the value types within a reference type do live in the heap embedded in the parent object. Reference types are always on the heap. Boxing and unboxing are not symmetric. Boxing can be a bigger concern than unboxing. Boxing will require copying the contents of the value type from the stack to the heap. Depending on how frequently this happens to you there may be no point in having a struct instead of a class. If you have some performance critical code and you're not sure if boxing and unboxing is happening use a tool to examine the IL code of your method. You'll see the words box and unbox in the IL. Personally, I would measure the performance of my code and only then see if this is a candidate for worry. In your case I don't think this will be such a critical issue. You are not going to have to copy from the stack to the heap (box) every time you access this value type inside the reference type. That scenario is where boxing becomes a more meaningful problem. A: * *Ans#1: Heap. Paraphrasing Don Box from his excellent 'Essential .Net Vol 1' Reference Types(RT) always yield instances that are allocated on the heap. In contrast, value types(VT) are dependent on the context - If a local var is a VT, the CLR allocates memory on the stack. If a field in a class is a member of a VT, then the CLR allocates memory for the instance as part of the layout of the object/Type in which field is declared. * *Ans#2: No. Boxing would occur only when you access a struct via a Object Reference / Interface Pointer. obInstance.VT_typedfield will not box. RT variables contains the address of the object it refers to. 2 RT var can point to the same object. In contrast, VT variables are the instances themselves. 2 VT var cannot point to same object(struct) *Ans#3: Don Box's Essential .net / Jeffrey Richter's CLR via C#. I have a copy of the former... though the later may be more updated for .Net revisions A: Do value types within objects live on the stack or the heap? On the heap. They are part of the allocation of the footprint of the object, just like the pointers to hold references would be. Is boxing/unboxing value types in an object a concern? There's no boxing here. Are there any detailed, yet understandable, resources on this topic? +1 vote for Richter's book. A: A variable or other storage location of a structure type is an aggregation of that type's public and private instance fields. Given struct Foo {public int x,y; int z;} a declaration Foo bar; will cause bar.x, bar.y, and bar.z to be stored wherever bar is going to be stored. Adding such a declaration of bar to a class will, from a storage-layout perspective, be equivalent to adding three int fields. Indeed, if one never did anything with bar except access its fields, the fields of bar would behave the same as would three fields bar_x, bar_y, and bar_cantaccessthis_z [accessing the last one would require doing things with bar other than accessing its fields, but it would take up space whether or not it's ever actually used for anything]. Recognizing structure-type storage locations as being aggregations of fields is the first step to understanding structures. Trying to view them as holding some kind of object might seem "simpler", but doesn't match how they actually work.
{ "language": "en", "url": "https://stackoverflow.com/questions/24829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Execute script after specific delay using JavaScript Is there any JavaScript method similar to the jQuery delay() or wait() (to delay the execution of a script for a specific amount of time)? A: why can't you put the code behind a promise? (typed in off the top of my head) new Promise(function(resolve, reject) { setTimeout(resolve, 2000); }).then(function() { console.log('do whatever you wanted to hold off on'); }); A: The simple reply is: setTimeout( function () { x = 1; }, 1000); The function above waits for 1 second (1000 ms) then sets x to 1. Obviously this is an example; you can do anything you want inside the anonymous function. A: I really liked Maurius' explanation (highest upvoted response) with the three different methods for calling setTimeout. In my code I want to automatically auto-navigate to the previous page upon completion of an AJAX save event. The completion of the save event has a slight animation in the CSS indicating the save was successful. In my code I found a difference between the first two examples: setTimeout(window.history.back(), 3000); This one does not wait for the timeout--the back() is called almost immediately no matter what number I put in for the delay. However, changing this to: setTimeout(function() {window.history.back()}, 3000); This does exactly what I was hoping. This is not specific to the back() operation, the same happens with alert(). Basically with the alert() used in the first case, the delay time is ignored. When I dismiss the popup the animation for the CSS continues. Thus, I would recommend the second or third method he describes even if you are using built in functions and not using arguments. A: Just to expand a little... You can execute code directly in the setTimeout call, but as @patrick says, you normally assign a callback function, like this. The time is milliseconds setTimeout(func, 4000); function func() { alert('Do stuff here'); } A: If you really want to have a blocking (synchronous) delay function (for whatsoever), why not do something like this: <script type="text/javascript"> function delay(ms) { var cur_d = new Date(); var cur_ticks = cur_d.getTime(); var ms_passed = 0; while(ms_passed < ms) { var d = new Date(); // Possible memory leak? var ticks = d.getTime(); ms_passed = ticks - cur_ticks; // d = null; // Prevent memory leak? } } alert("2 sec delay") delay(2000); alert("done ... 500 ms delay") delay(500); alert("done"); </script> A: Just to add to what everyone else have said about setTimeout: If you want to call a function with a parameter in the future, you need to set up some anonymous function calls. You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following will call the alert at once, and it will display 'Hello world': var a = "world"; setTimeout(alert("Hello " + a), 2000); To fix this you can either put the name of a function (as Flubba has done) or you can use an anonymous function. If you need to pass a parameter, then you have to use an anonymous function. var a = "world"; setTimeout(function(){alert("Hello " + a)}, 2000); a = "Stack Overflow"; But if you run that code you will notice that after 2 seconds the popup will say 'Hello Stack Overflow'. This is because the value of the variable a has changed in those two seconds. To get it to say 'Hello world' after two seconds, you need to use the following code snippet: function callback(a){ return function(){ alert("Hello " + a); } } var a = "world"; setTimeout(callback(a), 2000); a = "Stack Overflow"; It will wait 2 seconds and then popup 'Hello world'. A: As other said, setTimeout is your safest bet But sometimes you cannot separate the logic to a new function then you can use Date.now() to get milliseconds and do the delay yourself.... function delay(milisecondDelay) { milisecondDelay += Date.now(); while(Date.now() < milisecondDelay){} } alert('Ill be back in 5 sec after you click OK....'); delay(5000); alert('# Im back # date:' +new Date()); A: delay function: /** * delay or pause for some time * @param {number} t - time (ms) * @return {Promise<*>} */ const delay = async t => new Promise(resolve => setTimeout(resolve, t)); usage inside async function: await delay(1000); Or delay(1000).then(() => { // your code... }); Or without a function new Promise(r => setTimeout(r, 1000)).then(() => { // your code ... }); // or await new Promise(r => setTimeout(r, 1000)); // your code... A: There is the following: setTimeout(function, milliseconds); function which can be passed the time after which the function will be executed. See: Window setTimeout() Method. A: You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it! A: You can also use window.setInterval() to run some code repeatedly at a regular interval. A: To add on the earlier comments, I would like to say the following : The setTimeout() function in JavaScript does not pause execution of the script per se, but merely tells the compiler to execute the code sometime in the future. There isn't a function that can actually pause execution built into JavaScript. However, you can write your own function that does something like an unconditional loop till the time is reached by using the Date() function and adding the time interval you need. A: If you only need to test a delay you can use this: function delay(ms) { ms += new Date().getTime(); while (new Date() < ms){} } And then if you want to delay for 2 second you do: delay(2000); Might not be the best for production though. More on that in the comments A: I had some ajax commands I wanted to run with a delay in between. Here is a simple example of one way to do that. I am prepared to be ripped to shreds though for my unconventional approach. :) // Show current seconds and milliseconds // (I know there are other ways, I was aiming for minimal code // and fixed width.) function secs() { var s = Date.now() + ""; s = s.substr(s.length - 5); return s.substr(0, 2) + "." + s.substr(2); } // Log we're loading console.log("Loading: " + secs()); // Create a list of commands to execute var cmds = [ function() { console.log("A: " + secs()); }, function() { console.log("B: " + secs()); }, function() { console.log("C: " + secs()); }, function() { console.log("D: " + secs()); }, function() { console.log("E: " + secs()); }, function() { console.log("done: " + secs()); } ]; // Run each command with a second delay in between var ms = 1000; cmds.forEach(function(cmd, i) { setTimeout(cmd, ms * i); }); // Log we've loaded (probably logged before first command) console.log("Loaded: " + secs()); You can copy the code block and paste it into a console window and see something like: Loading: 03.077 Loaded: 03.078 A: 03.079 B: 04.075 C: 05.075 D: 06.075 E: 07.076 done: 08.076 A: The simplest solution to call your function with delay is: function executeWithDelay(anotherFunction) { setTimeout(anotherFunction, delayInMilliseconds); }
{ "language": "en", "url": "https://stackoverflow.com/questions/24849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "200" }
Q: What is the difference between ++i and i++? In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop? A: i++ and ++i This little code may help to visualize the difference from a different angle than the already posted answers: int i = 10, j = 10; printf ("i is %i \n", i); printf ("i++ is %i \n", i++); printf ("i is %i \n\n", i); printf ("j is %i \n", j); printf ("++j is %i \n", ++j); printf ("j is %i \n", j); The outcome is: //Remember that the values are i = 10, and j = 10 i is 10 i++ is 10 //Assigns (print out), then increments i is 11 j is 10 ++j is 11 //Increments, then assigns (print out) j is 11 Pay attention to the before and after situations. for loop As for which one of them should be used in an incrementation block of a for loop, I think that the best we can do to make a decision is use a good example: int i, j; for (i = 0; i <= 3; i++) printf (" > iteration #%i", i); printf ("\n"); for (j = 0; j <= 3; ++j) printf (" > iteration #%i", j); The outcome is: > iteration #0 > iteration #1 > iteration #2 > iteration #3 > iteration #0 > iteration #1 > iteration #2 > iteration #3 I don't know about you, but I don't see any difference in its usage, at least in a for loop. A: The following C code fragment illustrates the difference between the pre and post increment and decrement operators: int i; int j; Increment operators: i = 1; j = ++i; // i is now 2, j is also 2 j = i++; // i is now 3, j is 2 A: i++: In this scenario first the value is assigned and then increment happens. ++i: In this scenario first the increment is done and then value is assigned Below is the image visualization and also here is a nice practical video which demonstrates the same. A: Shortly: ++i and i++ works same if you are not writing them in a function. If you use something like function(i++) or function(++i) you can see the difference. function(++i) says first increment i by 1, after that put this i into the function with new value. function(i++) says put first i into the function after that increment i by 1. int i=4; printf("%d\n",pow(++i,2));//it prints 25 and i is 5 now i=4; printf("%d",pow(i++,2));//it prints 16 i is 5 now A: Pre-crement means increment on the same line. Post-increment means increment after the line executes. int j = 0; System.out.println(j); // 0 System.out.println(j++); // 0. post-increment. It means after this line executes j increments. int k = 0; System.out.println(k); // 0 System.out.println(++k); // 1. pre increment. It means it increments first and then the line executes When it comes with OR, AND operators, it becomes more interesting. int m = 0; if((m == 0 || m++ == 0) && (m++ == 1)) { // False // In the OR condition, if the first line is already true // then the compiler doesn't check the rest. It is a // technique of compiler optimization System.out.println("post-increment " + m); } int n = 0; if((n == 0 || n++ == 0) && (++n == 1)) { // True System.out.println("pre-increment " + n); // 1 } In Array System.out.println("In Array"); int[] a = { 55, 11, 15, 20, 25 }; int ii, jj, kk = 1, mm; ii = ++a[1]; // ii = 12. a[1] = a[1] + 1 System.out.println(a[1]); // 12 jj = a[1]++; // 12 System.out.println(a[1]); // a[1] = 13 mm = a[1]; // 13 System.out.printf("\n%d %d %d\n", ii, jj, mm); // 12, 12, 13 for (int val: a) { System.out.print(" " + val); // 55, 13, 15, 20, 25 } In C++ post/pre-increment of pointer variable #include <iostream> using namespace std; int main() { int x = 10; int* p = &x; std::cout << "address = " << p <<"\n"; // Prints the address of x std::cout << "address = " << p <<"\n"; // Prints (the address of x) + sizeof(int) std::cout << "address = " << &x <<"\n"; // Prints the address of x std::cout << "address = " << ++&x << "\n"; // Error. The reference can't reassign, because it is fixed (immutable). } A: ++i increments the value, then returns it. i++ returns the value, and then increments it. It's a subtle difference. For a for loop, use ++i, as it's slightly faster. i++ will create an extra copy that just gets thrown away. A: Please don't worry about the "efficiency" (speed, really) of which one is faster. We have compilers these days that take care of these things. Use whichever one makes sense to use, based on which more clearly shows your intent. A: I assume you understand the difference in semantics now (though honestly I wonder why people ask 'what does operator X mean' questions on stack overflow rather than reading, you know, a book or web tutorial or something. But anyway, as far as which one to use, ignore questions of performance, which are unlikely important even in C++. This is the principle you should use when deciding which to use: Say what you mean in code. If you don't need the value-before-increment in your statement, don't use that form of the operator. It's a minor issue, but unless you are working with a style guide that bans one version in favor of the other altogether (aka a bone-headed style guide), you should use the form that most exactly expresses what you are trying to do. QED, use the pre-increment version: for (int i = 0; i != X; ++i) ... A: The Main Difference is * *i++ Post(After Increment) and *++i Pre (Before Increment) * *post if i =1 the loop increments like 1,2,3,4,n *pre if i =1 the loop increments like 2,3,4,5,n A: The difference can be understood by this simple C++ code below: int i, j, k, l; i = 1; //initialize int i with 1 j = i+1; //add 1 with i and set that as the value of j. i is still 1 k = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1 l = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l. cout << i << ' ' << j << ' ' << k << ' '<< l << endl; return 0; A: In simple words the difference between both is in the steps take a look to the image below. Example: int i = 1; int j = i++; The j result is 1 int i = 1; int j = ++i; The j result is 2 Note: in both cases i values is 2 A: The only difference is the order of operations between the increment of the variable and the value the operator returns. This code and its output explains the the difference: #include<stdio.h> int main(int argc, char* argv[]) { unsigned int i=0, a; printf("i initial value: %d; ", i); a = i++; printf("value returned by i++: %d, i after: %d\n", a, i); i=0; printf("i initial value: %d; ", i); a = ++i; printf(" value returned by ++i: %d, i after: %d\n",a, i); } The output is: i initial value: 0; value returned by i++: 0, i after: 1 i initial value: 0; value returned by ++i: 1, i after: 1 So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented. Another example: #include<stdio.h> int main () int i=0; int a = i++*2; printf("i=0, i++*2=%d\n", a); i=0; a = ++i * 2; printf("i=0, ++i*2=%d\n", a); i=0; a = (++i) * 2; printf("i=0, (++i)*2=%d\n", a); i=0; a = (i++) * 2; printf("i=0, (i++)*2=%d\n", a); return 0; } Output: i=0, i++*2=0 i=0, ++i*2=2 i=0, (++i)*2=2 i=0, (i++)*2=0 Many times there is no difference Differences are clear when the returned value is assigned to another variable or when the increment is performed in concatenation with other operations where operations precedence is applied (i++*2 is different from ++i*2, as well as (i++)*2 and (++i)*2) in many cases they are interchangeable. A classical example is the for loop syntax: for(int i=0; i<10; i++) has the same effect of for(int i=0; i<10; ++i) Efficiency Pre-increment is always at least as efficient as post-increment: in fact post-increment usually involves keeping a copy of the previous value around and might add a little extra code. As others have suggested, due to compiler optimisations many times they are equally efficient, probably a for loop lies within these cases. Rule to remember To not make any confusion between the two operators I adopted this rule: Associate the position of the operator ++ with respect to the variable i to the order of the ++ operation with respect to the assignment Said in other words: * *++ before i means incrementation must be carried out before assignment; *++ after i means incrementation must be carried out after assignment: A: The reason ++i can be slightly faster than i++ is that i++ can require a local copy of the value of i before it gets incremented, while ++i never does. In some cases, some compilers will optimize it away if possible... but it's not always possible, and not all compilers do this. I try not to rely too much on compilers optimizations, so I'd follow Ryan Fox's advice: when I can use both, I use ++i. A: i++ is known as post increment whereas ++i is called pre increment. i++ i++ is post increment because it increments i's value by 1 after the operation is over. Let’s see the following example: int i = 1, j; j = i++; Here value of j = 1, but i = 2. Here the value of i will be assigned to j first, and then i will be incremented. ++i ++i is pre increment because it increments i's value by 1 before the operation. It means j = i; will execute after i++. Let’s see the following example: int i = 1, j; j = ++i; Here the value of j = 2 but i = 2. Here the value of i will be assigned to j after the i incremention of i. Similarly, ++i will be executed before j=i;. For your question which should be used in the incrementation block of a for loop? the answer is, you can use any one... It doesn't matter. It will execute your for loop same number of times. for(i=0; i<5; i++) printf("%d ", i); And for(i=0; i<5; ++i) printf("%d ", i); Both the loops will produce the same output. I.e., 0 1 2 3 4. It only matters where you are using it. for(i = 0; i<5;) printf("%d ", ++i); In this case output will be 1 2 3 4 5. A: The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances. In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations. However, you should consider two main problems with the preceding logic. * *Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler. *In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment. In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization. This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice." A: * *++i will increment the value of i, and then return the incremented value. i = 1; j = ++i; (i is 2, j is 2) *i++ will increment the value of i, but return the original value that i held before being incremented. i = 1; j = i++; (i is 2, j is 1) For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R. In any case, follow the guideline "prefer ++i over i++" and you won't go wrong. There's a couple of comments regarding the efficiency of ++i and i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical. The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C? As @OnFreund notes, it's different for a C++ object, since operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value. A: ++i: is pre-increment the other is post-increment. i++: gets the element and then increments it. ++i: increments i and then returns the element. Example: int i = 0; printf("i: %d\n", i); printf("i++: %d\n", i++); printf("++i: %d\n", ++i); Output: i: 0 i++: 0 ++i: 2 A: ++i (Prefix operation): Increments and then assigns the value (eg): int i = 5, int b = ++i In this case, 6 is assigned to b first and then increments to 7 and so on. i++ (Postfix operation): Assigns and then increments the value (eg): int i = 5, int b = i++ In this case, 5 is assigned to b first and then increments to 6 and so on. Incase of for loop: i++ is mostly used because, normally we use the starting value of i before incrementing in for loop. But depending on your program logic it may vary. A: You can think of the internal conversion of that as multiple statements: // case 1 i++; /* you can think as, * i; * i= i+1; */ // case 2 ++i; /* you can think as, * i = i+i; * i; */ A: a=i++ means a contains the current i value. a=++i means a contains the incremented i value.
{ "language": "en", "url": "https://stackoverflow.com/questions/24853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1123" }
Q: Is it essential that I use libraries to manipulate XML? I am using Java back end for creating an XML string which is passed to the browser. Currently I am using simple string manipulation to produce this XML. Is it essential that I use some XML library in Java to produce the XML string? I find the libraries very difficult to use compared to what I need. A: Xml is hard. Parsing yourself is a bad idea, it's even a worse idea to generate content yourself. Have a look at the Xml 1.1 spec. You have to deal with such things as proper encoding, attribute encoding (e.g., produces invalid xml), proper CDATA escaping, UTF encoding, custom DTD entities, and that's without throwing in the mix xml namespaces with the default / empty namespace, namespace attributes, etc. Learn a toolkit, there's plenty available. A: I think that custom string manipulation is fine, but you have to keep two things in mind: * *Your code isn't as mature as the library. Allocate time in your plan to handle the bugs that pop-up. *Your approach will probably not scale as well as a 3rd party library when the xml starts to grow (both in terms of performance and ease of use). I know a code base that uses custom string manipulation for xml output (and a 3rd party library for input). It was fine to begin with but became a real hassle after a while. A: Yes, use the library. Somebody took the time and effort to create something that is usually better than what you could come up with. String manipulation is for sending back a single node, but once you start needing to manipulate the DOM, or use an XPath query, the library will save you. A: By not using a library, you risk generating or parsing data that isn't well-formed, which sooner or later will happen. For the same reason document.write isn't allowed in XHTML, you shouldn't write your XML markup as a string. A: Yes. It makes no sense to skip essential tool: even writing xml is non-trivial with having to escape those ampersands and lts, not to mention namespace bindings (if needed). And in the end libs can generally read and write xml not only more reliably but more efficiently (esp. so for Java). But you may have been looking at wrong tools, if they seem overcomplicated. Data binding using JAXB or XStream is simple; but for simple straight-forward XML output, I go with StaxMate. It can actually simplify the task in many ways (automatically closes start tags, writes namespace declarations if needde etc). A: It's not essential, but advisable. However, if string manipulation works for you, then go for it! There are plenty of cases where small or simple XML text can be safely built by hand. Just be aware that creating XML text is harder than it looks. Here's some criteria I would consider: * *First: how much control do you have on the information that goes into the xml? The less control you have on the source data, the more likely you will have trouble, and the more advantageous the library becomes. For example: (a) Can you guarantee that the element names will never have a character that is illegal in a name? (b) How about quotes in an attribute's content? Can they happen, and are you handling them? (c) Does the data ever contain anything that might need to be encoded as an entity (like the less-than which often needs to be output as &lt;); are you doing it correctly? * *Second, maintainability: is the code that builds the XML easy to understand by someone else? You probably don't want to be stuck with the code for life. I've worked with second-hand C++ code that hand-builds XML and it can be surprisingly obscure. Of course, if this is a personal project of yours, then you don't need to worry about "others": substitute "in a year" for "others" above. I wouldn't worry about performance. If your XML is simple enough that you can hand-write it, any overhead from the library is probably meaningless. Of course, your case might be different, but you should measure to prove it first. Finally, Yes; you can hand build XML text by hand if it's simple enough; but not knowing the libraries available is probably not the right reason. A modern XML library is a quite powerful tool, but it can also be daunting. However, learning the essentials of your XML library is not that hard, and it can be quite handy; among other things, it's almost a requisite in today's job marketplace. Just don't get bogged down by namespaces, schemas and other fancier features until you get the essentials. Good luck. A: No - If you can parse it yourself (as you are doing), and it will scale for your needs, you do not need any library. Just ensure that your future needs are going to be met - complex xml creation is better done using libraries - some of which come in very simple flavors too. A: You don't have to use library to parse XML, but check out this question What considerations should be made before reinventing the wheel? before you start writing your own code for parsing/generating xml. A: The only time I've done something like this in production code was when a collegue and I built a pre-processor so that we could embed XML fragments from other files into a larger XML. On load we would first parse these embed (file references in XML comment strings) and replace them with the actual fragment they referenced. Then we would pass on the combined result to the XML Parser. A: No - especially for generating (parsing I would be less inclined to as input text can always surprise you). I think its fine - but be prepared to shift to a library should you find yourself spending more then a few minutes maintaining your own code. A: I don't think that using the DOM XML API wich comes with the JDK is difficult, it's easy to create Element nodes, attributes, etc... and later is easy convert strings to a DOM document sor DOM documents into a String In the first page google finds from Spain (spanish XML example): public String DOM2String(Document doc) { TransformerFactory transformerFactory =TransformerFactory.newInstance(); Transformer transformer = null; try{ transformer = transformerFactory.newTransformer(); }catch (javax.xml.transform.TransformerConfigurationException error){ coderror=123; msgerror=error.getMessage(); return null; } Source source = new DOMSource(doc); StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); try{ transformer.transform(source,result); }catch (javax.xml.transform.TransformerException error){ coderror=123; msgerror=error.getMessage(); return null; } String s = writer.toString(); return s; } public Document string2DOM(String s) { Document tmpX=null; DocumentBuilder builder = null; try{ builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); }catch(javax.xml.parsers.ParserConfigurationException error){ coderror=10; msgerror="Error crando factory String2DOM "+error.getMessage(); return null; } try{ tmpX=builder.parse(new ByteArrayInputStream(s.getBytes())); }catch(org.xml.sax.SAXException error){ coderror=10; msgerror="Error parseo SAX String2DOM "+error.getMessage(); return null; }catch(IOException error){ coderror=10; msgerror="Error generando Bytes String2DOM "+error.getMessage(); return null; } return tmpX; }
{ "language": "en", "url": "https://stackoverflow.com/questions/24866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How do I fix "for loop initial declaration used outside C99 mode" GCC error? I'm trying to solve the 3n+1 problem and I have a for loop that looks like this: for(int i = low; i <= high; ++i) { res = runalg(i); if (res > highestres) { highestres = res; } } Unfortunately I'm getting this error when I try to compile with GCC: 3np1.c:15: error: 'for' loop initial declaration used outside C99 mode I don't know what C99 mode is. Any ideas? A: if you compile in C change for (int i=0;i<10;i++) { .. to int i; for (i=0;i<10;i++) { .. You can also compile with the C99 switch set. Put -std=c99 in the compilation line: gcc -std=c99 foo.c -o foo REF: http://cplusplus.syntaxerrors.info/index.php?title='for'_loop_initial_declaration_used_outside_C99_mode A: For anyone attempting to compile code from an external source that uses an automated build utility such as Make, to avoid having to track down the explicit gcc compilation calls you can set an environment variable. Enter on command prompt or put in .bashrc (or .bash_profile on Mac): export CFLAGS="-std=c99" Note that a similar solution applies if you run into a similar scenario with C++ compilation that requires C++ 11, you can use: export CXXFLAGS="-std=c++11" A: To switch to C99 mode in CodeBlocks, follow the next steps: Click Project/Build options, then in tab Compiler Settings choose subtab Other options, and place -std=c99 in the text area, and click Ok. This will turn C99 mode on for your Compiler. I hope this will help someone! A: Jihene Stambouli answered OP question most directly... Question was; why does for(int i = low; i <= high; ++i) { res = runalg(i); if (res > highestres) { highestres = res; } } produce the error; 3np1.c:15: error: 'for' loop initial declaration used outside C99 mode for which the answer is for(int i = low... should be int i; for (i=low... A: Enable C99 mode in Code::Blocks 16.01 * *Go to Settings-> Compiler... *In Compiler Flags section of Compiler settings tab, select checkbox 'Have gcc follow the 1999 ISO C language standard [-std=c99]' A: I'd try to declare i outside of the loop! Good luck on solving 3n+1 :-) Here's an example: #include <stdio.h> int main() { int i; /* for loop execution */ for (i = 10; i < 20; i++) { printf("i: %d\n", i); } return 0; } Read more on for loops in C here. A: I've gotten this error too. for (int i=0;i<10;i++) { .. is not valid in the C89/C90 standard. As OysterD says, you need to do: int i; for (i=0;i<10;i++) { .. Your original code is allowed in C99 and later standards of the C language. A: @Blorgbeard: New Features in C99 * *inline functions *variable declaration no longer restricted to file scope or the start of a compound statement *several new data types, including long long int, optional extended integer types, an explicit boolean data type, and a complex type to represent complex numbers *variable-length arrays *support for one-line comments beginning with //, as in BCPL or C++ *new library functions, such as snprintf *new header files, such as stdbool.h and inttypes.h *type-generic math functions (tgmath.h) *improved support for IEEE floating point *designated initializers *compound literals *support for variadic macros (macros of variable arity) *restrict qualification to allow more aggressive code optimization http://en.wikipedia.org/wiki/C99 A Tour of C99 A: There is a compiler switch which enables C99 mode, which amongst other things allows declaration of a variable inside the for loop. To turn it on use the compiler switch -std=c99 Or as @OysterD says, declare the variable outside the loop. A: I had the same problem and it works you just have to declare the i outside of the loop: int i; for(i = low; i <= high; ++i) { res = runalg(i); if (res > highestres) { highestres = res; } } A: For Qt-creator: just add next lines to *.pro file... QMAKE_CFLAGS_DEBUG = \ -std=gnu99 QMAKE_CFLAGS_RELEASE = \ -std=gnu99
{ "language": "en", "url": "https://stackoverflow.com/questions/24881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "126" }
Q: Is there a performance difference between i++ and ++i in C? Is there a performance difference between i++ and ++i if the resulting value is not used? A: @Mark Even though the compiler is allowed to optimize away the (stack based) temporary copy of the variable and gcc (in recent versions) is doing so, doesn't mean all compilers will always do so. I just tested it with the compilers we use in our current project and 3 out of 4 do not optimize it. Never assume the compiler gets it right, especially if the possibly faster, but never slower code is as easy to read. If you don't have a really stupid implementation of one of the operators in your code: Alwas prefer ++i over i++. A: I have been reading through most of the answers here and many of the comments, and I didn't see any reference to the one instance that I could think of where i++ is more efficient than ++i (and perhaps surprisingly --i was more efficient than i--). That is for C compilers for the DEC PDP-11! The PDP-11 had assembly instructions for pre-decrement of a register and post-increment, but not the other way around. The instructions allowed any "general-purpose" register to be used as a stack pointer. So if you used something like *(i++) it could be compiled into a single assembly instruction, while *(++i) could not. This is obviously a very esoteric example, but it does provide the exception where post-increment is more efficient(or I should say was, since there isn't much demand for PDP-11 C code these days). A: In C, the compiler can generally optimize them to be the same if the result is unused. However, in C++ if using other types that provide their own ++ operators, the prefix version is likely to be faster than the postfix version. So, if you don't need the postfix semantics, it is better to use the prefix operator. A: A better answer is that ++i will sometimes be faster but never slower. Everyone seems to be assuming that i is a regular built-in type such as int. In this case there will be no measurable difference. However if i is complex type then you may well find a measurable difference. For i++ you must make a copy of your class before incrementing it. Depending on what's involved in a copy it could indeed be slower since with ++i you can just return the final value. Foo Foo::operator++() { Foo oldFoo = *this; // copy existing value - could be slow // yadda yadda, do increment return oldFoo; } Another difference is that with ++i you have the option of returning a reference instead of a value. Again, depending on what's involved in making a copy of your object this could be slower. A real-world example of where this can occur would be the use of iterators. Copying an iterator is unlikely to be a bottle-neck in your application, but it's still good practice to get into the habit of using ++i instead of i++ where the outcome is not affected. A: Executive summary: No. i++ could potentially be slower than ++i, since the old value of i might need to be saved for later use, but in practice all modern compilers will optimize this away. We can demonstrate this by looking at the code for this function, both with ++i and i++. $ cat i++.c extern void g(int i); void f() { int i; for (i = 0; i < 100; i++) g(i); } The files are the same, except for ++i and i++: $ diff i++.c ++i.c 6c6 < for (i = 0; i < 100; i++) --- > for (i = 0; i < 100; ++i) We'll compile them, and also get the generated assembler: $ gcc -c i++.c ++i.c $ gcc -S i++.c ++i.c And we can see that both the generated object and assembler files are the same. $ md5 i++.s ++i.s MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e $ md5 *.o MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22 MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22 A: I can think of a situation where postfix is slower than prefix increment: Imagine a processor with register A is used as accumulator and it's the only register used in many instructions (some small microcontrollers are actually like this). Now imagine the following program and their translation into a hypothetical assembly: Prefix increment: a = ++b + c; ; increment b LD A, [&b] INC A ST A, [&b] ; add with c ADD A, [&c] ; store in a ST A, [&a] Postfix increment: a = b++ + c; ; load b LD A, [&b] ; add with c ADD A, [&c] ; store in a ST A, [&a] ; increment b LD A, [&b] INC A ST A, [&b] Note how the value of b was forced to be reloaded. With prefix increment, the compiler can just increment the value and go ahead with using it, possibly avoid reloading it since the desired value is already in the register after the increment. However, with postfix increment, the compiler has to deal with two values, one the old and one the incremented value which as I show above results in one more memory access. Of course, if the value of the increment is not used, such as a single i++; statement, the compiler can (and does) simply generate an increment instruction regardless of postfix or prefix usage. As a side note, I'd like to mention that an expression in which there is a b++ cannot simply be converted to one with ++b without any additional effort (for example by adding a - 1). So comparing the two if they are part of some expression is not really valid. Often, where you use b++ inside an expression you cannot use ++b, so even if ++b were potentially more efficient, it would simply be wrong. Exception is of course if the expression is begging for it (for example a = b++ + 1; which can be changed to a = ++b;). A: Short answer: There is never any difference between i++ and ++i in terms of speed. A good compiler should not generate different code in the two cases. Long answer: What every other answer fails to mention is that the difference between ++i versus i++ only makes sense within the expression it is found. In the case of for(i=0; i<n; i++), the i++ is alone in its own expression: there is a sequence point before the i++ and there is one after it. Thus the only machine code generated is "increase i by 1" and it is well-defined how this is sequenced in relation to the rest of the program. So if you would change it to prefix ++, it wouldn't matter in the slightest, you would still just get the machine code "increase i by 1". The differences between ++i and i++ only matters in expressions such as array[i++] = x; versus array[++i] = x;. Some may argue and say that the postfix will be slower in such operations because the register where i resides has to be reloaded later. But then note that the compiler is free to order your instructions in any way it pleases, as long as it doesn't "break the behavior of the abstract machine" as the C standard calls it. So while you may assume that array[i++] = x; gets translated to machine code as: * *Store value of i in register A. *Store address of array in register B. *Add A and B, store results in A. *At this new address represented by A, store the value of x. *Store value of i in register A // inefficient because extra instruction here, we already did this once. *Increment register A. *Store register A in i. the compiler might as well produce the code more efficiently, such as: * *Store value of i in register A. *Store address of array in register B. *Add A and B, store results in B. *Increment register A. *Store register A in i. *... // rest of the code. Just because you as a C programmer is trained to think that the postfix ++ happens at the end, the machine code doesn't have to be ordered in that way. So there is no difference between prefix and postfix ++ in C. Now what you as a C programmer should be vary of, is people who inconsistently use prefix in some cases and postfix in other cases, without any rationale why. This suggests that they are uncertain about how C works or that they have incorrect knowledge of the language. This is always a bad sign, it does in turn suggest that they are making other questionable decisions in their program, based on superstition or "religious dogmas". "Prefix ++ is always faster" is indeed one such false dogma that is common among would-be C programmers. A: Taking a leaf from Scott Meyers, More Effective c++ Item 6: Distinguish between prefix and postfix forms of increment and decrement operations. The prefix version is always preferred over the postfix in regards to objects, especially in regards to iterators. The reason for this if you look at the call pattern of the operators. // Prefix Integer& Integer::operator++() { *this += 1; return *this; } // Postfix const Integer Integer::operator++(int) { Integer oldValue = *this; ++(*this); return oldValue; } Looking at this example it is easy to see how the prefix operator will always be more efficient than the postfix. Because of the need for a temporary object in the use of the postfix. This is why when you see examples using iterators they always use the prefix version. But as you point out for int's there is effectively no difference because of compiler optimisation that can take place. A: I always prefer pre-increment, however ... I wanted to point out that even in the case of calling the operator++ function, the compiler will be able to optimize away the temporary if the function gets inlined. Since the operator++ is usually short and often implemented in the header, it is likely to get inlined. So, for practical purposes, there likely isn't much of a difference between the performance of the two forms. However, I always prefer pre-increment since it seems better to directly express what I"m trying to say, rather than relying on the optimizer to figure it out. Also, giving the optmizer less to do likely means the compiler runs faster. A: Here's an additional observation if you're worried about micro optimisation. Decrementing loops can 'possibly' be more efficient than incrementing loops (depending on instruction set architecture e.g. ARM), given: for (i = 0; i < 100; i++) On each loop you you will have one instruction each for: * *Adding 1 to i. *Compare whether i is less than a 100. *A conditional branch if i is less than a 100. Whereas a decrementing loop: for (i = 100; i != 0; i--) The loop will have an instruction for each of: * *Decrement i, setting the CPU register status flag. *A conditional branch depending on CPU register status (Z==0). Of course this works only when decrementing to zero! Remembered from the ARM System Developer's Guide. A: First of all: The difference between i++ and ++i is neglegible in C. To the details. 1. The well known C++ issue: ++i is faster In C++, ++i is more efficient iff i is some kind of an object with an overloaded increment operator. Why? In ++i, the object is first incremented, and can subsequently passed as a const reference to any other function. This is not possible if the expression is foo(i++) because now the increment needs to be done before foo() is called, but the old value needs to be passed to foo(). Consequently, the compiler is forced to make a copy of i before it executes the increment operator on the original. The additional constructor/destructor calls are the bad part. As noted above, this does not apply to fundamental types. 2. The little known fact: i++ may be faster If no constructor/destructor needs to be called, which is always the case in C, ++i and i++ should be equally fast, right? No. They are virtually equally fast, but there may be small differences, which most other answerers got the wrong way around. How can i++ be faster? The point is data dependencies. If the value needs to be loaded from memory, two subsequent operations need to be done with it, incrementing it, and using it. With ++i, the incrementation needs to be done before the value can be used. With i++, the use does not depend on the increment, and the CPU may perform the use operation in parallel to the increment operation. The difference is at most one CPU cycle, so it is really neglegible, but it is there. And it is the other way round then many would expect. A: From Efficiency versus intent by Andrew Koenig : First, it is far from obvious that ++i is more efficient than i++, at least where integer variables are concerned. And : So the question one should be asking is not which of these two operations is faster, it is which of these two operations expresses more accurately what you are trying to accomplish. I submit that if you are not using the value of the expression, there is never a reason to use i++ instead of ++i, because there is never a reason to copy the value of a variable, increment the variable, and then throw the copy away. So, if the resulting value is not used, I would use ++i. But not because it is more efficient: because it correctly states my intent. A: Please don't let the question of "which one is faster" be the deciding factor of which to use. Chances are you're never going to care that much, and besides, programmer reading time is far more expensive than machine time. Use whichever makes most sense to the human reading the code. A: My C is a little rusty, so I apologize in advance. Speedwise, I can understand the results. But, I am confused as to how both files came out to the same MD5 hash. Maybe a for loop runs the same, but wouldn't the following 2 lines of code generate different assembly? myArray[i++] = "hello"; vs myArray[++i] = "hello"; The first one writes the value to the array, then increments i. The second increments i then writes to the array. I'm no assembly expert, but I just don't see how the same executable would be generated by these 2 different lines of code. Just my two cents.
{ "language": "en", "url": "https://stackoverflow.com/questions/24886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "525" }
Q: C Memory Management I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case. Can someone show me (with code examples) an example of when you would have to do some "memory management" ? A: I think the most concise way to answer the question in to consider the role of the pointer in C. The pointer is a lightweight yet powerful mechanism that gives you immense freedom at the cost of immense capacity to shoot yourself in the foot. In C the responsibility of ensuring your pointers point to memory you own is yours and yours alone. This requires an organized and disciplined approach, unless you forsake pointers, which makes it hard to write effective C. The posted answers to date concentrate on automatic (stack) and heap variable allocations. Using stack allocation does make for automatically managed and convenient memory, but in some circumstances (large buffers, recursive algorithms) it can lead to the horrendous problem of stack overflow. Knowing exactly how much memory you can allocate on the stack is very dependent on the system. In some embedded scenarios a few dozen bytes might be your limit, in some desktop scenarios you can safely use megabytes. Heap allocation is less inherent to the language. It is basically a set of library calls that grants you ownership of a block of memory of given size until you are ready to return ('free') it. It sounds simple, but is associated with untold programmer grief. The problems are simple (freeing the same memory twice, or not at all [memory leaks], not allocating enough memory [buffer overflow], etc) but difficult to avoid and debug. A hightly disciplined approach is absolutely mandatory in practive but of course the language doesn't actually mandate it. I'd like to mention another type of memory allocation that's been ignored by other posts. It's possible to statically allocate variables by declaring them outside any function. I think in general this type of allocation gets a bad rap because it's used by global variables. However there's nothing that says the only way to use memory allocated this way is as an undisciplined global variable in a mess of spaghetti code. The static allocation method can be used simply to avoid some of the pitfalls of the heap and automatic allocation methods. Some C programmers are surprised to learn that large and sophisticated C embedded and games programs have been constructed with no use of heap allocation at all. A: There are some great answers here about how to allocate and free memory, and in my opinion the more challenging side of using C is ensuring that the only memory you use is memory you've allocated - if this isn't done correctly what you end up with is the cousin of this site - a buffer overflow - and you may be overwriting memory that's being used by another application, with very unpredictable results. An example: int main() { char* myString = (char*)malloc(5*sizeof(char)); myString = "abcd"; } At this point you've allocated 5 bytes for myString and filled it with "abcd\0" (strings end in a null - \0). If your string allocation was myString = "abcde"; You would be assigning "abcde" in the 5 bytes you've had allocated to your program, and the trailing null character would be put at the end of this - a part of memory that hasn't been allocated for your use and could be free, but could equally be being used by another application - This is the critical part of memory management, where a mistake will have unpredictable (and sometimes unrepeatable) consequences. A: A thing to remember is to always initialize your pointers to NULL, since an uninitialized pointer may contain a pseudorandom valid memory address which can make pointer errors go ahead silently. By enforcing a pointer to be initialized with NULL, you can always catch if you are using this pointer without initializing it. The reason is that operating systems "wire" the virtual address 0x00000000 to general protection exceptions to trap null pointer usage. A: There are two places where variables can be put in memory. When you create a variable like this: int a; char c; char d[16]; The variables are created in the "stack". Stack variables are automatically freed when they go out of scope (that is, when the code can't reach them anymore). You might hear them called "automatic" variables, but that has fallen out of fashion. Many beginner examples will use only stack variables. The stack is nice because it's automatic, but it also has two drawbacks: (1) The compiler needs to know in advance how big the variables are, and (2) the stack space is somewhat limited. For example: in Windows, under default settings for the Microsoft linker, the stack is set to 1 MB, and not all of it is available for your variables. If you don't know at compile time how big your array is, or if you need a big array or struct, you need "plan B". Plan B is called the "heap". You can usually create variables as big as the Operating System will let you, but you have to do it yourself. Earlier postings showed you one way you can do it, although there are other ways: int size; // ... // Set size to some value, based on information available at run-time. Then: // ... char *p = (char *)malloc(size); (Note that variables in the heap are not manipulated directly, but via pointers) Once you create a heap variable, the problem is that the compiler can't tell when you're done with it, so you lose the automatic releasing. That's where the "manual releasing" you were referring to comes in. Your code is now responsible to decide when the variable is not needed anymore, and release it so the memory can be taken for other purposes. For the case above, with: free(p); What makes this second option "nasty business" is that it's not always easy to know when the variable is not needed anymore. Forgetting to release a variable when you don't need it will cause your program to consume more memory that it needs to. This situation is called a "leak". The "leaked" memory cannot be used for anything until your program ends and the OS recovers all of its resources. Even nastier problems are possible if you release a heap variable by mistake before you are actually done with it. In C and C++, you are responsible to clean up your heap variables like shown above. However, there are languages and environments such as Java and .NET languages like C# that use a different approach, where the heap gets cleaned up on its own. This second method, called "garbage collection", is much easier on the developer but you pay a penalty in overhead and performance. It's a balance. (I have glossed over many details to give a simpler, but hopefully more leveled answer) A: Here's an example. Suppose you have a strdup() function that duplicates a string: char *strdup(char *src) { char * dest; dest = malloc(strlen(src) + 1); if (dest == NULL) abort(); strcpy(dest, src); return dest; } And you call it like this: main() { char *s; s = strdup("hello"); printf("%s\n", s); s = strdup("world"); printf("%s\n", s); } You can see that the program works, but you have allocated memory (via malloc) without freeing it up. You have lost your pointer to the first memory block when you called strdup the second time. This is no big deal for this small amount of memory, but consider the case: for (i = 0; i < 1000000000; ++i) /* billion times */ s = strdup("hello world"); /* 11 bytes */ You have now used up 11 gig of memory (possibly more, depending on your memory manager) and if you have not crashed your process is probably running pretty slowly. To fix, you need to call free() for everything that is obtained with malloc() after you finish using it: s = strdup("hello"); free(s); /* now not leaking memory! */ s = strdup("world"); ... Hope this example helps! A: Also you might want to use dynamic memory allocation when you need to define a huge array, say int[10000]. You can't just put it in stack because then, hm... you'll get a stack overflow. Another good example would be an implementation of a data structure, say linked list or binary tree. I don't have a sample code to paste here but you can google it easily. A: (I'm writing because I feel the answers so far aren't quite on the mark.) The reason you have to memory management worth mentioning is when you have a problem / solution that requires you to create complex structures. (If your programs crash if you allocate to much space on the stack at once, that's a bug.) Typically, the first data structure you'll need to learn is some kind of list. Here's a single linked one, off the top of my head: typedef struct listelem { struct listelem *next; void *data;} listelem; listelem * create(void * data) { listelem *p = calloc(1, sizeof(listelem)); if(p) p->data = data; return p; } listelem * delete(listelem * p) { listelem next = p->next; free(p); return next; } void deleteall(listelem * p) { while(p) p = delete(p); } void foreach(listelem * p, void (*fun)(void *data) ) { for( ; p != NULL; p = p->next) fun(p->data); } listelem * merge(listelem *p, listelem *q) { while(p != NULL && p->next != NULL) p = p->next; if(p) { p->next = q; return p; } else return q; } Naturally, you'd like a few other functions, but basically, this is what you need memory management for. I should point out that there are a number tricks that are possible with "manual" memory management, e.g., * *Using the fact that malloc is guaranteed (by the language standard) to return a pointer divisible by 4, *allocating extra space for some sinister purpose of your own, *creating memory pools.. Get a good debugger... Good luck! A: You have to do "memory management" when you want to use memory on the heap rather than the stack. If you don't know how large to make an array until runtime, then you have to use the heap. For example, you might want to store something in a string, but don't know how large its contents will be until the program is run. In that case you'd write something like this: char *string = malloc(stringlength); // stringlength is the number of bytes to allocate // Do something with the string... free(string); // Free the allocated memory A: @Ted Percival: ...you don't need to cast malloc()'s return value. You are correct, of course. I believe that has always been true, although I don't have a copy of K&R to check. I don't like a lot of the implicit conversions in C, so I tend to use casts to make "magic" more visible. Sometimes it helps readability, sometimes it doesn't, and sometimes it causes a silent bug to be caught by the compiler. Still, I don't have a strong opinion about this, one way or another. This is especially likely if your compiler understands C++-style comments. Yeah... you caught me there. I spend a lot more time in C++ than C. Thanks for noticing that. A: @Euro Micelli One negative to add is that pointers to the stack are no longer valid when the function returns, so you cannot return a pointer to a stack variable from a function. This is a common error and a major reason why you can't get by with just stack variables. If your function needs to return a pointer, then you have to malloc and deal with memory management. A: In C, you actually have two different choices. One, you can let the system manage the memory for you. Alternatively, you can do that by yourself. Generally, you would want to stick to the former as long as possible. However, auto-managed memory in C is extremely limited and you will need to manually manage the memory in many cases, such as: a. You want the variable to outlive the functions, and you don't want to have global variable. ex: struct pair{ int val; struct pair *next; } struct pair* new_pair(int val){ struct pair* np = malloc(sizeof(struct pair)); np->val = val; np->next = NULL; return np; } b. you want to have dynamically allocated memory. Most common example is array without fixed length: int *my_special_array; my_special_array = malloc(sizeof(int) * number_of_element); for(i=0; i c. You want to do something REALLY dirty. For example, I would want a struct to represent many kind of data and I don't like union (union looks soooo messy): struct data{ int data_type; long data_in_mem; }; struct animal{/*something*/}; struct person{/*some other thing*/}; struct animal* read_animal(); struct person* read_person(); /*In main*/ struct data sample; sampe.data_type = input_type; switch(input_type){ case DATA_PERSON: sample.data_in_mem = read_person(); break; case DATA_ANIMAL: sample.data_in_mem = read_animal(); default: printf("Oh hoh! I warn you, that again and I will seg fault your OS"); } See, a long value is enough to hold ANYTHING. Just remember to free it, or you WILL regret. This is among my favorite tricks to have fun in C :D. However, generally, you would want to stay away from your favorite tricks (T___T). You WILL break your OS, sooner or later, if you use them too often. As long as you don't use *alloc and free, it is safe to say that you are still virgin, and that the code still looks nice. A: Sure. If you create an object that exists outside of the scope you use it in. Here is a contrived example (bear in mind my syntax will be off; my C is rusty, but this example will still illustrate the concept): class MyClass { SomeOtherClass *myObject; public MyClass() { //The object is created when the class is constructed myObject = (SomeOtherClass*)malloc(sizeof(myObject)); } public ~MyClass() { //The class is destructed //If you don't free the object here, you leak memory free(myObject); } public void SomeMemberFunction() { //Some use of the object myObject->SomeOperation(); } }; In this example, I'm using an object of type SomeOtherClass during the lifetime of MyClass. The SomeOtherClass object is used in several functions, so I've dynamically allocated the memory: the SomeOtherClass object is created when MyClass is created, used several times over the life of the object, and then freed once MyClass is freed. Obviously if this were real code, there would be no reason (aside from possibly stack memory consumption) to create myObject in this way, but this type of object creation/destruction becomes useful when you have a lot of objects, and want to finely control when they are created and destroyed (so that your application doesn't suck up 1GB of RAM for its entire lifetime, for example), and in a Windowed environment, this is pretty much mandatory, as objects that you create (buttons, say), need to exist well outside of any particular function's (or even class') scope.
{ "language": "en", "url": "https://stackoverflow.com/questions/24891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "101" }
Q: Is there a performance difference between i++ and ++i in C++? We have the question is there a performance difference between i++ and ++i in C? What's the answer for C++? A: Yes. There is. The ++ operator may or may not be defined as a function. For primitive types (int, double, ...) the operators are built in, so the compiler will probably be able to optimize your code. But in the case of an object that defines the ++ operator things are different. The operator++(int) function must create a copy. That is because postfix ++ is expected to return a different value than what it holds: it must hold its value in a temp variable, increment its value and return the temp. In the case of operator++(), prefix ++, there is no need to create a copy: the object can increment itself and then simply return itself. Here is an illustration of the point: struct C { C& operator++(); // prefix C operator++(int); // postfix private: int i_; }; C& C::operator++() { ++i_; return *this; // self, no copy created } C C::operator++(int ignored_dummy_value) { C t(*this); ++(*this); return t; // return a copy } Every time you call operator++(int) you must create a copy, and the compiler can't do anything about it. When given the choice, use operator++(); this way you don't save a copy. It might be significant in the case of many increments (large loop?) and/or large objects. A: * *++i - faster not using the return value *i++ - faster using the return value When not using the return value the compiler is guaranteed not to use a temporary in the case of ++i. Not guaranteed to be faster, but guaranteed not to be slower. When using the return value i++ allows the processor to push both the increment and the left side into the pipeline since they don't depend on each other. ++i may stall the pipeline because the processor cannot start the left side until the pre-increment operation has meandered all the way through. Again, a pipeline stall is not guaranteed, since the processor may find other useful things to stick in. A: Here's a benchmark for the case when increment operators are in different translation units. Compiler with g++ 4.5. Ignore the style issues for now // a.cc #include <ctime> #include <array> class Something { public: Something& operator++(); Something operator++(int); private: std::array<int,PACKET_SIZE> data; }; int main () { Something s; for (int i=0; i<1024*1024*30; ++i) ++s; // warm up std::clock_t a = clock(); for (int i=0; i<1024*1024*30; ++i) ++s; a = clock() - a; for (int i=0; i<1024*1024*30; ++i) s++; // warm up std::clock_t b = clock(); for (int i=0; i<1024*1024*30; ++i) s++; b = clock() - b; std::cout << "a=" << (a/double(CLOCKS_PER_SEC)) << ", b=" << (b/double(CLOCKS_PER_SEC)) << '\n'; return 0; } O(n) increment Test // b.cc #include <array> class Something { public: Something& operator++(); Something operator++(int); private: std::array<int,PACKET_SIZE> data; }; Something& Something::operator++() { for (auto it=data.begin(), end=data.end(); it!=end; ++it) ++*it; return *this; } Something Something::operator++(int) { Something ret = *this; ++*this; return ret; } Results Results (timings are in seconds) with g++ 4.5 on a virtual machine: Flags (--std=c++0x) ++i i++ -DPACKET_SIZE=50 -O1 1.70 2.39 -DPACKET_SIZE=50 -O3 0.59 1.00 -DPACKET_SIZE=500 -O1 10.51 13.28 -DPACKET_SIZE=500 -O3 4.28 6.82 O(1) increment Test Let us now take the following file: // c.cc #include <array> class Something { public: Something& operator++(); Something operator++(int); private: std::array<int,PACKET_SIZE> data; }; Something& Something::operator++() { return *this; } Something Something::operator++(int) { Something ret = *this; ++*this; return ret; } It does nothing in the incrementation. This simulates the case when incrementation has constant complexity. Results Results now vary extremely: Flags (--std=c++0x) ++i i++ -DPACKET_SIZE=50 -O1 0.05 0.74 -DPACKET_SIZE=50 -O3 0.08 0.97 -DPACKET_SIZE=500 -O1 0.05 2.79 -DPACKET_SIZE=500 -O3 0.08 2.18 -DPACKET_SIZE=5000 -O3 0.07 21.90 Conclusion Performance-wise If you do not need the previous value, make it a habit to use pre-increment. Be consistent even with builtin types, you'll get used to it and do not run risk of suffering unecessary performance loss if you ever replace a builtin type with a custom type. Semantic-wise * *i++ says increment i, I am interested in the previous value, though. *++i says increment i, I am interested in the current value or increment i, no interest in the previous value. Again, you'll get used to it, even if you are not right now. Knuth. Premature optimization is the root of all evil. As is premature pessimization. A: I would like to point out an excellent post by Andrew Koenig on Code Talk very recently. http://dobbscodetalk.com/index.php?option=com_myblog&show=Efficiency-versus-intent.html&Itemid=29 At our company also we use convention of ++iter for consistency and performance where applicable. But Andrew raises over-looked detail regarding intent vs performance. There are times when we want to use iter++ instead of ++iter. So, first decide your intent and if pre or post does not matter then go with pre as it will have some performance benefit by avoiding creation of extra object and throwing it. A: @Ketan ...raises over-looked detail regarding intent vs performance. There are times when we want to use iter++ instead of ++iter. Obviously post and pre-increment have different semantics and I'm sure everyone agrees that when the result is used you should use the appropriate operator. I think the question is what should one do when the result is discarded (as in for loops). The answer to this question (IMHO) is that, since the performance considerations are negligible at best, you should do what is more natural. For myself ++i is more natural but my experience tells me that I'm in a minority and using i++ will cause less metal overhead for most people reading your code. After all that's the reason the language is not called "++C".[*] [*] Insert obligatory discussion about ++C being a more logical name. A: [Executive Summary: Use ++i if you don't have a specific reason to use i++.] For C++, the answer is a bit more complicated. If i is a simple type (not an instance of a C++ class), then the answer given for C ("No there is no performance difference") holds, since the compiler is generating the code. However, if i is an instance of a C++ class, then i++ and ++i are making calls to one of the operator++ functions. Here's a standard pair of these functions: Foo& Foo::operator++() // called for ++i { this->data += 1; return *this; } Foo Foo::operator++(int ignored_dummy_value) // called for i++ { Foo tmp(*this); // variable "tmp" cannot be optimized away by the compiler ++(*this); return tmp; } Since the compiler isn't generating code, but just calling an operator++ function, there is no way to optimize away the tmp variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact. A: Mark: Just wanted to point out that operator++'s are good candidates to be inlined, and if the compiler elects to do so, the redundant copy will be eliminated in most cases. (e.g. POD types, which iterators usually are.) That said, it's still better style to use ++iter in most cases. :-) A: The performance difference between ++i and i++ will be more apparent when you think of operators as value-returning functions and how they are implemented. To make it easier to understand what's happening, the following code examples will use int as if it were a struct. ++i increments the variable, then returns the result. This can be done in-place and with minimal CPU time, requiring only one line of code in many cases: int& int::operator++() { return *this += 1; } But the same cannot be said of i++. Post-incrementing, i++, is often seen as returning the original value before incrementing. However, a function can only return a result when it is finished. As a result, it becomes necessary to create a copy of the variable containing the original value, increment the variable, then return the copy holding the original value: int int::operator++(int& _Val) { int _Original = _Val; _Val += 1; return _Original; } When there is no functional difference between pre-increment and post-increment, the compiler can perform optimization such that there is no performance difference between the two. However, if a composite data type such as a struct or class is involved, the copy constructor will be called on post-increment, and it will not be possible to perform this optimization if a deep copy is needed. As such, pre-increment generally is faster and requires less memory than post-increment. A: It's not entirely correct to say that the compiler can't optimize away the temporary variable copy in the postfix case. A quick test with VC shows that it, at least, can do that in certain cases. In the following example, the code generated is identical for prefix and postfix, for instance: #include <stdio.h> class Foo { public: Foo() { myData=0; } Foo(const Foo &rhs) { myData=rhs.myData; } const Foo& operator++() { this->myData++; return *this; } const Foo operator++(int) { Foo tmp(*this); this->myData++; return tmp; } int GetData() { return myData; } private: int myData; }; int main(int argc, char* argv[]) { Foo testFoo; int count; printf("Enter loop count: "); scanf("%d", &count); for(int i=0; i<count; i++) { testFoo++; } printf("Value: %d\n", testFoo.GetData()); } Whether you do ++testFoo or testFoo++, you'll still get the same resulting code. In fact, without reading the count in from the user, the optimizer got the whole thing down to a constant. So this: for(int i=0; i<10; i++) { testFoo++; } printf("Value: %d\n", testFoo.GetData()); Resulted in the following: 00401000 push 0Ah 00401002 push offset string "Value: %d\n" (402104h) 00401007 call dword ptr [__imp__printf (4020A0h)] So while it's certainly the case that the postfix version could be slower, it may well be that the optimizer will be good enough to get rid of the temporary copy if you're not using it. A: The Google C++ Style Guide says: Preincrement and Predecrement Use prefix form (++i) of the increment and decrement operators with iterators and other template objects. Definition: When a variable is incremented (++i or i++) or decremented (--i or i--) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement). Pros: When the return value is ignored, the "pre" form (++i) is never less efficient than the "post" form (i++), and is often more efficient. This is because post-increment (or decrement) requires a copy of i to be made, which is the value of the expression. If i is an iterator or other non-scalar type, copying i could be expensive. Since the two types of increment behave the same when the value is ignored, why not just always pre-increment? Cons: The tradition developed, in C, of using post-increment when the expression value is not used, especially in for loops. Some find post-increment easier to read, since the "subject" (i) precedes the "verb" (++), just like in English. Decision: For simple scalar (non-object) values there is no reason to prefer one form and we allow either. For iterators and other template types, use pre-increment. A: @Mark: I deleted my previous answer because it was a bit flip, and deserved a downvote for that alone. I actually think it's a good question in the sense that it asks what's on the minds of a lot of people. The usual answer is that ++i is faster than i++, and no doubt it is, but the bigger question is "when should you care?" If the fraction of CPU time spent in incrementing iterators is less than 10%, then you may not care. If the fraction of CPU time spent in incrementing iterators is greater than 10%, you can look at which statements are doing that iterating. See if you could just increment integers rather than using iterators. Chances are you could, and while it may be in some sense less desirable, chances are pretty good you will save essentially all the time spent in those iterators. I've seen an example where the iterator-incrementing was consuming well over 90% of the time. In that case, going to integer-incrementing reduced execution time by essentially that amount. (i.e. better than 10x speedup) A: @wilhelmtell The compiler can elide the temporary. Verbatim from the other thread: The C++ compiler is allowed to eliminate stack based temporaries even if doing so changes program behavior. MSDN link for VC 8: http://msdn.microsoft.com/en-us/library/ms364057(VS.80).aspx A: Since you asked for C++ too, here is a benchmark for java (made with jmh) : private static final int LIMIT = 100000; @Benchmark public void postIncrement() { long a = 0; long b = 0; for (int i = 0; i < LIMIT; i++) { b = 3; a += i * (b++); } doNothing(a, b); } @Benchmark public void preIncrement() { long a = 0; long b = 0; for (int i = 0; i < LIMIT; i++) { b = 3; a += i * (++b); } doNothing(a, b); } The result shows, even when the value of the incremented variable (b) is actually used in some computation, forcing the need to store an additional value in case of post-increment, the time per operation is exactly the same : Benchmark Mode Cnt Score Error Units IncrementBenchmark.postIncrement avgt 10 0,039 0,001 ms/op IncrementBenchmark.preIncrement avgt 10 0,039 0,001 ms/op A: An the reason why you ought to use ++i even on built-in types where there's no performance advantage is to create a good habit for yourself. A: The intended question was about when the result is unused (that's clear from the question for C). Can somebody fix this since the question is "community wiki"? About premature optimizations, Knuth is often quoted. That's right. but Donald Knuth would never defend with that the horrible code which you can see in these days. Ever seen a = b + c among Java Integers (not int)? That amounts to 3 boxing/unboxing conversions. Avoiding stuff like that is important. And uselessly writing i++ instead of ++i is the same mistake. EDIT: As phresnel nicely puts it in a comment, this can be summed up as "premature optimization is evil, as is premature pessimization". Even the fact that people are more used to i++ is an unfortunate C legacy, caused by a conceptual mistake by K&R (if you follow the intent argument, that's a logical conclusion; and defending K&R because they're K&R is meaningless, they're great, but they aren't great as language designers; countless mistakes in the C design exist, ranging from gets() to strcpy(), to the strncpy() API (it should have had the strlcpy() API since day 1)). Btw, I'm one of those not used enough to C++ to find ++i annoying to read. Still, I use that since I acknowledge that it's right. A: Both are as fast ;) If you want it is the same calculation for the processor, it's just the order in which it is done that differ. For example, the following code : #include <stdio.h> int main() { int a = 0; a++; int b = 0; ++b; return 0; } Produce the following assembly : 0x0000000100000f24 <main+0>: push %rbp 0x0000000100000f25 <main+1>: mov %rsp,%rbp 0x0000000100000f28 <main+4>: movl $0x0,-0x4(%rbp) 0x0000000100000f2f <main+11>: incl -0x4(%rbp) 0x0000000100000f32 <main+14>: movl $0x0,-0x8(%rbp) 0x0000000100000f39 <main+21>: incl -0x8(%rbp) 0x0000000100000f3c <main+24>: mov $0x0,%eax 0x0000000100000f41 <main+29>: leaveq 0x0000000100000f42 <main+30>: retq You see that for a++ and b++ it's an incl mnemonic, so it's the same operation ;) A: i++ is sometimes faster than ++i! For x86-architectures that use ILP (instruction level paralellism) i++ might in some situations outperform ++i. Why? Because of data dependencies. Modern CPUs parallelise a lot of stuff. If the next few CPU cycles don't have any direct dependency on the incremented value of i, the CPU might omit microcode to delay the increment of i and shove it in a "free slot". This means that you essentially get a "free" increment. I don't know how far ILE goes in this case but I suppose if the iterator becomes too complicated and does pointer dereferencing this might not work. Here's a talk by Andrei Alexandrescu explaining the concept: https://www.youtube.com/watch?v=vrfYLlR8X8k&list=WL&index=5 A: ++i is faster than i++ because it doesn't return an old copy of the value. It's also more intuitive: x = i++; // x contains the old value of i y = ++i; // y contains the new value of i This C example prints "02" instead of the "12" you might expect: #include <stdio.h> int main(){ int a = 0; printf("%d", a++); printf("%d", ++a); return 0; } Same for C++: #include <iostream> using namespace std; int main(){ int a = 0; cout << a++; cout << ++a; return 0; } A: Time to provide folks with gems of wisdom ;) - there is simple trick to make C++ postfix increment behave pretty much the same as prefix increment (Invented this for myself, but the saw it as well in other people code, so I'm not alone). Basically, trick is to use helper class to postpone increment after the return, and RAII comes to rescue #include <iostream> class Data { private: class DataIncrementer { private: Data& _dref; public: DataIncrementer(Data& d) : _dref(d) {} public: ~DataIncrementer() { ++_dref; } }; private: int _data; public: Data() : _data{0} {} public: Data(int d) : _data{d} {} public: Data(const Data& d) : _data{ d._data } {} public: Data& operator=(const Data& d) { _data = d._data; return *this; } public: ~Data() {} public: Data& operator++() { // prefix ++_data; return *this; } public: Data operator++(int) { // postfix DataIncrementer t(*this); return *this; } public: operator int() { return _data; } }; int main() { Data d(1); std::cout << d << '\n'; std::cout << ++d << '\n'; std::cout << d++ << '\n'; std::cout << d << '\n'; return 0; } Invented is for some heavy custom iterators code, and it cuts down run-time. Cost of prefix vs postfix is one reference now, and if this is custom operator doing heavy moving around, prefix and postfix yielded the same run-time for me. A: ++i is faster than i = i +1 because in i = i + 1 two operation are taking place, first increment and second assigning it to a variable. But in i++ only increment operation is taking place.
{ "language": "en", "url": "https://stackoverflow.com/questions/24901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "407" }
Q: BizTalk DB2 adapter connection error My colleagues are attempting to connect BizTalk 2006 R2 via DB2/MVS adapter to a database hosted on z/OS mainframe. When testing the connecting settings, they are getting the following error Could not connect to data source 'New Data Source': The network connection was terminated because the host failed to send any data. SQLSTATE: 08S01, SQLCODE: -605 When putting the settings in a regular connection string and opening with .NET code, that is fine. I am new to BizTalk and DB2. Can anybody suggest what to look out for when this error surfaces? 24 Aug 08: Well, if normal .NET code with a regular DB2 connection string is used, the connection can be made and queries submitted. What this DB2 adapter is reporting is it cannot even make a proper connection handshake, let alone submitting queries. I am unsure of what are the actual mechanisms involved to make a DB2 connection happen. 25 Aug 08: According to this MSDN forums posting, it seems to be a login issue. I have seen that and that is not the case here. If we put the user name as the Package Collection it still hits the same problem. 26 Aug 08: Because of the scarcity of information regarding connecting to mainframe DB2 databases from Microsoft products, I undertook the task of inspecting raw network packets to get a clue what is going on between the .NET DB2 provider's connection (which works) and the BizTalk 2006 DB2 adapter (which bombs). I observed DB2 traffic is done using the DRDA protocol. And ultimately concluded the BizTalk adapter method fails because of what's recorded in the server's reply SECCHKRM packet DRDA (Security Check) DDM (SECCHKRM) Length: 55 Magic: 0xd0 Format: 0x02 0... = Reserved: Not set .0.. = Chained: Not set ..0. = Continue: Not set ...0 = Same correlation: Not set DSS type: RPYDSS (2) CorrelId: 0 Length2: 49 Code point: SECCHKRM (0x1219) Parameter (Severity Code) Length: 6 Code point: SVRCOD (0x1149) Data (ASCII): Data (EBCDIC): Parameter (Security Check Code) Length: 5 Code point: SECCHKCD (0x11a4) Data (ASCII): Data (EBCDIC): Parameter (Server Diagnostic Information) Length: 34 Code point: SRVDGN (0x1153) Data (ASCII): \304\331\304\301@\301\331z@\301\344\343\310\305\325\343\311\303\301\343\311\326\325@\206\201\211\223\205\204 Data (EBCDIC): DRDA AR: AUTHENTICATION failed Why the same credentials fails here while succeeding in the .NET provider is beyond me. Right now, what I can observe is a marked difference between each method when it comes to the sequence of packets transferred. .NET DB2 provider No. Time Source Destination Protocol Info 1 0.000000 [client IP] [DB2 server IP] TCP kpop > 50000 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=1 2 0.000399 [DB2 server IP] [client IP] TCP 50000 > kpop [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 3 0.000414 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1 Ack=1 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 4 0.000532 [client IP] [DB2 server IP] DRDA EXCSAT | ACCSEC 5 0.038162 [DB2 server IP] [client IP] DRDA EXCSATRD | ACCSECRD 6 0.041829 [client IP] [DB2 server IP] DRDA ACCSEC | SECCHK | ACCRDB 7 0.083626 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=108 Ack=542 Win=65535 Len=0 8 0.190534 [DB2 server IP] [client IP] DRDA ACCSECRD | SECCHKRM | ACCRDBRM | SQLCARD 9 0.199776 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 10 0.293307 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 11 0.293359 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 12 0.293377 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=1444 Win=64092 [TCP CHECKSUM INCORRECT] Len=0 13 0.293404 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 14 0.293452 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 15 0.293461 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=2516 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 16 0.293855 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 17 0.293908 [DB2 server IP] [client IP] DRDA SQLDARD 18 0.293918 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=3588 Win=64464 [TCP CHECKSUM INCORRECT] Len=0 19 0.293957 [DB2 server IP] [client IP] DRDA QRYDSC 20 0.294008 [DB2 server IP] [client IP] DRDA QRYDTA 21 0.294017 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=4660 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 22 0.294023 [DB2 server IP] [client IP] DRDA SQLCARD 23 0.295346 [client IP] [DB2 server IP] DRDA RDBCMM 24 0.297868 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 25 0.421392 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 26 0.456504 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD 27 0.456756 [client IP] [DB2 server IP] DRDA RDBCMM 28 0.488311 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 29 0.498806 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 30 0.630477 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=5157 Ack=1579 Win=65171 Len=0 31 0.788165 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA 32 0.788203 [DB2 server IP] [client IP] DRDA ENDQRYRM 33 0.788225 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1579 Ack=5815 Win=64380 [TCP CHECKSUM INCORRECT] Len=0 34 0.788648 [client IP] [DB2 server IP] DRDA RDBCMM 35 0.795951 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 36 0.807365 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 37 0.838046 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD 38 0.838328 [client IP] [DB2 server IP] DRDA RDBCMM 39 0.841866 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 40 0.973506 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1906 Ack=6304 Win=65482 [TCP CHECKSUM INCORRECT] Len=0 BizTalk DB2 adapter No. Time Source Destination Protocol Info 1 0.000000 [client IP] [DB2 server IP] TCP 28165 > 50000 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=8 2 0.002587 [DB2 server IP] [client IP] TCP 50000 > 28165 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 3 0.010146 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=1 Ack=1 Win=65536 Len=0 4 0.019698 [client IP] [DB2 server IP] DRDA EXCSAT 5 0.020849 [DB2 server IP] [client IP] DRDA EXCSATRD 6 0.034699 [client IP] [DB2 server IP] DRDA ACCSEC 7 0.036584 [DB2 server IP] [client IP] DRDA ACCSECRD 8 0.042031 [client IP] [DB2 server IP] DRDA SECCHK 9 0.046350 [DB2 server IP] [client IP] DRDA SECCHKRM 10 0.046642 [DB2 server IP] [client IP] TCP 50000 > 28165 [FIN, ACK] Seq=160 Ack=200 Win=65336 Len=0 11 0.053787 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=200 Ack=161 Win=65536 Len=0 12 0.056891 [client IP] [DB2 server IP] DRDA ACCRDB 13 0.058084 [DB2 server IP] [client IP] TCP 50000 > 28165 [RST, ACK] Seq=161 Ack=295 Win=0 Len=0 It is interesting to witness the .NET provider issue out various DRDA protocol packets within in a single TCP segment. The BizTalk adapter on the other hand, places only one protocol packet per TCP segment. I do not know why this is so. However, I at the moment think that is a red herring and the true difference causing the failure in authentication is in the DRDA data exchange. I do not know the DRDA protocol so will have to study it before I can make more sense of it. 18 Sep 08: At this stage the problem is still not solved, as getting cooperation from the DB2 DBA team and help from Microsoft have been met with many obstacles. What I do want to report is, I have observed perhaps one crucial difference between all the cases of successful connection versus the failed attempt: The BizTalk DB2 adapter is underlyingly using Microsoft ODBC Driver for DB2. The other software tests that succeed make use of IBM DB2 ODBC DRIVER or IBM DB2 ODBC DRIVER – IBMCL1. The IBM driver's parameter configuration is different from Microsoft's driver. But we do not see any obviously critical difference that may lead to a failed authentication for the Microsoft driver. A: Why, it certainly took Microsoft long enough to explicitly confirm this: proxy connections via DB2Connect is not supported by BizTalk DB2 Adapter Since our customer's policy is to only access DB2 databases via DB2Connect, the adapter is out of the question. MORE BACKGROUND INFO The reason why the DB2 Adapter only works for a direct connection to a z/OS mainframe host, is due to legal restrictions. Technically it is possible to work a connection with DB2Connect, but IBM has made it a priorietary node and prevented other parties from legally establishing the correct DRDA sequence to connect to it. A: I've never used this adapter but myself, so I'm guessing, but maybe it's to do with the account that BizTalk is using to connect or your ports are not configured correctly. A: According to this MSDN forums posting, it seems to be a login issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/24915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Difference between EXISTS and IN in SQL? What is the difference between the EXISTS and IN clause in SQL? When should we use EXISTS, and when should we use IN? A: Based on rule optimizer: * *EXISTS is much faster than IN, when the sub-query results is very large. *IN is faster than EXISTS, when the sub-query results is very small. Based on cost optimizer: * *There is no difference. A: I think, * *EXISTS is when you need to match the results of query with another subquery. Query#1 results need to be retrieved where SubQuery results match. Kind of a Join.. E.g. select customers table#1 who have placed orders table#2 too *IN is to retrieve if the value of a specific column lies IN a list (1,2,3,4,5) E.g. Select customers who lie in the following zipcodes i.e. zip_code values lies in (....) list. When to use one over the other... when you feel it reads appropriately (Communicates intent better). A: I'm assuming you know what they do, and thus are used differently, so I'm going to understand your question as: When would it be a good idea to rewrite the SQL to use IN instead of EXISTS, or vice versa. Is that a fair assumption? Edit: The reason I'm asking is that in many cases you can rewrite an SQL based on IN to use an EXISTS instead, and vice versa, and for some database engines, the query optimizer will treat the two differently. For instance: SELECT * FROM Customers WHERE EXISTS ( SELECT * FROM Orders WHERE Orders.CustomerID = Customers.ID ) can be rewritten to: SELECT * FROM Customers WHERE ID IN ( SELECT CustomerID FROM Orders ) or with a join: SELECT Customers.* FROM Customers INNER JOIN Orders ON Customers.ID = Orders.CustomerID So my question still stands, is the original poster wondering about what IN and EXISTS does, and thus how to use it, or does he ask wether rewriting an SQL using IN to use EXISTS instead, or vice versa, will be a good idea? A: * *EXISTS is much faster than IN when the subquery results is very large. IN is faster than EXISTS when the subquery results is very small. CREATE TABLE t1 (id INT, title VARCHAR(20), someIntCol INT) GO CREATE TABLE t2 (id INT, t1Id INT, someData VARCHAR(20)) GO INSERT INTO t1 SELECT 1, 'title 1', 5 UNION ALL SELECT 2, 'title 2', 5 UNION ALL SELECT 3, 'title 3', 5 UNION ALL SELECT 4, 'title 4', 5 UNION ALL SELECT null, 'title 5', 5 UNION ALL SELECT null, 'title 6', 5 INSERT INTO t2 SELECT 1, 1, 'data 1' UNION ALL SELECT 2, 1, 'data 2' UNION ALL SELECT 3, 2, 'data 3' UNION ALL SELECT 4, 3, 'data 4' UNION ALL SELECT 5, 3, 'data 5' UNION ALL SELECT 6, 3, 'data 6' UNION ALL SELECT 7, 4, 'data 7' UNION ALL SELECT 8, null, 'data 8' UNION ALL SELECT 9, 6, 'data 9' UNION ALL SELECT 10, 6, 'data 10' UNION ALL SELECT 11, 8, 'data 11' *Query 1 SELECT FROM t1 WHERE not EXISTS (SELECT * FROM t2 WHERE t1.id = t2.t1id) Query 2 SELECT t1.* FROM t1 WHERE t1.id not in (SELECT t2.t1id FROM t2 ) If in t1 your id has null value then Query 1 will find them, but Query 2 cant find null parameters. I mean IN can't compare anything with null, so it has no result for null, but EXISTS can compare everything with null. A: As per my knowledge when a subquery returns a NULL value then the whole statement becomes NULL. In that cases we are using the EXITS keyword. If we want to compare particular values in subqueries then we are using the IN keyword. A: Which one is faster depends on the number of queries fetched by the inner query: * *When your inner query fetching thousand of rows then EXIST would be better choice *When your inner query fetching few rows, then IN will be faster EXIST evaluate on true or false but IN compare multiple value. When you don't know the record is exist or not, your should choose EXIST A: Difference lies here: select * from abcTable where exists (select null) Above query will return all the records while below one would return empty. select * from abcTable where abcTable_ID in (select null) Give it a try and observe the output. A: The reason is that the EXISTS operator works based on the “at least found” principle. It returns true and stops scanning table once at least one matching row found. On the other hands, when the IN operator is combined with a subquery, MySQL must process the subquery first, and then uses the result of the subquery to process the whole query. The general rule of thumb is that if the subquery contains a large volume of data, the EXISTS operator provides a better performance. However, the query that uses the IN operator will perform faster if the result set returned from the subquery is very small. A: The exists keyword can be used in that way, but really it's intended as a way to avoid counting: --this statement needs to check the entire table select count(*) from [table] where ... --this statement is true as soon as one match is found exists ( select * from [table] where ... ) This is most useful where you have if conditional statements, as exists can be a lot quicker than count. The in is best used where you have a static list to pass: select * from [table] where [field] in (1, 2, 3) When you have a table in an in statement it makes more sense to use a join, but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) in queries will always get a nested join plan, while join queries will use nested, merge or hash as appropriate. More modern implementations are smarter and can adjust the plan even when in is used. A: If you are using the IN operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS, the SQL engine will stop the scanning process as soon as it found a match. A: In certain circumstances, it is better to use IN rather than EXISTS. In general, if the selective predicate is in the subquery, then use IN. If the selective predicate is in the parent query, then use EXISTS. https://docs.oracle.com/cd/B19306_01/server.102/b14211/sql_1016.htm#i28403 A: IN supports only equality relations (or inequality when preceded by NOT). It is a synonym to =any / =some, e.g select * from t1 where x in (select x from t2) ; EXISTS supports variant types of relations, that cannot be expressed using IN, e.g. - select * from t1 where exists (select null from t2 where t2.x=t1.x and t2.y>t1.y and t2.z like '℅' || t1.z || '℅' ) ; And on a different note - The allegedly performance and technical differences between EXISTS and IN may result from specific vendor's implementations/limitations/bugs, but many times they are nothing but myths created due to lack of understanding of the databases internals. The tables' definition, statistics' accuracy, database configuration and optimizer's version have all impact on the execution plan and therefore on the performance metrics. A: EXISTS will tell you whether a query returned any results. e.g.: SELECT * FROM Orders o WHERE EXISTS ( SELECT * FROM Products p WHERE p.ProductNumber = o.ProductNumber) IN is used to compare one value to several, and can use literal values, like this: SELECT * FROM Orders WHERE ProductNumber IN (1, 10, 100) You can also use query results with the IN clause, like this: SELECT * FROM Orders WHERE ProductNumber IN ( SELECT ProductNumber FROM Products WHERE ProductInventoryQuantity > 0) A: The Exists keyword evaluates true or false, but IN keyword compare all value in the corresponding sub query column. Another one Select 1 can be use with Exists command. Example: SELECT * FROM Temp1 where exists(select 1 from Temp2 where conditions...) But IN is less efficient so Exists faster. A: My understand is both should be the same as long as we are not dealing with NULL values. The same reason why the query does not return the value for = NULL vs is NULL. http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/ As for as boolean vs comparator argument goes, to generate a boolean both values needs to be compared and that is how any if condition works.So i fail to understand how IN and EXISTS behave differently . A: If a subquery returns more than one value, you might need to execute the outer query- if the values within the column specified in the condition match any value in the result set of the subquery. To perform this task, you need to use the in keyword. You can use a subquery to check if a set of records exists. For this, you need to use the exists clause with a subquery. The exists keyword always return true or false value. A: I believe this has a straightforward answer. Why don't you check it from the people who developed that function in their systems? If you are a MS SQL developer, here is the answer directly from Microsoft. IN: Determines whether a specified value matches any value in a subquery or a list. EXISTS: Specifies a subquery to test for the existence of rows. A: I found that using EXISTS keyword is often really slow (that is very true in Microsoft Access). I instead use the join operator in this manner : should-i-use-the-keyword-exists-in-sql A: If you can use where in instead of where exists, then where in is probably faster. Using where in or where exists will go through all results of your parent result. The difference here is that the where exists will cause a lot of dependet sub-queries. If you can prevent dependet sub-queries, then where in will be the better choice. Example Assume we have 10,000 companies, each has 10 users (thus our users table has 100,000 entries). Now assume you want to find a user by his name or his company name. The following query using were exists has an execution of 141ms: select * from `users` where `first_name` ='gates' or exists ( select * from `companies` where `users`.`company_id` = `companies`.`id` and `name` = 'gates' ) This happens, because for each user a dependent sub query is executed: However, if we avoid the exists query and write it using: select * from `users` where `first_name` ='gates' or users.company_id in ( select id from `companies` where `name` = 'gates' ) Then depended sub queries are avoided and the query would run in 0,012 ms A: I did a little exercise on a query that I have recently been using. I originally created it with INNER JOINS, but I wanted to see how it looked/worked with EXISTS. I converted it. I will include both version here for comparison. SELECT DISTINCT Category, Name, Description FROM [CodeSets] WHERE Category NOT IN ( SELECT def.Category FROM [Fields] f INNER JOIN [DataEntryFields] def ON f.DataEntryFieldId = def.Id INNER JOIN Section s ON f.SectionId = s.Id INNER JOIN Template t ON s.Template_Id = t.Id WHERE t.AgencyId = (SELECT Id FROM Agencies WHERE Name = 'Some Agency') AND def.Category NOT IN ('OFFLIST', 'AGENCYLIST', 'RELTO_UNIT', 'HOSPITALS', 'EMS', 'TOWCOMPANY', 'UIC', 'RPTAGENCY', 'REP') AND (t.Name like '% OH %') AND (def.Category IS NOT NULL AND def.Category <> '') ) ORDER BY 1 Here are the statistics: Here is the converted version: SELECT DISTINCT cs.Category, Name, Description FROM [CodeSets] cs WHERE NOT Exists ( SELECT * FROM [Fields] f WHERE EXISTS (SELECT * FROM [DataEntryFields] def WHERE def.Id = f.DataEntryFieldId AND def.Category NOT IN ('OFFLIST', 'AGENCYLIST', 'RELTO_UNIT', 'HOSPITALS', 'EMS', 'TOWCOMPANY', 'UIC', 'RPTAGENCY', 'REP') AND (def.Category IS NOT NULL AND def.Category <> '') AND def.Category = cs.Category AND EXISTS (SELECT * FROM Section s WHERE f.SectionId = s.Id AND EXISTS (SELECT * FROM Template t WHERE s.Template_Id = t.Id AND EXISTS (SELECT * FROM Agencies WHERE Name = 'Some Agency' and t.AgencyId = Id) AND (t.Name like '% OH %') ) ) ) ) ORDER BY 1 The results, at least to me, were unimpressive. If I were more technically knowledgeable about how SQL works, I could give you an answer, but take this example as you may and make your own conclusion. The INNER JOIN and IN () is easier to read, however. A: If you are using the IN operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS, the SQL engine will stop the scanning process as soon as it found a match. A: EXISTS Is Faster in Performance than IN. If Most of the filter criteria is in subquery then better to use IN and If most of the filter criteria is in main query then better to use EXISTS.
{ "language": "en", "url": "https://stackoverflow.com/questions/24929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "498" }
Q: How to capture Python interpreter's and/or CMD.EXE's output from a Python script? * *Is it possible to capture Python interpreter's output from a Python script? *Is it possible to capture Windows CMD's output from a Python script? If so, which librar(y|ies) should I look into? A: I think I can point you to a good answer for the first part of your question. 1.  Is it possible to capture Python interpreter's output from a Python script? The answer is "yes", and personally I like the following lifted from the examples in the PEP 343 -- The "with" Statement document. from contextlib import contextmanager import sys @contextmanager def stdout_redirected(new_stdout): saved_stdout = sys.stdout sys.stdout = new_stdout try: yield None finally: sys.stdout.close() sys.stdout = saved_stdout And used like this: with stdout_redirected(open("filename.txt", "w")): print "Hello world" A nice aspect of it is that it can be applied selectively around just a portion of a script's execution, rather than its entire extent, and stays in effect even when unhandled exceptions are raised within its context. If you re-open the file in append-mode after its first use, you can accumulate the results into a single file: with stdout_redirected(open("filename.txt", "w")): print "Hello world" print "screen only output again" with stdout_redirected(open("filename.txt", "a")): print "Hello world2" Of course, the above could also be extended to also redirect sys.stderr to the same or another file. Also see this answer to a related question. A: Actually, you definitely can, and it's beautiful, ugly, and crazy at the same time! You can replace sys.stdout and sys.stderr with StringIO objects that collect the output. Here's an example, save it as evil.py: import sys import StringIO s = StringIO.StringIO() sys.stdout = s print "hey, this isn't going to stdout at all!" print "where is it ?" sys.stderr.write('It actually went to a StringIO object, I will show you now:\n') sys.stderr.write(s.getvalue()) When you run this program, you will see that: * *nothing went to stdout (where print usually prints to) *the first string that gets written to stderr is the one starting with 'It' *the next two lines are the ones that were collected in the StringIO object Replacing sys.stdout/err like this is an application of what's called monkeypatching. Opinions may vary whether or not this is 'supported', and it is definitely an ugly hack, but it has saved my bacon when trying to wrap around external stuff once or twice. Tested on Linux, not on Windows, but it should work just as well. Let me know if it works on Windows! A: If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation: python script_a.py | python script_b.py This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on standard streams on Wikipedia. If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication): import subprocess # Of course you can open things other than python here :) process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) x = process.stderr.readline() y = process.stdout.readline() process.wait() See the Python subprocess module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard file objects. For use with pipes, reading from standard input as lassevk suggested you'd do something like this: import sys x = sys.stderr.readline() y = sys.stdin.readline() sys.stdin and sys.stdout are standard file objects as noted above, defined in the sys module. You might also want to take a look at the pipes module. Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into polling which unfortunately does not work in windows, but I'm sure there's some alternative out there. A: You want subprocess. Look specifically at Popen in 17.1.1 and communicate in 17.1.2. A: In which context are you asking? Are you trying to capture the output from a program you start on the command line? if so, then this is how to execute it: somescript.py | your-capture-program-here and to read the output, just read from standard input. If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.
{ "language": "en", "url": "https://stackoverflow.com/questions/24931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Where can I find extended HTML reporters for Simpletest? I am using Simpletest as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter. I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself. Are there any good extended HTML reporters or GUI's out there for Simpletest? Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried Cool PHPUnit Test Runner, but was not convinced. A: For SimpleTest I can't say I've ever found any "better" test reporters, so you may have to just buckle down and hack together some quick HTML/PHP for what you need. As for PHPUnit, there's PHPUnit2_HTML_Runner, but it is far from ideal. However, if you're willing to set up a continuous integration server like Xinc or phpUnderControl you can get two very nice, very detailed automated testing interfaces. A: Does SimpleTest output JUnit XML style reports? If it does, you should be able to integrate it into CruiseControl or Bamboo.
{ "language": "en", "url": "https://stackoverflow.com/questions/24941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Windows: List and Launch applications associated with an extension How to determine the applications associated with a particular extension (e.g. .JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...). I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located. A: Like Anders said - It's a good idea to use the IQueryAssociations COM interface. Here's a sample from pinvoke.net A: Sample code: using System; using Microsoft.Win32; namespace GetAssociatedApp { class Program { static void Main(string[] args) { const string extPathTemplate = @"HKEY_CLASSES_ROOT\{0}"; const string cmdPathTemplate = @"HKEY_CLASSES_ROOT\{0}\shell\open\command"; // 1. Find out document type name for .jpeg files const string ext = ".jpeg"; var extPath = string.Format(extPathTemplate, ext); var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string; if (!string.IsNullOrEmpty(docName)) { // 2. Find out which command is associated with our extension var associatedCmdPath = string.Format(cmdPathTemplate, docName); var associatedCmd = Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string; if (!string.IsNullOrEmpty(associatedCmd)) { Console.WriteLine("\"{0}\" command is associated with {1} extension", associatedCmd, ext); } } } } } A: @aku: Don't forget HKEY_CLASSES_ROOT\SystemFileAssociations\ Not sure if they are exposed in .NET, but there are COM interfaces (IQueryAssociations and friends) that deal with this so you don't have to muck around in the registry and hope stuff does not change in the next windows version A: Also HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\ .EXT\OpenWithList key for the "Open width..." list ('a', 'b', 'c', 'd' etc string values for the choices) .EXT\UserChoice key for the "Always use the selected program to open this kind of file" ('Progid' string value value) All values are keys, used the same way as docName in the example above. A: The file type associations are stored in the Windows registry, so you should be able to use the Microsoft.Win32.Registry class to read which application is registered for which file format. Here are two articles that might be helpful: * *Reading and Writing the Registry in .NET *Windows Registry Using C#
{ "language": "en", "url": "https://stackoverflow.com/questions/24954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Debugging asp.net with firefox and visual studio.net - very slow compared to IE Debugging asp.net websites/web projects in visual studio.net 2005 with Firefox is loads slower than using IE. I've read something somewhere that there is a way of fixing this but i can't for the life of me find it again. Does anyone know what i'm on about and can point me in the right direction please? Cheers John edit sorry rob i haven't explained myself very well(again). I prefer Firefox for debugging (firebug etc) hitting F5 when debugging with IE the browser launches really quickly and clicking around my web application is almost instant and when a breakpont is hit i get to my code straight away with no delays. hitting F5 when debugging with FireFox the browser launches really slowly (ok i have plugins that slow FF loading) but clicking around my web application is really really slow and when a breakpoint is hit it takes ages to break into code. i swear i've read something somewhere that there is a setting in Firefox (about:config maybe?) that when changed to some magic setting sorts all this out. A: bingo. found the article i read before. i just changed my network.dns.ipv4OnlyDomains property in about:config to localhost. restarted firefox and now firefox performs the same as IE when debugging asp.net with visual studio (2005). hope this helps anyone else that has the same problem. A: "Alternative solution". Do the following in Firefox * *about:config in the address bar *set network.dns.disableIPv6 to true. A: Are you serious? One of the main reasons I stick to Firefox is because its so much nicer to develop with.. The live source update is awesome (view source > change code > rebuild > F5 in source)... What is actually "slow".. I mean, the some browsers tend to be slower at rendering, but I dont see how it affects your debug time? As soon as the request is made, and your breakpoint is hit in the code, it stops? A: For quick debugging try this.. Add Debugger.Break() into your code at an appropriate place. Browse to the page in firefox (via localhost) if on local dev machine? and the Visual Studio Just in Time debugger should pop up.. select the currently open instance of Visual Studio and you can step into the code where every you want without having to start from the beginning or jumping to cursor. -- Lee
{ "language": "en", "url": "https://stackoverflow.com/questions/24959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to learn MDX I am currently learning OLAP & MDX after many years of relational database development. Any tips on getting started in MDX? What are the best books and resources to learn MDX? A: Here is an MDX gentle introduction. A: I found the Spoffard book not very helpful. MDX is such an oddity compared to other languages you'll learn, it's so hard to grasp from a dry book. I really would recommend a training course, otherwise you will flounder for ages. A course will really jump-start you, and it provides access to an expert when you have questions which don't seem to have online answers. The worst trap to fall into, is to continually compare it with SQL! It uses some of the same keywords, but they mean something totally different, which makes the mental jump annoyingly harder. I think the most efficient way to learn either OLAP or MDX would be to find someone who knows it, and get them to show you around, begin with some small changes, or some very simple queries. A: You should also try and get hold of MDX Studio, a free MDX query tool written by Mosha Pasumansky (one of the original creators of MDX). It has similar MDX functionality to SQL Management Studio, but also allows you to parse and format queries, which can be very handy when trying to decipher them. A: I prefer dragging and dropping fields around in MS Excel, and then using SQL Server profiler to capture trace against SSAS. This way, you get an awesome frontend for building queries, and then you can get the queries that Excel is using through the profiler. A: If you create a Pivot Table that uses a cube (in Excel), you can see the query that is being sent using this (towards the bottom of the page) http://www.codeplex.com/OlapPivotTableExtend That might be a good way of getting a feel for the simpler stuff. N.B. This is only in Excel2007, not sure about earlier versions A: I would recommend MDX with Microsoft SQL Server 2008 R2 Analysis Services Cookbook A: Book: MDX Step by Step Video tutorials, e.g. MDX tutorial and Analysis Services introduction There are more. A: A classic, albeit a bit dated, book is Fast Track to MDX. It's a great overview and a quick read, though it doesn't cover the new MDX features of SQL Server 2005. The Spofford book MDX Solutions is more up date and a little deeper, but a bit harder to get through. I also highly recommend the blogs of Mosha Pasumansky, Chris Webb, and Darren Gosbell. A: We used the LearnItFirst.com training videos and found them to be a very thorough introduction to SSAS and MDX. There are around 40 hours of content plus exercises including around 6 hours of pure MDX Training. The details for the SSAS Course can be found at: Learn IT First SSAS Training A: Besides the books and resources mentioned by others, the easiest way to kick-start your MDX learning is to get a copy of ProClarity. Unfortunately getting your hands on ProClarity is nowhere near as easy as it used to be. Microsoft bought the company in 2006, and it is now licensed through PerformancePoint, I believe. Oh yeah, and they quit development on the product. Having said all that, if you are able to get a copy, you can build queries by dragging and dropping dimensions and measures onto your rows and columns. The results of the query are then displayed in either a grid, a chart, or both. How does this help you learn MDX? ProClarity lets you see the MDX for each query. It isn't always the most elegant MDX, but it will help you quickly learn how to write lots of different queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/24963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Beginning TDD - Challenges? Solutions? Recommendations? OK, I know there have already been questions about getting started with TDD.. However, I guess I kind of know the general concensus is to just do it , However, I seem to have the following problems getting my head into the game: * *When working with collections, do will still test for obvious add/remove/inserts successful, even when based on Generics etc where we kind of "know" its going to work? *Some tests seem to take forever to implement.. Such as when working with string output, is there a "better" way to go about this sort of thing? (e.g. test the object model before parsing, break parsing down into small ops and test there) In my mind you should always test the "end result" but that can vary wildly and be tedious to set up. *I don't have a testing framework to use (work wont pay for one) so I can "practice" more. Are there any good ones that are free for commercial use? (at the moment I am using good 'ol Debug.Assert :) *Probably the biggest.. Sometimes I don't know what to expect NOT to happen.. I mean, you get your green light but I am always concerned that I may be missing a test.. Do you dig deeper to try and break the code, or leave it be and wait for it all fall over later (which will cost more).. So basically what I am looking for here is not a " just do it " but more " I did this, had problems with this, solved them by this ".. The personal experience :) A: From my own experience: * *Only test your own code, not the underlying framework's code. So if you're using a generic list then there's no need to test Add, Remove etc. *There is no 2. Look over there! Monkeys!!! *NUnit is the way to go. *You definitely can't test every outcome. I test for what I expect to happen, and then test a few edge cases where I expect to get exceptions or invalid responses. If a bug comes up down the track because of something you forgot to test, the first thing you should do (before trying to fix the bug) is write a test to prove that the bug exists. A: First, it is alright and normal to feel frustrated when you first start trying to use TDD in your coding style. Just don't get discouraged and quit, you will need to give it some time. It is a major paradigm shift in how we think about solving a problem in code. I like to think of it like when we switched from procedural to object oriented programming. Secondly, I feel that test driven development is first and foremost a design activity that is used to flesh out the design of a component by creating a test that first describes the API it is going to expose and how you are going to consume it's functionality. The test will help shape and mold the System Under Test until you have been able to encapsulate enough functionality to satisfy whatever tasks you happen to be working on. Taking the above paragraph in mind, let's look at your questions: * *If I am using a collection in my system under test, then I will setup an expectation to make sure that the code was called to insert the item and then assert the count of the collection. I don't necessarily test the Add method on my internal list. I just make sure it was called when the method that adds the item is called. I do this by adding a mocking framework into the mix, with my testing framework. *Testing strings as output can be tedious. You cannot account for every outcome. You can only test what you expect based on the functionality of the system under test. You should always break your tests down to the smallest element that it is testing. Which means you will have a lot of tests, but tests that are small and fast and only test what they should, nothing else. *There are a lot of open source testing frameworks to choose from. I am not going to argue which is best. Just find one you like and start using it. * *MbUnit *nUnit *xUnit *All you can do is setup your tests to account for what you want to happen. If a scenario comes up that introduces a bug in your functionality, at least you have a test around the functionality to add that scenario into the test and then change your functionality until the test passes. One way to find where we may have missed a test is to use code coverage. I introduced you to the mocking term in the answer for question one. When you introduce mocking into your arsenal for TDD, it dramatically makes testing easier to abstract away the parts that are not part of the system under test. Here are some resources on the mocking frameworks out there are: * *Moq: Open Source *RhinoMocks: Open Source *TypeMock: Commercial Product *NSubstitute: Open Source One way to help in using TDD, besides reading about the process, is to watch people do it. I recommend in watching the screen casts by JP Boodhoo on DNRTV. Check these out: * *Jean Paul Boodhoo on Test Driven Development Part 1 *Jean Paul Boodhoo on Test Driven Development Part 2 *Jean Paul Boodhoo on Demystifying Design Patterns Part 1 *Jean Paul Boodhoo on Demystifying Design Patterns Part 2 *Jean Paul Boodhoo on Demystifying Design Patterns Part 3 *Jean Paul Boodhoo on Demystifying Design Patterns Part 4 *Jean Paul Boodhoo on Demystifying Design Patterns Part 5 OK, these will help you see how the terms I introduced are used. It will also introduce another tool called Resharper and how it can facilitate the TDD process. I couldn't recommend this tool enough when doing TDD. Seems like you are learning the process and you are just finding some of the problems that have already been solved with using other tools. I think I would be doing an injustice to the community, if I didn't update this by adding Kent Beck's new series on Test Driven Development on Pragmatic Programmer. A: My take on this is following: * *+1 for not testing framework code, but you may still need to test classes derived from framework classes. *If some class/method is cumbersome to test it may be strong indication that something is wrong with desing. I try to follow "1 class - 1 responsibility, 1 method - 1 action" principle. That way you will be able to test complex methods much easier by doing that in smaller portions. *+1 for xUnit. For Java you may also consider TestNG. *TDD is not single event it is a process. So do not try to envision everything from the beginning, but make sure that every bug found in code is actually covered by test once discovered. A: I think the most important thing with (and actually one of the great outcomes of, in a somewhat recursive manner) TDD is successful management of dependencies. You have to make sure that modules are tested in isolation with no elaborate setup needed. For example, if you're testing a component that eventually sends an email, make the email sender a dependency so that you can mock it in your tests. This leads to a second point - mocks are your friends. Get familiarized with mocking frameworks and the style of tests they promote (behavioral, as opposed to the classic state based), and the design choices they encourage (The "Tell, don't ask" principle). A: I found that the principles illustrated in the Three Index Cards to Easily Remember the Essence of TDD is a good guide. Anyway, to answer your questions * *You don't have to test something you "know" is going to work, unless you wrote it. You didn't write generics, Microsoft did ;) *If you need to do so much for your test, maybe your object/method is doing too much as well. *Download TestDriven.NET to immediately start unit testing on your Visual Studio, (except if it's an Express edition) *Just test the correct thing that will happen. You don't need to test everything that can go wrong: you have to wait for your tests to fail for that. Seriously, just do it, dude. :) A: I am no expert at TDD, by any means, but here is my view: * *If it is completely trivial (getters/setters etc) do not test it, unless you don't have confidence in the code for some reason. *If it is a quite simple, but non-trivial method, test it. The test is probably easy to write anyway. *When it comes to what to expect not to happen, I would say that if a certain potential problem is the responsibility of the class you are testing, you need to test that it handles it correctly. If it is not the current class' responsibility, don't test it. The xUnit testing frameworks are often free to use, so if you are a .Net guy, check out NUnit, and if Java is your thing check out JUnit. A: The above advice is good, and if you want a list of free frameworks you have to look no farther than the xUnit Frameworks List on Wikipedia. Hope this helps :) A: In my opinion (your mileage may vary): 1- If you didn't write it don't test it. If you wrote it and you don't have a test for it it doesn't exist. 3- As everyone's said, xUnit's free and great. 2 & 4- Deciding exactly what to test is one of those things you can debate about with yourself forever. I try to draw this line using the principles of design by contract. Check out 'Object Oriented Software Construction" or "The Pragmatic Programmer" for details on it. A: Keep tests short, "atomic". Test the smallest assumption in each test. Make each TestMethod independent, for integration tests I even create a new database for each method. If you need to build some data for each test use an "Init" method. Use mocks to isolate the class your testing from it's dependencies. I always think "what's the minimum amount of code I need to write to prove this works for all cases ?" A: Over the last year I have become more and more convinced of the benefits of TDD. The things that I have learned along the way: 1) dependency injection is your friend. I'm not talking about inversion of control containers and frameworks to assemble plugin architectures, just passing dependencies into the constructor of the object under test. This pays back huge dividends in the testability of your code. 2) I set out with the passion / zealotry of the convert and grabbed a mocking framework and set about using mocks for everything I could. This led to brittle tests that required lots of painful set up and would fall over as soon as I started any refactoring. Use the correct kind of test double. Fakes where you just need to honour an interface, stubs to feed data back to the object under test, mock only where you care about interaction. 3) Test should be small. Aim for one assertion or interaction being tested in each test. I try to do this and mostly I'm there. This is about robustness of test code and also about the amount of complexity in a test when you need to revisit it later. The biggest problem I have had with TDD has been working with a specification from a standards body and a third party implementation of that standard that was the de-facto standard. I coded lots of really nice unit tests to the letter of the specification only to find that the implementation on the other side of the fence saw the standard as more of an advisory document. They played quite loose with it. The only way to fix this was to test with the implementation as well as the unit tests and refactor the tests and code as necessary. The real problem was the belief on my part that as long as I had code and unit tests all was good. Not so. You need to be building actual outputs and performing functional testing at the same time as you are unit testing. Small pieces of benefit all the way through the process - into users or stakeholders hands. A: Just as an addition to this, I thought I would say I have put a blog post up on my thoughts on getting started with testing (following this discussion and my own research), since it may be useful to people viewing this thread. "TDD – Getting Started with Test-Driven Development" - I have got some great feedback so far and would really appreciate any more that you guys have to offer. I hope this helps! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/24965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: How do I profile a Maven Application in Netbeans? I've got a project using Maven 2 as the build tool. Now I am using Netbeans 6 as my IDE and really want to be able to use the profiler. Is there any way I can get this to work? A: I thought this might be more complicated. It wasn't. To use the Netbeans profiler with your Maven 2 project you simply need to add a single pair of parameters when running your java app. Call up the project's Properties dialogue, select the "Run" tab and add something like the following to the jvm args: -agentpath:"C:\Program Files\NetBeans 6.0\profiler2\lib\deployed\jdk15\windows\profilerinterface.dll=\"C:\\\"Program Files\"\\\"NetBeans 6.0\"\\profiler2\\lib\\"",5140 This meant that now when I ran my app (F6) execution would wait for me to attach the profiler. Cue real time graphy goodness. Sweet.
{ "language": "en", "url": "https://stackoverflow.com/questions/24986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why can't I explicitly pass the type argument to a generic Java method? I have defined a Java function: static <T> List<T> createEmptyList() { return new ArrayList<T>(); } One way to call it is like so: List<Integer> myList = createEmptyList(); // Compiles Why can't I call it by explicitly passing the generic type argument? : Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why? I get the error Illegal start of expression from the compiler. A: When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method(); Object list = Collections.<String> emptyList(); A: You can, if you pass in the type as a method parameter. static <T> List<T> createEmptyList( Class<T> type ) { return new ArrayList<T>(); } @Test public void createStringList() { List<String> stringList = createEmptyList( String.class ); } Methods cannot be genericised in the same way that a type can, so the only option for a method with a dynamically-typed generic return type -- phew that's a mouthful :-) -- is to pass in the type as an argument. For a truly excellent FAQ on Java generics, see Angelika Langer's generics FAQ. . . Follow-up: It wouldn't make sense in this context to use the array argument as in Collection.toArray( T[] ). The only reason an array is used there is because the same (pre-allocated) array is used to contain the results (if the array is large enough to fit them all in). This saves on allocating a new array at run-time all the time. However, for the purposes of education, if you did want to use the array typing, the syntax is very similar: static <T> List<T> createEmptyList( T[] array ) { return new ArrayList<T>(); } @Test public void testThing() { List<Integer> integerList = createEmptyList( new Integer[ 1 ] ); } A: @pauldoo Yes, you are quite right. It is one of the weaknesses with the java generics imho. I response to Cheekysoft I'd like to propose to also look at how it is done by the Java people themselves, such as T[] AbstractCollection#toArray(T[] a). I think Cheekysofts version is superior, but the Java one has the advantage of familiarity. Edit: Added link. Re-edit: Found a bug on SO :) Follow-up on Cheekysoft: Well, as it is a list of some type that should be returned the corresponding example should look something like: static <T> List<T> createEmptyList( List<T> a ) { return new ArrayList<T>(); } But yes, passing the class object is clearly the better one. My only argument is that of familiarity, and in this exact instance it isn't worth much (in fact it is bad).
{ "language": "en", "url": "https://stackoverflow.com/questions/24991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: InvalidOperationException while creating wcf web service instance I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message: Could not find default endpoint element that references contract 'MyServiceReference.IMyService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element. The code I am using to create the instance is: myServiceClient = new MyServiceClient(); where MyServiceClient inherits from System.ServiceModel.ClientBase How do I solve this? Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems. A: Or you can set the endpoint in your code: http://msdn.microsoft.com/en-us/library/ms731862.aspx BasicHttpBinding binding = new BasicHttpBinding(); EndpointAddress address = new EndpointAddress("http://url-to-service/"); // Create a client that is configured with this address and binding. MyServiceClient client = new MyServiceClient(binding, address); A: Here is my app.config file of the class library: You should put this configuration settings to main app's config file. .NET application (which is calling your class library) uses data from it's own config file not from your library config file. A: I had a similar case. I had a class-library that called a web service, then I had an .EXE that called the class-lib's .DLL. I think it's the .EXE's config file that is used and not that of the .DLL config. But as Richard said above, I had to fully-qualify the namespace. It's a bit of a pain. Below is exactly what I changed. The pain is that I had to change it in two places, one in the reference.cs that is generated when you create a service reference, and the other in the config file. Thus, everytime I change the web service and do an "Update Reference" I have to make the change to the C# code again. 1) You must actually change the ConfigurationName in the reference.cs as follows: From: [System.ServiceModel.ServiceContractAttribute(Namespace = "http://TFBIC.RCT.BizTalk.Orchestrations", ConfigurationName = " RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations")] To: [System.ServiceModel.ServiceContractAttribute(Namespace = "http://TFBIC.RCT.BizTalk.Orchestrations", ConfigurationName = "TFBIC.RCT.HIP.Components.RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations")] 2) and then also change the “contract” value in all related app.config (for .dll’s and .exe’s) as follows: From: <endpoint address=http://nxwtest08bt1.dev.txfb-ins.com/TFBIC.RCT.BizTalk.Orchestrations/WcfService_TFBIC_RCT_BizTalk_Orchestrations.svc binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ITwoWayAsync" contract="RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations" name="WSHttpBinding_ITwoWayAsync"> To: <endpoint address=http://nxwtest08bt1.dev.txfb-ins.com/TFBIC.RCT.BizTalk.Orchestrations/WcfService_TFBIC_RCT_BizTalk_Orchestrations.svc binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ITwoWayAsync" contract=" TFBIC.RCT.HIP.Components.RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations" name="WSHttpBinding_ITwoWayAsync"> Just to be clear - how did I know what the full namespace was? The program's namespace was TFBIC.RCT.HIP. Inside that, the C# code has one additional namespace statement: namespace RCTHipComponents A: It would probably help if you posted your app.config file, since this kind of error tends to point to a problem in the <endpoint> block. Make sure the contract attribute seems right to you. Edit: Try fully qualifying your contract value; use the full namespace. I think that is needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/24993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is there a functional language for C++ ecosystem? Java has Scala and .NET has F#. Both of these languages are very highly integrated into the respective Java and .NET platforms. Classes can be written in Scala then extended in Java for example. Does there exist an equivalent functional language that interoperates highly with C++? A: Ah, something else. Although this certainly isn't what you meant, template metaprogramming in C++ is purely functional. A: The Felix language by John Skaller is designed to interoperate with C++ and provide the functional paradigm. There are problems with doing this though. Functional languages provide first-class functions which allow the creation of closures: functions that have captured and carry values from the environment they were defined in. This makes it impossible to determine the lifetimes of values statically (because a closure might carry a value out of its scope) and, consequently, effectively requires a garbage collector but C++ is not garbage collected. A: C++ doesn't have an ecosystem in the sense of Java or .NET. There's no virtual machine, no runtime environment even, there's only a highly specialized standard library that by design doesn't operate well in a purely functional environment. C++ doesn't even have an ABI standard. All things considered, I'm not sure what you mean/expect. A: As has been said, I'm not really sure about a C++ 'ecosystem'. But Haskell does have a Foreign Function Interface that allows you to call C functions from Haskell and Haskell functions from C. Then again, that's C, I'm not really sure how far along the C++ FFI is... A: Since Scala compiles into Java bytecode and F# compiles into .NET bytecode, made to run on their respective virtual machines. The correct comparison would be if there is some functional language that compile to machine dependant code, ready to run on a computer, and yes, there are. I don't think that was what you meant though, but the best I have to offer is FC++. Boost is another library which has a lot of features that can be recognized as derived from functional programming. However, I'd wager there are no 'real' functional programming C++:es out there. A: The 'D' language was designed as a successor to C++. A purely functional subset of D is being developed by Andrei Alexandrescu for D 2.0. I am guessing D interoperates well with C++. A: I agree that I am not sure of an ecosystem for C++. OCaml is pretty popular for doing functional programming outside of .NET. F# is also based off of it. A: This question was posted in 2008. For reference, C++11 onwards have support for functional programming. See another discussion updated for this Functional Programming in C++ A: C++ may not be a pure functional language, but parts of STL are certainly functional. See Bjarne Stroustrup FAQ (the inventor of the c++)
{ "language": "en", "url": "https://stackoverflow.com/questions/24995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Conditional formatting -- percentage to color conversion What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%? I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much. Based on Marius and Andy's answers I'm using the following solution: double red = (percent < 50) ? 255 : 256 - (percent - 50) * 5.12; double green = (percent > 50) ? 255 : percent * 5.12; var color = Color.FromArgb(255, (byte)red, (byte)green, 0); Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ... A: What you probably want to do is to assign your 0% to 100% some points in a HSV or HSL color-space. From there you can interpolate colors (and yellow just happens to be between red and green :) and convert them to RGB. That will give you a nice looking gradient between the two. Assuming that you will use the color as a status indicator and from a user-interface perspective, however, that is probably not such a good idea, since we're quite bad at seeing small changes in color. So dividing the value into, for example, three to seven buckets would give you more noticeable differences when things change, at the cost of some precision (which you most likely would not be able to appreciate anyway). So, all the math aside, in the end I'd recommend a lookup table with the following colors with v being the input value: #e7241d for v <= 12% #ef832c for v > 12% and v <= 36% #fffd46 for v > 36% and v <= 60% #9cfa40 for v > 60% and v <= 84% #60f83d for v > 84% These have been very naïvely converted from HSL values (0.0, 1.0, 1.0), (30.0, 1.0, 1.0), (60.0, 1.0, 1.0), (90.0, 1.0, 1.0), (120.0, 1.0, 1.0), and you might want to adjust the colors somewhat to suit your purposes (some don't like that red and green aren't 'pure'). Please see: * *Using HSL Color (Hue, Saturation, Luminosity) To Create Better-Looking GUIs for some discussion and *RGB and HSL Colour Space Conversions for sample C# source-code. A: In pseudocode. * *From 0-50% your hex value would be FFxx00 where: XX = ( Percentage / 50 ) * 255 converted into hex. *From 50-100 your hex value would be xxFF00 where: XX = ((100-Percentage) / 50) * 255 converted into hex. Hope that helps and is understandable. A: This is a nice clean solution that improves on the currently accepted answer in three ways: * *Removes the magic number (5.12), therefore making the code easier to follow. *Won't produce the rounding error that's giving you -1 when the percentage is 100%. *Allows you to customise the minimum and maximum RGB values you use, so you can produce a lighter or darker range than simple rgb(255, 0, 0) - rgb(0, 255, 0). The code shown is C# but it's trivial to adapt the algorithm to any other language. private const int RGB_MAX = 255; // Reduce this for a darker range private const int RGB_MIN = 0; // Increase this for a lighter range private Color getColorFromPercentage(int percentage) { // Work out the percentage of red and green to use (i.e. a percentage // of the range from RGB_MIN to RGB_MAX) var redPercent = Math.Min(200 - (percentage * 2), 100) / 100f; var greenPercent = Math.Min(percentage * 2, 100) / 100f; // Now convert those percentages to actual RGB values in the range // RGB_MIN - RGB_MAX var red = RGB_MIN + ((RGB_MAX - RGB_MIN) * redPercent); var green = RGB_MIN + ((RGB_MAX - RGB_MIN) * greenPercent); return Color.FromArgb(red, green, RGB_MIN); } Notes Here's a simple table showing some percentage values, and the corresponding red and green proportions we want to produce: VALUE GREEN RED RESULTING COLOUR 100% 100% 0% green 75% 100% 50% yellowy green 50% 100% 100% yellow 25% 50% 100% orange 0% 0% 100% red Hopefully you can see pretty clearly that * *the green value is 2x the percentage value (but capped at 100) *the red is the inverse: 2x (100 - percentage) (but capped at 100) So my algorithm calculates the values from a table looking something like this... VALUE GREEN RED 100% 200% 0% 75% 150% 50% 50% 100% 100% 25% 50% 150% 0% 0% 200% ...and then uses Math.Min() to cap them to 100%. A: I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language: function setColor(p){ var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12); var green = p>50 ? 255 : Math.round((p)*5.12); return "rgb(" + red + "," + green + ",0)"; } A: As yellow is a mix of red and green, you can probably start with #F00 and then slide green up until you hit #FF0, then slide red down to #0F0: for (int i = 0; i < 100; i++) { var red = i < 50 ? 255 : 255 - (256.0 / 100 * ((i - 50) * 2)); var green = i < 50 ? 256.0 / 100 * (i * 2) : 255; var col = Color.FromArgb((int) red, (int) green, 0); } A: I wrote this python function based on the javascript code. it takes a percentage as a decimal. also i have squared the value to keep the colours redder for longer down the percentage scale. I also narrowed the range of colours from 255 to 180 to give a darker red and green at each end. these can be played with to give nice colours. I'd like to add a touch of orange in the middle, but i gotta get on with proper work, boo. def getBarColour(value): red = int( (1 - (value*value) ) * 180 ) green = int( (value * value )* 180 ) red = "%02X" % red green = "%02X" % green return '#' + red + green +'00' A: I use the following Python routines to blend between colours: def blendRGBHex(hex1, hex2, fraction): return RGBDecToHex(blendRGB(RGBHexToDec(hex1), RGBHexToDec(hex2), fraction)) def blendRGB(dec1, dec2, fraction): return [int(v1 + (v2-v1)*fraction) for (v1, v2) in zip(dec1, dec2)] def RGBHexToDec(hex): return [int(hex[n:n+2],16) for n in range(0,len(hex),2)] def RGBDecToHex(dec): return "".join(["%02x"%d for d in dec]) For example: >>> blendRGBHex("FF8080", "80FF80", 0.5) "BFBF80" Another routine wraps this to blend nicely between numerical values for "conditional formatting": def colourRange(minV, minC, avgV, avgC, maxV, maxC, v): if v < minV: return minC if v > maxV: return maxC if v < avgV: return blendRGBHex(minC, avgC, (v - minV)/(avgV-minV)) elif v > avgV: return blendRGBHex(avgC, maxC, (v - avgV)/(maxV-avgV)) else: return avgC So, in Jonas' case: >>> colourRange(0, "FF0000", 50, "FFFF00", 100, "00FF00", 25) "FF7F00" A: My solution for ActionScript 3: var red:Number = (percentage <= 50) ? 255 : 256 - (percentage - 50) * 5.12; var green:Number = (percentage >= 50) ? 255 : percentage * 5.12; var redHex:Number = Math.round(red) * 0x10000; var greenHex:Number = Math.round(green) * 0x100; var colorToReturn:uint = redHex + greenHex; A: Because it's R-G-B, the colors go from integer values of -1 (white), to -16777216 for black. with red green and yellow somewhere in the middle that. Yellow is actually -256, while red is -65536 and green is -16744448. So yellow actually isn't between red and green in the RGB notation. I know that in terms of wavelenghts, green is on one side, and red is on the other side of the spectrum, but I've never seen this type of notation used in computers, as the spectrum doesn't represent all visible colours.
{ "language": "en", "url": "https://stackoverflow.com/questions/25007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: I Am Not Getting the Result I Expect Using readLine() in Java I am using the code snippet below, however it's not working quite as I understand it should. public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; try { line = br.readLine(); while(line != null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } From reading the Javadoc about readLine() it says: Reads a line of text. A line is considered to be terminated by any one of a line feed (\n), a carriage return (\r), or a carriage return followed immediately by a linefeed. Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached Throws: IOException - If an I/O error occurs From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like \r. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly? A: No input is not the same as the end of the stream. You can usually simulate the end of the stream in a console by pressing Ctrl+D (AFAIK some systems use Ctrl+Z instead). But I guess this is not what you want so better test for empty strings additionally to null strings. A: From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\r'. That is not correct. readLine will return null if the end of the stream is reached. That is, for example, if you are reading a file, and the file ends, or if you're reading from a socket and the socket closses. But if you're simply reading the console input, hitting the return key on your keyboard does not constitute an end of stream. It's simply a character that is returned (\n or \r\n depending on your OS). So, if you want to break on both the empty string and the end of line, you should do: while (line != null && !line.equals("")) Also, your current program should work as expected if you pipe some file directly into it, like so: java -cp . Echo < test.txt A: There's a nice apache commons lang library which has a good api for common :) actions. You could use statically import StringUtils and use its method isNotEmpty(String ) to get: while(isNotEmpty(line)) { System.out.println(line); line = br.readLine(); } It might be useful someday:) There are also other useful classes in this lib.
{ "language": "en", "url": "https://stackoverflow.com/questions/25033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: span tag height in Firefox Using CSS, I'm trying to specify the height of a span tag in Firefox, but it's just not accepting it (IE does). Firefox accepts the height if I use a div, but the problem with using a div is the annoying line break after it, which I can't have in this particular instance. I tried setting the CSS style attribute of: display: inline for the div, but Firefox seems to revert that to span behavior anyway and ignores the height attribute once again. A: You can set any element to display: inline-block to allow it to receive a height or width. This also allows you to apply any other "block styles" to an element. One thing to be careful about however is that Firefox 2 does not support this property. Firefox 3 is the first Mozilla-based browser to support this property. All other browsers support this property, including Internet Explorer. Keep in mind that inline-block does not allow you to set text alignment inside the element on Firefox if running in quirks mode. All other browsers allow this as far as I know. If you want to set text-alignment while running in quirks mode, you'll have to use the property -moz-inline-stack instead of inline-block. Keep in mind this is a Mozilla-only property so you'll have to do some browser detection to ensure only Mozilla gets this, while other browsers get the standard inline-block. A: Since you're displaying it inline, the height should be set at the height of your line-height attribute. Depending on how it's laid out, you could always use float:left or float:right on the span/div to prevent the line break. But if you want it in the middle of a sentence, that option is out. A: Inline elements can't have heights (nor widths) like that. SPANs are already display: inline by default. Internet Explorer is actually the broken browser in this case. A: <style> #div1 { float:left; height:20px; width:20px; } #div2 { float:left; height:30px; width:30px } </style> <div id="div1">FirstDiv</div> <div id="div2">SecondDiv</div> As long as the container for whatever is holding div's 1 and 2 is wide enough for them to fit, this should be fine. A: You can only change the height (and width) of a span element when it is set to display: block;. This is because it is an inline element normally. div is set to display: block; normally. A solution could be to use: <div style="background: #f00;"> Text <span style="padding: 14px 0 14px 0; background: #ff0;">wooo</span> text. </div> A: The problem is that 'display: inline' can't get a height associated because, being inline, it gets its height from its the content. Anyway, how do you define the height of a box that is broken at the end of a line? You might try to set 'line-height' instead, or if this doesn't work to your satisfaction, set a padding: /* makes the whole box higher by inserting a space between the border and the content */ padding: 0.5em 0; A: To set height of span following should work in firefox span { display: block; height: 50px; } A: height in em = relative line-height for example height:1.1em with line-height:1.1 = 100% filled A: text alignment inside the element you can adjust using the padding and block-inline attributes. display:inline-block; padding-top:3px; for example
{ "language": "en", "url": "https://stackoverflow.com/questions/25041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Am I allowed to have "incomplete" aggregates in DDD? DDD states that you should only ever access entities through their aggregate root. So say for instance that you have an aggregate root X which potentially has a lot of child Y entities. Now, for some scenario, you only really care about a subset of these Y entities at a time (maybe you're displaying them in a paged list or whatever). Is it OK to implement a repository then, so that in such scenarios it returns an incomplete aggregate? Ie. an X object who'se Ys collection only contains the Y instances we're interested in and not all of them? This could for instance cause methods on X which perform some calculation involving the Ys to not behave as expected. Is this perhaps an indication that the Y entity in question should be considered promoted to an aggregate root? My current idea (in C#) is to leverage the delayed execution of LINQ, so that my X object has an IQueryable to represent its relationship with Y. This way, I can have transparent lazy loading with filtering... But getting this to work with an ORM (Linq to Sql in my case) might be a bit tricky. Any other clever ideas? A: I consider an aggregate root with a lot of child entities to be a code smell, or a DDD smell if you will. :-) Generally I look at two options. * *Split your aggregate into many smaller aggregates. This means that my original design was not optimal and I need to identify some new entities. *Split your domain into multiple bounded contexts. This means that there are specific sets of scenarios that use a common subset of the entities in the aggregate, while there are other sets of scenarios that use a different subset. A: Jimmy Nilsson hints in his book that instead of reading a complete aggregate you can read a snapshot of parts of it. But you are not supposed to be able to save changes in the snapshot classes to the database. Jimmy Nilsson's book Chapter 6: Preparing for infrastructure - Querying. Page 226. Snapshot pattern A: You're really asking two overlapping questions. * *The title and first half of your question are philosophical/theoretical. I think the reason for accessing entities only through their "aggregate root" is to abstract away the kinds of implementation details you're describing. Access through the aggregate root is a way to reduce complexity by having a trusted point of access. You're eliminating friction/ambiguity/uncertainty by adhering to a convention. It doesn't matter how it's implemented within the root, you just know that when you ask for an entity it will be there. I don't think this perspective rules out a "filtered repository" as you describe. But to provide a pit of success for devs to fall into, it should be impossible instantiate the repository without being explicit about its "filteredness;" likewise, if shared access to a repository instance is possible, the "filteredness" should be explicit when coding in the caller. *The second half of your question is about implementation on a specific platform. Not sure why you mention delayed execution, I think that's really orthogonal to the filtering question. The filtering itself could be a bit tricky to implement with LINQ. Maybe rather than inlining the Where lambdas, you set up a collection of them and select one depending on the filter you need. A: You are allowed since the code will compile anyway, but if you're going for a pure DDD design you should not have incomplete instances of objects. You should look into LazyLoading if you're afraid to load a huge object of which you will only use a small portion of its child entities. LazyLoading delays the loading of whatever you decide to lazy-load until the moment they are accessed. They make use of callbacks to call the loading method once the code calls for them. A: Is it OK to implement a repository then, so that in such scenarios it returns an incomplete aggregate? Not at all. Aggregate is a transnational boundary to change the state of your system. Never use aggregates for querying data. Split the system into Write and Read sides. (read about CQR & CQRS). When we think "CRUD" based, we implement our system, based on some resource. Lets say you have "Appointment" aggregate. Thinking "Crudish" means we should implement usecases Create, Update, Delete, GetAll appointments. That means Appointment[] should be returned for GetAll. When you think usecase based, (HexagonalArchitecture) your usecases would be ScheduleAppointment, RescheduleAppointment, CancelAppointment. But for query side it can be: /myCalendar. We return back all appointments for a specific user in a ClientCalendar object. Create separate DTO's for Query sides. Never use aggregates for this purpose.
{ "language": "en", "url": "https://stackoverflow.com/questions/25042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Lisp Executable I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable. I'm using clisp and clisp -c produces two files: * *.fas *.lib What do I do next to get an executable? A: I was actually trying to do this today, and I found typing this into the CLisp REPL worked: (EXT:SAVEINITMEM "executable.exe" :QUIET t :INIT-FUNCTION 'main :EXECUTABLE t :NORC t) where main is the name of the function you want to call when the program launches, :QUIET t suppresses the startup banner, and :EXECUTABLE t makes a native executable. It can also be useful to call (EXT:EXIT) at the end of your main function in order to stop the user from getting an interactive lisp prompt when the program is done. EDIT: Reading the documentation, you may also want to add :NORC t (read link). This suppresses loading the RC file (for example, ~/.clisprc.lisp). A: This is a Lisp FAQ (slightly adapted): *** How do I make an executable from my programme? This depends on your implementation; you will need to consult your vendor's documentation. * *With ECL and GCL, the standard compilation process will produce a native executable. *With LispWorks, see the Delivery User's Guide section of the documentation. *With Allegro Common Lisp, see the Delivery section of the manual. *etc... However, the classical way of interacting with Common Lisp programs does not involve standalone executables. Let's consider this during two phases of the development process: programming and delivery. Programming phase: Common Lisp development has more of an incremental feel than is common in batch-oriented languages, where an edit-compile-link cycle is common. A CL developer will run simple tests and transient interactions with the environment at the REPL (or Read-Eval-Print-Loop, also known as the listener). Source code is saved in files, and the build/load dependencies between source files are recorded in a system-description facility such as ASDF (which plays a similar role to make in edit-compile-link systems). The system-description facility provides commands for building a system (and only recompiling files whose dependencies have changed since the last build), and for loading a system into memory. Most Common Lisp implementations also provide a "save-world" mechanism that makes it possible to save a snapshot of the current lisp image, in a form which can later be restarted. A Common Lisp environment generally consists of a relatively small executable runtime, and a larger image file that contains the state of the lisp world. A common use of this facility is to dump a customized image containing all the build tools and libraries that are used on a given project, in order to reduce startup time. For instance, this facility is available under the name EXT:SAVE-LISP in CMUCL, SB-EXT:SAVE-LISP-AND-DIE in SBCL, EXT:SAVEINITMEM in CLISP, and CCL:SAVE-APPLICATION in OpenMCL. Most of these implementations can prepend the runtime to the image, thereby making it executable. Application delivery: rather than generating a single executable file for an application, Lisp developers generally save an image containing their application, and deliver it to clients together with the runtime and possibly a shell-script wrapper that invokes the runtime with the application image. On Windows platforms this can be hidden from the user by using a click-o-matic InstallShield type tool. A: For a portable way to do this, I recommend roswell. For any supported implementation you can create lisp scripts to run the program that can be run in a portable way by ros which can be used in a hash-bang line similarly to say a python or ruby program. For SBCL and CCL roswell can also create binary executables with ros dump executable. A: Take a look at the the official clisp homepage. There is a FAQ that answers this question. http://clisp.cons.org/impnotes/faq.html#faq-exec A: CLiki has a good answer as well: Creating Executables A: I know this is an old question but the Lisp code I'm looking at is 25 years old :-) I could not get compilation working with clisp on Windows 10. However, it worked for me with gcl. If my lisp file is jugs2.lisp, gcl -compile jugs2.lisp This produces the file jugs2.o if jugs2.lisp file has no errors. Run gcl with no parameters to launch the lisp interpreter: gcl Load the .o file: (load "jugs2.o") To create an EXE: (si:save-system "jugs2") When the EXE is run it needs the DLL oncrpc.dll; this is in the <gcl install folder>\lib\gcl-2.6.1\unixport folder that gcl.bat creates. When run it shows a lisp environment, call (main) to run the main function (main).
{ "language": "en", "url": "https://stackoverflow.com/questions/25046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: How to mentor a junior programmer Does anyone have any suggestions on how to mentor a junior programmer ? If you have mentored someone did you follow any process or was it quite informal ? If you've been mentored in the past what kind of things did you find most helpful ? A: At my first place of employment there was this really patient dude that would always help me solve my immediate problem, and then teach me some important underlying principle. I loved this because he would help me stay productive while teaching me how to become a better programmer. A: Try to set aside between 30-60 minutes a day to review their code together. If you can't do this, then try to get together to review their code whenever they make a code commit, unless it was very basic. Have them explain why they chose the approach they took in lieu of others. A process like this helps to establish a great relationship, as well as really stimulate the student to think on their own and be able to defend their decisions. Not only does the student end up with someone approachable whom they can trust, but you'll notice an improvement in their quality of code and logic almost immediately. Edit: Also, If you are unable to commit this much time to co-review with your junior, then you probably shouldn't be mentoring them and instead see if anyone else has a schedule that would allow it. The whole point of mentoring is to actively aid in the professional development of the student, and they're not going to learn much if proper attention and guidance is not given to them. A: I'd be the junior, I guess :) I think I'd value an informal approach. It probably depends a lot on your and your mentee's characters, but I'd say that you learn best if you don't have egos in the way. Break the ice, make sure there's feedback in both directions. Things like code reviewing (both ways?) and occasional pair programming may work, and if there's a good match, it may be a lot of fun, as well! A: Because I had to explain why I wanted to co-op (besides needing the money) during my interview, my manager made sure my first project allowed me to work on what I had identified as weak areas: very little Linux experience (I chose a Linux-only R&D team so I would be forced to learn), not knowing a useful text editor (I really wanted to learn Vim), and how to learn another programming language (very different approach than learning a language as you learn to program). He told me I was being paid to study for a while. I learn best by reading books, so after chuckling over Unix for Dummies (yay! I wasn't the only one who thought this was obscure and knuckleheaded sometimes) I started with Unix in a Nutshell and Sobell's Practical Guide to Linux Commands. After that I printed out the Vim documentation and started going through it. Then I looked through a couple books on Python, the language of my first project. I was given all the time I needed to feel comfortable about these things (which was the real problem, as I now understand) and then began adding functionality to a previous co-op's project. I realize now it would have been terrific to meet with someone every day or two for code review, as Kamikaze Mercenary said. A: In my experience, when mentoring someone, it is very important for the mentee to really WANT to learn more. Never ever spoon feed them. Instead point them towards things of value and have them utilize the new information they are learning in projects that they are using. Knowledge is useless if not put into practice. So encourage your mentee to code, code, code. A: Here would be my short list: Pair programming - This is helpful for many things, like reinforcing various ideas and practices. Getting used to Resharper is much easier when you pair with someone that uses it often. Informal chats - This is where we would go get a drink, go outside for someone to have a smoke break, go for lunch together, etc. While away from the desks, the discussion may be related to work immediately being done or it may be abstract philosophical stuff that can help bring someone's game up a notch or two. Talking about various upcoming technologies or changes in what coming can be exciting and help form bonds as well. Feedback and suggestions - This is what occured in both above cases. Books like "How to Win Friends and Influence People" by Dale Carnegie can help in understanding various human relationship dynamics, which while that sounds quite technical is really just about how to motivate someone else in various ways. A key point here is to know how to leave a trail of breadcrumbs to pick up some practices, like giving hint after hint about something rather than just give the answer. I have had various Math teachers that had a gift for this for how I developed some of this skill. So part of this is merely motivating the other person and trying to guide them as when someone figures something out for themself it can be an empowering and enlightening experience. The, "I did it! That's right, moi, yours truly!" kind of self-talk is quite nice when it happens. A: Ask them what would they try next to complete the task. This can give an idea of where from the "I don't know what to do" to "Well, I would try this but..." category are they in terms of having their own idea that may be useful for a starting point. Take a quick look at what they want to do and offer hints so that they figure out the problem. This is rather than give the answer of, "Just take out this line of code," suggest they look at what is there and is it all necessary A: I had the chance to work as an intern (one of two) in a small software company and had the opportunity to work on an "almost new" project they had. They had me set up with everything needed and gave me an introduction into what the project actually was (basic stuff like what the requirements were etc). At first we got to do minor tasks like researching things that mattered to the project (they had given us a list of topics). This was, I think, to see how much we could handle ourselves, as the things we needed to look up and research were not that trivial and it took a good 2 weeks or so (counting the basic demos we had to create for it). That testing phase was actually done really without much 'coaching'. However, after that period we could work on the actual project itself. This was also the moment we began to be coached together, in a similar style to pair programming, except there were three of us (2 interns and 1 'coach'). We learned a lot from him, but it was in an informal manner, and he didn't act like the 'all-knowing-listen-to-me' guy. When we had suggestions he would listen and think through with us whether they were any good. or give his view on why an idea should not be done in that way... Now that I think of it, he actively encouraged us to make suggestions, and to think about better ways to do things, instead of just sitting there 'taking orders' from someone who probably knows what to do better then you. So in short: * *Let the junior programmer work (mostly) on his own to study the materials at hand, give him a list of minor TODO things like looking up information, or building small demos. *Check the work he has done regularly and advise him if there are better ways to do things. Also point out the items he actually did well, that way he'll remember those for later. *Let him work on a real project, and mentor him by working together at the same project, giving him advice when he has questions. *The effort has to come from both directions: encourage him to ask questions, to challenge 'the way it is currently done'. Ask him questions on how he thinks it should be done and give him your opinion as well. *Make it 'enjoyable' - don't let it look like you are giving orders. A: During an internship w/ a large company that had a lot of in house IT, I was paired w/ a mentor. The practice definitely aided my career development, both in terms of technical skills and business skills. Here are some of the reasons the mentoring worked out so well: * *Credible: The mentor had 8+ years of experience and an accomplished background to draw upon in leading and training. He'd been through different challenges, worked in different environments, so he had a great perspective. *Genuine: The mentorship was encouraged by the supervisor, but not so formal as to make it an exercise in going through the motions. The mentor wanted to mentor, and I wanted someone to learn from. *Passion: The mentor loved the field he was in, the problems he was solving, and the technologies he was using. When I came under his wing, I found this to be infectious. *Sharp and Articulate: The mentor approached issues critically and framed them concisely. There wasn't a lot of fuzziness in our discussions; we got to the root of the matter and he directed me on wise courses of problem solving and action. *Meaningful: The work I was doing w/ the mentor was meaningful work, not just an exercise to keep busy or ramp up in a skill set. By jointly working on a task that tangibly aided the organization, that helped focus my interest and legitimize the mentoring process. A: I would recommend start giving parts of real assignments you have and make everything to be able to use his code. In other words train him as replacement for yourself. This way you will commit yourself to allocating time to work with junior and he will be able to see "real life". By working on real assignments and hearing lively feedback he will be able to get p to speed rather quickly. Drawback of this approach is that it is possible that it will have too narrow focus on you particular project. So be sure to show the trainee possible alternatives and encourage trade-offs analysis to widen his professional horizon. A: Couple of years ago I worked for a small company, where on the first day I was given a list of small task to complete - do some little changes in code, find and fix a small bug in the project. It really helped me to ask the right questions from my mentor and familiarize myself with the environment, the code base. These tasks were easy to complete, so I had a little bit of self confidence, before turning to the bigger tasks. This way of mentoring really worked with me very well, so I am planning to do the same with our new colleague. A: I have mentored several junior people under me before. My approach varied slightly based on the person a bit based on how they learned. In short, I gave the junior people small, self-contained projects when I could and gave them a relatively fixed time to complete the task. Once the task was complete I would review their approach, code and solution and made suggestions for improvements or a better way to handle the problem. I think this way they don't feel overwhelmed being part of a much larger project. Hope this helps a bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/25063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: Binary buffer in Python In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ByteArrayOutputStream? The use-case I have is I want to create a ZIP file in memory, and ZipFile requires a file-like object. A: You are probably looking for io.BytesIO class. It works exactly like StringIO except that it supports binary data: from io import BytesIO bio = BytesIO(b"some initial binary data: \x00\x01") StringIO will throw TypeError: from io import StringIO sio = StringIO(b"some initial binary data: \x00\x01") A: Look at the struct package: https://docs.python.org/library/struct.html, it allows you to interpret strings as packed binary data. Not sure if this will completely answer your question but you can use struct.unpack() to convert binary data to python objects. import struct f = open(filename, "rb") s = f.read(8) x, y = struct.unpack(">hl", s) int this example, the ">" tells to read big-endian the "h" reads a 2-byte short, and the "l" is for a 4-byte long. you can obviously change these to whatever you need to read out of the binary data... A: As long as you don't try to put any unicode data into your StringIO and you are careful NOT to use cStringIO you should be fine. According to the StringIO documentation, as long as you keep to either unicode or 8-bits everything works as expected. Presumably, StringIO does something special when someone does a f.write(u"asdf") (which ZipFile does not do, to my knowledge). Anyway; import zipfile import StringIO s = StringIO.StringIO() z = zipfile.ZipFile(s, "w") z.write("test.txt") z.close() f = file("x.zip", "w") f.write(s.getvalue()) s.close() f.close() works just as expected, and there's no difference between the file in the resulting archive and the original file. If you know of a particular case where this approach does not work, I'd be most interested to hear about it :)
{ "language": "en", "url": "https://stackoverflow.com/questions/25116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "69" }
Q: How to create images in PHP Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing? A: Yes this is possible. I believe there are multiple libraries to accomplish this. The most widely used is probably ImageMagick which is actually not PHP specific but comes with appropriate bindings. See also in the PHP documentation. A: Check out GD. It contains a ton of functions for image creation,manipulation and interrogation. Your PHP install just has to built with the GD library which it probably was. A: For decent tutorials on image generation using PHP: GD - http://devzone.zend.com/node/view/id/1269 ImageMagick - http://www.sitepoint.com/article/dynamic-images-imagemagick A: I prefer the GD library - check out the Examples, and this example: <?php header ("Content-type: image/png"); $im = @imagecreatetruecolor(120, 20) or die("Cannot Initialize new GD image stream"); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, "A Simple Text String", $text_color); imagepng($im); imagedestroy($im); ?> Outputs: (source: php.net) See imagecreatetruecolor. A: PHP GD Pear Image_Canvas (and Image_Graph for graphs) Those are the two I know of. A: MagickWand is pretty good for that as well, and pretty powerful. http://www.bitweaver.org/doc/magickwand/index.html This snippet will take an image, wrie the 'rose' in Vera, or whatever fonts are available, and flush the image to the browser. $drawing_wand=NewDrawingWand(); DrawSetFont($drawing_wand,"/usr/share/fonts/bitstream-vera/Vera.ttf"); DrawSetFontSize($drawing_wand,20); DrawSetGravity($drawing_wand,MW_CenterGravity); $pixel_wand=NewPixelWand(); PixelSetColor($pixel_wand,"white"); DrawSetFillColor($drawing_wand,$pixel_wand); if (MagickAnnotateImage($magick_wand,$drawing_wand,0,0,0,"Rose") != 0) { header("Content-type: image/jpeg"); MagickEchoImageBlob( $magick_wand ); } else { echo MagickGetExceptionString($magick_wand); } A: you can use gd library with different function of it. and create good image with the code header("Content-Type: image/png"); //try to create an image $im = @imagecreate(800, 600) or die("Cannot Initialize new GD image stream"); //set the background color of the image $background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD); //set the color for the text $text_color = imagecolorallocate($im, 133, 14, 91); //adf the string to the image imagestring($im, 5, 300, 300, "I'm a pretty picture:))", $text_color); //outputs the image as png imagepng($im); //frees any memory associated with the image imagedestroy($im); color to Negative if(!file_exists('dw-negative.png')) { $img = imagecreatefrompng('dw-manipulate-me.png'); imagefilter($img,IMG_FILTER_NEGATE); imagepng($img,'db-negative.png'); imagedestroy($img); }
{ "language": "en", "url": "https://stackoverflow.com/questions/25128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Are named entities in HTML still necessary in the age of Unicode aware browsers? I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, "htmlentities" seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effort into keeping every string localizable, only store UTF-8 in your database, only deliver UTF-8 webpages etc. Suddenly, somewhere between your database and the browser there's this hopelessly naive function pretending every byte is a character and messes everything up. I would just love to just dump this kind of functions, they seem totally superfluous. Is it still necessary these days to write '&auml;' instead of 'ä'? At least my Firefox seems perfectly happy to display even the strangest Asian glyphs as long as they're served in a proper encoding. Update: To be more precise: Are named entities necessary for anything else than displaying HTML tags (as in "&lt;" for "<") Update 2: @Konrad: Are you saying that, no, named entities are not needed? @Ross: But wouldn't it be better to sanitize user input when it's entered, to keep my output logic free from such issues? (assuming of course, that reliable sanitizing on input is possible - but then, if it isn't, can it be on output?) A: Named entities in "real" XHTML (i.e. with application/xhtml+xml, rather than the more frequently-used text/html compatibility mode) are discouraged. Aside from the five defined in XML itself (&lt;, &gt;, &amp;, &quot;, &apos;), they'd all have to be defined in the DTD of the particular DocType you're using. That means your browser has to explicitly support that DocType, which is far from a given. Numbered entities, on the other hand, obviously only require a lookup table to get the right Unicode character. As for whether you need entities at all these days: you can pretty much expect any modern browser to support UTF-8. Therefore, as long as you can guarantee that the database, the markup and the web server all agree to serve that, ditch the entities. A: If using XHTML, it's actually recommended not to use named entities ([citation needed]). Some browsers (Firefox …), when parsing this as XML (which they normally don't), don't read the DTD files and thus are unable to handle the entities. As it's best practice anyway to use UTF-8 as encoding if there are no compelling reasons to do otherwise, this only means that the creator of the documents needs a decent editor that can not only handle the documents but also provides a good way of entering the divers glyphs. OS X doesn't really have this problem because most needed glyphs can be reached via “alt” keys but Windows doesn't have this feature. @Konrad: Are you saying that, no, named entities are not needed? Precisely. Unless, of course, there are silly restrictions, e.g. legacy database drivers that choke on UTF-8 etc. A: Safari seems to have issues with some glyphs but not others, it may not be needed but it's probably best to do so, of course, this is my opinion and not backed up by anything but my own observations.
{ "language": "en", "url": "https://stackoverflow.com/questions/25132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: What is your experience with software model checking? * *What types of applications have you used model checking for? *What model checking tool did you use? *How would you summarize your experience w/ the technique, specifically in evaluating its effectiveness in delivering higher quality software? In the course of my studies, I had a chance to use Spin, and it aroused my curiosity as to how much actual model checking is going on and how much value are organizations getting out of it. In my work experience, I've worked on business applications, where there is (naturally) no consideration of applying formal verification to the logic. I'd really like to learn about SO folks model checking experience and thoughts on the subject. Will model checking ever become a more widely used developing practice that we should have in our toolkit? A: I just finished a class on model checking and the big tools we used were Spin and SMV. We ended up using them to check properties on common synchronization problems, and I found SMV just a little bit easier to use. Although these tools were fun to use, I think they really shine when you combine them with something that dynamically enforces constraints on your program (so that it's a bit easier to verify 'useful' things about your program). We ended up taking the Spring WebFlow framework, which uses XML to write a state-machine like file that specifies which web pages can transition to which other ones, and using SMV to be able to perform verification on said applications (shameless plug here). To answer your last question, I think model checking is definitely useful to have, but I lean more towards using unit testing as a technique that makes me feel comfortable about delivering my final product. A: We have used several model checkers in teaching, systems design, and systems development. Our toolbox includes SPIN, UPPAL, Java Pathfinder, PVS, and Bogor. Each has its strengths and weaknesses. All find problems with models that are simply impossible for human beings to discover. Their usability varies, though most are pushbutton automated. When to use a model checker? I'd say any time you are describing a model that must have (or not have) particular properties and it is any larger than a handful of concepts. Anyone who thinks that they can describe and understand anything larger or more complex is fooling themselves. A: What types of applications have you used model checking for? We used the Java Path Finder model checker to verify some security (deadlock, race condition) and temporal properties (using Linear temporal logic to specify them). It supports classical assertions (like NotNull) on Java (bytecode) - it is for program model checking. What model checking tool did you use? We used Java Path Finder (for academic purposes). It's open source software developed by NASA initially. How would you summarize your experience w/ the technique, specifically in evaluating its effectiveness in delivering higher quality software? Program model checking has a major problem with state space explosion (memory & disk usage). But there are a wide variety of techniques to reduce the problems, to handle large artifacts, such as partial order reduction, abstraction, symmetry reduction, etc. A: I used SPIN to find a concurrency issue in PLC software. It found an unsuspected race condition that would have been very tough to find by inspection or testing. By the way, is there a "SPIN for Dummies" book? I had to learn it out of "The SPIN Model Checker" book and various on-line tutorials. A: I've done some research on that subject during my time at the university, expanding the State Exploring Assembly Model Checker. We used a virtual machine to walk each and every possible path/state of the program, using A* and some heuristic, depending on the kind of error (deadlock, I/O errors, ...) It was inspired by Java Pathfinder and it worked with C++ code. (Everything GCC could compile) But in our experiences this kind of technology will not be used in business applications soon, because of GUI related problems, the work necessary for creating an initial test environment and the enormous hardware requirements. (You need lots of RAM and disc space, because of the gigantic state space)
{ "language": "en", "url": "https://stackoverflow.com/questions/25137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Stored Procedure and Timeout I'm running a long process stored procedure. I'm wondering if in case of a timeout or any case of disconnection with the database after initiating the call to the stored procedure. Is it still working and implementing the changes on the server? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: Anyway if the client is not there to commit at the end of the job the changes should be rolled back by the server. In other words, if you have a stored procedure making changes to the database and there is a possibility that the connection might disconnect in the middle, be sure to enclose all changes within a transaction. A: It depends on the server I guess. I know Firebird will detect disconnected clients and stop working. Anyway if the client is not there to commit at the end of the job the changes should be rolled back by the server. A: I would suggest running your profiler on the database and watching the activity, and also create a basic test case so that you know for sure what happens. The outcome is dependent on your database and what you are using to connect to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/25142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I merge PHP arrays? I have two arrays of animals (for example). $array = array( array( 'id' => 1, 'name' => 'Cat', ), array( 'id' => 2, 'name' => 'Mouse', ) ); $array2 = array( array( 'id' => 2, 'age' => 321, ), array( 'id' => 1, 'age' => 123, ) ); How can I merge the two arrays into one by the ID? A: First off, why don't you use the ID as the index (or key, in the mapping-style array that php arrays are imo)? $array = array( 1 => array( 'name' => 'Cat', ), 2 => array( 'name' => 'Mouse', ) ); after that you'll have to foreach through one array, performing array_merge on the items of the other: foreach($array2 as $key=>$value) { if(!is_array($array[$key])) $array[$key] = $value; else $array[$key] = array_merge($array[key], $value); } Something like that at least. Perhaps there's a better solution? A: This does what Erik suggested (id no. as array key) and merges vlaues in $array2 to $results. $results = array(); foreach($array as $subarray) { $results[$subarray['id']] = array('name' => $subarray['name']); } foreach($array2 as $subarray) { if(array_key_exists($subarray['id'], $results)) { // Loop through $subarray would go here if you have extra $results[$subarray['id']]['age'] = $subarray['age']; } } A: <?php $a = array('a' => '1', 'b' => array('t' => '4', 'g' => array('e' => '8'))); $b = array('c' => '3', 'b' => array('0' => '4', 'g' => array('h' => '5', 'v' => '9'))); $c = array_merge_recursive($a, $b); print_r($c); ?> array_merge_recursive — Merge two or more arrays recursively outputs: Array ( [a] => 1 [b] => Array ( [t] => 4 [g] => Array ( [e] => 8 [h] => 5 [v] => 9 ) [0] => 4 ) [c] => 3 ) A: @Andy http://se.php.net/array_merge That was my first thought but it doesn't quite work - however array_merge_recursive might work - too lazy to check right now. A: @Andy I've already looked at that and didn't see how it can help merge multidimensional arrays. Maybe you could give an example. @kevin That is probably what I will need to do as I think the code below will be very slow. The actual code is a bit different because I'm using ADOdb (and ODBC for the other query) but I'll make it work and post my own answer. This works, however I think it will be very slow as it goes through the second loop every time: foreach($array as &$animal) { foreach($array2 as $animal2) { if($animal['id'] === $animal2['id']) { $animal = array_merge($animal, $animal2); break; } } } A: I would rather prefer array_splice over array_merge because of its performance issues, my solution would be: <?php array_splice($array1,count($array1),0,$array2); ?> A: foreach ($array as $a) $new_array[$a['id']]['name'] = $a['name']; foreach ($array2 as $a) $new_array[$a['id']]['age'] = $a['age']; and this is result: [1] => Array ( [name] => Cat [age] => 123 ) [2] => Array ( [name] => Mouse [age] => 321 ) A: <?php $array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result); ?> A: With PHP 5.3 you can do this sort of merge with array_replace_recursive() http://www.php.net/manual/en/function.array-replace-recursive.php You're resultant array should look like: Array ( [0] => Array ( [id] => 2 [name] => Cat [age] => 321 ) [1] => Array ( [id] => 1 [name] => Mouse [age] => 123 ) ) Which is what I think you wanted as a result. A: $new = array(); foreach ($array as $arr) { $match = false; foreach ($array2 as $arr2) { if ($arr['id'] == $arr2['id']) { $match = true; $new[] = array_merge($arr, $arr2); break; } } if ( !$match ) $new[] = $arr; }
{ "language": "en", "url": "https://stackoverflow.com/questions/25147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Building C# .NET windows application with multiple views I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C). The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see. What is the best practice to switch between the views? From start to running? Between the running views? Ideas: * *Use one form and hide and show controls *Use one start form and then a form with a TabControl *Use six separate forms A: Creating a bunch of overlaid panels is a design-time nightmare. I would suggest using a tab control with each "view" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event: tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height; tabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height; tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height)); A: What I do is to have a Panel where your different views will sit on the main form. then create user controls for your different views. Then when I want to switch between a'view' you dock it to Panel on the main form.. code looks a little like this. i preffer this because you can then reuse your views, like if you want to open up a view in a tab you can dock your user controls inside tab pages.. or even inherit from tabpage instead of usercontrol to make things a bit more generic public partial class MainForm : Form { public enum FormViews { A, B } private MyViewA viewA; //user control with view a on it private MyViewB viewB; //user control with view b on it private FormViews _formView; public FormViews FormView { get { return _formView; } set { _formView = value; OnFormViewChanged(_formView); } } protected virtual void OnFormViewChanged(FormViews view) { //contentPanel is just a System.Windows.Forms.Panel docked to fill the form switch (view) { case FormViews.A: if (viewA != null) viewA = new MyViewA(); //extension method, you could use a static function. this.contentPanel.DockControl(viewA); break; case FormViews.B: if (viewB != null) viewB = new MyViewB(); this.contentPanel.DockControl(viewB); break; } } public MainForm() { InitializeComponent(); FormView = FormViews.A; //simply change views like this } } public static class PanelExtensions { public static void DockControl(this Panel thisControl, Control controlToDock) { thisControl.Controls.Clear(); thisControl.Controls.Add(controlToDock); controlToDock.Dock = DockStyle.Fill; } } A: Tabbed forms are usually good... but only if you want the user to be able to see any view at any time... and it sounds like you might not. Separate forms definitely works, but you need to make sure that the switch is seemless...if you make sure the new form appears the same exact size and location of the old form, it will look like it thew same for with changing controls. The method I often use is actually to pre-setup all my controls on individual "Panel" controls and then show and hide these panels as I need them. The "Panel" control is basically a control container... you can move the panel and all controls on it move relative. And if you show or hide the panel, the controls on it do the same. They are great for situations like this. A: The method I often use is actually to pre-setup all my controls on individual "Panel" controls and then show and hide these panels as I need them. Instead of making each view a panel within a single form you could make each view a UserControl. Then create a single form and write code to create and display the correct UserControl in the Form and to switch from one to the next. This would be easier to maintain because you will have a separate class for each view instead of a single Form class with 6 panels each with their own controls -- that seems difficult and error prone to maintain. A: I would also check out Composite Application Guidance for WPF or Smart Client Software Factory
{ "language": "en", "url": "https://stackoverflow.com/questions/25158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Tooltips on an image I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo. Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing? A: Yes, you can do this without Javascript. Use an HTML image map, with title attributes, like this: <img usemap="#logo" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png"> <map name="logo"> <area shape="rect" href="" coords="52,42,121,65" title="Stack"> <area shape="rect" href="" coords="122,42,245,65" title="Overflow"> </map> The Stack Overflow logo refers to the image map, which defines a rectangle for each of the two words using an area tag. Each area tag's title element specifies the text that browsers generally show as a tooltip. The shape attribute can also specify a circle or polygon. A: The title attribute is the simplest solution and guaranteed to work, and degrade gracefully for useragents that don't support it correctly. A: A single image alone doesn't give the browser the semantic information on the logos within. You could use an image map to supply the coordinates. To achieve tooltips, just apply a title attribute to each link. For more sophisticated tooltips (such as with styling, multiple lines, etc.), you'll need something non-standard, such as UniTip. A: MooTools has a nifty script for this. See MooTools Tips. Lightweight on the HTML as well. Here's a demo of the 1.11 version. A: Indeed mootools is one of the many frameworks that allow you to add functionality to any element on your webpage. Here is a link to a small tutorial. http://mootorial.com/wiki/mootorial/08-plugins/03-interface/01-tips Mootools isn't really a copy-paste type of framework, it encourages you to look over the supplied code and roll your own solution with some excellent examples. A: You can try javascript widget at http://www.taggify.net/ . Script allows to add tooltips for the part of the image - when user move mouse over the region on the photo the script popups tooltip, draws border around region and fades other parts. Cool thing for marking people on the photo. See demo at http://www.taggify.net/demo.aspx A: you can use title attribute for simple tooltip. its works on almost all DOM objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/25161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to prevent session timeout in Symfony 1.0? I've used the PHP MVC framework Symfony to build an on-demand web app. It has an annoying bug - the session expires after about 15-30 minutes of inactivity. There is a config directive to prevent session expiration but it does not work. Even workarounds such as this one did not help me. I intend not to migrate to Symfony 1.1 (which fixes this bug) in the foreseeable future. Has anyone been there and solved it? I would be most grateful for a hint or two! A: I looked into it, and my coworker agrees that a heartbeat page call should work, you just have to make sure that the action invoked does reset the session timer (things like ajax field completion don't do this on their own). A: The company I work for has been using Symfony and the workaround that we've used is to trigger a warning with javascript before the user gets logged out. I suspect that there is a a way to make 'heartbeat' ajax calls to the server to trigger the timer to reset, but that may be a lot of trouble. I think that there may not be a full fix that's suitable for you though, except maybe re-writing the session handler. Sorry I couldn't be more specific, if I get the chance, I'll ask our Symfony devs if they know of a better solution. A: you could always set timeout to some large number ( like 10 days or so ) all: .settings: timeout: 864000 A: You can use all: .settings: timeout: false
{ "language": "en", "url": "https://stackoverflow.com/questions/25174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What's optimal? UNION vs WHERE IN (str1, str2, str3) I'm writing a program that sends an email out at a client's specific local time. I have a .NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s). The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing? SELECT email FROM tClient WHERE timezoneID in (1, 4, 9) or SELECT email FROM tClient WHERE timezoneID = 1 UNION ALL SELECT email FROM tClient WHERE timezoneID = 4 UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9 Edit: timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName. Also, I went with WHERE IN since I didn't feel like opening up the analyzer. Edit 2: Query processes 200k rows in under 100 ms, so at this point I'm done. A: For most database related performance questions, the real answer is to run it and analyze what the DB does for your dataset. Run an explain plan or trace to see if your query is hitting the proper indexes or create indexes if necessary. I would likely go with the first using the IN clause since that carries the most semantics of what you want. The timezoneID seems like a primary key on some timezone table, so it should be a foreign key on email and indexed. Depending on the DB optimizer, I would think it should do an index scan on the foreign key index. A: Hey! These queries are not equivalent. Results will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster. Always use UNION ALL, unless you know why you want to use UNION. If you are not sure what is difference see this SO question. Note: that yell belongs to previous version of question. A: In the book "SQL Performance Tuning", the authors found that the UNION queries were slower in all 7 DBMS' that they tested (SQL Server 2000, Sybase ASE 12.5, Oracle 9i, DB2, etc.): http://books.google.com/books?id=3H9CC54qYeEC&pg=PA32&vq=UNION&dq=sql+performance+tuning&source=gbs_search_s&sig=ACfU3U18uYZWYVHxr2I3uUj8kmPz9RpmiA#PPA33,M1 The later DBMS' may have optimized that difference away, but it's doubtful. Also, the UNION method is much longer and more difficult to maintain (what if you want a third?) vs. the IN. Unless you have good reason to use UNION, stick with the OR/IN method. A: My first guess would be that SELECT email FROM tClient WHERE timezoneID in (1, 4, 9) will be faster as it requires only single scan of the table to find the results, but I suggest checking the execution plan for both queries. A: I do not have MS SQL Query Analyzer at hand to actually check my hypothesis, but think that WHERE IN variant would be faster because with UNION server will have to do 3 table scans whereas with WHERE IN will need only one. If you have Query Analyzer check execution plans for both queries. On the Internet you may often encounter suggestions to avoid using WHERE IN, but that refers to cases where subqueries a used. So this case is out of scope of this recommendation and additionally is easier for reading and understanding. A: I think that there are several very important information missing in the question. First of all, it is of great importance weather timezoneID is indexed or not, is it part of the primary key etc. I would advice everyone to have a look at the analyzer, but in my experience the WHERE clause should be faster, especially with an index. The logic is something like, there is an additional overhead in the union query, checking types, column numbers in each etc. A: Some DBMS's Query Optimizers modify your query to make it more efficient, so depending on the DBMS your using, you probably shouldn't care.
{ "language": "en", "url": "https://stackoverflow.com/questions/25182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Java SWIFT Library I'm looking for a Java library for SWIFT messages. I want to * *parse SWIFT messages into an object model *validate SWIFT messages (including SWIFT network validation rules) *build / change SWIFT messages by using an object model Theoretically, I need to support all SWIFT message types. But at the moment I need MT103+, MT199, MT502, MT509, MT515 and MT535. So far I've looked at two libraries * *AnaSys Message Objects (link text) *Datamation SWIFT Message Suite (link text) Both libraries allow to accomplish the tasks mentioned above but in both cases I'm not really happy. AnaSys uses a internal XML representation for all SWIFT messages which you need to know in order to access the fields of a message. And you need to operate on the DOM of the XML representation, there is no way to say "get the contents of field '50K' of the SWIFT message". And the Datamation library seems to have the nicer API but does not find all errors. So does anyone know other SWIFT libraries to use? A: You can combine the open source implementation WIFE with the commercial validation component from http://www.prowidesoftware.com. It validates that the messages you create with the model or XML representation are good through SWIFT network validation rules. A: Have you looked at WIFE? We use that in our application which translates SWIFT messages to an internal XML format and back again. We haven't had any problems with it. Also, it's licensed under the LGPL, so you can hack it up if you need to. Check it out. A: SWIFT is releasing a "Standards Developer Kit" which includes an "MT/XML Schema Library". From the doc: "The MT/XML Schema Library is a complete set of XML schema definitions for MT messages, and software which shows how to convert messages from an MT format to an MT XML representation and back. This approach allows XML integration between applications while the MT (FIN) format will continue to be transported over the SWIFT network." Java source code will also be made available, again from the doc: "Working sample Java source code that converts a message in MT format to an XML instance and from an XML instance to a message in MT format." See: http://www.swift.com/support/drc/develop/standards.page This can be a great aid in dealing with FIN messages in XML syntax. A: There is a product call Volanté that make a great job. Their solution is certified by SWIFT and the integration is easy ( I sound like I'm working for them ... I'm not). I've been using it since a couple of month . IBM is also offering a solution (cannot remember to name right now) but then you are committed to the big blue. A: If your company is not comfortable with the LGPL license, You might want to check Progress Sonic ESB, or ArtixDS (recently acquired), TIBCO ActiveWhatever or Oracle/BEA Aqualogic. Chances are you are already using something from these companies and you can get decent discount. A: I can not really help you out with a Java implementation. Microsoft of course, have their own Biztalk adapter for ISO15022 and 20022. And they will actually do the validation fairly well. But as you say you are actually looking for a java solution. You might find, as I did when I researched this 6 years ago, that mapping FIN messages to XML and then to into objects, a standard library will only get you partly to your goal. You will have to integrate this with your backend application and whatever market practices you face in the particular messages you need to support. I finally ended up writing a generic FIN parser /150022 class library in c++. Anyway, good luck. An idea is to be more specific in your question. What types of messages do you need to support? A: Along with jodonnell, we also use WIFE. It works very well. I'm not sure if it does the network validation rules (#2 on your list) though. A: paymentcomponents (http://www.paymentcomponents.com/) parser was easy to use and found all errors. Their site definitely needs work but if u look there, u'll find what u r looking for A: Datamation's libraries have evolved since then. If you need a corresponding solution in 2021, you can check FINaplo by PaymentComponents (formerly called Datamation), a multi-purpose implementation for financial messages. It provides online validation/parse/translation/envelope services, Java SDKs, as well as REST solutions, all including error specifications. I am actually one of the authors. A demo for a SWIFT MT Java library can be found in this GitHub link.
{ "language": "en", "url": "https://stackoverflow.com/questions/25192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: C#.NET Winforms: Is it possible to override Label.Autosize? I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a AutoSize = false in my constructor, however, when I place it in design mode, the property always is True. I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"? Here's the full source code of my Label in case anyone is interested. using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Dentactil.UI.WinControls { [DefaultProperty("TextString")] [DefaultEvent("TextClick")] public partial class RoundedLabel : UserControl { private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 ); private const float DEFAULT_BORDER_WIDTH = 2.0F; private const int DEFAULT_ROUNDED_WIDTH = 16; private const int DEFAULT_ROUNDED_HEIGHT = 12; private Color mBorderColor = DEFAULT_BORDER_COLOR; private float mBorderWidth = DEFAULT_BORDER_WIDTH; private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH; private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT; public event EventHandler TextClick; private Padding mPadding = new Padding(8); public RoundedLabel() { InitializeComponent(); } public Cursor TextCursor { get { return lblText.Cursor; } set { lblText.Cursor = value; } } public Padding TextPadding { get { return mPadding; } set { mPadding = value; UpdateInternalBounds(); } } public ContentAlignment TextAlign { get { return lblText.TextAlign; } set { lblText.TextAlign = value; } } public string TextString { get { return lblText.Text; } set { lblText.Text = value; } } public override Font Font { get { return base.Font; } set { base.Font = value; lblText.Font = value; } } public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; lblText.ForeColor = value; } } public Color BorderColor { get { return mBorderColor; } set { mBorderColor = value; Invalidate(); } } [DefaultValue(DEFAULT_BORDER_WIDTH)] public float BorderWidth { get { return mBorderWidth; } set { mBorderWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_WIDTH)] public int RoundedWidth { get { return mRoundedWidth; } set { mRoundedWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_HEIGHT)] public int RoundedHeight { get { return mRoundedHeight; } set { mRoundedHeight = value; Invalidate(); } } private void UpdateInternalBounds() { lblText.Left = mPadding.Left; lblText.Top = mPadding.Top; int width = Width - mPadding.Right - mPadding.Left; lblText.Width = width > 0 ? width : 0; int heigth = Height - mPadding.Bottom - mPadding.Top; lblText.Height = heigth > 0 ? heigth : 0; } protected override void OnLoad(EventArgs e) { UpdateInternalBounds(); base.OnLoad(e); } protected override void OnPaint(PaintEventArgs e) { SmoothingMode smoothingMode = e.Graphics.SmoothingMode; e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; int roundedWidth = RoundedWidth > (Width - 1)/2 ? (Width - 1)/2 : RoundedWidth; int roundedHeight = RoundedHeight > (Height - 1)/2 ? (Height - 1)/2 : RoundedHeight; GraphicsPath path = new GraphicsPath(); path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight); path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90); path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90); path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90); path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0); path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90); e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path); e.Graphics.SmoothingMode = smoothingMode; base.OnPaint(e); } protected override void OnResize(EventArgs e) { UpdateInternalBounds(); base.OnResize(e); } private void lblText_Click(object sender, EventArgs e) { if (TextClick != null) { TextClick(this, e); } } } } (there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code). I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel ;) I basically hate the autosize property "on by default". A: I've seen similar behaviour when setting certain properties of controls in the constructor of the form itself. They seem to revert back to their design-time defaults. I notice you're already overriding the OnLoad method. Have you tried setting AutoSize = false there? Or are you mainly concerned with providing a default value of false? A: I spent a lot of time with it and this finally works! (my code is vb.net but is simple to convert it) Private _Autosize As Boolean Public Sub New() _Autosize=False End Sub Public Overrides Property AutoSize() As Boolean Get Return MyBase.AutoSize End Get Set(ByVal Value As Boolean) If _Autosize <> Value And _Autosize = False Then MyBase.AutoSize = False _Autosize = Value Else MyBase.AutoSize = Value End If End Set End Property A: Your problem could be that you're not actually overriding Autosize in your code (ie, in the same way that you're overriding Font or ForeColor). A: I don't see this.AutoSize = false in your constructor. Your class is marked as partial -- perhaps you have a constructor in another file with that line. The visual studio designer will call that parameterless constructor you've got there. A: I managed to disable the Autosize feature of my personal label by overriding the "OnCreateControl()" method, as simple as that: protected override void OnCreateControl() { AutoSize = false; } I hope it worked for you :)
{ "language": "en", "url": "https://stackoverflow.com/questions/25200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: joining latest of various usermetadata tags to user rows I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata: 15, 'QHS', '20', '2008-08-24 13:36:33.465567-04' 15, 'QHE', '8', '2008-08-24 12:07:08.660519-04' 15, 'QHS', '21', '2008-08-24 09:44:44.39354-04' 15, 'QHE', '10', '2008-08-24 08:47:57.672058-04' I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code. A: This is actually not that hard to do in PostgreSQL because it has the "DISTINCT ON" clause in its SELECT syntax (DISTINCT ON isn't standard SQL). SELECT DISTINCT ON (code) code, content, createtime FROM metatable WHERE userid = 15 ORDER BY code, createtime DESC; That will limit the returned results to the first result per unique code, and if you sort the results by the create time descending, you'll get the newest of each. A: I suppose you're not willing to modify your schema, so I'm afraid my answe might not be of much help, but here goes... One possible solution would be to have the time field empty until it was replaced by a newer value, when you insert the 'deprecation date' instead. Another way is to expand the table with an 'active' column, but that would introduce some redundancy. The classic solution would be to have both 'Valid-From' and 'Valid-To' fields where the 'Valid-To' fields are blank until some other entry becomes valid. This can be handled easily by using triggers or similar. Using constraints to make sure there is only one item of each type that is valid will ensure data integrity. Common to these is that there is a single way of determining the set of current fields. You'd simply select all entries with the active user and a NULL 'Valid-To' or 'deprecation date' or a true 'active'. You might be interested in taking a look at the Wikipedia entry on temporal databases and the article A consensus glossary of temporal database concepts. A: A subselect is the standard way of doing this sort of thing. You just need a Unique Constraint on UserId, Code, and Date - and then you can run the following: SELECT * FROM Table JOIN ( SELECT UserId, Code, MAX(Date) as LastDate FROM Table GROUP BY UserId, Code ) as Latest ON Table.UserId = Latest.UserId AND Table.Code = Latest.Code AND Table.Date = Latest.Date WHERE UserId = @userId
{ "language": "en", "url": "https://stackoverflow.com/questions/25224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }