text
stringlengths
8
267k
meta
dict
Q: How do you create a static class in C++? How do you create a static class in C++? I should be able to do something like: cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl; Assuming I created the BitParser class. What would the BitParser class definition look like? A: As it has been noted here, a better way of achieving this in C++ might be using namespaces. But since no one has mentioned the final keyword here, I'm posting what a direct equivalent of static class from C# would look like in C++11 or later: class BitParser final { public: BitParser() = delete; static bool GetBitAt(int buffer, int pos); }; bool BitParser::GetBitAt(int buffer, int pos) { // your code } A: You can also create a free function in a namespace: In BitParser.h namespace BitParser { bool getBitAt(int buffer, int bitIndex); } In BitParser.cpp namespace BitParser { bool getBitAt(int buffer, int bitIndex) { //get the bit :) } } In general this would be the preferred way to write the code. When there's no need for an object don't use a class. A: You 'can' have a static class in C++, as mentioned before, a static class is one that does not have any objects of it instantiated it. In C++, this can be obtained by declaring the constructor/destructor as private. End result is the same. A: In Managed C++, static class syntax is:- public ref class BitParser abstract sealed { public: static bool GetBitAt(...) { ... } } ... better late than never... A: Unlike other managed programming language, "static class" has NO meaning in C++. You can make use of static member function. A: If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++. But the looks of your sample, you just need to create a public static method on your BitParser object. Like so: BitParser.h class BitParser { public: static bool getBitAt(int buffer, int bitIndex); // ...lots of great stuff private: // Disallow creating an instance of this object BitParser() {} }; BitParser.cpp bool BitParser::getBitAt(int buffer, int bitIndex) { bool isBitSet = false; // .. determine if bit is set return isBitSet; } You can use this code to call the method in the same way as your example code. A: This is similar to C#'s way of doing it in C++ In C# file.cs you can have private var inside a public function. When in another file you can use it by calling the namespace with the function as in: MyNamespace.Function(blah); Here's how to imp the same in C++: SharedModule.h class TheDataToBeHidden { public: static int _var1; static int _var2; }; namespace SharedData { void SetError(const char *Message, const char *Title); void DisplayError(void); } SharedModule.cpp //Init the data (Link error if not done) int TheDataToBeHidden::_var1 = 0; int TheDataToBeHidden::_var2 = 0; //Implement the namespace namespace SharedData { void SetError(const char *Message, const char *Title) { //blah using TheDataToBeHidden::_var1, etc } void DisplayError(void) { //blah } } OtherFile.h #include "SharedModule.h" OtherFile.cpp //Call the functions using the hidden variables SharedData::SetError("Hello", "World"); SharedData::DisplayError(); A: Consider Matt Price's solution. * *In C++, a "static class" has no meaning. The nearest thing is a class with only static methods and members. *Using static methods will only limit you. What you want is, expressed in C++ semantics, to put your function (for it is a function) in a namespace. Edit 2011-11-11 There is no "static class" in C++. The nearest concept would be a class with only static methods. For example: // header class MyClass { public : static void myMethod() ; } ; // source void MyClass::myMethod() { // etc. } But you must remember that "static classes" are hacks in the Java-like kind of languages (e.g. C#) that are unable to have non-member functions, so they have instead to move them inside classes as static methods. In C++, what you really want is a non-member function that you'll declare in a namespace: // header namespace MyNamespace { void myMethod() ; } // source namespace MyNamespace { void myMethod() { // etc. } } Why is that? In C++, the namespace is more powerful than classes for the "Java static method" pattern, because: * *static methods have access to the classes private symbols *private static methods are still visible (if inaccessible) to everyone, which breaches somewhat the encapsulation *static methods cannot be forward-declared *static methods cannot be overloaded by the class user without modifying the library header *there is nothing that can be done by a static method that can't be done better than a (possibly friend) non-member function in the same namespace *namespaces have their own semantics (they can be combined, they can be anonymous, etc.) *etc. Conclusion: Do not copy/paste that Java/C#'s pattern in C++. In Java/C#, the pattern is mandatory. But in C++, it is bad style. Edit 2010-06-10 There was an argument in favor to the static method because sometimes, one needs to use a static private member variable. I disagree somewhat, as show below: The "Static private member" solution // HPP class Foo { public : void barA() ; private : void barB() ; static std::string myGlobal ; } ; First, myGlobal is called myGlobal because it is still a global private variable. A look at the CPP source will clarify that: // CPP std::string Foo::myGlobal ; // You MUST declare it in a CPP void Foo::barA() { // I can access Foo::myGlobal } void Foo::barB() { // I can access Foo::myGlobal, too } void barC() { // I CAN'T access Foo::myGlobal !!! } At first sight, the fact the free function barC can't access Foo::myGlobal seems a good thing from an encapsulation viewpoint... It's cool because someone looking at the HPP won't be able (unless resorting to sabotage) to access Foo::myGlobal. But if you look at it closely, you'll find that it is a colossal mistake: Not only your private variable must still be declared in the HPP (and so, visible to all the world, despite being private), but you must declare in the same HPP all (as in ALL) functions that will be authorized to access it !!! So using a private static member is like walking outside in the nude with the list of your lovers tattooed on your skin : No one is authorized to touch, but everyone is able to peek at. And the bonus: Everyone can have the names of those authorized to play with your privies. private indeed... :-D The "Anonymous namespaces" solution Anonymous namespaces will have the advantage of making things private really private. First, the HPP header // HPP namespace Foo { void barA() ; } Just to be sure you remarked: There is no useless declaration of barB nor myGlobal. Which means that no one reading the header knows what's hidden behind barA. Then, the CPP: // CPP namespace Foo { namespace { std::string myGlobal ; void Foo::barB() { // I can access Foo::myGlobal } } void barA() { // I can access myGlobal, too } } void barC() { // I STILL CAN'T access myGlobal !!! } As you can see, like the so-called "static class" declaration, fooA and fooB are still able to access myGlobal. But no one else can. And no one else outside this CPP knows fooB and myGlobal even exist! Unlike the "static class" walking on the nude with her address book tattooed on her skin the "anonymous" namespace is fully clothed, which seems quite better encapsulated AFAIK. Does it really matter? Unless the users of your code are saboteurs (I'll let you, as an exercise, find how one can access to the private part of a public class using a dirty behaviour-undefined hack...), what's private is private, even if it is visible in the private section of a class declared in a header. Still, if you need to add another "private function" with access to the private member, you still must declare it to all the world by modifying the header, which is a paradox as far as I am concerned: If I change the implementation of my code (the CPP part), then the interface (the HPP part) should NOT change. Quoting Leonidas : "This is ENCAPSULATION!" Edit 2014-09-20 When are classes static methods are actually better than namespaces with non-member functions? When you need to group together functions and feed that group to a template: namespace alpha { void foo() ; void bar() ; } struct Beta { static void foo() ; static void bar() ; }; template <typename T> struct Gamma { void foobar() { T::foo() ; T::bar() ; } }; Gamma<alpha> ga ; // compilation error Gamma<Beta> gb ; // ok gb.foobar() ; // ok !!! Because, if a class can be a template parameter, a namespaces cannot. A: One (of the many) alternative, but the most (in my opinion) elegant (in comparison to using namespaces and private constructors to emulate the static behavior), way to achieve the "class that cannot be instantiated" behavior in C++ would be to declare a dummy pure virtual function with the private access modifier. class Foo { public: static int someMethod(int someArg); private: virtual void __dummy() = 0; }; If you are using C++11, you could go the extra mile to ensure that the class is not inherited (to purely emulate the behavior of a static class) by using the final specifier in the class declaration to restrict the other classes from inheriting it. // C++11 ONLY class Foo final { public: static int someMethod(int someArg); private: virtual void __dummy() = 0; }; As silly and illogical as it may sound, C++11 allows the declaration of a "pure virtual function that cannot be overridden", which you can use alongside declaring the class final to purely and fully implement the static behavior as this results in the resultant class to not be inheritable and the dummy function to not be overridden in any way. // C++11 ONLY class Foo final { public: static int someMethod(int someArg); private: // Other private declarations virtual void __dummy() = 0 final; }; // Foo now exhibits all the properties of a static class A: If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example static classes are just the compiler hand-holding you and stopping you from writing any instance methods/variables. If you just write a normal class without any instance methods/variables, it's the same thing, and this is what you'd do in C++ A: Can I write something like static class? No, according to the C++11 N3337 standard draft Annex C 7.1.1: Change: In C ++, the static or extern specifiers can only be applied to names of objects or functions. Using these specifiers with type declarations is illegal in C ++. In C, these specifiers are ignored when used on type declarations. Example: static struct S { // valid C, invalid in C++ int i; }; Rationale: Storage class specifiers don’t have any meaning when associated with a type. In C ++, class members can be declared with the static storage class specifier. Allowing storage class specifiers on type declarations could render the code confusing for users. And like struct, class is also a type declaration. The same can be deduced by walking the syntax tree in Annex A. It is interesting to note that static struct was legal in C, but had no effect: Why and when to use static structures in C programming? A: In C++ you want to create a static function of a class (not a static class). class BitParser { public: ... static ... getBitAt(...) { } }; You should then be able to call the function using BitParser::getBitAt() without instantiating an object which I presume is the desired result. A: class A final { ~A() = delete; static bool your_func(); } final means that a class cannot be inherited from. delete for a destructor means that you can not create an instance of such a class. This pattern is also know as an "util" class. As many say the concept of static class doesn't exist in C++. A canonical namespace that contains static functions preferred as a solution in this case. A: There is no such thing as a static class in C++. The closest approximation is a class that only contains static data members and static methods. Static data members in a class are shared by all the class objects as there is only one copy of them in memory, regardless of the number of objects of the class. A static method of a class can access all other static members ,static methods and methods outside the class A: One case where namespaces may not be so useful for achieving "static classes" is when using these classes to achieve composition over inheritance. Namespaces cannot be friends of classes and so cannot access private members of a class. class Class { public: void foo() { Static::bar(*this); } private: int member{0}; friend class Static; }; class Static { public: template <typename T> static void bar(T& t) { t.member = 1; } };
{ "language": "en", "url": "https://stackoverflow.com/questions/9321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "308" }
Q: Generate sitemap on the fly I'm trying to generate a sitemap.xml on the fly for a particular asp.net website. I found a couple solutions: * *chinookwebs *cervoproject *newtonking Chinookwebs is working great but seems a bit inactive right now and it's impossible to personalize the "priority" and the "changefreq" tags of each and every page, they all inherit the same value from the config file. What solutions do you guys use? A: Usually you'll use an HTTP Handler for this. Given a request for... http://www.yoursite.com/sitemap.axd ...your handler will respond with a formatted XML sitemap. Whether that sitemap is generated on the fly, from a database, or some other method is up to the HTTP Handler implementation. Here's roughly what it would look like: void IHttpHandler.ProcessRequest(HttpContext context) { // // Important to return qualified XML (text/xml) for sitemaps // context.Response.ClearHeaders(); context.Response.ClearContent(); context.Response.ContentType = "text/xml"; // // Create an XML writer // XmlTextWriter writer = new XmlTextWriter(context.Response.Output); writer.WriteStartDocument(); writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9"); // // Now add entries for individual pages.. // writer.WriteStartElement("url"); writer.WriteElementString("loc", "http://www.codingthewheel.com"); // use W3 date format.. writer.WriteElementString("lastmod", postDate.ToString("yyyy-MM-dd")); writer.WriteElementString("changefreq", "daily"); writer.WriteElementString("priority", "1.0"); writer.WriteEndElement(); // // Close everything out and go home. // result.WriteEndElement(); result.WriteEndDocument(); writer.Flush(); } This code can be improved but that's the basic idea. A: Custom handler to generate the sitemap. A: Using ASP.NET MVC just whipped up a quick bit of code using the .NET XML generation library and then just passed that to a view page that had an XML control on it. In the code-behind I tied the control with the ViewData. This seemed to override the default behaviour of view pages to present a different header.
{ "language": "en", "url": "https://stackoverflow.com/questions/9336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Quality Control / Log Monitoring One of the articles I really enjoyed reading recently was Quality Control by Last.FM. In the spirit of this article, I was wondering if anyone else had favorite monitoring setups for web type applications. Or maybe if you don't believe in Log Monitoring, why? I'm looking for a mix of opinion slash experience here I guess. A: We get a bunch of email/pager alerts from an older host/app/network monitoring environment that get gradually more abusive depending on severity of the problem/time taken to respond. Fortunately we all have thick skins and very broad senses of humour. :) A: We use log4net, and normally write both to log files and the database. However, when we've been tracking down a particularly difficult problem, we've enabled the email appender, so that critical log messages went straight to a developer's email account. This allowed us to figure out what was happening more immediately. In addition, our infrastructure team has several tools they use to monitor system uptime, event logs, etc., to give them early warning when something is about to go down. We've also helped them implement custom monitoring scripts that test specific functionality of our code.
{ "language": "en", "url": "https://stackoverflow.com/questions/9338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Running Javascript after control's selected value has been set Simple ASP.NET application. I have two drop-down controls. On the first-drop down I have a JavaScript onChange event. The JavaScript enables the second drop-down and removes a value from it (the value selected in the first drop-down). If they click the blank first value of the drop-down, then the second drop-down will be disabled (and the options reset). I also have code in the OnPreRender method that will enable or disable the second drop-down based on the value of the first drop-down. This is so that the value of the first drop-down can be selected in code (loading user settings). My problem is: * *The user selects something in the first drop-down. The second drop-down will become enabled through JavaScript. *They then change a third drop-down that initiates a post back. After the post back the drop-downs are in the correct state (first value selected, second drop-down enabled). *If they then click the back button, the second drop-down will no longer be enabled although it should be since there's something selected in the first drop-down. I've tried adding a startup script (that will set the correct state of the second-drop down) through ClientScript.RegisterStartupScript, however when this gets called the first drop-down has a selectedIndex of 0, not what it actually is. My guess is that the value of the selection gets set after my start script (but still doesn't call the onChange script). Any ideas on what to try? A: If the second dropdown is initially enabled through javascript (I'm assuming this is during a javascript onchange, since you didn't specify), then clicking the back button to reload the previous postback will never enable it. Mixing ASP.NET with classic javascript can be hairy. You might want to have a look at ASP.NET's Ajax implementation (or the third-party AjaxPanel control if you're forced to use an older ASP.NET version). Those will give you the behaviour that you want through pure C#, without forcing you to resort to javascript hackery-pokery. A: <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void indexChanged(object sender, EventArgs e) { Label1.Text = " I did something! "; } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Test Page</title> </head> <body> <script type="text/javascript"> function firstChanged() { if(document.getElementById("firstSelect").selectedIndex != 0) document.getElementById("secondSelect").disabled = false; else document.getElementById("secondSelect").disabled = true; } </script> <form id="form1" runat="server"> <div> <select id="firstSelect" onchange="firstChanged()"> <option value="0"></option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <select id="secondSelect" disabled="disabled"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <asp:DropDownList ID="DropDownList1" AutoPostBack="true" OnSelectedIndexChanged="indexChanged" runat="server"> <asp:ListItem Text="One" Value="1"></asp:ListItem> <asp:ListItem Text="Two" Value="2"></asp:ListItem> </asp:DropDownList> <asp:Label ID="Label1" runat="server"></asp:Label> </div> </form> <script type="text/javascript"> window.onload = function() {firstChanged();} </script> </body> </html> Edit: Replaced the whole code. This should work even in your user control. I believe that Register.ClientScriptBlock is not working because the code you write in that block is executed before window.onload is called. And, I assume (I am not sure of this point) that the DOM objects do not have their values set at that time. And, this is why you are getting selectedIndex as always 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/9341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Programmatically select multiple files in windows explorer I can display and select a single file in windows explorer like this: explorer.exe /select, "c:\path\to\file.txt" However, I can't work out how to select more than one file. None of the permutations of select I've tried work. Note: I looked at these pages for docs, neither helped. https://support.microsoft.com/kb/314853 http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm A: The true way of selecting multiple files in Explorer is the next Unmanaged code looks like this (compiled from China code posts with fixing its bugs) static class NativeMethods { [DllImport("shell32.dll", ExactSpelling = true)] public static extern int SHOpenFolderAndSelectItems( IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern IntPtr ILCreateFromPath([MarshalAs(UnmanagedType.LPTStr)] string pszPath); [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("000214F9-0000-0000-C000-000000000046")] public interface IShellLinkW { [PreserveSig] int GetPath(StringBuilder pszFile, int cch, [In, Out] ref WIN32_FIND_DATAW pfd, uint fFlags); [PreserveSig] int GetIDList([Out] out IntPtr ppidl); [PreserveSig] int SetIDList([In] ref IntPtr pidl); [PreserveSig] int GetDescription(StringBuilder pszName, int cch); [PreserveSig] int SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName); [PreserveSig] int GetWorkingDirectory(StringBuilder pszDir, int cch); [PreserveSig] int SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir); [PreserveSig] int GetArguments(StringBuilder pszArgs, int cch); [PreserveSig] int SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs); [PreserveSig] int GetHotkey([Out] out ushort pwHotkey); [PreserveSig] int SetHotkey(ushort wHotkey); [PreserveSig] int GetShowCmd([Out] out int piShowCmd); [PreserveSig] int SetShowCmd(int iShowCmd); [PreserveSig] int GetIconLocation(StringBuilder pszIconPath, int cch, [Out] out int piIcon); [PreserveSig] int SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); [PreserveSig] int SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, uint dwReserved); [PreserveSig] int Resolve(IntPtr hwnd, uint fFlags); [PreserveSig] int SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile); } [Serializable, StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode), BestFitMapping(false)] public struct WIN32_FIND_DATAW { public uint dwFileAttributes; public FILETIME ftCreationTime; public FILETIME ftLastAccessTime; public FILETIME ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } public static void OpenFolderAndSelectFiles(string folder, params string[] filesToSelect) { IntPtr dir = ILCreateFromPath(folder); var filesToSelectIntPtrs = new IntPtr[filesToSelect.Length]; for (int i = 0; i < filesToSelect.Length; i++) { filesToSelectIntPtrs[i] = ILCreateFromPath(filesToSelect[i]); } SHOpenFolderAndSelectItems(dir, (uint) filesToSelect.Length, filesToSelectIntPtrs, 0); ReleaseComObject(dir); ReleaseComObject(filesToSelectIntPtrs); } private static void ReleaseComObject(params object[] comObjs) { foreach (object obj in comObjs) { if (obj != null && Marshal.IsComObject(obj)) Marshal.ReleaseComObject(obj); } } } A: it cannot be done through explorer.exe A: Depending on what you actually want to accomplish you may be able to do it with AutoHotKey. It is an amazing free tool for automating things you normally can't do. It should come with Windows. This script will select your file and highlight the next two files below it when you hit F12. F12:: run explorer.exe /select`, "c:\path\to\file.txt" SendInput {Shift Down}{Down}{Down}{Shift Up} return It is also possible to just put those two middle lines in a text file and then pass it is a parm to autohotkey.exe. They have an option to compile the script also, which would make it a standalone exe that you could call. Works great with a great help file. @Orion, It is possible to use autohotkey from C#. You can make an autohotkey script into a standalone executable (about 400k) that can be launched by your C# app (just the way you are launching explorer). You can also pass it command line parameters. It does not have any runtime requirements. A: There are COM Automation LateBinding IDispatch interfaces, these are easy to use from PowerShell, Visual Basic.NET and C#, some sample code: $shell = New-Object -ComObject Shell.Application function SelectFiles($filesToSelect) { foreach ($fileToSelect in $filesToSelect) { foreach ($window in $shell.Windows()) { foreach ($folderItem in $window.Document.Folder.Items()) { if ($folderItem.Path -eq $fileToSelect) { $window.Document.SelectItem($folderItem, 1 + 8) } } } } } - Option Strict Off Imports Microsoft.VisualBasic Public Class ExplorerHelp Shared ShellApp As Object = CreateObject("Shell.Application") Shared Sub SelectFile(filepath As String) For Each i In ShellApp.Windows For Each i2 In i.Document.Folder.Items() If i2.Path = filepath Then i.Document.SelectItem(i2, 1 + 8) Exit Sub End If Next Next End Sub End Class https://learn.microsoft.com/en-us/windows/win32/shell/shellfolderview-selectitem A: This should be possible with the shell function SHOpenFolderAndSelectItems EDIT Here is some sample code showing how to use the function in C/C++, without error checking: //Directory to open ITEMIDLIST *dir = ILCreateFromPath(_T("C:\\")); //Items in directory to select ITEMIDLIST *item1 = ILCreateFromPath(_T("C:\\Program Files\\")); ITEMIDLIST *item2 = ILCreateFromPath(_T("C:\\Windows\\")); const ITEMIDLIST* selection[] = {item1,item2}; UINT count = sizeof(selection) / sizeof(ITEMIDLIST); //Perform selection SHOpenFolderAndSelectItems(dir, count, selection, 0); //Free resources ILFree(dir); ILFree(item1); ILFree(item2); A: This is one of those questions where it may be good to consider what you're trying to achieve, and whether there's a better method. To add some more context - Our company develops a C# client application, which allows users to load files and do stuff with them, kind of like how iTunes manages your MP3 files without showing you the actual file on disk. It's useful to select a file in the application, and do a 'Show me this file in Windows Explorer` command - this is what I'm trying to achieve, and have done so for single files. We have a ListView which allows users to select multiple files within the application, and move/delete/etc them. It would be nice to have this 'show me this file in windows' command work for multiple selected files - at least if all the source files are in the same directory, but if it's not possible then it's not a major feature. A: I suppose you can use FindWindowEx to get the SysListView32 of Windows Explorer, then use SendMessage with LVM_SETITEMSTATE to select the items. The difficulty being to know the position of the items... Perhaps LVM_FINDITEM can be used for this. A: Grr i would like to do this as well. Media Player does it when you select 2+ files and right click and do "open file location" but not exactly sure how (nor do i really feel like spending the time w/ procmon to figure it out).
{ "language": "en", "url": "https://stackoverflow.com/questions/9355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: ICE Faces fileInput file path and file name properties I'd like to utilize an ICE Faces fileInput control to fill in the file path & file name for the input to an input field on a web page based on file that the user selects. How can I capture these properties without actually performing any file transfer operations? A: I believe that the real answer is that you can't. The file path won't be sent by the browser for security reasons. The file name will be sent, however I don't believe it gets sent without an actual upload. The closest you could come, afaik, would be to forcibly kill the connection just when the upload starts. That would net you the filename with little actual transferred data, but it doesn't sound like it would be useful to you. Alternatively, a signed Java applet might get you closer to a solution that you'd want.
{ "language": "en", "url": "https://stackoverflow.com/questions/9361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I prevent IIS7 from dropping my cookies? I'm using Windows Vista x64 with SP1, and I'm developing an ASP.NET app with IIS7 as the web server. I've got a problem where my cookies aren't "sticking" to the session, so I had a Google and found that there was a known issue with duplicate response headers overwriting instead of being added to the session. This problem was, however, supposed to have been fixed in Service Pack 1 for Vista. Any ideas as to what my trouble might be? I'm using an Integrated app pool, and the max number of worker processes == 1. What's the significance of the underscore? Does it matter where in the URL it is (e.g. it matters if it's in the host name, but not if it's in the query string)? A: Just a thought, have you got an underscore in the url. e.g. http://my_site ? And one other thing, you're not running the app pool in web garden mode? i.e. Process Model -> Maximum Worker Processes: > 1 What type of app pool are you using - Integrated or Classic mode ?
{ "language": "en", "url": "https://stackoverflow.com/questions/9372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ILMerge Best Practices Do you use ILMerge? Do you use ILMerge to merge multiple assemblies to ease deployment of dll's? Have you found problems with deployment/versioning in production after ILMerging assemblies together? I'm looking for some advice in regards to using ILMerge to reduce deployment friction, if that is even possible. A: I know this is an old question, but we not only use ILMerge to reduce the number of dependencies but also to internalise the "internal" dependencies (eg automapper, restsharp, etc) that are used by the utility. This means they are completely abstracted away, and the project using the merged utility doesn't need to know about them. This again reduces the required references in the project, and allows it to use / update its own version of the same external library if required. A: I use ILMerge for almost all of my different applications. I have it integrated right into the release build process so what I end up with is one exe per application with no extra dll's. You can't ILMerge any C++ assemblies that have native code. You also can't ILMerge any assemblies that contain XAML for WPF (at least I haven't had any success with that). It complains at runtime that the resources cannot be located. I did write a wrapper executable for ILMerge where I pass in the startup exe name for the project I want to merge, and an output exe name, and then it reflects the dependent assemblies and calls ILMerge with the appropriate command line parameters. It is much easier now when I add new assemblies to the project, I don't have to remember to update the build script. A: Introduction This post shows how to replace all .exe + .dll files with a single combined .exe. It also keeps the debugging .pdb file intact. For Console Apps Here is the basic Post Build String for Visual Studio 2010 SP1, using .NET 4.0. I am building a console .exe with all of the sub-.dll files included in it. "$(SolutionDir)ILMerge\ILMerge.exe" /out:"$(TargetDir)$(TargetName).all.exe" "$(TargetDir)$(TargetName).exe" "$(TargetDir)*.dll" /target:exe /targetplatform:v4,C:\Windows\Microsoft.NET\Framework64\v4.0.30319 /wildcards Basic hints * *The output is a file "AssemblyName.all.exe" which combines all sub-dlls into one .exe. *Notice the ILMerge\ directory. You need to either copy the ILMerge utility into your solution directory (so you can distribute the source without having to worry about documenting the install of ILMerge), or change the this path to point to where ILMerge.exe resides. Advanced hints If you have problems with it not working, turn on Output, and select Show output from: Build. Check the exact command that Visual Studio actually generated, and check for errors. Sample Build Script This script replaces all .exe + .dll files with a single combined .exe. It also keeps the debugging .pdb file intact. To use, paste this into your Post Build step, under the Build Events tab in a C# project, and make sure you adjust the path in the first line to point to ILMerge.exe: rem Create a single .exe that combines the root .exe and all subassemblies. "$(SolutionDir)ILMerge\ILMerge.exe" /out:"$(TargetDir)$(TargetName).all.exe" "$(TargetDir)$(TargetName).exe" "$(TargetDir)*.dll" /target:exe /targetplatform:v4,C:\Windows\Microsoft.NET\Framework64\v4.0.30319 /wildcards rem Remove all subassemblies. del *.dll rem Remove all .pdb files (except the new, combined pdb we just created). ren "$(TargetDir)$(TargetName).all.pdb" "$(TargetName).all.pdb.temp" del *.pdb ren "$(TargetDir)$(TargetName).all.pdb.temp" "$(TargetName).all.pdb" rem Delete the original, non-combined .exe. del "$(TargetDir)$(TargetName).exe" rem Rename the combined .exe and .pdb to the original project name we started with. ren "$(TargetDir)$(TargetName).all.pdb" "$(TargetName).pdb" ren "$(TargetDir)$(TargetName).all.exe" "$(TargetName).exe" exit 0 A: We use ILMerge on quite a few projects. The Web Service Software Factory, for example produces something like 8 assemblies as its output. We merge all of those DLLs into a single DLL so that the service host will only have to reference one DLL. It makes life somewhat easier, but it's not a big deal either. A: We had the same problem with combining WPF dependencies .... ILMerge doesn't appear to deal with these. Costura.Fody worked perfectly for us however and took about 5 minutes to get going... a very good experience. Just install with Nuget (selecting the correct default project in the Package Manager Console). It introduces itself into the target project and the default settings worked immediately for us. It merges the all DLLs marked "Copy Local" = true and produces a merged .EXE (alongside the standard output), which is nicely compressed in size (much less than the total output size). The license is MIT as so you can modify/distribute as required. https://github.com/Fody/Costura/ A: Note that for windows GUI programs (eg WinForms) you'll want to use the /target:winexe switch. The /target:exe switch creates a merged console application. A: I'm just starting out using ILMerge as part of my CI build to combine a lot of finely grained WCF contracts into a single library. It works very well, however the new merged lib can't easily co-exist with its component libraries, or other libs that depend on those component libraries. If, in a new project, you reference both your ILMerged lib and also a legacy library that depends on one of the inputs you gave to ILMerge, you'll find that you can't pass any type from the ILMerged lib to any method in the legacy library without doing some sort of type mapping (e.g. automapper or manual mapping). This is because once everything's compiled, the types are effectively qualified with an assembly name. The names will also collide but you can fix that using extern alias. My advice would be to avoid including in your merged assembly any publicly available lib that your merged assembly exposes (e.g. via a return type, method/constructor parameter, field, property, generic...) unless you know for sure that the user of your merged assembly does not and will never depend on the free-standing version of the same library. A: We use ILMerge on the Microsoft application blocks - instead of 12 seperate DLL files, we have a single file that we can upload to our client areas, plus the file system structure is alot neater. After merging the files, I had to edit the visual studio project list, remove the 12 seperate assmeblies and add the single file as a reference, otherwise it would complain that it couldnt find the specific assembly. Im not too sure how this would work on post deployment though, could be worth giving it a try. A: We ran into problems when merging DLLs that have resources in the same namespace. In the merging process one of the resource namespaces was renamed and thus the resources couldn't be located. Maybe we're just doing something wrong there, still investigating the issue. A: We just started using ILMerge in our solutions that are redistributed and used in our other projects and so far so good. Everything seems to work okay. We even obfuscated the packaged assembly directly. We are considering doing the same with the MS Enterprise Library assemblies. The only real issue I see with it is versioning of individual assemblies from the package. A: I recently had issue where I had ilmerged assembly in the assembly i had some classes these were being called via reflection in Umbraco opensource CMS. The information to make the call via reflection was taken from db table that had assembly name and namespace of class that implemented and interface. The issue was that the reflection call would fail when dll was il merged however if dll was separate it all worked fine. I think issue may be similar to the one longeasy is having? A: It seems to me like the #1 ILMerge Best Practice is Don't Use ILMerge. Instead, use SmartAssembly. One reason for this is that the #2 ILMerge Best Practice is to always run PEVerify after you do an ILMerge, because ILMerge does not guarantee it will correctly merge assemblies into a valid executable. Other ILMerge disadvantages: * *when merging, it strips XML Comments (if I cared about this, I would use an obfuscation tool) *it doesn't correctly handle creating a corresponding .pdb file Another tool worth paying attention to is Mono.Cecil and the Mono.Linker [2] tool. [2]: http:// www.mono-project.com/Linker
{ "language": "en", "url": "https://stackoverflow.com/questions/9376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "73" }
Q: Access a SQL Server 2005 Express Edition from a network computer How do you access a SQL Server 2005 Express Edition from a application in a network computer? The access I need is both from application (Linq-to-SQL and ODBC) and from Management Studio A: See this KB Article. How to configure SQL Server 2005 to allow remote connections. Oh, and remember that the SQLServer name will probably be MyMachineName\SQLExpress A: If you're running it on a 2k3 box, you need to install all updates for Sql Server and the 2003 server. Check the event logs after you start the Sql Server. It logs everything well, telling you if its being blocked, and where it is listening for connections. From a remote machine, you can use telnet to see if a sql server is listening for remote connections. You just need the IP and the port of the server (default is 1433). From the command line: telnet 192.168.10.10 1433 If you get a blank screen, its listening. If you get thrown back to the command prompt, something is blocking you.
{ "language": "en", "url": "https://stackoverflow.com/questions/9383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Datagrid: Calculate Avg or Sum for column in Footer I have a datagrid getting bound to a dataset, and I want to display the average result in the footer for a column populated with integers. The way I figure, there's 2 ways I can think of: 1."Use the Source, Luke" In the code where I'm calling DataGrid.DataBind(), use the DataTable.Compute() method (or in my case DataSet.DataTable(0).Compute()). For example: Dim strAverage = DataTable.Compute("Avg(ColumnName)", "") But once I have this, how can I insert it into the footer? 2."Bound for Glory" Using the DataGrid.ItemDataBound event, and calculating a running total from every ListItemType.Item and ListItemType.AlternatingItem, finally displaying in ListItemType.Footer. For example: Select Case e.Item.ItemType Case ListItemType.Item, ListItemType.AlternatingItem runningTotal += CInt(e.Item.Cells(2).Text) Case ListItemType.Footer e.Item.Cells(2).Text = runningTotal/DataGrid.Items.Count End Select This just feels wrong, plus I would have to make sure the runningTotal is reset on every DataBind. Is there a better way? A: I don't know if either are necessarily better, but two alternate ways would be: * *Manually run through the table once you hit the footer and calculate from the on-screen text *Manually retrieve the data and do the calculation separately from the bind Of course, #2 sort of offsets the advantages of data binding (assuming that's what you're doing). A: Thanks DannySmurf, your first answer made me see sense. (Why do we always look for that magic solution?). For reference, here's what I ended up doing: (Warning: VB below, may not contain enough semicolons) Case ListItemType.Footer e.Item.Cells(0).Text = "Average" For i As Integer = 3 To 8 Dim runningTotal As Integer = 0 For Each row As DataGridItem In DataGrid.Items If IsNumeric(row.Cells(i).Text) Then runningTotal += CInt(row.Cells(i).Text) End If Next e.Item.Cells(i).Text = Math.Round(runningTotal / DataGrid.Items.Count, 0) Next End Select I needed to do it for several columns (hence 3 to 8), ultimately why I was looking for the magical solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/9409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do you pass a function as a parameter in C? I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C? A: Declaration A prototype for a function which takes a function parameter looks like the following: void func ( void (*f)(int) ); This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type: void print ( int x ) { printf("%d\n", x); } Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func, passing the print function to it. Function Body As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly: for ( int ctr = 0 ; ctr < 5 ; ctr++ ) { print(ctr); } Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f: void func ( void (*f)(int) ) { for ( int ctr = 0 ; ctr < 5 ; ctr++ ) { (*f)(ctr); } } Source A: Pass address of a function as parameter to another function as shown below #include <stdio.h> void print(); void execute(void()); int main() { execute(print); // sends address of print return 0; } void print() { printf("Hello!"); } void execute(void f()) // receive address of print { f(); } Also we can pass function as parameter using function pointer #include <stdio.h> void print(); void execute(void (*f)()); int main() { execute(&print); // sends address of print return 0; } void print() { printf("Hello!"); } void execute(void (*f)()) // receive address of print { f(); } A: I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function. Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement. Compare Function bool compare(int a, int b) { return a > b; } Now , the Bubble sort that takes another function as its parameter to perform comparison Bubble sort function void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) { for (int i = 0;i < n - 1;i++) { for (int j = 0;j < (n - 1 - i);j++) { if (cmp(arr[j], arr[j + 1])) { swap(arr[j], arr[j + 1]); } } } } Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument. int main() { int i, n = 10, key = 11; int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 }; bubble_sort(arr, n, compare); cout<<"Sorted Order"<<endl; for (int i = 0;i < n;i++) { cout << arr[i] << " "; } } Output: Sorted Order 3 6 8 11 12 12 15 18 20 22 A: You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it. A: Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this: void foo(int bar(int, int)); is equivalent to this: void foo(int (*bar)(int, int)); A: This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example. typedef void (*functiontype)(); Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do: void dosomething() { } functiontype func = &dosomething; func(); For a function that returns an int and takes a char you would do typedef int (*functiontype2)(char); and to use it int dosomethingwithchar(char a) { return 1; } functiontype2 func2 = &dosomethingwithchar int result = func2('a'); There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort! boost::function<int (char a)> functiontype2; is so much nicer than the above. A: Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g., std::function<bool (int)> where bool is the return type here of a one-argument function whose first argument is of type int. I have included an example program below: // g++ test.cpp --std=c++11 #include <functional> double Combiner(double a, double b, std::function<double (double,double)> func){ return func(a,b); } double Add(double a, double b){ return a+b; } double Mult(double a, double b){ return a*b; } int main(){ Combiner(12,13,Add); Combiner(12,13,Mult); } Sometimes, though, it is more convenient to use a template function: // g++ test.cpp --std=c++11 template<class T> double Combiner(double a, double b, T func){ return func(a,b); } double Add(double a, double b){ return a+b; } double Mult(double a, double b){ return a*b; } int main(){ Combiner(12,13,Add); Combiner(12,13,Mult); } A: It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do. #include <stdio.h> int IncMultInt(int a, int b) { a++; return a * b; } int main(int argc, char *argv[]) { int a = 5; int b = 7; printf("%d * %d = %d\n", a, b, IncMultInt(a, b)); b = 9; // Create some local code with it's own local variable printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) ); return 0; } A: typedef int function(); function *g(function *f) { f(); return f; } int main(void) { function f; function *fn = g(f); fn(); } int f() { return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/9410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "795" }
Q: Do you name controls on forms using the same convention as a private variable? For some reason I never see this done. Is there a reason why not? For instance I like _blah for private variables, and at least in Windows Forms controls are by default private member variables, but I can't remember ever seeing them named that way. In the case that I am creating/storing control objects in local variables within a member function, it is especially useful to have some visual distinction. A: Hungarian notation or not, I'm more curious if people prepend m_ or _ or whatever they use for standard private member variables. A: This might be counter-intuitive for some, but we use the dreaded Hungarian notation for UI elements. The logic is simple: for any given data object you may have two or more controls associated with it. For example, you have a control that indicates a birth date on a text box, you will have: * *the text box *a label indicating that the text box is for birth dates *a calendar control that will allow you to select a date For that, I would have lblBirthDate for the label, txtBirthDate for the text box, and calBirthDate for the calendar control. I am interested in hearing how others do this, however. :) A: I personally prefix private objects with _ Form controls are always prefixed with the type, the only reason I do this is because of intellisense. With large forms it becomes easier to "get a labels value" by just typing lbl and selecting it from the list ^_^ It also follows the logic stated by Jon Limjap. Although this does go again Microsofts .NET Coding Guidelines, check them out here. A: For me, the big win with the naming convention of prepending an underscore to private members has to do with Intellisense. Since underscore precedes any letter in the alphabet, when I do a ctrl-space to bring up Intellisense, there are all of my _privateMembers, right at the top. Controls, though, are a different story, as far as naming goes. I think that scope is assumed, and prepending a few letters to indicate type (txtMyGroovyTextbox, for example) makes more sense for the same reason; controls are grouped in Intellisense by type. But at work, it's VB all the way, and we do mPrivateMember. I think the m might stand for module. A: I came through VB and have held onto the control type prefix for controls. My private members use lower-camel case (firstLetterLowercase) while public members use Pascal/upper-camel case (FirstLetterUppercase). If there are too many identifiers/members/locals to have a 90% chance of remembering/guessing what it is called, more abstraction is probably necessary. I have never been convinced that a storage type prefix is useful and/or necessary. I do, however, make a strong habit of following the style of whatever code I am using. A: I don't, but I appreciate your logic. I guess the reason most people don't is that underscores would look kind of ugly in the Properties window at design time. It'd also take up an extra character of horizontal space, which is at a premium in a docked window like that. A: Hungarian notation or not, I'm more curious if people prepend m_ or _ or whatever they use for standard private member variables. Luke, I use _ prefix for my class library objects. I use Hungarian notation exclusively for the UI, for the reason I stated. A: I never use underscores in my variable names. I've found that anything besides alpha (sometimes alphanumeric) characters is excessive unless demanded by the language. A: I'm in the Uppercase/Lowercase camp ("title" is private, "Title" is public), mixed with the "hungarian" notation for UI Components (tbTextbox, lblLabel etc.), and I am happy that we do not have Visual Case-Insensitive-Basic developers in the team :-) I don't like the underscore because it looks kinda ugly, but I have to admit it has an advantage (or a disadvantage, depending on your point): In the debugger, all the private Variables will be on top due to the _ being on top of the alphabet. But then again, I prefer my private/public pair to be together, because that allows for easier debugging of getter/setter logic as you see the private and public property next to each other, A: I write down the name of the database column they represent. A: I use m_ for member variables, but I'm increasingly becoming tempted to just using lowerCamelCase like I do for method parameters and local variables. Public stuff is in UpperCamelCase. This seems to be more or less accepted convention across the .NET community.
{ "language": "en", "url": "https://stackoverflow.com/questions/9433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Add multiple window.onload events In my ASP.NET User Control I'm adding some JavaScript to the window.onload event: if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName)) Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName, "window.onload = function() {myFunction();};", true); My problem is, if there is already something in the onload event, than this overwrites it. How would I go about allowing two user controls to each execute JavaScript in the onload event? Edit: Thanks for the info on third party libraries. I'll keep them in mind. A: I had a similar problem today so I solved it having an index.js with the following: window.onloadFuncs = []; window.onload = function() { for(var i in this.onloadFuncs) { this.onloadFuncs[i](); } } and in additional js files that i want to attach the onload event I just have to do this: window.onloadFuncs.push(function(){ // code here }); I normally use jQuery though, but this time I was restricted to pure js wich forced to use my mind for a while! A: Mootools is another great JavaScript framework which is fairly easy to use, and like RedWolves said with jQuery you can can just keep chucking as many handlers as you want. For every *.js file I include I just wrap the code in a function. window.addEvent('domready', function(){ alert('Just put all your code here'); }); And there are also advantages of using domready instead of onload A: Try this: window.attachEvent("onload", myOtherFunctionToCall); function myOtherFunctionToCall() { // do something } edit: hey, I was just getting ready to log in with Firefox and reformat this myself! Still doesn't seem to format code for me with IE7. A: There still is an ugly solution (which is far inferior to using a framework or addEventListener/attachEvent) that is to save the current onload event: function addOnLoad(fn) { var old = window.onload; window.onload = function() { old(); fn(); }; } addOnLoad(function() { // your code here }); addOnLoad(function() { // your code here }); addOnLoad(function() { // your code here }); Note that frameworks like jQuery will provide a way to execute code when the DOM is ready and not when the page loads. DOM being ready means that your HTML has loaded but not external components like images or stylesheets, allowing you to be called long before the load event fires. A: Most of the "solutions" suggested are Microsoft-specific, or require bloated libraries. Here's one good way. This works with W3C-compliant browsers and with Microsoft IE. if (window.addEventListener) // W3C standard { window.addEventListener('load', myFunction, false); // NB **not** 'onload' } else if (window.attachEvent) // Microsoft { window.attachEvent('onload', myFunction); } A: I don't know a lot about ASP.NET, but why not write a custom function for the onload event that in turn calls both functions for you? If you've got two functions, call them both from a third script which you register for the event. A: Actually, according to this MSDN page, it looks like you can call this function multiple times to register multiple scripts. You just need to use different keys (the second argument). Page.ClientScript.RegisterStartupScript( this.GetType(), key1, function1, true); Page.ClientScript.RegisterStartupScript( this.GetType(), key2, function2, true); I believe that should work. A: You can do this with jquery $(window).load(function () { // jQuery functions to initialize after the page has loaded. });
{ "language": "en", "url": "https://stackoverflow.com/questions/9434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "67" }
Q: Planning and Building a mobile enabled site for your main site We are in the initial planning stages of building out a mobile site for one of our clients. This mobile site will be in addition to the main site that we have already built for them. We've determined that the content is going to be a small subsection of the main site and will target the main audience that is expected to use the site. While looking through some sample mobile sites we noticed that a lot of site that have WAP in the url are actually just simplified HTML files. http://wap.mlb.com is not really WAP enabled but simple HTML. My question is WAP a think of the past? With smartphones and the iPhone having the ability to render sites as is do we need to worry about WML and WAP or will a stripped down html version be enough? Also can you recommend a blog or tutorial or answer below how best to check for mobile devices? Do we as the programmer need to know each variation of user agent in order to redirect them to our mobile site? Finally, would you program a mobile site for the iPhone/Touch Safari browser or just leave the site as is? A: Newer phones come with WAP2 which uses HTML Mobile Profile (XHTML MP), which is quite similar to normal HTML. Older phones use Wireless Markup Language (WML). Depending on your audience I would consider making a mobile phone friendly version of the site using XHTML MP and drop WML completely. By mobile phone friendly I mean light graphics, little JavaScript and simple navigation. To check capabilities of different hand phones, take look at WURFL. Also, you might want to take a look at Mobile Web Best Practices from w3c. A: Here are two things you can do to improve support for iPhones without doing much work: Make page scroll up to hide URL bar: <script type="application/x-javascript"> if (navigator.userAgent.indexOf('iPhone') != -1) { addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); } function hideURLbar() { window.scrollTo(0, 1); } </script> And set scaling for the page width (best to do some testing and play with this, also look for other examples that may use user-scalable=true): <meta name="viewport" content="width=320; user-scalable=false" /> A: I would highly recommend you check out Cameron Molls' book Mobile Web Design. Its not so much a technical how-to for building mobile optimised sites but makes you think about the various options available and summarises each ones pros and cons. Will definately make you think about what approach you're taking and whether its the right one. I think it also has some pointers to resources that help detect mobile device requests to your site, there are various options out there. A: As of now(2014) We may not need separate site for mobile devices instead we can go for front end libaries like Twitter Bootstrap which uses responsive rendering so that site adapts itself to the screen size whether it be Tablet or Mobile device or Desktop One of Major advantages is it takes less maintenance when compared to having separate websites for mobile and desktop. To know more about Twitter Bootstrap click here A: I think the main difference with the 2.5G phones and the new 3G phones is that while 2.5G phones used their own browsers, browsers on 3G phones have become much more similar/accurate in their rendering capabilities. On the other hand, you can use CSS to render the same HTML in either a large screen format or a small mobile-optimized one, so I guess what has happened is that the "simple HTML" approach just appeared to be the least difficult path to take. Also, tableless layouts allow websites to scale better, making it easier to render a site in both large and small screen formats. So the end question will be that of a target market. Are you targeting a tech-savvy audience who will tend to have fully 3G-capable phones? Are you targeting people who might have 2.5G at the most? A: My experience is that it really depends on what you're trying to do and who/where the users are. While WAP got a lot of bad press, it's strength is where you have low bandwidth high-latency connections. The WML content gets optimised by the carrier's gateway to greatly reduce the amount of data transmitted over the air. If you have iPhones and the like, in areas with solid 3G coverage you can afford to go for richer content, but if you want an app to still perform well in more out of the way areas, WAP has a big advantage. One thing to watch out for with WAP is that the quality of the WAP support in handsets varies a lot (guess you'd also say the same for smartphone web browsers). Most of them display pages ok, but the form handling is truly awful in some browsers. If you vary content based on user-agent, you should also provide an explicit way to access a specific type of content (e.g. seperate uri's) - the automated choice is not always right and you want the client to be able to override it . If you go with WAP development check out WinWAP - a Windows-based WAP browser. A: If you want to spend a very small amount of money, you can find a used copy of my book "Palm OS Web Application Developer's Guide" on Amazon for under $1. While the specific tips about the old Palm VII devices don't apply anymore, there's a few sections on making mobile websites that might still apply. My basic advice is this: make pages small with relevant information first, then navigation links; push generic/boilerplate content to other pages; try to optimize to reduce the amount of time a user spends on a single page; and avoid downloading lots of objects (images, JavaScript files) for a page to reduce latency. A: The code: Causes the w3 validator to return 11 erorrs when I use it. Here's the index page it was tried in: You'll not some multiple lines, not used. They're template lines. <!DOCTYPE HTML> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Photography Aerial Commercial Portrait Underwater Wedding Tom Szabo</title> <meta name="description" content="A Thomas Image professional photography serving Cleveland Northeast Ohio Chagrin Falls Chardon Kirtland Madison Mentor Painesville Perry and Willoughby"> <meta name="keywords" content="A Thomas Image, professional, photography, cleveland, northeast ohio, chagrin falls, chardon, concord, kirtland, madison, mentor, painesville, perry, willoughby,commercial, marketing, advertising, executive, head shot, portrait, baby, children, family, high school senior, family reunion, underwater, scuba diving, pool party, wedding, bride, groom,"> <meta name="y_key" content="7b00158550200c1c"> <meta name="y_key" content="b5a3e0c1d778ff8a"> <meta name="msvalidate.01" content="7C6C4CEC2EB84051B1DCFEC558B77724" /> <meta name="verify-v1" content="G4nmk0aesZsCjneBo0W6kVlv5NpImVnTfsQ+fXEk1fA=" /> <meta name="viewport" content=”width=320,user-scalable=false”>
{ "language": "en", "url": "https://stackoverflow.com/questions/9435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Running xinc on OpenBSD's Apache Server Has anyone been able to get xinc to run correctly under OpenBSD's chrooted default Apache? I'd like to keep our development server running fully chrooted just like our Production server so that we make sure our code runs just fine chrooted. A: Have you posted the issue on the Xinc bug tracker? Xinc itself should run fine as it runs both as a daemon and as a web app. As you alluded to, the issue may be that the daemon is not running in a chroot'ed environment where as the web interface is, leading to either side not grabbing the files. A: @dragonmantank In Xinc's case, I hope you used PEAR to install it. pear list-files xinc/Xinc This should do it, and show you where your Xinc install put its files. So even though Xinc is "just" one big PHP script, it's still spread out into rc scripts and all those other things which are necessary to make an application run. I'm sure you don't need to add all paths listed there, but probably some in order to make it run. Aside from Xinc itself, I think it also needs phpUnit and a bunch of other PEAR libs to run, so what I'd propose is this: pear config-get php_dir And then you need to add that path (like Henrik suggested) to the chroot environment. A: Having never used xinc myself, I can only hint as to how I usually get to chrooting apps. First step would be to gather information on everything the app needs to run; this I usually accomplish by running systrace(1) and ldd(1) to find out what is needed to run the software. Go through the output of systrace -A -d. <app> ldd <app> and make sure that everything the app touches and needs (quite a lot of apps touch stuff it doesn't actually need) is available in the chroot environment. You might need to tweak configs and environment variables a bit. Also, if there is an option to have the app log to syslog, I usually do that and create a syslog socket (see the -a option of syslogd(8)) in order to decrease the places the app needs write access to. What I just described is a generic way to make just about any program run in a chroot environment (however, if you need to import half the userland and some suid commands, you might want to just not do chroot :). For apps running under Apache (I'm sure you're aware that the OpenBSD httpd(8) is slightly different) you have the option (once the program has started; any dynamic libraries still needs to be present in the jail) of using apache to access the files, allowing the use of httpd.conf to import resources in the chroot environment without actually copying them. Also useful (if slightly outdated) is this link, outlining some gotchas in chrooted PHP on OpenBSD. A: First step would be to gather information on everything the app needs to run; this I usually accomplish by running systrace(1) and ldd(1) to find out what is needed to run the software. I'll give this a try. The big issue I've found with xinc is that while it is a PHP application, it wants to know application installation paths (yet it still spreads stuff into other folders) and runs some PHP scripts in daemon mode (those scripts being the hardest to get running). So, for example, I told it to install to /var/www/xinc and then made a symlink of /var/www/var/www/xinc -> /var/www/xinc and it partially worked. I got the GUI to come up bit it refused to recognize any projects that I had set up. I think the biggest problem is that part of it is running a chroot and the other half is running outside. If all else fails I'm going to just have to build something as we program inside chrooted environments since our production is chrooted. We've run into issues where we code outside of a chroot and then have to back track to find what we need to make it work inside a chroot.
{ "language": "en", "url": "https://stackoverflow.com/questions/9455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Best way to write a RESTful service "client" in .Net? What techniques do people use to "consume" services in the REST stile on .Net ? Plain http client? Related to this: many rest services are now using JSON (its tighter and faster) - so what JSON lib is used? A: My approach was * *Write some libraries and interfaces to serialize your objects into REST-compatible XML. You can't neccessarily just use the built-in serializers, because your service may not accept the same kind of XML that .NET wants to give you. Example: When passing booleans to a Rails REST service, "true" gets unserialized as true, whereas "True" (which .NET gives you) unserializes to false. *Write some libraries to do the HTTP, wrapping around the basic .NET WebRequest objects. You might get some mileage out of some third party libraries in this area as it tends to be more standard. I found some issues though, such as this lovely bug in the .NET framework, so I'm glad I stuck with the basics.
{ "language": "en", "url": "https://stackoverflow.com/questions/9467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: WCF Backward Compatibility Issue I have a WCF service that I have to reference from a .net 2.0 project. I have tried to reference it using the "add web reference" method but it messes up the params. For example, I have a method in the service that expects a char[] to be passed in, but when I add the web reference, the method expects an int[]. So then I tried to setup svcutil and it worked... kind of. I could only get the service class to compile by adding a bunch of .net 3.0 references to my .net 2.0 project. This didn't sit well with the architect so I've had to can it (and probably for the best too). So I was wondering if anyone has any pointers or resources on how I can setup a .net 2.0 project to reference a WCF service. A: One of those instances that you need to edit the WSDL. For a start a useful tool http://codeplex.com/storm A: What binding are you using - I think if you stick to the basicHttp binding you should be able to generate a proxy using the "add web reference" approach from a .net 2 project? Perhaps if you post the contract/interface definition it might help? Cheers Richard A: Thanks for the resource. It certainly helped me test out the webservice, but it didn't much help with using the WCF service in my .net 2.0 application. What I eventually ended up doing was going back to the architects and explaining that the 3.0 dll's that I needed to reference got compiled back to run on the 2.0 CLR. We don't necessarily like the solution, but we're going to go with it for now as there doesn't seem to be too many viable alternatives A: I was using the basicHttp binding but the problem was actually with the XMLSerializer. It doesn't properly recognize the wsdl generated by WCF (even with basicHttp bindings) for anything other than basic value types. We got around this by added the reference to the 3.0 dll's and using the datacontract serializer.
{ "language": "en", "url": "https://stackoverflow.com/questions/9472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RaisePostBackEvent not firing I have a custom control that implements IPostBackEventHandler. Some client-side events invoke __doPostBack(controlID, eventArgs). The control is implemented in two different user controls. In one control, RaisePostBackEvent is fired on the server-side when __doPostBack is invoked. In the other control, RaisePostBackEvent is never invoked. I checked the __EVENTTARGET parameter and it does match the ClientID of the control... where else might I look to troubleshoot this? A: There's a lot of ways this can fall apart. Are you adding the control to the page dynamically in code behind? If so alot of times your UniqueID can be off - even though the client id's are equal. Do you have a code sample that might demonstrate what you're doing? A: Double check that it is indeed a derivation of the UserControl class, not the WebControl one. This one has had me by surprise many times. If you need to use WebControl for the styling, you need to let your control implement INamingContainer. (Don't worry, its a marker interface) So.. public class MyControl : UserControl {} Or public class MyControl : WebControl, INamingContainer {}
{ "language": "en", "url": "https://stackoverflow.com/questions/9473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I make Visual Studio auto generate braces for a function block? I could swear I've seen people typing function headers and then hitting some key combination to auto-create function braces and insert the cursor between them like so: void foo()_ to void foo() { _ } Is this a built-in feature? A: The tools look nice (especially Resharper but at $200-350 ouch!) but I ended up just recording a macro and assigning it to ctrl+alt+[ Macro came out like this: Sub FunctionBraces() DTE.ActiveDocument.Selection.NewLine DTE.ActiveDocument.Selection.Text = "{}" DTE.ActiveDocument.Selection.CharLeft DTE.ActiveDocument.Selection.NewLine(2) DTE.ActiveDocument.Selection.LineUp DTE.ActiveDocument.Selection.Indent End Sub Edit: I used the macro recorder to make this and it wasn't too bad A: Check out Resharper - it is a Visual Studio add-on with this feature, among many other development helps. Also see C# Completer, another add-on. If you want to roll your own, check out this article. Insane that one should have to do that, though. A: It can be achieved by using code snippets, some are already built in (try typing "svm" and hitting TAB-TAB).. There's a wealth of info on the net on creating these: Jeff did a post himself here Have a google! I use them LOTS! :D A: Take a look at visual assist as well. A: I just created one based on @Luke's above. This one, you want to hit Enter then hit your key combination and it will insert: if () { } else { } And it will put your cursor in the parenthesis by the if statement. Sub IfStatement() DTE.ActiveDocument.Selection.Text = "if ()" DTE.ActiveDocument.Selection.NewLine() DTE.ActiveDocument.Selection.Text = "{" DTE.ActiveDocument.Selection.NewLine(2) DTE.ActiveDocument.Selection.Text = "}" DTE.ActiveDocument.Selection.NewLine() DTE.ActiveDocument.Selection.Text = "else" DTE.ActiveDocument.Selection.NewLine(2) DTE.ActiveDocument.Selection.Text = "{" DTE.ActiveDocument.Selection.NewLine(2) DTE.ActiveDocument.Selection.Text = "}" DTE.ActiveDocument.Selection.LineUp(False, 7) DTE.ActiveDocument.Selection.EndOfLine() DTE.ActiveDocument.Selection.CharLeft(3) End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/9486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Replicating load related crashes in non-production environments We're running a custom application on our intranet and we have found a problem after upgrading it recently where IIS hangs with 100% CPU usage, requiring a reset. Rather than subject users to the hangs, we've rolled back to the previous release while we determine a solution. The first step is to reproduce the problem -- but we can't. Here's some background: Prod has a single virtualized (vmware) web server with two CPUs and 2 GB of RAM. The database server has 4GB, and 2 CPUs as well. It's also on VMWare, but separate physical hardware. During normal usage the application runs fine. The w3wp.exe process normally uses betwen 5-20% CPU and around 200MB of RAM. CPU and RAM fluctuate slightly under normal use, but nothing unusual. However, when we start running into problems, the RAM climbs dramatically and the CPU pegs at 98% (or as much as it can get). The site becomes unresponsive, necessitating a IIS restart. Resetting the app pool does nothing in this situation, a full IIS restart is required. It does not happen during the night (no usage). It happens more when the site is under load, but it has also happened under non-peak periods. First step to solving this problem is reproducing it. To simulate the load, we starting using JMeter to simulate usage. Our load script is based on actual usage around the time of the crash. Using JMeter, we can ramp the usage up quite high (2-3 times the load during the crash) but the site behaves fine. CPU is up high, and the site does become sluggish, but memory usage is reasonable and nothing is hanging. Does anyone have any tips on how to reproduce a problem like this in a non-production environment? We'd really like to reproduce the error, determine a solution, then test again to make sure we've resolved it. During the process we've found a number of small things that we've improved that might solve the problem, but I'd really feel a lot more confident if we could reproduce the problem and test the improved version. Any tools, techniques or theories much appreciated! A: You can find some information about troubleshooting this kind of problem at this blog entry. Her blog is generally a good debugging resource. A: I have an article about debugging ASP.NET in production which may provide some pointers. A: Is your test env the same really as live? i.e 2 separate vm instances on 2 physical servers - with the network connection and account types? Is there any other instances on the Database? Is there any other web applications in IIS? Is the .Net Config right? Is the App Pool Config right for service accounts ? Try look at this - MS Article on II6 Optmising for Performance Lots of tricks.
{ "language": "en", "url": "https://stackoverflow.com/questions/9501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: C# 2.0 code consuming assemblies compiled with C# 3.0 This should be fine seeing as the CLR hasn't actually changed? The boxes running the C# 2.0 code have had .NET 3.5 rolled out. The background is that we have a windows service (.NET 2.0 exe built with VS2005, deployed to ~150 servers) that dynamically loads assemblies (almost like plug-ins) to complete various work items asked of it. Whenever we roll out a new version of the bus logic, we just drop the assemblies on an FTP server and the windows service knows how to check for, grab and store the latest versions. New assemblies are now built using VS2008 and targetting .NET 2.0, we know that works ok. However we'd like to start taking advantage of C# 3.0 language features such as LINQ and targetting the assemblies against .NET 3.5 without having to build and deploy a new version of the windows service. A: C#3 and .Net 3.5 adds new assemblies, but the IL is unchanged. This means that with .Net 2 assemblies you can compile and use C#3, as long as you don't use Linq or anything else that references System.Linq or System.Core yield, var, lambda syntax, anon types and initialisers are all compiler cleverness. The IL they produce is cross-compatible. If you can reference the new assemblies for 3.5 it should all just work. There is no new version of ASP.Net - it should still be 2.0.50727 - but you should still compile for 3.5 A: yield, var, lambda syntax, anon types and initialisers are all compiler cleverness. The IL they produce is cross-compatible. Minor nit-picking point, but yield was a 2.0 feature anyway. A: This is interesting stuff. I was looking at LinqBridge yesterday after someone on this forum suggested it to me and they are doing a similar thing. I find it strange that Microsoft named the frameworks 2.0, 3.0 and 3.5 when they all compile down to produce the same IL required by the 2.0 CLR. I would have thought adding versions onto 2.0 would have made more sense altho I suppose it also is hard to get people to get their head around the fact that there are different versions of runtimes, compilers and languages.
{ "language": "en", "url": "https://stackoverflow.com/questions/9508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How do you deploy your SharePoint solutions? I am now in the process of planning the deployment of a SharePoint solution into a production environment. I have read about some tools that promise an easy way to automate this process, but nothing that seems to fit my scenario. In the testing phase I have used SharePoint Designer to copy site content between the different development and testing servers, but this process is manual and it seems a bit unnecessary. The site is made up of SharePoint web part pages with custom web parts, and a lot of Reporting Services report definitions. So, is there any good advice out there in this vast land of geeks on how to most efficiently create and deploy a SharePoint site for a multiple deployment scenario? Edit Just to clarify. I need to deploy several "SharePoint Sites" into an existing site collection. Since SharePoint likes to have its sites in the SharePoint content database, just putting the files into IIS is not an option at this time. A: I would also suggest checking out the SharePoint Content Deployment Wizard by Chris O'Brien. http://www.codeplex.com/SPDeploymentWizard Should help smooth the process you describe, and it's a nice tool for your kitbag regardless A: We have a BizTalk 2006 with Web Application and Several WebServices that need to go from Dev to UAT to Live. We use MSBuild right from within VS to build, run tests, dependent on test result, complie, zip and ship to servers. Small MSBuild script on server to unzip, move the files, install clean web app, unlist biztalk bits, install new biztalk bits, re enlist and then start the stuff. MSBuild is hugh and more people need to use it as it there now right in the platform => Use MSBuild A: Note that "solution" has a specific meaning in Sharepoint: a collection of features (like web parts, list definitions and so on) packaged for deployment as a .wsp file. You typically build sharepoint solutions in Visual Studio and package and deploy them using some tool like Sharepoint SmartTemplates http://www.codeplex.com/smarttemplates However in your case you already have content in a live sharepoint site which you want to move to another site. It will probably be too cumbersome to use a solution for this, especially if you want to do it more than once (though it is possible to generate a solution from a live site using SharePoint Solution Generator). The easiest way to deploy all content from one live site to another is to create a backup of the site using stsadm and then restore it to the new site again using stsadm restore. This completely overwrites the new site. You can move select files/lists using import/export (rather than backup/restore). A tool like SharePoint Content Deployment Wizard makes it easier to select the content to move.
{ "language": "en", "url": "https://stackoverflow.com/questions/9543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: What libraries do I need to link my mixed-mode application to? I'm integrating .NET support into our C++ application. It's an old-school MFC application, with 1 extra file compiled with the "/clr" option that references a CWinFormsControl. I'm not allowed to remove the linker flag "/NODEFAULTLIB". (We have our own build management system, not Visual Studio's.) This means I have to specify all necessary libraries: VC runtime and MFC. Other compiler options include "/MD" Next to that: I can't use the linker flag "/FORCE:MULTIPLE" and just add everything: I'm looking for a non-overlapping set of libraries. A: As a bare minimum: mscoree.lib MSVCRT.lib mfc90.lib (adjust version appropriately) And iterate from there. A: Use the AppWizard to create a bare-bones MFC app in your style (SDI / MDI / dialog ) and then put on your depends. A: How I solved it: * *link with "/FORCE:MULTIPLE /verbose" (that links ok) and set the output aside. *link with "/NODEFAULTIB /verbose" and trace all unresolveds in the output of the previous step and add the libraries 1 by 1. *This resulted in doubles: "AAA.lib: XXX already defined in BBB.lib" *Then I finally got it: Recompiled managed AND unmanaged units with /MD and link to (among others): mscoree.lib msvcmrt.lib mfcm80d.lib Mixing /MT (unmanaged) and /MD (managed) turned out to be the bad idea: different(overlapping) libraries are needed. @ajryan: Dependcy Walker only tells me what dll's are used, not what libraries are linked to when linking. (e.g. msvcmrt.lib ?) I think. Thanks for the answers! Jan
{ "language": "en", "url": "https://stackoverflow.com/questions/9570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a good tool for Makefile generation? I'm looking for a tool which can generate a Makefile for a C/C++ project for different compilers (GCC, Microsoft Visual C++, C++Builder, etc.) and different platforms (Windows, Linux, and Mac). A: Try Automatic Makefile Generator. It has support for the following compilers: * *Borland 3.1 *Borland 5.0 *Borland 5.0, 16 bit *Borland 5.5 *Borland 5.6 *Borland 5.8 *CC *GNU g++ *GNU g++, dynamic library *Intel 5, 6, 7 for Linux *Intel 5, 6, 7 for Linux, dynamic library *Intel 5, 6, 7 for Windows *Intel 8,9,10 for Linux *Intel 8,9,10 for Linux, dynamic library *Intel 8,9 for Windows *Intel 10 for Windows *Visual C++ 5 *Visual C++ 6, 7, 7.1 *Visual C++ 8 *Open Watcom *Watcom 10A *Watcom 10A, 16 bit A: I've used Bakefile before with some success. It's fairly simple and seems to work well. A: CMake is the only tool which can actually generate real Visual Studio projects (i.e., not "Makefile"-projects which call out to an external tool), and which automatically recreates the projects when the build input file (CMakeLists.txt) changes. SCons performance issues are well-known and a thoroughly debated topic on the SCons mailing lists. A: I would vote for OMake. It fixes all complains I had with GNU make: * *it's a full-blown language. *uses MD5 instead of timestamps. *provides a minimal shell which implements the most useful Unix commands on all platforms: find, sed, AWK, etc. *works with either Unix or DOS style pathnames. *extensively documented. *supports parallel builds. *fast. A: Other suggestions you may want to consider: * *Scons is a cross-platform, cross-compiler build library, uses Python scripting for the build systems. Used in a variety of large projects, and performs very well. *If you're using Qt, QMake is a nice build system too. *CMake is also pretty sweet. *Finally, if all else fails... A: I'll also second CMake. I've been using it for quite a while on a multi-platform project and I'm very satisfied with it. A: Automatic generation of (M|m)akefiles makes me worry about what you're trying to do here. Do you understand what goes on under the covers when you type make? Or gmake? I'm only asking because if you don't when things break, such as new code changes not being incorporated into the build, you'll have difficulties trying to work what has happened. To start to understand make, can I suggest having a read of "Managing Projects with GNU Make" by Robert Mecklenberg. The early chapters cover how make is working. Getting your heard around the fact that make is backward chaining is one of the biggest things you can do. If you don't, and your system appears to work, then you'll be, to use The Pragmatic Programmers' term, "programming by coincidence". (-: BTW Great articles available at their site! And I'm not involved with them. YMMV. Yada-yada... A: One issue to consider is do you want a "makefile" creator or a replacement build system? The problem with replacement build systems is that you typically don't get good IDE integration for platforms whose users expect this (Visual C++). If you do want a makefile creator instead of a replacement build system, take a look at MPC. It's free and open source. A: A recent addition to the list of make replacements is waf. From personal experience, SCons does the job pretty well. A: I am working on a similar Makefile auto-generator projection called CodeMate, developed by using Ruby. Maybe it is not that mature for large applications right now, but I will keep working on it to make it better. Users should not need to edit any configuration file to build the software, or at least it is supposed to be. The learning curve should be minimized.
{ "language": "en", "url": "https://stackoverflow.com/questions/9589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "50" }
Q: What WPF books would you recommend? Well, i've got a nice WPF book its called Sams Windows Presentation Foundation Unleashed. I really like to read and learn with it. Are there any other WPF books you could recommend? A: I've found the following books very useful: Windows Presentation Foundation Unleashed - Adam Nathan You mention you already have this book, however I wanted to give my opinion on it. It is a great book for the newcomer - it is printed in full color which is a great help for visualizing both xaml and concepts for WPF. Essential Windows Presentation Foundation - Chris Anderson This is also another great book for the newcomer. While it is not printed in color, it does give a great insight into how WPF works. Pro WPF in C# 2008 - Matthew Macdonald This is a great reference book - one that sits on my desk and is constantly referred too. However, I didn't feel is was as newbie friendly as the other two books above. This is the most recently released book (at the time of this posting), and has been updated for VS2008. This is useful, as there are some changes with the versions of WPF. I believe there is a VB.NET version available. Programming WPF - Chris Sells & Ian Griffiths Another great book - I wish this was available when I was first learning the framework. Application = Code + Markup - Charles Petzold This was the very first WPF I purchased. It is not very newbie friendly, and I wouldn't recommend it for a first-time-wpf'er. The fact that Xaml is not introduced until page 457 makes learning the technology for the real world very difficult. That said, this book is invaluable if you really want to understand how things work at a very deep level (which is also important to get the most of the framework. The only book I would totally avoid is: Professional WPF Programming - Chris Andrade et al. While the content was Ok in this book, I just found the other books to be much clearer and delve to a much deeper level. Hope this helps! WPF has a steep learning curve, but once you "get it", UI programming can actually become "fun"! A: WPF in Action with Visual Studio 2008 It is in print now. A: Adam's book is fantastic - http://blogs.msdn.com/adam_nathan/archive/2006/05/17/599301.aspx Also Petzold's is good although a little chewey to get through :-) http://www.charlespetzold.com/wpf/ A: MCTS Self-Paced Training Kit - Microsoft .NET 3.5 Windows Presentation Foundation (70-502) I personally find that I become much more motivated to read and learn about a topic if the learning process culminates with a Microsoft Certification. If you're anything like me, you may find it more rewarding to dive into this certification study guide that just came out a week or two ago. A: A new book just came out by notable WPF expert, Pavan Podila (with a little help from Kevin Hoffman). It's all about building controls in WPF and is aptly called: WPF Control Development Unleashed If you're going to be building visuals, elements, or controls in WPF, you will want this book on your shelf. Getting to the point where you understand enough of the WPF API and concepts to write a decent control, takes enough time ... this book will ease your journey! A: Sams Teach Yourself WPF in 24 Hours. I'm one of the authors, so my opinion is biased. Our book is structured around building four applications. It's not as in-depth as Nathan's or Petzold's books. Its intent is not to be exhaustive (or a reference), rather it is a means to coming up to speed quickly on WPF. Likewise, to provide a foundation so that you won't feel overwhelmed when you encounter some of the various nooks and crannies in the technology. A: I am with KiwiB* awesome book. Although you need to now .net to get some of the examples, as they miss some of the using statements for the code examples. A: I'm currently starting in on "Pro WPF with VB 2008: Windows Presentation Foundation with .NET 3.5 (Paperback)" and so far am pretty happy with it. Good for us VB'ers... :) A: Yes, I highly recommend this one
{ "language": "en", "url": "https://stackoverflow.com/questions/9591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "65" }
Q: Visual Studio 2008 Window layout annoyance I'm having a weird issue with Visual Studio 2008. Every time I fire it up, the solution explorer is about an inch wide. It's like it can't remember it's layout settings. Every un-docked window is in the position I place it. But if I dock a window, it's position is saved, but it's size will be reset to very-narrow (around an inch) when I load. I've never come across this before and it's pretty annoying. Any ideas? The things I've tried: * *Saving, then reloading settings via Import/Export. *Resetting all environment settings via Import/Export. *Window -> Reset Window layout. *Comination of rebooting after changing the above. *Installed SP1. No improvement none of which changed the behaviour of docked windows. (Also, definitely no other instances running..) I do run two monitors, but I've had this setup on three different workstations and this is the first time I've come across it. A: I occasionally get this bug, and others related to layout/fonts/colouring etc. A little trick I've found is use the Tools -> Import and Export Settings, export your current settings once you've got everything setup as you like, then close and reopen Visual Studio and import. Hopefully that'll sort you out. In 2005 there were some little bugs with viewing Project/Solution property panels when the Solution Explorer wasn't in its default position, docked on the left of the screen - I don't know if that's changed in VS2008, but you might want to put it back there and see. Now, when are we going to get decent MultiMonitor support?! A: I had the same problem. It turned out that if the VS window was non-maximized, it was really small. So after making the non-maximized wider, the problem disappeared. A: Maybe you're closing Visual Studio while some other instance is still alive. The settings of the last instance that is closed is the one that will be applied.
{ "language": "en", "url": "https://stackoverflow.com/questions/9601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Setting Group Type for new Active Directory Entry in VB.NET I'm trying to set the group type for a new Active Directory Entry via VB.NET and DirectoryServices to create a distribution list. How do I access the ADS_GROUP_TYPE enumerations? Specifically I'm after ADS_GROUP_TYPE_GLOBAL_GROUP. A: Add a reference to the com ActiveDS Dll and import the namespace using ActiveDS, then you will get the above enum value. A: I don't think I can access the enumerations via .NET so instead I created the specific constant I needed. For what it's worth here's my code: Const ADS_GROUP_TYPE_GLOBAL_GROUP As Object = &H2 adNewGroup.Properties("groupType").Value = ADS_GROUP_TYPE_GLOBAL_GROUP Refactoring welcome! A: You're correct, you can't actually get access to the enumerations. Just a wee nitpick, this constant doesn't need to be an object, you can make it an int32 - Const ADS_GROUP_TYPE_GLOBAL_GROUP As Object = &H2
{ "language": "en", "url": "https://stackoverflow.com/questions/9612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Bidirectional outer join Suppose we have a table A: itemid mark 1 5 2 3 and table B: itemid mark 1 3 3 5 I want to join A*B on A.itemid=B.itemid both right and left ways. i.e. result: itemid A.mark B.mark 1 5 3 2 3 NULL 3 NULL 5 Is there a way to do it in one query in MySQL? A: It's called a full outer join and it's not supported natively in MySQL, judging from its docs. You can work around this limitation using UNION as described in the comments to the page I linked to. [edit] Since others posted snippets, here you go. You can see explanation on the linked page. SELECT * FROM A LEFT JOIN B ON A.id = B.id UNION ALL SELECT * FROM A RIGHT JOIN B ON A.id = B.id WHERE A.id IS NULL A: Could do with some work but here is some sql select distinct T.itemid, A.mark as "A.mark", B.mark as "B.mark" from (select * from A union select * from B) T left join A on T.itemid = A.itemid left join B on T.itemid = B.itemid; This relies on the left join, which returns all the rows in the original table (in this case this is the subselect table T). If there are no matches in the joined table, then it will set the column to NULL. A: This works for me on SQL Server: select isnull(a.id, b.id), a.mark, b.mark from a full outer join b on b.id = a.id
{ "language": "en", "url": "https://stackoverflow.com/questions/9614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Displaying vector graphics in a browser I need to display some interactive (attaching with DOM listeners etc. and event handling) vector graphics in web site I am working on. There is a W3C recommendation for SVG though this format is still not recognized by Internet Explorer support of which is a must (for a public website). IE handles VML though and there are even javascript libraries that do some canvas-like drawing depending on a browser (SVG vs. VML) - excanvas, GFX of Dojo Toolkit and more. That would be nice and acceptable though none of them can display an SVG image from the given markup. So the question actually consists of several parts: * *Are there any cross-browser Javascript libraries that display vector graphics from given markup (not obligatory SVG) and offer availability to attach to DOM events? *If there are not, which of the most pupular browser-embedded technologies would be most suitable for doing such a task? I can choose from Flex/Flash, Java applet. Silverlight is not an option because of Windows lock-in. [EDIT] Thank you all for your comments/suggestions. Below are just some my random notes/conclusions on this matter: * *The level of interactivity I need is ability to detect DOM events on the vector image being displayed - mouseover, mouseout, click etc. - and ability to react on them like changing background color, displaying dialog etc. *The idea of sticking with SVG format is quite well as it is native on many browsers except the most popular one - IE. After some experimenting with displaying dynamic SVG I realized that IE version 7 the most problematic. There's too much hassle because of browser incompatibilities. *Cake seems a great Javascript framework, though I could not get the examples working on IE7. *Java Applets - I liked that idea the most as I though I could use the Apache Batik library, a quality SVG renderer. However, Batik is very big library and I cannot afford deploying an applet that weights few megabytes. *I decided to stick with the Flex option. I found a nice vector graphics library Degrafa. It uses its own markup format however it recognizes SVG path notation, so in my case it is going to be quite easy to transform my SVGs using XSLT or just parsing them. [EDIT 2] Some more comments appeared. I'd like to clarify that by "Windows lock-in" I mean the situation that Silverlight would normally run on Windows, more specifically, IE. I doubt it is an accepted solution (like Flash or Java Applet, for instance) on other systems. Yes, I have no doubt that one is able to launch Silverlight app on any system though I fear it would be too much effort for an average user. @Akira: Have you had any problems with those "SVG renderers" on IE7? I get thrown Javascript errors all the time. A: Safari, Opera and Firefox all support SVG natively (eg. without plugins) to varying degrees of completeness and correctness, including the ability to script the svg from javascript. There's also the canvas element which is now being standardised in html5, and is already supported in the above browsers as well (with various quirks in certain edge cases due to relatively recent changes in the html5 draft). Unfortunately any standards based approach is kind of destroyed by IE's willful disregard of what is happening outside its own ecosystem, however there are a number of libraries that try to convert canvas/svg into VML (IE's proprietary vector language) such as iecanvas. [Edit: whoops, i forgot my favourite js library -- Cake! which can parse and display svg in canvas, and believe supports IE as well] [Yet another edit: Cake actually has a demo doing what i think you want to do] A: Take a look at the Raphael Javascript library. It's early days but it looks very promising. I remember the IE roadmap that had SVG support listed in IE7.2. Depends on how interactive you want it? A: Can you clarify what you mean by the "Windows lock-in" thing with Silverlight? It runs on Windows and MacIntel, and the vector portions run just fine on Linux with the Moonlight plugin. Were you thrown off by the lack of Amiga support? A: Have a look at the new Canvas element which has been implemented in many browsers. I heard also that there is an ActiveX control for IE that implements the Canvas element too. Update: Wait, you already said that. I should read the whole question next time! :) A: Walter Zorn has a JavaScript library for arbitrary vector graphics. It looks decent. A: IE supports VML, but nothing else does and it's ugly. Microsoft claimed that they'd dropped it (with new XAML and all) but it's still part of their Office XML format (it's how Excel .xlsx supports comments, weirdly enough). FX and loads more support the new Canvas element. Many support SVG, but given the work MS are doing on Silverlight I can't see IE supporting SVG any time soon. Microsoft are supposed to be providing Silverlight plug ins for no MS operating systems. I've been using Flex - it's pretty good despite using Eclipse. You don't need to buy the hugely expensive Adobe server components to use Flex - it can consume SOAP services. The dev tools for Flex are quite affordable, and nearly everyone has Flash. A: I don't think SVG is a good choice for the future. From Wikipedia: * *"The most common IE plugin was produced by Adobe. Adobe, however, are planning to withdraw this product at the beginning of 2009" *"... Internet Explorer which will also not support SVG in the upcoming version IE8" *"...all have incomplete support for the SVG 1.1..." *"The Corel SVG Viewer plugin was once offered from Corel. Its development has stopped." A: Of all the possibilities you list, the only one that's not a horrible abuse of an existing technology (Javascript), barely supported (SVG, Canvas element) or a lot of work (Java) is Flash. It was designed as a vector graphics package and is compatible with more browsers than SVG and the canvas tag. The only reason I wouldn't choose Flash over all other options is if you're aiming at mobile browsers or don't have the budget for the Flash package. A: Go for SVG - and just tell the users to get the ADOBE SVG plug in for IE. See this excellent site - which is a UK Government Site (public service) ELGIN
{ "language": "en", "url": "https://stackoverflow.com/questions/9615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Playing wave file ends immediately (C++, Windows) I have got the following situation. On a machine there is a Fritz ISDN card. There is a process that is responsible for playing a certain wave file on this device's wave out (ISDN connection is made at startup and made persistent). The scenario is easy, whenever needed the process calls waveOutWrite() on the previously opened wave device (everything initialized without any problems of course) and a callback function waits for MM_WOM_DONE msg to know that the playback has been finished. Since a few days however (nothing changed neither in the process nor the machine) the MM_WOM_DONE message has been coming immediately after calling waveOutWrite() even though the wave lasts a couple of seconds. Again no error is reported, it looks like the file was played but had zero length (which is not the case). I am also sure that waveOutReset() was not called by my process (it would also trigger sending the mentioned message). I have already used to have some strange problems in the past that where solved simply by reinstalling TAPI drivers. This time for some reason it is problematic for me to perform that once again and I am trying more analytical approach :). Any suggestions what might cause such a behavior? Maybe something on the other end of the ISDN line? A: Based on your description, you are doing the playing asynchonously. Are you sure that the backing memory for the wav file is not being cleaned up in that time? A: I don't have the time to Google too much for this, but I know that either Larry Osterman or Raymond Chen blogged about a similar situation. I'll check back later when I have more time to see if this question is still open. A: What is the return value when the sound does not play? If you get MMSYSERR_NOERROR that points to the driver incorrectly reporting to the OS that the buffer was processed. Has the WAV file itself changed? This blog entry indicates that some pretty in-depth validation is done on the metadata.
{ "language": "en", "url": "https://stackoverflow.com/questions/9629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WPF: How to style or disable the default ContextMenu of a TextBox Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background. I know this works well: <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <TextBox ContextMenu="{x:Null}"/> </Page> But this doesn't work: <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Page.Resources> <Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}"> <Setter Property="ContextMenu" Value="{x:Null}"/> </Style> </Page.Resources> <TextBox/> </Page> Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF? A: Due to a late bug report we discovered that we cannot use the ApplicationComands Cut Paste and Copy directly in a partial trusted application. Therefor, using these commands in any Commmand of your controls will do absolutely nothing when executed. So in essence Brads answer was almost there, it sure looked the right way i.e. no black background, but did not fix the problem. We decided to "remove" the menu based on Brads answer, like so: <ContextMenu x:Key="TextBoxContextMenu" Width="0" Height="0" /> And use this empty context menu like so: <Style TargetType="{x:Type TextBox}"> <Setter Property="ContextMenu" Value="{StaticResource TextBoxContextMenu}" /> </Style> A: To style ContextMenu's for all TextBoxes, I would do something like the following: First, in the resources section, add a ContextMenu which you plan to use as your standard ContextMenu in a textbox. e.g. <ContextMenu x:Key="TextBoxContextMenu" Background="White"> <MenuItem Command="ApplicationCommands.Copy" /> <MenuItem Command="ApplicationCommands.Cut" /> <MenuItem Command="ApplicationCommands.Paste" /> </ContextMenu> Secondly, create a style for your TextBoxes, which uses the context menu resource: <Style TargetType="{x:Type TextBox}"> <Setter Property="ContextMenu" Value="{StaticResource TextBoxContextMenu}" /> </Style> Finally, use your text box as normal: <TextBox /> If instead you want to apply this context menu to only some of your textboxes, do not create the style above, and add the following to your TextBox markup: <TextBox ContextMenu="{StaticResource TextBoxContextMenu}" /> Hope this helps! A: Bizarre. ContextMenu="{x:Null}" doesn't do the trick. This does, however: <TextBox.ContextMenu> <ContextMenu Visibility="Collapsed"> </ContextMenu> </TextBox.ContextMenu> A: Doesn't matter, if you do not provide a key, it will use the TargetType as key just the same way my example uses :) Taken from MSDN on Style: Setting the TargetType property to the TextBlock type without setting an x:Key implicitly sets the x:Key to {x:Type TextBlock}. This also means that if you > > give the above Style an x:Key value of anything other than {x:Type TextBlock}, the Style would not be applied to all TextBlock elements automatically. Instead, you need to apply the style to the TextBlock elements explicitly. http://msdn.microsoft.com/en-us/library/system.windows.style.targettype.aspx A: This is way is what I always use: <TextBox x:Name="MyTextbox"> <TextBox.ContextMenu> <ContextMenu Visibility="Hidden"/> </TextBox.ContextMenu> </TextBox> And also can use: MyTextbox.ContextMenu.Visibility = Visibility.Hidden; MyTextbox.ContextMenu.Visibility = Visibility.Visble; A: Try removing the x:Key attribute from the Style resource, leaving TargetType. I know, you're supposed to have that x:Key for a resource, but if you have it along with your TargetType the Key prevails. Here's a sample style that I use in a project to skin all tooltips in one of my apps (this is in App.Resources--notice, no Key) <Style TargetType="{x:Type ToolTip}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ToolTip}"> <Grid Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"> <Rectangle RadiusX="9" RadiusY="9" Stroke="LightGray" StrokeThickness="2"> <Rectangle.Fill> <RadialGradientBrush> <GradientStop /> <GradientStop Color="FloralWhite" Offset="0" /> <GradientStop Color="Cornsilk" Offset="2" /> </RadialGradientBrush> </Rectangle.Fill> </Rectangle> <ContentPresenter Margin="6 4 6 4" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
{ "language": "en", "url": "https://stackoverflow.com/questions/9632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Lisp/Scheme interpreter without Emacs? I've been wanting to teach myself Lisp for a while. However, all the interpreters of which I've heard involve some flavor of emacs. Are there any command line interpreters, such that I could type this into the command line: lispinterpret sourcefile.lisp just like I can run perl or python. While I'd also like to become more familiar with Emacs (if only not to be frustrated when I work with somebody who uses Emacs), I'd rather decouple learning Emacs from learning Lisp. Edit: I actually want to follow SICP which uses Scheme, so an answer about Scheme would be more useful. I'm just not that familiar with the differences. A: It looks like Steel Bank Common Lisp (SBCL) also caters to what you want: http://www.sbcl.org/manual/#Shebang-Scripts SBCL is both top rate and open source. A: Checkout CLISP wiki-link that ie. was used by Paul Graham Direct link A: I often write lisp shell scripts which start with this line: #!/usr/bin/clisp Then you don't even need to type "lispinterpret" on the command-line. Just mark the script executable and run it directly. A: Most scheme interpreters that I am familiar with can be run from the command line. (Much of the list below is extracted from the comparative table at Alexey Radul's Scheme Implementation Choices page. There is a more extensive list at schemewiki but that page does not immediately provide command-line invocation syntax.) Here's how you run a number of implementations at the command line: * *Chez Scheme: scheme, petite *MIT Scheme: mit-scheme *Scheme 48: scheme48 *RScheme: rs *Racket: racket (But I recommend trying the DrRacket IDE, especially for beginners.) *Guile: guile *Bigloo: bigloo *Chicken: csi *Gambit: gsi *Gauche: gosh *IronScheme: IronScheme.Console *Kawa: kawa, java kawa.repl *Larceny: larceny *SCM: scm A: If you are looking for Scheme to work with the SICP, take a look at MIT/GNU Scheme http://groups.csail.mit.edu/mac/projects/scheme/ http://www.gnu.org/software/mit-scheme/index.html A: The most widely used IDE for Common Lisp, particularly in the free software subset of the community, is in fact SLIME, which runs on Emacs. You can use whatever CL compiler you prefer and invoke Lisp source files the way you describe, but if you do that, you won't be taking advantage of many of Lisps dynamic features that are so incredibly useful while developing your application. I suggest you take a look at this SLIME demonstration video to see what I mean, even though it might be a bit outdated at this point. If the problem is that you (think you) don't like Emacs, I seriously suggest you try to learn it. Seriously. No, really, I mean that. However, there are alternatives, such as the IDEs provided by commercial Lisp implementations such as Allegro and Lispworks (free trials available), or an Eclipse plug-in called Cusp. A: You could also try DrScheme, which whilst not exactly a standalone interpreter, isn't emacs :) It's basically a simple IDE that has an area to type in code that can be executed as a file, and then another area that is the running interpreter that you can interact with. (Also, find the UC Berkeley CS61A podcasts and listen to them, as well as reading SICP) A: Did you try Allegro CL from http://www.franz.com/? A: @Nathan: I've upmodded the Common Lisp links, because you asked about Lisp (especially with reference to Emacs Lisp). However, Common Lisp is very different from Scheme. A program written for one is unlikely to run on the other. As you mentioned, SICP is for learning Scheme, not Lisp (or at least, not Common Lisp and not Emacs Lisp). There are some overlap in principles, however you can't simply cut and paste code from SICP and expect it to run on any Common Lisp or Emacs Lisp system. :-) A: No "interpreter" requires emacs. Also, emacs can run elisp in a headless manner. A: It seems like scheme shell is suitable for your purpose. Take a look at http://www.scsh.net/index.html A: Another good dialect of lisp is cmucl. They used to love to brag about being the "fastest" lisp.
{ "language": "en", "url": "https://stackoverflow.com/questions/9650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Is accessing a variable in C# an atomic operation? I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write. However, I was looking through System.Web.Security.Membership using Reflector and found code like this: public static class Membership { private static bool s_Initialized = false; private static object s_lock = new object(); private static MembershipProvider s_Provider; public static MembershipProvider Provider { get { Initialize(); return s_Provider; } } private static void Initialize() { if (s_Initialized) return; lock(s_lock) { if (s_Initialized) return; // Perform initialization... s_Initialized = true; } } } Why is the s_Initialized field read outside of the lock? Couldn't another thread be trying to write to it at the same time? Are reads and writes of variables atomic? A: The correct answer seems to be, "Yes, mostly." * *John's answer referencing the CLI spec indicates that accesses to variables not larger than 32 bits on a 32-bit processor are atomic. *Further confirmation from the C# spec, section 5.5, Atomicity of variable references: Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic. *The code in my example was paraphrased from the Membership class, as written by the ASP.NET team themselves, so it was always safe to assume that the way it accesses the s_Initialized field is correct. Now we know why. Edit: As Thomas Danecker points out, even though the access of the field is atomic, s_Initialized should really be marked volatile to make sure that the locking isn't broken by the processor reordering the reads and writes. A: For the definitive answer go to the spec. :) Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size." So that confirms that s_Initialized will never be unstable, and that read and writes to primitve types smaller than 32 bits are atomic. In particular, double and long (Int64 and UInt64) are not guaranteed to be atomic on a 32-bit platform. You can use the methods on the Interlocked class to protect these. Additionally, while reads and writes are atomic, there is a race condition with addition, subtraction, and incrementing and decrementing primitive types, since they must be read, operated on, and rewritten. The interlocked class allows you to protect these using the CompareExchange and Increment methods. Interlocking creates a memory barrier to prevent the processor from reordering reads and writes. The lock creates the only required barrier in this example. A: This is a (bad) form of the double check locking pattern which is not thread safe in C#! There is one big problem in this code: s_Initialized is not volatile. That means that writes in the initialization code can move after s_Initialized is set to true and other threads can see uninitialized code even if s_Initialized is true for them. This doesn't apply to Microsoft's implementation of the Framework because every write is a volatile write. But also in Microsoft's implementation, reads of the uninitialized data can be reordered (i.e. prefetched by the cpu), so if s_Initialized is true, reading the data that should be initialized can result in reading old, uninitialized data because of cache-hits (ie. the reads are reordered). For example: Thread 1 reads s_Provider (which is null) Thread 2 initializes the data Thread 2 sets s\_Initialized to true Thread 1 reads s\_Initialized (which is true now) Thread 1 uses the previously read Provider and gets a NullReferenceException Moving the read of s_Provider before the read of s_Initialized is perfectly legal because there is no volatile read anywhere. If s_Initialized would be volatile, the read of s_Provider would not be allowed to move before the read of s_Initialized and also the initialization of the Provider is not allowed to move after s_Initialized is set to true and everything is ok now. Joe Duffy also wrote an Article about this problem: Broken variants on double-checked locking A: The Initialize function is faulty. It should look more like this: private static void Initialize() { if(s_initialized) return; lock(s_lock) { if(s_Initialized) return; s_Initialized = true; } } Without the second check inside the lock it's possible the initialisation code will be executed twice. So the first check is for performance to save you taking a lock unnecessarily, and the second check is for the case where a thread is executing the initialisation code but hasn't yet set the s_Initialized flag and so a second thread would pass the first check and be waiting at the lock. A: Hang about -- the question that is in the title is definitely not the real question that Rory is asking. The titular question has the simple answer of "No" -- but this is no help at all, when you see the real question -- which i don't think anyone has given a simple answer to. The real question Rory asks is presented much later and is more pertinent to the example he gives. Why is the s_Initialized field read outside of the lock? The answer to this is also simple, though completely unrelated to the atomicity of variable access. The s_Initialized field is read outside of the lock because locks are expensive. Since the s_Initialized field is essentially "write once" it will never return a false positive. It's economical to read it outside the lock. This is a low cost activity with a high chance of having a benefit. That's why it's read outside of the lock -- to avoid paying the cost of using a lock unless it's indicated. If locks were cheap the code would be simpler, and omit that first check. (edit: nice response from rory follows. Yeh, boolean reads are very much atomic. If someone built a processor with non-atomic boolean reads, they'd be featured on the DailyWTF.) A: I think you're asking if s_Initialized could be in an unstable state when read outside the lock. The short answer is no. A simple assignment/read will boil down to a single assembly instruction which is atomic on every processor I can think of. I'm not sure what the case is for assignment to 64 bit variables, it depends on the processor, I would assume that it is not atomic but it probably is on modern 32 bit processors and certainly on all 64 bit processors. Assignment of complex value types will not be atomic. A: Reads and writes of variables are not atomic. You need to use Synchronisation APIs to emulate atomic reads/writes. For an awesome reference on this and many more issues to do with concurrency, make sure you grab a copy of Joe Duffy's latest spectacle. It's a ripper! A: "Is accessing a variable in C# an atomic operation?" Nope. And it's not a C# thing, nor is it even a .net thing, it's a processor thing. OJ is spot on that Joe Duffy is the guy to go to for this kind of info. ANd "interlocked" is a great search term to use if you're wanting to know more. "Torn reads" can occur on any value whose fields add up to more than the size of a pointer. A: You could also decorate s_Initialized with the volatile keyword and forego the use of lock entirely. That is not correct. You will still encounter the problem of a second thread passing the check before the first thread has had a chance to to set the flag which will result in multiple executions of the initialisation code. A: An If (itisso) { check on a boolean is atomic, but even if it was not there is no need to lock the first check. If any thread has completed the Initialization then it will be true. It does not matter if several threads are checking at once. They will all get the same answer, and, there will be no conflict. The second check inside the lock is necessary because another thread may have grabbed the lock first and completed the initialization process already. A: I thought they were - I'm not sure of the point of the lock in your example unless you're also doing something to s_Provider at the same time - then the lock would ensure that these calls happened together. Does that //Perform initialization comment cover creating s_Provider? For instance private static void Initialize() { if (s_Initialized) return; lock(s_lock) { s_Provider = new MembershipProvider ( ... ) s_Initialized = true; } } Otherwise that static property-get's just going to return null anyway. A: What you're asking is whether accessing a field in a method multiple times atomic -- to which the answer is no. In the example above, the initialise routine is faulty as it may result in multiple initialization. You would need to check the s_Initialized flag inside the lock as well as outside, to prevent a race condition in which multiple threads read the s_Initialized flag before any of them actually does the initialisation code. E.g., private static void Initialize() { if (s_Initialized) return; lock(s_lock) { if (s_Initialized) return; s_Provider = new MembershipProvider ( ... ) s_Initialized = true; } } A: Perhaps Interlocked gives a clue. And otherwise this one i pretty good. I would have guessed that their not atomic. A: To make your code always work on weakly ordered architectures, you must put a MemoryBarrier before you write s_Initialized. s_Provider = new MemershipProvider; // MUST PUT BARRIER HERE to make sure the memory writes from the assignment // and the constructor have been wriitten to memory // BEFORE the write to s_Initialized! Thread.MemoryBarrier(); // Now that we've guaranteed that the writes above // will be globally first, set the flag s_Initialized = true; The memory writes that happen in the MembershipProvider constructor and the write to s_Provider are not guaranteed to happen before you write to s_Initialized on a weakly ordered processor. A lot of thought in this thread is about whether something is atomic or not. That is not the issue. The issue is the order that your thread's writes are visible to other threads. On weakly ordered architectures, writes to memory do not occur in order and THAT is the real issue, not whether a variable fits within the data bus. EDIT: Actually, I'm mixing platforms in my statements. In C# the CLR spec requires that writes are globally visible, in-order (by using expensive store instructions for every store if necessary). Therefore, you don't need to actually have that memory barrier there. However, if it were C or C++ where no such guarantee of global visibility order exists, and your target platform may have weakly ordered memory, and it is multithreaded, then you would need to ensure that the constructors writes are globally visible before you update s_Initialized, which is tested outside the lock. A: Ack, nevermind... as pointed out, this is indeed incorrect. It doesn't prevent a second thread from entering the "initialize" code section. Bah. You could also decorate s_Initialized with the volatile keyword and forego the use of lock entirely.
{ "language": "en", "url": "https://stackoverflow.com/questions/9666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "66" }
Q: Validating a Win32 Window Handle Given a handle of type HWND is it possible to confirm that the handle represents a real window? A: Generally no. By the time you've got confirmation that a Window is valid another process/thread my come along and remove it for you. A: There is a function IsWindow which does exactly what you asked for. BOOL isRealHandle = IsWindow(unknwodnHandle); Look at this link for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/9667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do I remove duplicates from a C# array? I have been working with a string[] array in C# that gets returned from a function call. I could possibly cast to a Generic collection, but I was wondering if there was a better way to do it, possibly by using a temp array. What is the best way to remove duplicates from a C# array? A: This might depend on how much you want to engineer the solution - if the array is never going to be that big and you don't care about sorting the list you might want to try something similar to the following: public string[] RemoveDuplicates(string[] myList) { System.Collections.ArrayList newList = new System.Collections.ArrayList(); foreach (string str in myList) if (!newList.Contains(str)) newList.Add(str); return (string[])newList.ToArray(typeof(string)); } A: List<String> myStringList = new List<string>(); foreach (string s in myStringArray) { if (!myStringList.Contains(s)) { myStringList.Add(s); } } This is O(n^2), which won't matter for a short list which is going to be stuffed into a combo, but could be rapidly be a problem on a big collection. A: Here is a O(n*n) approach that uses O(1) space. void removeDuplicates(char* strIn) { int numDups = 0, prevIndex = 0; if(NULL != strIn && *strIn != '\0') { int len = strlen(strIn); for(int i = 0; i < len; i++) { bool foundDup = false; for(int j = 0; j < i; j++) { if(strIn[j] == strIn[i]) { foundDup = true; numDups++; break; } } if(foundDup == false) { strIn[prevIndex] = strIn[i]; prevIndex++; } } strIn[len-numDups] = '\0'; } } The hash/linq approaches above are what you would generally use in real life. However in interviews they usually want to put some constraints e.g. constant space which rules out hash or no internal api - which rules out using LINQ. A: -- This is Interview Question asked every time. Now i done its coding. static void Main(string[] args) { int[] array = new int[] { 4, 8, 4, 1, 1, 4, 8 }; int numDups = 0, prevIndex = 0; for (int i = 0; i < array.Length; i++) { bool foundDup = false; for (int j = 0; j < i; j++) { if (array[i] == array[j]) { foundDup = true; numDups++; // Increment means Count for Duplicate found in array. break; } } if (foundDup == false) { array[prevIndex] = array[i]; prevIndex++; } } // Just Duplicate records replce by zero. for (int k = 1; k <= numDups; k++) { array[array.Length - k] = '\0'; } Console.WriteLine("Console program for Remove duplicates from array."); Console.Read(); } A: protected void Page_Load(object sender, EventArgs e) { string a = "a;b;c;d;e;v"; string[] b = a.Split(';'); string[] c = b.Distinct().ToArray(); if (b.Length != c.Length) { for (int i = 0; i < b.Length; i++) { try { if (b[i].ToString() != c[i].ToString()) { Response.Write("Found duplicate " + b[i].ToString()); return; } } catch (Exception ex) { Response.Write("Found duplicate " + b[i].ToString()); return; } } } else { Response.Write("No duplicate "); } } A: Here is the HashSet<string> approach: public static string[] RemoveDuplicates(string[] s) { HashSet<string> set = new HashSet<string>(s); string[] result = new string[set.Count]; set.CopyTo(result); return result; } Unfortunately this solution also requires .NET framework 3.5 or later as HashSet was not added until that version. You could also use array.Distinct(), which is a feature of LINQ. A: Add all the strings to a dictionary and get the Keys property afterwards. This will produce each unique string, but not necessarily in the same order your original input had them in. If you require the end result to have the same order as the original input, when you consider the first occurance of each string, use the following algorithm instead: * *Have a list (final output) and a dictionary (to check for duplicates) *For each string in the input, check if it exists in the dictionary already *If not, add it both to the dictionary and to the list At the end, the list contains the first occurance of each unique string. Make sure you consider things like culture and such when constructing your dictionary, to make sure you handle duplicates with accented letters correctly. A: The following piece of code attempts to remove duplicates from an ArrayList though this is not an optimal solution. I was asked this question during an interview to remove duplicates through recursion, and without using a second/temp arraylist: private void RemoveDuplicate() { ArrayList dataArray = new ArrayList(5); dataArray.Add("1"); dataArray.Add("1"); dataArray.Add("6"); dataArray.Add("6"); dataArray.Add("6"); dataArray.Add("3"); dataArray.Add("6"); dataArray.Add("4"); dataArray.Add("5"); dataArray.Add("4"); dataArray.Add("1"); dataArray.Sort(); GetDistinctArrayList(dataArray, 0); } private void GetDistinctArrayList(ArrayList arr, int idx) { int count = 0; if (idx >= arr.Count) return; string val = arr[idx].ToString(); foreach (String s in arr) { if (s.Equals(arr[idx])) { count++; } } if (count > 1) { arr.Remove(val); GetDistinctArrayList(arr, idx); } else { idx += 1; GetDistinctArrayList(arr, idx); } } A: Maybe hashset which do not store duplicate elements and silently ignore requests to add duplicates. static void Main() { string textWithDuplicates = "aaabbcccggg"; Console.WriteLine(textWithDuplicates.Count()); var letters = new HashSet<char>(textWithDuplicates); Console.WriteLine(letters.Count()); foreach (char c in letters) Console.Write(c); Console.WriteLine(""); int[] array = new int[] { 12, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 }; Console.WriteLine(array.Count()); var distinctArray = new HashSet<int>(array); Console.WriteLine(distinctArray.Count()); foreach (int i in distinctArray) Console.Write(i + ","); } A: Simple solution: using System.Linq; ... public static int[] Distinct(int[] handles) { return handles.ToList().Distinct().ToArray(); } A: You could possibly use a LINQ query to do this: int[] s = { 1, 2, 3, 3, 4}; int[] q = s.Distinct().ToArray(); A: NOTE : NOT tested! string[] test(string[] myStringArray) { List<String> myStringList = new List<string>(); foreach (string s in myStringArray) { if (!myStringList.Contains(s)) { myStringList.Add(s); } } return myStringList.ToString(); } Might do what you need... EDIT Argh!!! beaten to it by rob by under a minute! A: Tested the below & it works. What's cool is that it does a culture sensitive search too class RemoveDuplicatesInString { public static String RemoveDups(String origString) { String outString = null; int readIndex = 0; CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo; if(String.IsNullOrEmpty(origString)) { return outString; } foreach (var ch in origString) { if (readIndex == 0) { outString = String.Concat(ch); readIndex++; continue; } if (ci.IndexOf(origString, ch.ToString().ToLower(), 0, readIndex) == -1) { //Unique char as this char wasn't found earlier. outString = String.Concat(outString, ch); } readIndex++; } return outString; } static void Main(string[] args) { String inputString = "aAbcefc"; String outputString; outputString = RemoveDups(inputString); Console.WriteLine(outputString); } } --AptSenSDET A: This code 100% remove duplicate values from an array[as I used a[i]].....You can convert it in any OO language..... :) for(int i=0;i<size;i++) { for(int j=i+1;j<size;j++) { if(a[i] == a[j]) { for(int k=j;k<size;k++) { a[k]=a[k+1]; } j--; size--; } } } A: Generic Extension method : public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) { if (source == null) throw new ArgumentNullException(nameof(source)); HashSet<TSource> set = new HashSet<TSource>(comparer); foreach (TSource item in source) { if (set.Add(item)) { yield return item; } } } A: The following tested and working code will remove duplicates from an array. You must include the System.Collections namespace. string[] sArray = {"a", "b", "b", "c", "c", "d", "e", "f", "f"}; var sList = new ArrayList(); for (int i = 0; i < sArray.Length; i++) { if (sList.Contains(sArray[i]) == false) { sList.Add(sArray[i]); } } var sNew = sList.ToArray(); for (int i = 0; i < sNew.Length; i++) { Console.Write(sNew[i]); } You could wrap this up into a function if you wanted to. A: If you needed to sort it, then you could implement a sort that also removes duplicates. Kills two birds with one stone, then. A: you can using This code when work with an ArrayList ArrayList arrayList; //Add some Members :) arrayList.Add("ali"); arrayList.Add("hadi"); arrayList.Add("ali"); //Remove duplicates from array for (int i = 0; i < arrayList.Count; i++) { for (int j = i + 1; j < arrayList.Count ; j++) if (arrayList[i].ToString() == arrayList[j].ToString()) arrayList.Remove(arrayList[j]); A: public static int RemoveDuplicates(ref int[] array) { int size = array.Length; // if 0 or 1, return 0 or 1: if (size < 2) { return size; } int current = 0; for (int candidate = 1; candidate < size; ++candidate) { if (array[current] != array[candidate]) { array[++current] = array[candidate]; } } // index to count conversion: return ++current; } A: Below is an simple logic in java you traverse elements of array twice and if you see any same element you assign zero to it plus you don't touch the index of element you are comparing. import java.util.*; class removeDuplicate{ int [] y ; public removeDuplicate(int[] array){ y=array; for(int b=0;b<y.length;b++){ int temp = y[b]; for(int v=0;v<y.length;v++){ if( b!=v && temp==y[v]){ y[v]=0; } } } } A: The best way? Hard to say, the HashSet approach looks fast, but (depending on the data) using a sort algorithm (CountSort ?) can be much faster. using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { Random r = new Random(0); int[] a, b = new int[1000000]; for (int i = b.Length - 1; i >= 0; i--) b[i] = r.Next(b.Length); a = new int[b.Length]; Array.Copy(b, a, b.Length); a = dedup0(a); Console.WriteLine(a.Length); a = new int[b.Length]; Array.Copy(b, a, b.Length); var w = System.Diagnostics.Stopwatch.StartNew(); a = dedup0(a); Console.WriteLine(w.Elapsed); Console.Read(); } static int[] dedup0(int[] a) // 48 ms { return new HashSet<int>(a).ToArray(); } static int[] dedup1(int[] a) // 68 ms { Array.Sort(a); int i = 0, j = 1, k = a.Length; if (k < 2) return a; while (j < k) if (a[i] == a[j]) j++; else a[++i] = a[j++]; Array.Resize(ref a, i + 1); return a; } static int[] dedup2(int[] a) // 8 ms { var b = new byte[a.Length]; int c = 0; for (int i = 0; i < a.Length; i++) if (b[a[i]] == 0) { b[a[i]] = 1; c++; } a = new int[c]; for (int j = 0, i = 0; i < b.Length; i++) if (b[i] > 0) a[j++] = i; return a; } } Almost branch free. How? Debug mode, Step Into (F11) with a small array: {1,3,1,1,0} static int[] dedupf(int[] a) // 4 ms { if (a.Length < 2) return a; var b = new byte[a.Length]; int c = 0, bi, ai, i, j; for (i = 0; i < a.Length; i++) { ai = a[i]; bi = 1 ^ b[ai]; b[ai] |= (byte)bi; c += bi; } a = new int[c]; i = 0; while (b[i] == 0) i++; a[0] = i++; for (j = 0; i < b.Length; i++) a[j += bi = b[i]] += bi * i; return a; } A solution with two nested loops might take some time, especially for larger arrays. static int[] dedup(int[] a) { int i, j, k = a.Length - 1; for (i = 0; i < k; i++) for (j = i + 1; j <= k; j++) if (a[i] == a[j]) a[j--] = a[k--]; Array.Resize(ref a, k + 1); return a; } A: private static string[] distinct(string[] inputArray) { bool alreadyExists; string[] outputArray = new string[] {}; for (int i = 0; i < inputArray.Length; i++) { alreadyExists = false; for (int j = 0; j < outputArray.Length; j++) { if (inputArray[i] == outputArray[j]) alreadyExists = true; } if (alreadyExists==false) { Array.Resize<string>(ref outputArray, outputArray.Length + 1); outputArray[outputArray.Length-1] = inputArray[i]; } } return outputArray; } A: int size = a.Length; for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { if (a[i] == a[j]) { for (int k = j; k < size; k++) { if (k != size - 1) { int temp = a[k]; a[k] = a[k + 1]; a[k + 1] = temp; } } j--; size--; } } } A: So I was doing an interview session and got the same question to sort and distinct static void Sort() { try { int[] number = new int[Convert.ToInt32(Console.ReadLine())]; for (int i = 0; i < number.Length; i++) { number[i] = Convert.ToInt32(Console.ReadLine()); } Array.Sort(number); int[] num = number.Distinct().ToArray(); for (int i = 0; i < num.Length; i++) { Console.WriteLine(num[i]); } } catch (Exception ex) { Console.WriteLine(ex); } Console.Read(); } A: using System; using System.Collections.Generic; using System.Linq; namespace Rextester { public class Program { public static void Main(string[] args) { List<int> listofint1 = new List<int> { 4, 8, 4, 1, 1, 4, 8 }; List<int> updatedlist= removeduplicate(listofint1); foreach(int num in updatedlist) Console.WriteLine(num); } public static List<int> removeduplicate(List<int> listofint) { List<int> listofintwithoutduplicate= new List<int>(); foreach(var num in listofint) { if(!listofintwithoutduplicate.Any(p=>p==num)) { listofintwithoutduplicate.Add(num); } } return listofintwithoutduplicate; } } } A: strINvalues = "1,1,2,2,3,3,4,4"; strINvalues = string.Join(",", strINvalues .Split(',').Distinct().ToArray()); Debug.Writeline(strINvalues); Kkk Not sure if this is witchcraft or just beautiful code 1 strINvalues .Split(',').Distinct().ToArray() 2 string.Join(",", XXX); 1 Splitting the array and using Distinct [LINQ] to remove duplicates 2 Joining it back without the duplicates. Sorry I never read the text on StackOverFlow just the code. it make more sense than the text ;) A: Removing duplicate and ignore case sensitive using Distinct & StringComparer.InvariantCultureIgnoreCase string[] array = new string[] { "A", "a", "b", "B", "a", "C", "c", "C", "A", "1" }; var r = array.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList(); Console.WriteLine(r.Count); // return 4 items A: Find answer below. class Program { static void Main(string[] args) { var nums = new int[] { 1, 4, 3, 3, 3, 5, 5, 7, 7, 7, 7, 9, 9, 9 }; var result = removeDuplicates(nums); foreach (var item in result) { Console.WriteLine(item); } } static int[] removeDuplicates(int[] nums) { nums = nums.ToList().OrderBy(c => c).ToArray(); int j = 1; int i = 0; int stop = 0; while (j < nums.Length) { if (nums[i] != nums[j]) { nums[i + 1] = nums[j]; stop = i + 2; i++; } j++; } nums = nums.Take(stop).ToArray(); return nums; } } Just a bit of contribution based on a test i just solved, maybe helpful and open to improvement by other top contributors here. Here are the things i did: * *I used OrderBy which allows me order or sort the items from smallest to the highest using LINQ *I then convert it to back to an array and then re-assign it back to the primary datasource *So i then initialize j which is my right hand side of the array to be 1 and i which is my left hand side of the array to be 0, i also initialize where i would i to stop to be 0. *I used a while loop to increment through the array by going from one position to the other left to right, for each increment the stop position is the current value of i + 2 which i will use later to truncate the duplicates from the array. *I then increment by moving from left to right from the if statement and from right to right outside of the if statement until i iterate through the entire values of the array. *I then pick from the first element to the stop position which becomes the last i index plus 2. that way i am able to remove all the duplicate items from the int array. which is then reassigned.
{ "language": "en", "url": "https://stackoverflow.com/questions/9673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "242" }
Q: Document Server: Handling Concurrent Saves I'm implementing a document server. Currently, if two users open the same document, then modify it and save the changes, the document's state will be undefined (either the first user's changes are saved permanently, or the second's). This is entirely unsatisfactory. I considered two possibilities to solve this problem: The first is to lock the document when it is opened by someone the first time, and unlock it when it is closed. But if the network connection to the server is suddenly interrupted, the document would stay in a forever-locked state. The obvious solution is to send regular pings to the server. If the server doesn't receive K pings in a row (K > 1) from a particular client, documents locked by this client are unlocked. If that client re-appears, documents are locked again, if someone hadn't already locked them. This could also help if the client application (running in web browser) is terminated unexpectedly, making it impossible to send a 'quitting, unlock my documents' signal to the server. The second is to store multiple versions of the same document saved by different users. If changes to the document are made in rapid succession, the system would offer either to merge versions or to select a preferred version. To optimize storage space, only document diffs should be kept (just like source control software). What method should I choose, taking into consideration that the connection to the server might sometimes be slow and unresponsive? How should the parameters (ping interval, rapid succession interval) be determined? P.S. Unfortunately, I can't store the documents in a database. A: The first option you describe is essentially a pessimistic locking model whilst the second is an optimistic model. Which one to choose really comes down to a number of factors but essentially boils down to how the business wants to work. For example, would it unduly inconvenience the users if a document they needed to edit was locked by another user? What happens if a document is locked and someone goes on holiday with their client connected? What is the likely contention for each document - i.e. how likely is it that the same document will be modified by two users at the same time?, how localised are the modifications likely to be within a single document? (If the same section is modified regularly then performing a merge may take longer than simply making the changes again). Assuming the contention is relatively low and/or the size of each change is fairly small then I would probably opt for an optimistic model that resolves conflicts using an automatic or manual merge. A version number or a checksum of the document's contents can be used to determine if a merge is required. A: My suggestion would be something like your first one. When the first user (Bob) opens the document, he acquires a lock so that other users can only read the current document. If the user saves the document while he is using it, he keeps the lock. Only when he exits the document, it is unlocked and other people can edit it. If the second user (Kate) opens the document while Bob has the lock on it, Kate will get a message saying the document is uneditable but she can read it until it the lock has been released. So what happens when Bob acquires the lock, maybe saves the document once or twice but then exits the application leaving the lock hanging? As you said yourself, requiring the client with the lock to send pings at a certain frequency is probably the best option. If you don't get a ping from the client for a set amount of time, this effectively means his client is not responding anymore. If this is a web application you can use javascript for the pings. The document that was last saved releases its lock and Kate can now acquire it. A ping can contain the name of the document that the client has a lock on, and the server can calculate when the last ping for that document was received. A: Currently documents are published by a limited group of people, each of them working on a separate subject. So, the inconvenience introduced by locks is minimized. People mostly extend existing documents and correct mistakes in them. Speaking about the pessimistic model, the 'left client connected for N days' scenario could be avoided by setting lock expire date to, say, one day before lock start date. Because documents edited are by no means mission critical, and are modified by multiple users quite rarely, that could be enough. Now consider the optimistic model. How should the differences be detected, if the documents have some regular (say, hierarchical) structure? If not? What are the chances of successful automatic merge in these cases? The situation becomes more complicated, because some of the documents (edited by the 'admins' user group) contain important configuration information (document global index, user roles, etc.). To my mind, locks are more advantageous for precisely this kind of information, because it's not changed on everyday basis. So some hybrid solution might be acceptable. What do you think?
{ "language": "en", "url": "https://stackoverflow.com/questions/9675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Need Pattern for dynamic search of multiple sql tables I'm looking for a pattern for performing a dynamic search on multiple tables. I have no control over the legacy (and poorly designed) database table structure. Consider a scenario similar to a resume search where a user may want to perform a search against any of the data in the resume and get back a list of resumes that match their search criteria. Any field can be searched at anytime and in combination with one or more other fields. The actual sql query gets created dynamically depending on which fields are searched. Most solutions I've found involve complicated if blocks, but I can't help but think there must be a more elegant solution since this must be a solved problem by now. Yeah, so I've started down the path of dynamically building the sql in code. Seems godawful. If I really try to support the requested ability to query any combination of any field in any table this is going to be one MASSIVE set of if statements. shiver I believe I read that COALESCE only works if your data does not contain NULLs. Is that correct? If so, no go, since I have NULL values all over the place. A: As far as I understand (and I'm also someone who has written against a horrible legacy database), there is no such thing as dynamic WHERE clauses. It has NOT been solved. Personally, I prefer to generate my dynamic searches in code. Makes testing convenient. Note, when you create your sql queries in code, don't concatenate in user input. Use your @variables! The only alternative is to use the COALESCE operator. Let's say you have the following table: Users ----------- Name nvarchar(20) Nickname nvarchar(10) and you want to search optionally for name or nickname. The following query will do this: SELECT Name, Nickname FROM Users WHERE Name = COALESCE(@name, Name) AND Nickname = COALESCE(@nick, Nickname) If you don't want to search for something, just pass in a null. For example, passing in "brian" for @name and null for @nick results in the following query being evaluated: SELECT Name, Nickname FROM Users WHERE Name = 'brian' AND Nickname = Nickname The coalesce operator turns the null into an identity evaluation, which is always true and doesn't affect the where clause. A: Search and normalization can be at odds with each other. So probably first thing would be to get some kind of "view" that shows all the fields that can be searched as a single row with a single key getting you the resume. then you can throw something like Lucene in front of that to give you a full text index of those rows, the way that works is, you ask it for "x" in this view and it returns to you the key. Its a great solution and come recommended by joel himself on the podcast within the first 2 months IIRC. A: What you need is something like SphinxSearch (for MySQL) or Apache Lucene. As you said in your example lets imagine a Resume that will composed of several fields: * *List item *Name, *Adreess, *Education (this could be a table on its own) or *Work experience (this could grow to its own table where each row represents a previous job) So searching for a word in all those fields with WHERE rapidly becomes a very long query with several JOINS. Instead you could change your framework of reference and think of the Whole resume as what it is a Single Document and you just want to search said document. This is where tools like Sphinx Search do. They create a FULL TEXT index of your 'document' and then you can query sphinx and it will give you back where in the Database that record was found. Really good search results. Don't worry about this tools not being part of your RDBMS it will save you a lot of headaches to use the appropriate model "Documents" vs the incorrect one "TABLES" for this application.
{ "language": "en", "url": "https://stackoverflow.com/questions/9687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Visual Studio 2005 Macros stop working when Visual Studio 2008 is installed I have a number of macros written for Visual Studio 2005, but they have since stopped working once I installed Visual Studio 2008 on my computer. No error is returned by the macro when I try and run it, and the environment merely shows the hourglass for a second and then returns to the normal cursor. Currently uninstalling one or the other is not possible, and I am wondering if there is anyway to get the macros to work again? A: You may need to install (reinstall) VS 2005 SP1, since a security update from Microsoft (KB928365) on July 10 may have caused the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/9693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Default database IDs; system and user values As part of our current database work, we are looking at a dealing with the process of updating databases. A point which has been brought up recurrently, is that of dealing with system vs. user values; in our project user and system vals are stored together. For example... We have a list of templates. 1, <system template> 2, <system template> 3, <system template> These are mapped in the app to an enum (1, 2, 3) Then a user comes in and adds... 4, <user template> ...and... 5, <user template> Then.. we issue an upgrade.. and insert as part of our upgrade scripts... <new id> [6], <new system template> THEN!!... we find a bug in the new system template and need to update it... The problem is how? We cannot update record using ID6 (as we may have inserted it as 9, or 999, so we have to identify the record using some other mechanism) So, we've come to two possible solutions for this. In the red corner (speed).... We simply start user Ids at 5000 (or some other value) and test data at 10000 (or some other value). This would allow us to make modifications to system values and test them up to the lower limit of the next ID range. Advantage...Quick and easy to implement, Disadvantage... could run out of values if we don't choose a big enough range! In the blue corner (scalability)... We store, system and user data separately, use GUIDs as Ids and merge the two lists using a view. Advantage...Scalable..No limits w/regard to DB size. Disadvantage.. More complicated to implement. (many to one updatable views etc.) I plump squarely for the first option, but looking for some ammo to back me up! Does anyone have any thoughts on these approaches, or even one(s) that we've missed? A: I recommend using the second with the modification that you store the system and user values in one table. GUID is quite reliable in this manner. Another idea: use any text-based ID (not necessary GUID), which you give for the system values and is generated by a random string or a string based on some kind of custom logic for the user values. Another idea: use the first approach, but extend the table with a flag which shows if a value is system or user. Maybe this is the easiest. Ok, you have to write some kind of mechanism to update the correct system value, but it can be done easily. A: +1 for Biri's text based ID - define a "template_mnemonic" text based column and make it the primary key. This will be a known value when you insert it as you, the developers will have decided on it (or auto-generated it) and you will always be able to reference a template by its mnemonic regardless of how many user specified templates there are. It also allows users to have a meaningful naming convention for their templates. A: I have never had problems (performance or development - TDD & unit testing included) using GUIDs as the ID for my databases, and I've worked on some pretty big ones. Have a look here, here and here if you want to find out more about using GUIDs (and the potential GOTCHAS involved) as your primary keys - but I can't recommend it highly enough since moving data around safely and DB synchronisation becomes as easy as brushing your teeth in the morning :-) For your question above, I would either recommend a third column (if possible) that indicates whether or not the template is user or system based, or you can at the very least generate GUIDs for system templates as you insert them and keep a list of those on hand, so that if you need to update the template, you can just target that same GUID in your DEV, UAT and /or PRODUCTION databases without fear of overwriting other templates. The third column would come in handy though for selecting all system or user templates at will, without the need to seperate them into two tables (this is overkill IMHO). I hope that helps, Rob G A: Maybe I didn't get it, but couldn't you use GUIDs as Ids and still have user and system data together? Then you can access the system data by the (non-changable) GUIDs. A: I don't think that GUID should make any problem. If you want to avoid it, then use a flag: ID int template whatever flag enum/int/bool Flag shows whether the actual value is a system or a user value. If you would like to update a system value, then ask only for system values ordered by ID, and it will show you actual order of insertion (you should have a bigint or something for ID to make sure that it doesn't get full and it doesn't get the deleted IDs back to work). With this list the x. record is the x. inserted system value. A: I think there is a better third solution. It strikes me that you're storing two different things in the same table and that you might be better off creating 2 separate tables one for user templates and one for system templates. You might then be able to create a view over the two tables to make them appear as a single object to your application. Obviously I don't have full knowledge of your application and this may be impossible for you for any number of reasons but I think it's a neater solution than GUIDs and way safer than ranges of IDs (seriously don't do ID ranges it'll bite you one day)
{ "language": "en", "url": "https://stackoverflow.com/questions/9702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent the mouse cursor from being hidden after calling CComboBox::ShowDropDown? In my MFC application, when I call CComboBox::ShowDropDown(), the mouse cursor is hidden until interaction with the combo box completes (when the combo box loses focus.) It doesn't reappear when the mouse is moved, like it does with edit boxes. How can I keep the mouse cursor from being hidden? A: Call SetCursor(LoadCursor(NULL, IDC_ARROW)); immediately after the ShowDropDown() call.
{ "language": "en", "url": "https://stackoverflow.com/questions/9704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to extend project properties page? Is it possible to add a custom tab to a project properties page in the Visual Studio 2008? What I want to do is to be able to add a custom tab to properties page for the projects created from default project templates (WPF Application, WPF custom controls library, etc). A: Keith, I'm working on VS add-in for WPF applications localization. I want to be able to manage project specific settings via "project properties" page. I did some research and it seems that it is not possible to extend existing projects in this way. A: It seems that during the time this question was asked, this feature was not implemented in Visual Studio SDK. There's answer for similar question https://stackoverflow.com/a/5325158/2617201 which refers to Microsoft Documentation at Adding and Removing Property Pages. The article refers to Visual Studio 2015 (later versions should have the same feature).
{ "language": "en", "url": "https://stackoverflow.com/questions/9729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: C#.Net case-insensitive string Why does C#.Net allow the declaration of the string object to be case-insensitive? String sHello = "Hello"; string sHello = "Hello"; Both the lower-case and upper-case S of the word String are acceptable and this seems to be the only object that allows this. Can anyone explain why? A: Further to the other answers, it's good practice to use keywords if they exist. E.g. you should use string rather than System.String. A: string is a language keyword while System.String is the type it aliases. Both compile to exactly the same thing, similarly: * *int is System.Int32 *long is System.Int64 *float is System.Single *double is System.Double *char is System.Char *byte is System.Byte *short is System.Int16 *ushort is System.UInt16 *uint is System.UInt32 *ulong is System.UInt64 I think in most cases this is about code legibility - all the basic system value types have aliases, I think the lower case string might just be for consistency. A: "String" is the name of the class. "string" is keyword that maps this class. it's the same like * *Int32 => int *Decimal => decimal *Int64 => long ... and so on... A: "string" is a C# keyword. it's just an alias for "System.String" - one of the .NET BCL classes. A: "string" is just an C# alias for the class "String" in the System-namespace. A: string is an alias for System.String. They are the same thing. By convention, though, objects of type (System.String) are generally refered to as the alias - e.g. string myString = "Hello"; whereas operations on the class use the uppercase version e.g. String.IsNullOrEmpty(myStringVariable); A: I use String and not string, Int32 instead of int, so that my syntax highlighting picks up on a string as a Type and not a keyword. I want keywords to jump out at me.
{ "language": "en", "url": "https://stackoverflow.com/questions/9734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What kind of servers did you virtualize lately? I wonder what type of servers for internal usage you virtualize in the last -say- 6 months. Here's what we got virtual so far: * *mediawiki *bugtracker (mantis) *subversion We didn't virtualize spezialized desktop PCs which are running a certain software product, that is only used once in a while. Do you plan to get rid of those old machines any time soon? And which server products do you use? Vmware ESX, Vmware Server, Xen installations...? A: My standard answer to questions like this is, "virtualization is great; be aware of its limitations". I would never rely on a purely-virtual implementation of anything that's an infrastructure-level service (eg the authoritative DNS server for your site; management and monitoring tools). I work for a company that provides server and network management tools. We are constantly trying to overcome the marketing chutzpah of virtualization vendors in that infrastructure tools shouldn't live in infrastructure tools. Virtualization wants to control all of your services. However, there are some things that should always exist on physical hardware. When something goes wrong with your virtual setup, troubleshooting and recovery can take a long time. If you're still running some of those services you require for your company on physical hardware, you're not dead-in-the-water. Virtualization also introduces clock lag, disk and network IO lag, and other issues you wouldn't see on physical hardware. Lastly, the virtualization tool you pick then becomes in charge of all of the resources under its command for its hosted VMs. That translates to the hypervisor - not you - deciding what VM should have priority at any given moment. If you're concerned about any tool, service, or function being guaranteed to have certain resources, it will need to be on physical hardware. For anything that "doesn't matter", like web, mail, dhcp, ldap, etc - virtualization is great. A: Our build machine running FinalBuilder runs on a Windows XP Virtual Machine running in VMWare Server on Linux. It is very practical to move it and also to backup, we just stop the Virtual Machine and copy the disk image. Some days ago we needed to change the host pc, it took less than 2 hours to have our builder up and running on another pc. A: We migrate to a new SBS 2005 Domain last month. We take the opotunity to create virtual machines for the following servers * *Buid Machine *Svn Repository Machine *Bug Traking Machine (FogBugz) *Testing Databases A: I recently had to build an internal network for our training division, enabling the classrooms to be networked and have access to various technologies. Because of the lack of hardware and equipment and running in an exclusive cash only environment I decided to go with a virtual solution on the server. The server itself is running CentOS 5.1 with VMWare 1.0.6 loaded as the virtualisation provider. On top of this we have 4 Windows Server 2003 machines running, making up the Active Directory, Exchange, ISA, Database and Windows/AV updates component. File sharing and internet routing through the corporate network and ADSL is handled via the CentOS platform. The setup allows us to expand to physical machines at a later stage quickly, and allows the main server to replaced with minimum downtime on the network, as it only requires the moving of the Virtual Machines and starting them up on the new box. A: * *Project Management (dotProject) *Generic Testing Servers (IIS, PHP, etc) Do you plan to get rid of those old machines any time soon? No And which server products do you use? MS Virtual Server A: We use ESX in our labs and lately we've virtualized our document sharing service (KnowledgeTree), the lab management tools and almost all of our department's internal web servers. We also virtualized almost all of our QA department's test machines, with the exception of the performance and stability testing hardware. We aren't going to get rid of the hardware any time soon, it will be used to decrease the budget needs and increase the number of projects that can be handled by one lab. We use VMware ESX 3.5.x exclusively. A: We virtualise a copy of a test client and server, so we can deploy to them before sending the files to the customer. They also gets used to test bug reports. We find this is the biggest benefit to virtualisation as we can keep lots of per-customer versions around. We also VM our web server, and corporate division has virtualised everything.
{ "language": "en", "url": "https://stackoverflow.com/questions/9749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I reverse the ON bits in a byte? I was reading Joel's book where he was suggesting as interview question: Write a program to reverse the "ON" bits in a given byte. I only can think of a solution using C. Asking here so you can show me how to do in a Non C way (if possible) A: What specifically does that question mean? Does reverse mean setting 1's to 0's and vice versa? Or does it mean 00001100 --> 00110000 where you reverse their order in the byte? Or perhaps just reversing the part that is from the first 1 to the last 1? ie. 00110101 --> 00101011? Assuming it means reversing the bit order in the whole byte, here's an x86 assembler version: ; al is input register ; bl is output register xor bl, bl ; clear output ; first bit rcl al, 1 ; rotate al through carry rcr bl, 1 ; rotate carry into bl ; duplicate above 2-line statements 7 more times for the other bits not the most optimal solution, a table lookup is faster. A: Reversing the order of bits in C#: byte ReverseByte(byte b) { byte r = 0; for(int i=0; i<8; i++) { int mask = 1 << i; int bit = (b & mask) >> i; int reversedMask = bit << (7 - i); r |= (byte)reversedMask; } return r; } I'm sure there are more clever ways of doing it but in that precise case, the interview question is meant to determine if you know bitwise operations so I guess this solution would work. In an interview, the interviewer usually wants to know how you find a solution, what are you problem solving skills, if it's clean or if it's a hack. So don't come up with too much of a clever solution because that will probably mean you found it somewhere on the Internet beforehand. Don't try to fake that you don't know it neither and that you just come up with the answer because you are a genius, this is will be even worst if she figures out since you are basically lying. A: If you're talking about switching 1's to 0's and 0's to 1's, using Ruby: n = 0b11001100 ~n If you mean reverse the order: n = 0b11001100 eval("0b" + n.to_s(2).reverse) If you mean counting the on bits, as mentioned by another user: n = 123 count = 0 0.upto(8) { |i| count = count + n[i] } ♥ Ruby A: I'm probably misremembering, but I thought that Joel's question was about counting the "on" bits rather than reversing them. Here you go: #include <stdio.h> int countBits(unsigned char byte); int main(){ FILE* out = fopen( "bitcount.c" ,"w"); int i; fprintf(out, "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n"); fprintf(out, "int bitcount[256] = {"); for(i=0;i<256;i++){ fprintf(out, "%i", countBits((unsigned char)i)); if( i < 255 ) fprintf(out, ", "); } fprintf(out, "};\n\n"); fprintf(out, "int main(){\n"); fprintf(out, "srand ( time(NULL) );\n"); fprintf(out, "\tint num = rand() %% 256;\n"); fprintf(out, "\tprintf(\"The byte %%i has %%i bits set to ON.\\n\", num, bitcount[num]);\n"); fprintf(out, "\treturn 0;\n"); fprintf(out, "}\n"); fclose(out); return 0; } int countBits(unsigned char byte){ unsigned char mask = 1; int count = 0; while(mask){ if( mask&byte ) count++; mask <<= 1; } return count; } A: I claim trick question. :) Reversing all bits means a flip-flop, but only the bits that are on clearly means: return 0; A: The classic Bit Hacks page has several (really very clever) ways to do this, but it's all in C. Any language derived from C syntax (notably Java) will likely have similar methods. I'm sure we'll get some Haskell versions in this thread ;) A: byte ReverseByte(byte b) { return b ^ 0xff; } That works if ^ is XOR in your language, but not if it's AND, which it often is. A: And here's a version directly cut and pasted from OpenJDK, which is interesting because it involves no loop. On the other hand, unlike the Scheme version I posted, this version only works for 32-bit and 64-bit numbers. :-) 32-bit version: public static int reverse(int i) { // HD, Figure 7-1 i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; i = (i << 24) | ((i & 0xff00) << 8) | ((i >>> 8) & 0xff00) | (i >>> 24); return i; } 64-bit version: public static long reverse(long i) { // HD, Figure 7-1 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; i = (i << 48) | ((i & 0xffff0000L) << 16) | ((i >>> 16) & 0xffff0000L) | (i >>> 48); return i; } A: pseudo code.. while (Read()) Write(0); A: What specifically does that question mean? Good question. If reversing the "ON" bits means reversing only the bits that are "ON", then you will always get 0, no matter what the input is. If it means reversing all the bits, i.e. changing all 1s to 0s and all 0s to 1s, which is how I initially read it, then that's just a bitwise NOT, or complement. C-based languages have a complement operator, ~, that does this. For example: unsigned char b = 102; /* 0x66, 01100110 */ unsigned char reverse = ~b; /* 0x99, 10011001 */ A: I'm probably misremembering, but I thought that Joel's question was about counting the "on" bits rather than reversing them. A: Here's the obligatory Haskell soln for complementing the bits, it uses the library function, complement: import Data.Bits import Data.Int i = 123::Int i32 = 123::Int32 i64 = 123::Int64 var2 = 123::Integer test1 = sho i test2 = sho i32 test3 = sho i64 test4 = sho var2 -- Exception sho i = putStrLn $ showBits i ++ "\n" ++ (showBits $complement i) showBits v = concatMap f (showBits2 v) where f False = "0" f True = "1" showBits2 v = map (testBit v) [0..(bitSize v - 1)] A: I'd modify palmsey's second example, eliminating a bug and eliminating the eval: n = 0b11001100 n.to_s(2).rjust(8, '0').reverse.to_i(2) The rjust is important if the number to be bitwise-reversed is a fixed-length bit field -- without it, the reverse of 0b00101010 would be 0b10101 rather than the correct 0b01010100. (Obviously, the 8 should be replaced with the length in question.) I just got tripped up by this one. A: If the question means to flip all the bits, and you aren't allowed to use C-like operators such as XOR and NOT, then this will work: bFlipped = -1 - bInput; A: Asking here so you can show me how to do in a Non C way (if possible) Say you have the number 10101010. To change 1s to 0s (and vice versa) you just use XOR: 10101010 ^11111111 -------- 01010101 Doing it by hand is about as "Non C" as you'll get. However from the wording of the question it really sounds like it's only turning off "ON" bits... In which case the answer is zero (as has already been mentioned) (unless of course the question is actually asking to swap the order of the bits). A: Since the question asked for a non-C way, here's a Scheme implementation, cheerfully plagiarised from SLIB: (define (bit-reverse k n) (do ((m (if (negative? n) (lognot n) n) (arithmetic-shift m -1)) (k (+ -1 k) (+ -1 k)) (rvs 0 (logior (arithmetic-shift rvs 1) (logand 1 m)))) ((negative? k) (if (negative? n) (lognot rvs) rvs)))) (define (reverse-bit-field n start end) (define width (- end start)) (let ((mask (lognot (ash -1 width)))) (define zn (logand mask (arithmetic-shift n (- start)))) (logior (arithmetic-shift (bit-reverse width zn) start) (logand (lognot (ash mask start)) n)))) Rewritten as C (for people unfamiliar with Scheme), it'd look something like this (with the understanding that in Scheme, numbers can be arbitrarily big): int bit_reverse(int k, int n) { int m = n < 0 ? ~n : n; int rvs = 0; while (--k >= 0) { rvs = (rvs << 1) | (m & 1); m >>= 1; } return n < 0 ? ~rvs : rvs; } int reverse_bit_field(int n, int start, int end) { int width = end - start; int mask = ~(-1 << width); int zn = mask & (n >> start); return (bit_reverse(width, zn) << start) | (~(mask << start) & n); } A: Reversing the bits. For example we have a number represented by 01101011 . Now if we reverse the bits then this number will become 11010110. Now to achieve this you should first know how to do swap two bits in a number. Swapping two bits in a number:- XOR both the bits with one and see if results are different. If they are not then both the bits are same otherwise XOR both the bits with XOR and save it in its original number; Now for reversing the number FOR I less than Numberofbits/2 swap(Number,I,NumberOfBits-1-I);
{ "language": "en", "url": "https://stackoverflow.com/questions/9750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Sending emails without looking like spam I want so send every week an update by email. But Im afraid that if there are too many emails sent, they will be marked as spam. Any of you has experience sending many emails (thousands) weekly? What techniques do you use? A: A good answer for this question would be a real gold mine for a motivated spammer :) Not really -- as you'll see in that other thread, answers center on showing that you are the authorative sender of the email, and various aspects that are useless to spammers and useful to non-spammers who send a lot of email.
{ "language": "en", "url": "https://stackoverflow.com/questions/9751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can I script FlexBuilder without writing an extension? I'd like to script FlexBuilder so that I can run debug or profile without having to switch to FlexBuilder and manually clicking the button (or using the key combo). Is this possible without writing an extension? To be more specific, this is exactly what I want to do: I want to create a TextMate command that talks to FlexBuilder and makes it run the debug target for the currently selected project. TextMate already has support for interacting with Xcode in this way, and it would be great to be able to do the same with FlexBuilder. A: When compiling I use Ant and have full control over that from TextMate, what I want is to be able to launch the debugger and the profiler. The command line debugger is unusable and there is no other profiler available than the one in FlexBuilder. A: Since FlexBuilder essentially is an extended version of Eclipse, any tools/scripts for doing the same in Eclipse should work for FlexBuilder aswell. I couldn't find any tools like this googling it, have you considered doing away with FlexBuilder completely, there are plenty of guides for using the mxmlc (or fcsh) compilers directly from your editor. A: I do not know if there is a plugin like this for Eclipse however if not you can write one as it should be easy. If the specific command that you want to call shows up in Windows/Preferences - General/Keys, you can create a plugin that takes commands from TextMate (I do not know what protocol TextMate uses, socket or something else) and executed the specific action that is associated with the command that also appears in preferences.
{ "language": "en", "url": "https://stackoverflow.com/questions/9769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle XE or SQL Server Express I'm starting a new project here (Windows Forms). What's the best option today for a small (free as in beer) DBMS? I've used SQL Server Express on the past projects, but time and time again I hear people saying that the product from Oracle is faster and more powerful. It will be used in a small company (around 20 users) and will not reach the 4 GB limit any time soon :) I don't want to start a flame war on my first post, so please point me to some link showing a good (and actual) comparison between the 2 products, if possible. PS: I've heard about IBM DB2 Express too, but I coudn't find any information about it. (Marketing material from IBM doesn't count :) ) A: It would be hard to argue either way given the needs you outlined, that either would shine over the other. What I will say is this: * *You say you are already familar with SSExpress, then that is a good reason to stick with it *IMHO the tools with SSExpress are superior and easier to use than the Oracle equivalent That said, I have much more experience with SS than Oracle so YMMV. A: Sorry, no link, but one advice. Because we support Oracle and SQL Server, I know that getting fixes for the 'normal' Oracle database, is not something what I call fun. You have to pay for it, and if you have no tool which updates your Oracle system for you, it's a pain in the a.., if you ask me. Check out how the Oracle XE is supported with updates/fixes. I don't know, I only use the 'normal' Oracle (Developer) database. A: I would go for the SQL Server Express solution, unless you absolutely have to use a feature in Oracle that SQL Server does not have and you have no usable workaround. Example of Oracle's strengths: * *Analytical Functions in Oracle ROCK! *PL/SQL is better than T-SQL. *If you're going to scale up the system to 1,000's of users all updating the same small dataset *You scale upto multi-TB databases, *You need to scale to need big numbers of CPU's in your server (over 8). *need instant failover (RAC) *you really cannot afford to lose a transaction. Maybe you can tell, I'm a big Oracle fan! But I think that Oracle Express is a commercial reaction to SQL Server Express and I don't think Oracle really deep deep down likes it. * *You know with SQL Server that there is an upgrade path (SQL Server 2008 is soon) plus service packs. *SQL Express is also more "install and forget" than Oracle. *and it will integrate better with your IDE (if your using .NET) In terms of speed, both are going to be lighting quick with such a small dataset size. A: I think it's great to rethink things every once in a while and that it's very smart to consider alternative products when you are at a junction to do so. If you are comfortable optimizing systems and are dba level in skills, I'd consider PostgreSQL. I do not consider myself a dba and have middling database skills and find SQL Server Express extremely easy to use. Also, I've had products exceed the limits of SQL Server Express - the transition to SQL Server Standard/Enterprise is seemless. I realize that this doesn't matter at a technical level, but Larry Ellison buys jets and prostitutes with his profit. Bill Gates is solving problems of immense importance to humanity with his. All things being equal, I always prefer to give my money to Bill Gates. A: Is this any use: https://web.archive.org/web/1/http://downloads.techrepublic%2ecom%2ecom/5138-9592-6028761.html NB Registration is required A: Both of KiwiBastard's points are very good and I completely agree with him. If you really want a free alternative that is similar to MS SQL and supports growth should you need it, you could have a look at MySQL or PostgreSQL. SQLite also seems a good choice. Surely you can afford an old Linux server if you work in a company with 20 employees. A: 100% SQL Express, more easy to install and maintain than Oracle. A: IMHO the major problem with SQL Server, has for a long time been, no multi-version read consistency. Fortunately this has been corrected since SQL Server 2005 with the snapshot isolation level. If your looking for a good RDBMS for a small project requring minimal knowledge for maintenance, SQL Server Express Edition is a good pick. The SQL Server Express Edition UI is much easier to understand than RMAN or the "easier"-to-use backup scripts included with Oracle Database XE which requires offlining your database. Oracle Database XE is on my *** list. They recently released an ODBC driver for Linux that wasn't compiled properly (ld returns missing symbols for required ODBC functions) to be at all usable (10.2.0.4). With this kind of lack of attention to any reasonable amount of QA even for a 'free' product I would think twice about going down that road. A: For DB2 Express-C see: "DB2 Express-C™ is the free version of one of the most advanced database management systems in the world. Why pay when you can have all you need for free? DB2 Express-C is free to develop, deploy and distribute. It is a fast, secure, reliable, and amazingly scalable dataserver, ideal for most startups and small/medium sized businesses. DB2 Express-C 9.7 is available on Linux, Unix, Windows, and now Mac OS X as well! It also enables developers to easily handle XML through the native storage technology called pureXML™. Whether you develop in Java, .Net, Ruby, Python, Perl or pretty much any other programming language out there, DB2 can be your technological advantage."
{ "language": "en", "url": "https://stackoverflow.com/questions/9783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Calculate DateTime Weeks into Rows I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop: var iWeeks = 6; for (int w = 0; w < iWeeks; w++) { This works fine, however, some month will only have 5 weeks and in some rare cases, 4. How can I calculate the number of rows that will be required for a particular month? This is an example of what I am creating: As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row. Image found on google This is an example of what I am creating: As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row. Image found on google A: Here is the method that does it: public int GetWeekRows(int year, int month) { DateTime firstDayOfMonth = new DateTime(year, month, 1); DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1); System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar; int lastWeek = calendar.GetWeekOfYear(lastDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); int firstWeek = calendar.GetWeekOfYear(firstDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); return lastWeek - firstWeek + 1; } You can customize the calendar week rule by modifying the System.Globalization.CalendarWeekRule.FirstFourDayWeek part. I hope the code is self explanatory. A: Well, it depends on the culture you're using, but let's assume you can use Thread.CurrentThread.CurrentCulture, then the code to get the week of today would be: Culture culture = Thread.CurrentThread.CurrentCulture; Calendar cal = culture.Calendar; Int32 week = cal.GetWeekOfYear(DateTime.Today, culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek); A: How about checking which week the first and last days will be in? A: The months in the Julian / Gregorian calendar have the same number of days each year, except February who can have 28 or 29 days depending on the leapness of the year. You can find the number of days in the Description section at http://en.wikipedia.org/wiki/Gregorian_calendar. As @darkdog mentioned you have DateTime.DaysInMonth. Just do this: var days = DateTime.DaysInMonth(year, month) + WhatDayOfWeekTheMonthStarts(year, month); int rows = (days / 7); if (0 < days % 7) { ++rows; } Take into consideration the fact that for globalization / localization purposes, some parts of the world use different calendars / methods of organization of the year. A: Try this, DateTime.DaysInMonth A: Check Calendar.GetWeekOfYear. It should do the trick. There is a problem with it, it does not follow the 4 day rule by ISO 8601, but otherwise it is neat. A: you can get the days of a month by using DateTime.DaysInMonth(int WhichYear,int WhichMonth); A: The problem isn't the number of days in the month, it's how many weeks it spans over. February in a non-leap year will have 28 days, and if the first day of the month is a monday, february will span exactly 4 week numbers. However, if the first day of the month is a tuesday, or any other day of the week, february will span 5 week numbers. A 31 day month can span 5 or 6 weeks the same way. If the month starts on a monday, the 31 days gives you 5 week numbers. If the month starts on saturday or sunday, it will span 6 week numbers. So the right way to obtain this number is to find the week number of the first and last days of the month. Edit #1: Here's how to calculate the number of weeks a given month spans: Edit #2: Fixed bugs in code public static Int32 GetWeekForDateCurrentCulture(DateTime dt) { CultureInfo culture = Thread.CurrentThread.CurrentCulture; Calendar cal = culture.Calendar; return cal.GetWeekOfYear(dt, culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek); } public static Int32 GetWeekSpanCountForMonth(DateTime dt) { DateTime firstDayInMonth = new DateTime(dt.Year, dt.Month, 1); DateTime lastDayInMonth = firstDayInMonth.AddMonths(1).AddDays(-1); return GetWeekForDateCurrentCulture(lastDayInMonth) - GetWeekForDateCurrentCulture(firstDayInMonth) + 1; } A: First Find out which weekday the first day of the month is in. Just new up a datetime with the first day, always 1, and the year and month in question, there is a day of week property on it. Then from here, you can use the number of days in the month, DateTime.DaysInMonth, in order to determine how many weeks when you divide by seven and then add the number of days from 1 that your first day falls on. For instance, public static int RowsForMonth(int month, int year) { DateTime first = new DateTime(year, month, 1); //number of days pushed beyond monday this one sits int offset = ((int)first.DayOfWeek) - 1; int actualdays = DateTime.DaysInMonth(month, year) + offset; decimal rows = (actualdays / 7); if ((rows - ((int)rows)) > .1) { rows++; } return rows; }
{ "language": "en", "url": "https://stackoverflow.com/questions/9805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Mootools: Drag & Drop problems I've asked this question to the forums on the Mootools website and one person said that my class selection was corrupted before an admin came along and changed my post status to invalid. Needless to say this did not help much. I then posted to a google group for Mootools with no response. My question is why doesn't the 'enter', 'leave', 'drop' events fire for my '.drop' elements? The events for the .drag elements are working. <title>Untitled Page</title> <script type="text/javascript" src="/SDI/includes/mootools-1.2.js"></script> <script type="text/javascript" src="/SDI/includes/mootools-1.2-more.js"></script> <script type="text/javascript" charset="utf-8"> window.addEvent('domready', function() { var fx = []; $$('#draggables div').each(function(drag){ new Drag.Move(drag, { droppables: $$('#droppables div'), onDrop: function(element, droppable){ if(!droppable) { } else { element.setStyle('background-color', '#1d1d20'); } element.dispose(); }, onEnter: function(element, droppable){ element.setStyle('background-color', '#ffffff'); }, onLeave: function(element, droppable){ element.setStyle('background-color', '#000000'); } }); }); $$('#droppables div').each(function(drop, index){ drop.addEvents({ 'enter': function(el, obj){ drop.setStyle('background-color', '#78ba91'); }, 'leave': function(el, obj){ drop.setStyle('background-color', '#1d1d20'); }, 'drop': function(el, obj){ el.remove(); } }); }); }); </script> <form id="form1" runat="server"> <div> <div id="draggables"> <div class="drag"></div> <div class="drag"></div> <div class="drag"></div> <div class="drag"></div> <div class="drag"></div> <div class="drag"></div> <div class="drag"></div> <div class="drag"></div> <div class="drag"></div> <div class="drag"></div> </div> <div id="droppables"> <div class="drop"></div> <div class="drop"></div> <div class="drop"></div> <div class="drop"></div> <div class="drop"></div> <div class="drop"></div> </div> </div> </form> A: Ok, it looks like there are a couple of issues here. As far as I can tell, there is no such thing as a "droppable" in mootools. This means your events like 'enter', 'leave' and 'drop' won't work. (These are events on the drag object) If you change those names to events that elements in mootools have (as in, DOM events) your code works perfectly. For instance, if you change 'enter' and 'leave' to 'mouseover' and 'mouseout', your events fire with no problem. (Opera 9.51 on Windows Vista) This appears to be the revelant line in the documentation for this, which stats to use DOM events. http://docs.mootools.net/Element/Element.Event#Element:addEvents Also, on that page, is a link to the events that regular elements can have http://www.w3schools.com/html/html_eventattributes.asp However, the advice "TG in SD" gave you in the nabble forums is probably best. If you can, don't bother using these events. Put whatever it is you need to do in the draggable object, and save yourself all this hassle. A: According to Mootools Docs, "droppables" is one of the options expected by the Drag.Move class. In fact, this is the array of elements that interact with the element when it fires the "drop," "enter," and "leave" event.
{ "language": "en", "url": "https://stackoverflow.com/questions/9831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Developer Friendly ERP My company is currently using Sage MAS as their ERP system. While integrating our shopping cart is not going to be impossible, it uses COM and has it's own challenges. I was wondering if there was a more developer friendly ERP out there. I have looked into Microsoft Dynamics but getting information on ERP systems that isn't a bunch of business jargon is next to impossible. I will be using C# 3.whatever and .NET MVC. A: When you talk about Microsoft Dynamics, it sounds a bit like you are talking about a specific product. However there are close to 10 different systems in the Dynamics line-up from Microsoft and at least 6 of them are different ERP system, all with different functionalities and extendabilities. The new verions of Microsoft Dynamics AX as well as Microsoft Dynamics NAV, have Web service support out of the box. I hope this helps. A: MS Dyanamics is very cool app. V3 was fully Web Serviced V4 i assume even more- all actions are exposed as webservices, there is a big license hit on MS CRM due to "internet" licensing. We use CRMv3 in a totally .NET SOA here and its great. You should have no problems doing the integration - security aside => A: I've done a bit of integration between ASP.NET and Dynamics AX4 - it has a .NET API called Business Connector that gives you access to AX's full internal object model - if AX does it, your web app can do it too. My app had to execute arbitrary AX business logic functions and, apart from the crummy API documentation (I've been spoiled by MSDN), it was all pretty easy. The Business Connector is the lowest-level API - there's a bunch of web service options as well that work at a higher level.
{ "language": "en", "url": "https://stackoverflow.com/questions/9836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Performance critical GUI application (windows,linux) I've been tasked with updating a series of applications which are performance critical VB.NET apps that essentially just monitor and return networking statistics. I've only got three requirements: convert it to C#, make it fast, and make it stable One caveat is that we "may" migrate from a .NET platform to linux "soon" I will be responsible for maintaining these apps in the future so I'd like to do this right. I have decided to refactor these apps according to the MVP pattern so that I can properly unit test the hell out of this bad boy. But I was also thinking since I was using MVP that I could also do the computationally expensive stuff in native C/C++ code while the GUI would be done with .NET forms, or Qt or whatever. questions: * *does it make sense to do a GUI in winforms but the expensive stuff in native, unmanaged C/C++ ? *any recommendations for a good cross platform windowing kit that would fit for the scenario described above? A: 1) Premature optimization is evil. Implement your "expensive stuff" in C# and see if you need to refactor it. Or, at least set up a test that will allow you to determine this. 2) Yowch. Cross platform UI. I wouldn't put up with the "may" stuff. Nail the weasels down; how can you possibly make design decisions without knowing what you're designing? If you go with a pure .NET implementation, will they complain if you have to (at a minimum) refactor it to work in Mono? If you create it in Java, will they be annoyed that it looks ugly as hell and users complain that they can't find their .exe file amongst all those .jars? A: First off, I would put some time into trying out a few VB.NET to C# converters. You're basically porting syntax, and there's no reason to do that by hand if you don't have to. Sure, you might have to clean up what comes out of the converter, but that's way better than a by-hand conversion. Now, as for your questions: 1) does it make sense to do a GUI in winforms but the expensive stuff in native, unmanaged C/C++ ? Not yet. Wait until you've done the conversion, and then find out where you're actually spending your time. There's no reason to jump into mixing C/C++ with C# until you find out that it's necessary. You may find that dropping into unsafe C# is sufficient. Even that may be unnecessary. You might just need to optimize algorithms. Find out what your bottlenecks are and then decide how to fix them. 2) any recommendations for a good cross platform windowing kit that would fit for the scenario described above? I'd be looking into mono for sure. That's really the best you can do if you're going with C#. It's pretty much either mono or another rewrite in another language when/if you move to Linux. A: 1) Not necessarily. I think it would be more correct to say that it's probably worthwhile writing your backend code in C++, regardless of the performance implications. Even though you can't tie your higher-ups down on the platform switch, it would be prudent of you to make preparations for that eventuality, since management types tend to change their mind alot without good reason (or warning); even if they decide not to switch now, that doesn't mean that they won't decide to switch six months from now. Writing your logic in C++ now, knowing that it's a possibility, though more difficult, may make your life significantly easier later. 2) Not really. There are "solutions" like wxWindows and GTK#, but often they're buggy, or difficult to get working properly, or they lack something important on one platform or another. They also usually lock you into a lowest-common-denominator UI (ie, general controls work fine but you can forget about ever doing something interesting -- WPF, for example -- with it). UIs are easy to write, so I think if you write your logic in something that's portable, it should be a trivial matter to knock together several platform-specific UIs. A: For the first question, it is really hard to say if it would make sense as it would likely depend upon what sort of performance you need to be getting. I personally haven't seen any system wide slow downs due to the GUI in properly designed GUIs using WinForms so I don't see why it would should cause any problems, and in all likelihood it would make your life easier in regards to the GUI. As for your second question, if you are going to be moving to another platform at some point - you want to take a look at the libraries that have been implemented by Mono (http://www.mono-project.com/Main_Page), this should also cover most of your needs in regards to cross platform windowing as it supports WinForms and GTK#. A: No, it does not make sense to do the "expensive stuff" in C/C++. The potential (and most likely minor) performance improvements never, ever outweigh your productivity being an abject, sick joke when compared to C#. Really. It's not even close. Read through this (and all posts referenced within): http://blogs.msdn.com/ricom/archive/2005/05/10/416151.aspx A: You might want to look into using Mono. This is a open source version of .NET that runs on many plateforms...Linux,Mac, Solaris, Windows, etc.. Now about coding your expensive stuff in C/C++. Here's an article that does a very good job explaining the differences between C/C++ & C# performance. A: And again, let me emphasize, the C++ stuff is veerrrryyyy expensive. Would it make sense to do what I mentioned above? (.NET forms hiding heavy lifting C++) As noted before, I personally haven't noticed any system wide slow downs due to WinForms in applications written in both VB.NET and C#. However, if the application is truly performance intensive then you might notice a slight slow down if you wrote everything in C# due to it being complied into CIL (http://www.cl.cam.ac.uk/research/srg/han/hprls/orangepath/timestable-demo/). As such, writing the GUI in a language such as C# will likely make that part of the development a bit easier which would give you more time to work on the critical parts of the code. The only catch-22 here is might notice some slow downs due to the calls to the C/C++ code from the C# code; however, this is likely very unlikely. A: 1) does it make sense to do a GUI in winforms but the expensive stuff in native, unmanaged C/C++ ? Most likely not. Unless you're communicating with a lot of other native C dlls or so on, C# is likely to be between 5% slower to 5% faster than C++ (std::string really kills you if you're using it) 2) any recommendations for a good cross platform windowing kit that would fit for the scenario described above? If it's just some simple forms with buttons, mono will likely be able to run them unmodified. It's support for .NET WinForms is pretty good these days. It is however, butt ugly :-) A: I might be misunderstanding the issue, but if it is a network monitoring system, why isn't it written as a "dedicated" Windows service? VB.NET shouldn't be much slower than C#. I'm not 100% certain if there is any big differences in the generated IL-code, but the only advantage (and justifiable reason to rewrite it in C#) I could think of (except that C# have a nicer syntax and some other goodies) is the use of unsafe code block that could speed things up a little. A: gtk-sharp is a pretty nice cross platform toolkit. Gtk# is a Graphical User Interface Toolkit for mono and .Net. The project binds the gtk+ toolkit and assorted GNOME libraries, enabling fully native graphical Gnome application development using the Mono and .Net development frameworks. A: The c/c++ stuff may end up being a good idea, but right now YAGNI. Same with the Linux stuff. Ignore it, you ain't gonna need it until you need it. Keep it simple. Unit test the hell out of it, as you say. Get the code working and evolve the design from there. A: I had similar dilemma some time back, while trying to find out a best way to develop a PC based H/W Testing tool (which obviously means "with UI options") that interacts with an embedded hardware (via PCMCIA interface). The bottleneck was that the testing should run at maximum deviation of 10ms from the intended time specified by the tester. E.g: If the tester creates the following test sequence: * 1. Remotely activate the H/W 2. Wait for 50ms delay. 3. Read an H/W information. the delay mentioned in step 2 should not be > 60ms. I chose C++ WIN32 application as my back-end and VC++ 2005 Winform (.NET platform) for UI development. Detailed information on how to interface these two is available in msdn I segregated the system like this: In VC++ .NET: * 1. UI to have complete information about the H/W (read via back-end application) and to control the H/W on demand. (Buttons, combo-box etc.. etc..) 2. UI to run time critical test sequences (as mentioned in the above example). 3. Gathering these information and building a stream (File-stream) in a Time-linear format (i.e, in the precise order of steps in which it has to be performed). 4. Triggering and hand-shaking mechanism (by redirecting standard input and standard output) with WIN32 back-end application. The common resources will be the File-streams. In C++ WIN32: * 1. Interpreting the Input File-Stream. 2. Interaction with H/W. 3. Gathering information from H/W and putting it in its Output File-Stream. 4. Indication of test completion to UI (via redirected standard output). The complete system is up and running. It seems to be pretty stable. (Without the timing deviation mentioned above). Note that, the testing PC we use is solely for the H/W Testing purpose (it had just the UI running on it, with no auto-updates, virus scan etc.. etc.. ).
{ "language": "en", "url": "https://stackoverflow.com/questions/9846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Personal Website Construction I'm currently trying to build a personal website to create a presence on the web for myself. My plan is to include content such as my resume, any projects that I have done on my own and links to open source projects that I have contributed to, and so on. However, I'm not sure which approach would be better from a perspective of "advertising" myself, since that what this site does, especially since I am a software developer. Should I use an out-of-the-box system and extend it as needed, with available modules and custom modules where needed or should I custom build a site and all of its features as I need them? Does a custom site look better in the eyes of a potential employer who might visit my site? A: If you are a web-specific developer I would go with a custom site, but if you focus more on desktop applications or backend technologies, I think an out of the box system would be fine. A: A nice looking, default, off the shelf, complete website could be more impressive than a poorly done, broken, tacked together, incomplete website. Perhaps start with something "off the shelf" but nice looking, keep it simple, professional, and then eventually add more custom functionality, style and content. Potential employers may like to see that you are capable of reusing tried and trued solutions instead of trying to create everything from scratch without a good reason. Or you could spend time combining great components into something even better than the sum of the parts, as Jeff Atwood talks about extensively in the Stack Overflow podcasts. Stack Overflow is a good example of writing lots of custom code, but combining that with some of the best Web 2.0 technologies/widgets/etc. into something coherent, instead of trying to prove that they could implement x/y/z from scratch. (On the other hand, it's really fun to build your own login system, blog, or photo gallery. If you really enjoy it and you want to learn a lot or create something new and different, then go for it!) A: Here's what I did (or am currently doing). First, use an out of the box solution to begin with. In my case, I used BlogEngine.NET, which was open source and easy to set up. This allows me to put content on my site as fast as possible. Now, I can continue to use BlogEngine.NET, and skin my site to give it more personality or I can start rolling out my own solution. However, I haven't found a requirement yet that would give me a reason to waste time building my own solution. Odds are you probably won't either. A: I don't think it matters if your site is blatantly using a framework or other "generic" solution. The real question is "is it done well, with taste?" If you are using an out of the box solution, you should take the time and pay attention to details when customizing it as if you were creating it from scratch. Alternatively, if you're looking for a great learning experience and something to spend a lot of your free time on -- write it yourself. But know that you are re-inventing the wheel, and embrace it. edit A recent post from 37Signals, Gearheads don't get it, really sums up a good point about not focusing on the technical details, but "content and community". A: Reinventing the wheel is not such a great idea when you are building a personal site. Building your own CMS is fun, and to some degree is something to brag about, but not so much features you won't have the time to build and all the security holes that you won't have the time to fix. It's much better to pick a good, well-established engine, build a custom theme, and contribute a module or two to it: you'll be writing code that you can show off as a code sample and at the same time creating something useful. Knowing your way around an open source CMS is a good skill in just about any job: when your boss says - hey, we need a three pager site for client/product/person X in 10 hours, you can say - no problem. A: I've toyed with this idea in the past but I don't think it's really a good idea for a number of reasons. Firstly, there are a number of places that can take care of most of this without you needing to do the work or maintenance. Just signing up for a linkedIn account for example will allow you to get most of your needs catered for in this regard. You can create your resume there and bio information etc and make it publicly viewable. The other issue with your "own site" is that if you don't update it often, the information gets stale, and worse yet, people have no reason to go back because "nothing has changed" - and that's not much of an advert for you is it? Now that I've said all that, I'll make another recommendation. Why not start a blog instead?! If you've got decent experience, why not share that. I'd be willing to bet that this will be the best advert for your skills because: * *It's always updated (if you post often) *It's not like you're looking for work doing it - but your (future) employer, or their developers will check it out anyway to get a better insight into your character. *Putting something on your resume doesn't mean you can do it. I'm not saying that you'd lie about your skills :-), but there's no argument about your ability when you're writing articles about the stuff, getting comments and feedback, and better yet, learning EVEN MORE about your passions. Best of all - you can run your blog from your chosen domain and also point to your resume that is stored in linkedIn. Just an idea... That's my two pennys worth on that - hope it helps you come to a decision! A: For a simpler portfolio site, Wordpress might meet your needs. You can set up 'static' Wordpress pages for contact information, various portfolios, a resume, etc. This would also give you a blog if you want to do this. Wordpress does give you the flexibility to "hide" the blogging part of it and use it basically as a simpler CMS. For example, your root URL of example.com could point to a WP static page, while example.com/blog would be the actual blog pages. If you self-host Wordpress on your own domain (which I really would recommend instead of going through wordpress.com), it should be trivial to set up a few subdomains for extra content. For example, downloads.example.com could host the actual downloads for projects you've developed linked from the Wordpress portfolio pages. Similarly, if you're doing a lot of web work, a subdomain like lab.example.com or samples.example.com could then host various static (or dynamic) pages where you show off sandboxed pages that are not under the control of Wordpress. Keep in mind though that you'll want to make your page look good. A sloppy looking site can scare away potential clients, even if you are not looking to do any web work for them. A: Putting your resume up online somewhere helps, I get a lot of recruitment emails from people who happened on my resume via googling. However I agree with ColinYounger in that you'll probably get more bang for your buck from LinkedIn. My advice is this - if you want to take the time out to LEARN a CMS or something, to better yourself, then why not make your first project in one be your homepage? Maybe enlighten us as to the "features" you want to have on a personal homepage? Outside of a link to an HTML resume and perhaps some links to things you like, not sure exactly what the features of a homepage would be... A: It really depends on: a) what services you provide b) what your skill level is when it comes to web design/development If you are primarily a web applications developer then running an off the shelf product or using blatantly using DreamWeaver to develop it may not be so smart -- or maybe your clients aren't adept enough to notice? Likewise if you're primarily a web designer then it is probably a good idea to design your own website. A: Just as a side question and following up on my 'ego trip' comment: why would you take anything on the web to be 'true'? IME printed submissions, while not necessarily accurate, tend to be slightly less, erm... exaggerated than web submissions. Do those responding\viewing ever hire? I wouldn't google for a candidate. I might ego surf for a respondent, but would ignore CVs. Rounding back to the OP, I would suggest that you need to SHOW what you're good at - participate in Open Source projects and POST on their forums, link to projects you can post details of and generally try to show what a Good Employee you could be. Just telling me that you're good at [insert latest trend here] means diddly. A: I have come to see that the best way to advertise yourself is to put quality content out there. If you write about the technology that you have experience in, maybe create a few tutorials, and if you do all that often enough, that shows some authority in your chosen field of work. This alone is one of the best advertisements. However, you also want to show passion. And online, that can be shown through how meticulously your site is done (it doesn't have to be a super great UI or something), but it should be neat, clean, and professional. It doesn't matter if its out of the box, or custom designed. Either way, you will have to work hard to make it look good.
{ "language": "en", "url": "https://stackoverflow.com/questions/9877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Looking for algorithm that reverses the sprintf() function output I am working on a project that requires the parsing of log files. I am looking for a fast algorithm that would take groups messages like this: The temperature at P1 is 35F. The temperature at P1 is 40F. The temperature at P3 is 35F. Logger stopped. Logger started. The temperature at P1 is 40F. and puts out something in the form of a printf(): "The temperature at P%d is %dF.", Int1, Int2" {(1,35), (1, 40), (3, 35), (1,40)} The algorithm needs to be generic enough to recognize almost any data load in message groups. I tried searching for this kind of technology, but I don't even know the correct terms to search for. A: Overview: A naïve!! algorithm keeps track of the frequency of words in a per-column manner, where one can assume that each line can be separated into columns with a delimiter. Example input: The dog jumped over the moon The cat jumped over the moon The moon jumped over the moon The car jumped over the moon Frequencies: Column 1: {The: 4} Column 2: {car: 1, cat: 1, dog: 1, moon: 1} Column 3: {jumped: 4} Column 4: {over: 4} Column 5: {the: 4} Column 6: {moon: 4} We could partition these frequency lists further by grouping based on the total number of fields, but in this simple and convenient example, we are only working with a fixed number of fields (6). The next step is to iterate through lines which generated these frequency lists, so let's take the first example. * *The: meets some hand-wavy criteria and the algorithm decides it must be static. *dog: doesn't appear to be static based on the rest of the frequency list, and thus it must be dynamic as opposed to static text. We loop through a few pre-defined regular expressions and come up with /[a-z]+/i. *over: same deal as #1; it's static, so leave as is. *the: same deal as #1; it's static, so leave as is. *moon: same deal as #1; it's static, so leave as is. Thus, just from going over the first line we can put together the following regular expression: /The ([a-z]+?) jumps over the moon/ Considerations: * *Obviously one can choose to scan part or the whole document for the first pass, as long as one is confident the frequency lists will be a sufficient sampling of the entire data. *False positives may creep into the results, and it will be up to the filtering algorithm (hand-waving) to provide the best threshold between static and dynamic fields, or some human post-processing. *The overall idea is probably a good one, but the actual implementation will definitely weigh in on the speed and efficiency of this algorithm. A: Thanks for all the great suggestions. Chris, is right. I am looking for a generic solution for normalizing any kind of text. The solution of the problem boils down to dynmamically finding patterns in two or more similar strings. Almost like predicting the next element in a set, based on the previous two: 1: Everest is 30000 feet high 2: K2 is 28000 feet high => What is the pattern? => Answer: [name] is [number] feet high Now the text file can have millions of lines and thousands of patterns. I would like to parse the files very, very fast, find the patterns and collect the data sets that are associated with each pattern. I thought about creating some high level semantic hashes to represent the patterns in the message strings. I would use a tokenizer and give each of the tokens types a specific "weight". Then I would group the hashes and rate their similarity. Once the grouping is done I would collect the data sets. I was hoping, that I didn't have to reinvent the wheel and could reuse something that is already out there. Klaus A: It depends on what you are trying to do, if your goal is to quickly generate sprintf() input, this works. If you are trying to parse data, maybe regular expressions would do too.. A: I think you might be overlooking and missed fscanf() and sscanf(). Which are the opposite of fprintf() and sprintf(). A: You're not going to find a tool that can simply take arbitrary input, guess what data you want from it, and produce the output you want. That sounds like strong AI to me. Producing something like this, even just to recognize numbers, gets really hairy. For example is "123.456" one number or two? How about this "123,456"? Is "35F" a decimal number and an 'F' or is it the hex value 0x35F? You're going to have to build something that will parse in the way you need. You can do this with regular expressions, or you can do it with sscanf, or you can do it some other way, but you're going to have to write something custom. However, with basic regular expressions, you can do this yourself. It won't be magic, but it's not that much work. Something like this will parse the lines you're interested in and consolidate them (Perl): my @vals = (); while (defined(my $line = <>)) { if ($line =~ /The temperature at P(\d*) is (\d*)F./) { push(@vals, "($1,$2)"); } } print "The temperature at P%d is %dF. {"; for (my $i = 0; $i < @vals; $i++) { print $vals[$i]; if ($i < @vals - 1) { print ","; } } print "}\n"; The output from this isL The temperature at P%d is %dF. {(1,35),(1,40),(3,35),(1,40)} You could do something similar for each type of line you need to parse. You could even read these regular expressions from a file, instead of custom coding each one. A: I don't know of any specific tool to do that. What I did when I had a similar problem to solve was trying to guess regular expressions to match lines. I then processed the files and displayed only the unmatched lines. If a line is unmatched, it means that the pattern is wrong and should be tweaked or another pattern should be added. After around an hour of work, I succeeded in finding the ~20 patterns to match 10000+ lines. In your case, you can first "guess" that one pattern is "The temperature at P[1-3] is [0-9]{2}F.". If you reprocess the file removing any matched line, it leaves "only": Logger stopped. Logger started. Which you can then match with "Logger (.+).". You can then refine the patterns and find new ones to match your whole log. A: @John: I think that the question relates to an algorithm that actually recognises patterns in log files and automatically "guesses" appropriate format strings and data for it. The *scanf family can't do that on its own, it can only be of help once the patterns have been recognised in the first place. A: @Derek Park: Well, even a strong AI couldn't be sure it had the right answer. Perhaps some compression-like mechanism could be used: *Find large, frequent substrings *Find large, frequent substring patterns. (i.e. [pattern:1] [junk] [pattern:2]) Another item to consider might be to group lines by edit-distance. Grouping similar lines should split the problem into one-pattern-per-group chunks. Actually, if you manage to write this, let the whole world know, I think a lot of us would like this tool! A: @Anders Well, even a strong AI couldn't be sure it had the right answer. I was thinking that sufficiently strong AI could usually figure out the right answer from the context. e.g. Strong AI could recognize that "35F" in this context is a temperature and not a hex number. There are definitely cases where even strong AI would be unable to answer. Those are the same cases where a human would be unable to answer, though (assuming very strong AI). Of course, it doesn't really matter, since we don't have strong AI. :) A: http://www.logparser.com forwards to an IIS forum which seems fairly active. This is the official site for Gabriele Giuseppini's "Log Parser Toolkit". While I have never actually used this tool, I did pick up a cheap copy of the book from Amazon Marketplace - today a copy is as low as $16. Nothing beats a dead-tree-interface for just flipping through pages. Glancing at this forum, I had not previously heard about the "New GUI tool for MS Log Parser, Log Parser Lizard" at http://www.lizardl.com/. The key issue of course is the complexity of your GRAMMAR. To use any kind of log-parser as the term is commonly used, you need to know exactly what you're scanning for, you can write a BNF for it. Many years ago I took a course based on Aho-and-Ullman's "Dragon Book", and the thoroughly understood LALR technology can give you optimal speed, provided of course that you have that CFG. On the other hand it does seem you're possibly reaching for something AI-like, which is a different order of complexity entirely.
{ "language": "en", "url": "https://stackoverflow.com/questions/9882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Check for hung Office process when using Office Automation Is there a way to check to see if an Microsoft Office process (i.e. Word, Excel) has hung when using Office Automation? Additionally, if the process is hung, is there a way to terminate it? A: Let me start off saying that I don't recommend doing this in a service on a server, but I'll do my best to answer the questions. Running as a service makes it difficult to clean up. For example with what you have running as a service survive killing a hung word or excel. You may be in a position to have to kill the service. Will your service stop if word or excel is in this state. One problem with trying to test if it is hung, is that your test could cause a new instance of word to startup and work, while the one that the service is running would still be hung. The best way to determine if it's hung is to ask it to do what it is supposed to be doing and check for the results. I would need to know more about what it is actually doing. Here are some commands to use in a batch file for cleaning up (both should be in the path): * *sc stop servicename - stops service named servicename *sc start servicename - starts service named servicename *sc query servicename - Queries the status of servicename *taskkill /F /IM excel.exe - terminates all instances of excel.exe A: I remember doing this a few years ago - so I'm talking Office XP or 2003 days, not 2007. Obviously a better solution for automation these days is to use the new XML format that describes docx etc using the System.IO.Packaging namespace. Back then, I used to notice that whenever MSWord had kicked the bucket and had had enough, a process called "Dr. Watson" was running on the machine. This was my first clue that Word had tripped and fallen over. Sometimes I might see more than one WINWORD.EXE, but my code just used to scan for the good Doctor. Once I saw that (in code), I killed all WINWORD.EXE processes the good Doctor himself, and restarted the process of torturing Word :-) Hope that gives you some clues as to what to look for. All the best, Rob G P.S. I might even be able to dig out the code in my archives if you don't come right! A: I can answer the latter half; if you have a reference to the application object in your code, you can simply call "Quit" on it: private Microsoft.Office.Interop.Excel.Application _excel; // ... do some stuff ... _excel.Quit(); For checking for a hung process, I'd guess you'd want to try to get some data from the application and see if you get results in a reasonable time frame (check in a timer or other thread or something). There's probably a better way though.
{ "language": "en", "url": "https://stackoverflow.com/questions/9905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Analyzing Multithreaded Programs We have a codebase that is several years old, and all the original developers are long gone. It uses many, many threads, but with no apparent design or common architectural principles. Every developer had his own style of multithreaded programming, so some threads communicate with one another using queues, some lock data with mutexes, some lock with semaphores, some use operating-system IPC mechanisms for intra-process communications. There is no design documentation, and comments are sparse. It's a mess, and it seems that whenever we try to refactor the code or add new functionality, we introduce deadlocks or other problems. So, does anyone know of any tools or techniques that would help to analyze and document all the interactions between threads? FWIW, the codebase is C++ on Linux, but I'd be interested to hear about tools for other environments. Update I appreciate the responses received so far, but I was hoping for something more sophisticated or systematic than advice that is essentially "add log messages, figure out what's going on, and fix it." There are lots of tools out there for analyzing and documenting control-flow in single-threaded programs; is there nothing available for multi-threaded programs? See also Debugging multithreaded applications A: Invest in a copy of Intel's VTune and its thread profiling tools. It will give you both a system and a source level view of the thread behaviour. It's certainly not going to autodocument the thing for you, but should be a real help in at least visualising what is happening in different circumstances. I think there is a trial version that you can download, so may be worth giving that a go. I've only used the Windows version, but looking at the VTune webpage it also has a Linux version. A: As a starting point, I'd be tempted to add tracing log messages at strategic points within your application. This will allow you to analyse how your threads are interacting with no danger that the act of observing the threads will change their behaviour (as could be the case with step-by-step debugging). My experience is with the .NET platform and my favoured logging tool would be log4net since it's free, has extensive configuration options and, if you're sensible in how you implement your logging, it won't noticeably hinder your application's performance. Alternatively, there is .NET's built in Debug (or Trace) class in the System.Diagnostics namespace. A: I'd focus on the shared memory locks first (the mutexes and semaphores) as they are most likely to cause issues. Look at which state is being protected by locks and then determine which state is under the protection of several locks. This will give you a sense of potential conflicts. Look at situations where code that holds a lock calls out to methods (don't forget virtual methods). Try to eliminate these calls where possible (by reducing the time the lock is held). Given the list of mutexes that are held and a rough idea of the state that they protect, assign a locking order (i.e., mutex A should always be taken before mutex B). Try to enforce this in the code. See if you can combine several locks into one if concurrency won't be adversely affected. For example, if mutex A and B seem like they might have deadlocks and an ordering scheme is not easily done, combine them to one lock initially. It's not going to be easy but I'm for simplifying the code at the expense of concurrency to get a handle of the problem. A: This a really hard problem for automated tools. You might want to look into model checking your code. Don't expect magical results: model checkers are very limited in the amount of code and the number of threads they can effectively check. A tool that might work for you is CHESS (although it is unfortunately Windows-only). BLAST is another fairly powerful tool, but is very difficult to use and may not handle C++. Wikipedia also lists StEAM, which I haven't heard of before, but sounds like it might work for you: StEAM is a model checker for C++. It detects deadlocks, segmentation faults, out of range variables and non-terminating loops. Alternatively, it would probably help a lot to try to converge the code towards a small number of well-defined (and, preferably, high-level) synchronization schemes. Mixing locks, semaphores, and monitors in the same code base is asking for trouble. A: One thing to keep in mind with using log4net or similar tool is that they change the timing of the application and can often hide the underlying race conditions. We had some poorly written code to debug and introduced logging and this actually removed race conditions and deadlocks (or greatly reduced their frequency). A: In Java, you have choices like FindBugs (for static bytecode analysis) to find certain kinds of inconsistent synchronization, or the many dynamic thread analyzers from companies like Coverity, JProbe, OptimizeIt, etc. A: Can't UML help you here ? If you reverse-engineer your codebase into UML, then you should be able to draw class diagrams that shows the relationships between your classes. Starting from the classes whose methods are the thread entry points, you could see which thread uses which class. Based on my experience with Rational Rose, this could be achieved using drag-and-drop ; if no relationship between the added class and the previous ones, then the added class is not directly used by the thread that started with the method you began the diagram with. This should gives you hints towards the role of each threads. This will also show the "data objects" that are shared and the objects that are thread-specific. If you draw a big class diagram and remove all the "data objects", then you should be able to layout that diagram as clouds, each clouds being a thread - or a group of threads, unless the coupling and cohesion of the code base is awful. This will only gives you one portion of the puzzle, but it could be helpful ; I just hope your codebase is not too muddy or too "procedural", in which case ...
{ "language": "en", "url": "https://stackoverflow.com/questions/9926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to setup Groovy + Eclipse + Junit4? I am working on a small webapp and I want to use Groovy to write some unit testing for my app. Most of my coding is done on Eclipse and I really want to run all the unit testing with the graphical test runner within Eclipse (I really like the green bar :) ) Sadly, after 4 hours of try-and-error, I'm still not able to setup properly. I tried to use the Eclipse Junit4 test runner to run a Groovy file with method annotated for testing using @Test. But it keeps complaining NoClassDefFoundException Anyone can help? Here is content of my groovy file, named simpleTest.groovy import org.junit.Test import static org.junit.Assert.assertEquals class simpleTest{ @Test void trial(){ assertEquals 6, 3+3 } } Anyone can help? A: You might want to give the updated plugin a try, see the the recent blog post for more details. The theme of this alpha release is providing an optimized edit/save/compile/test experience, which seems to be your exact use case. A: I have this working in my environment so here is a brief summary of what I have: In the run dialog under JUnit: * *Test Tab: The test class, this must have already been compiled by the Groovy plugin. *Classpath: All of the Jar files from my project as well as the Groovy Libraries library In Window->Preferences->Java->Build Path * *Classpath Variables: GROOVY_ECLIPSE_HOME = the location where the Groovy plugin is installed That does the trick for me. A: Unfortunately, the Groovy Eclipse plugin is pretty horrible at giving actual helpful information to let you know what is going wrong with your setup. I'm going to assume you already did the verification to make sure the plugin is actually building your Groovy files (i.e. doing a sample with no dependencies, checking the properly output directory, etc...) After that, it's a lot of really small configuration verification...I've run into problems where the particular "runner" I'm using in Eclipse (i.e. in the Run menu) doesn't have the write class name defined there or for some reason my project didn't get the JUnit library dependency properly inserted into it. Ultimately, it can be a configuration headache, but long term you'll end up saving some time and gaining some cool functionality if you can knock it out... A: I had faced a similar issue and it was the missing package statement that caused me to have problems. Groovy Eclipse plugin did not complain about it but my class was present in a package. I got the noClassDefError when running the file as a JUnit Test. Adding the package statement to top of class solved this issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/9928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What is a good way to open large files across a WAN? I have an application deployed into multiple zones and there are some issues with opening larger documents (20-50MB) across the WAN. Currently the documents are stored in Zone 1 (Americas) and a link stored in the database to the docs. I have heard some things about blobs in oracle and store binary in MS SQL Server 2005 and then perhaps copying the database to other zones. Any other suggestions or good results with one of the described options? A: Your best option here may be caching the document in the requested zone the first time it is requested, and pinging the source document's last modified each time the cached document is requested in order to determine if it needs refreshed. In this case you're only requesting a small piece of information (a date) across the WAN most of the times the document is accessed. This works best for a subset of documents that are frequently requested. If you have a large set of documents, each infrequently requested by a disparate group, then you may want to look into replicating the documents in each of your zones each time the master is updated. This may best be accomplished by storing the document as binary data in your master database and having the slaves pull from the master. A: If you're running on Windows you could look at Distributed File Systems
{ "language": "en", "url": "https://stackoverflow.com/questions/9932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generic iterator I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list. The custom list defines an iterator; class Iterator: public std::iterator<std::forward_iterator_tag, T> { // ... } Iterator begin() { return (Iterator(root)); } Iterator end() { return (Iterator(NULL)); } with the appropriate operators overloaded. Ideally, I would like to do this; class Foo { public: Foo() { std::list<int> x; std::vector<int> y; custom_list<int> z; iter = x.begin(); // OR iter = y.begin(); // OR iter = z.begin(); // ... }; private: std::iterator<int> iter; }; But obviously these are all iterators of different types. I can assume all the containers are of the same type however. Is there an elegant way to solve this problem? A: Here are some articles you might find of interest Giving STL Iterators a Base Class Type Erasure for C++ Iterators any_iterator Class Reference A: Better late than never... The latest issue of C-Vu turned up and guess what was in it: That's right, iterators that do exactly what you wanted. Unfortunately you need to become a member of the ACCU to view the magazine (the article references the Overload article from 2000 that David links to). But for a measly price a year you get a nice magazine to read, conferences and user groups. When you become a member you can view PDF's of the back issues so what are you waiting for? A: A case of being careful what you ask for. The any_iterator classes you see work on an unbounded set of iterator types. You only have three, which you know up front. Sure, you might need to add a fourth type in the future, but so what if that takes O(1) extra lines of code ? The big advantage of a closed set of possible contained types is that you have an upper bound on sizeof(), which means you can avoid the heap and the indirection it brings. Basically, stuff them all in a boost::variant and call apply_visitor.
{ "language": "en", "url": "https://stackoverflow.com/questions/9938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Query times out from web app but runs fine from management studio This is a question I asked on another forum which received some decent answers, but I wanted to see if anyone here has more insight. The problem is that you have one of your pages in a web application timing out when it gets to a stored procedure call, so you use Sql Profiler, or your application trace logs, to find the query and you paste it into management studio to figure our why it's running slow. But you run it from there and it just blazes along, returning in less than a second each time. My particular case was using ASP.NET 2.0 and Sql Server 2005, but I think the problem could apply to any RDBMS system. A: I've had similar problems. Try setting the with "WITH RECOMPILE" option on the sproc create to force the system to recompute the execution plan each time it is called. Sometimes the Query processor gets confused in complex stored procedures with lots of branching or case statements and just pulls a really sub-optimal execution plan. If that seems to "fix" the problem, you will probably need to verify statistics are up to date and/or break down the sproc. You can also confirm this by profiling the sproc. When you execute it from SQL Managment Studio, how does the IO compare to when you profile it from the ASP.NET application. If they very a lot, it just re-enforces that its pulling a bad execution plan. A: This is what I've learned so far from my research. .NET sends in connection settings that are not the same as what you get when you log in to management studio. Here is what you see if you sniff the connection with Sql Profiler: -- network protocol: TCP/IP set quoted_identifier off set arithabort off set numeric_roundabort off set ansi_warnings on set ansi_padding on set ansi_nulls off set concat_null_yields_null on set cursor_close_on_commit off set implicit_transactions off set language us_english set dateformat mdy set datefirst 7 set transaction isolation level read committed I am now pasting those setting in above every query that I run when logged in to sql server, to make sure the settings are the same. For this case, I tried each setting individually, after disconnecting and reconnecting, and found that changing arithabort from off to on reduced the problem query from 90 seconds to 1 second. The most probable explanation is related to parameter sniffing, which is a technique Sql Server uses to pick what it thinks is the most effective query plan. When you change one of the connection settings, the query optimizer might choose a different plan, and in this case, it apparently chose a bad one. But I'm not totally convinced of this. I have tried comparing the actual query plans after changing this setting and I have yet to see the diff show any changes. Is there something else about the arithabort setting that might cause a query to run slowly in some cases? The solution seemed simple: Just put set arithabort on into the top of the stored procedure. But this could lead to the opposite problem: change the query parameters and suddenly it runs faster with 'off' than 'on'. For the time being I am running the procedure 'with recompile' to make sure the plan gets regenerated each time. It's Ok for this particular report, since it takes maybe a second to recompile, and this isn't too noticeable on a report that takes 1-10 seconds to return (it's a monster). But it's not an option for other queries that run much more frequently and need to return as quickly as possible, in just a few milliseconds. A: Have you turned on ASP.NET tracing yet? I've had an instance where it wasn't the SQL stored procedure itself that was the problem, it was the fact that the procedure returned 5000 rows and the app was attempting to create databound ListItems with those 5000 items that was causing the problem. You might look into the execution times between the web app functions as well through the trace to help track things down. A: Same problem I had with SQL reporting services. Try to check type of variables, I was sending different type of variable to SQL like sending varchar in place where it should be integer, or something like that. After I synchronized the types of variables in Reporting Service and in stored procedure on SQL, I solved the problem. A: test this out on a staging box first, change it on a server level for sql server declare @option int set @option = @@options | 64 exec sp_configure 'user options', @option RECONFIGURE A: You could try using the sp_who2 command to see what process in question is doing. This will show you if it's blocked by another process, or using up an excessive amount of cpu and/or io time. A: We had the same issue and here's what we found out. our database log size was being kept at the default (814 MB) and auto growth was 10%. On the server, maximum server memory was kept at the default setting as well (2147483647 MB). When our log got full and needed to grow, it used all the memory from the server and there's nothing left for code to be run so it timed out. What we ended up doing was set database log file initial size to 1 MB and maximum server memory to 2048 MB. This instantly fixed our problem. Of course, you can change these two properties to fit your need but this is an idea for someone running into the timing out issue when executing a stored procedure via code but it runs super fast in SSMS and the solutions above do not help. A: Try changing the SelectCommand timeout value: DataAdapter.SelectCommand.CommandTimeout = 120;
{ "language": "en", "url": "https://stackoverflow.com/questions/9974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: What do you look for from a User Group? I'm in the process of starting a User Group in my area related to .NET development. The format of the community will be the average free food, presentation, and then maybe free swag giveaway. What would you, as a member of a user community, look for in order to keep you coming back month to month? A: I always like talks on different subjects. The real hard thing about talking to a specialized community is keeping the detail level high and the scope narrow. What's the point of talking to a bunch of .NET programmers about the benefits of Polymorphism? It always kills me when I go to a meeting on a particular subject and get the most rudimentary explanation and examples. Its a waste of time. MSDN webcasts have a level system that describes the complexity of the subject. Most are level 100 or 200. If you're dealing with a group of professionals, your talks should always be at level 600-1000. In addition to talking about technical subjects, another big area to hit is professional development. How do you make yourself a more valuable programmer? These types of talks are great for bringing in other people, such as management, sales, customers, etc. People who you normally only associate with under protest, and who you typically curse under your breath when they walk by. A user group forum is a great way to bring these people together with developers in a pseudo-group therapy like setting. Also, donuts. A: It's true that some of the talks out there are very rudimentary, unfortunately some times the bulk of your crowd may need that. I consider myself a novice in a lot of fields, but I've attend talks that I thought were beneath me and still people were asking very basic questions. Perhaps it would be worth having a bi-monthly user group, one week for entry level and one week for advanced. It doesn't necessarily have to mean twice the work if you can get someone to help you coordinate a lot of the work will overlap. On the other hand you might just need to feel out the members of the group and see what their average skill level is and play to that. A: If there isn't beer, its not a good enough user group to attend. The open source guys get this. Their user group meetings are funner, and more dynamic because of this. Just make it BYOB and it'll naturally get better in my experience.
{ "language": "en", "url": "https://stackoverflow.com/questions/9977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the easiest way to add compression to WCF in Silverlight? I have a silverlight 2 beta 2 application that accesses a WCF web service. Because of this, it currently can only use basicHttp binding. The webservice will return fairly large amounts of XML data. This seems fairly wasteful from a bandwidth usage standpoint as the response, if zipped, would be smaller by a factor of 5 (I actually pasted the response into a txt file and zipped it.). The request does have the "Accept-Encoding: gzip, deflate" - Is there any way have the WCF service gzip (or otherwise compress) the response? I did find this link but it sure seems a bit complex for functionality that should be handled out-of-the-box IMHO. OK - at first I marked the solution using the System.IO.Compression as the answer as I could never "seem" to get the IIS7 dynamic compression to work. Well, as it turns out: * *Dynamic Compression on IIS7 was working al along. It is just that Nikhil's Web Developer Helper plugin for IE did not show it working. My guess is that since SL hands the web service call off to the browser, that the browser handles it "under the covers" and Nikhil's tool never sees the compressed response. I was able to confirm this by using Fiddler which monitors traffic external to the browser application. In fiddler, the response was, in fact, gzip compressed!! *The other problem with the System.IO.Compression solution is that System.IO.Compression does not exist in the Silverlight CLR. So from my perspective, the EASIEST way to enable WCF compression in Silverlight is to enable Dynamic Compression in IIS7 and write no code at all. A: It should also be noted that you may need to add the mime type to applicationHost.config under <httpCompression><dynamicTypes> section in addition to enabling compression for the site: <add mimeType="application/soap+msbin1" enabled="true" /> If certain dynamic responses are not being compressed (and some are) it could be a mime type issue. Use Fiddler to get the specifics associated with the request. Failed request tracing may be useful in determining whether or not IIS is even attempting to compression the response. If compression is correctly configured you will see a NO_MATCHING_CONTENT_TYPE in the complete trace section of the trace output. A: WS-Compression for WCF allows you to configure compression on the binding. See WS-Compression for WCF by Pablo M. Cibraro Alternatively, try Microsofts GZip Encoder Sample which "creates an encoder channel that uses the System.IO.Compression.GZipStream class to compress outgoing WCF messages" A: I didn't see a native way for WCF to do compression when doing a WCF project recently. I just used the System.IO.Compression namespace and made a quick compressor. Here's the code i used public static class CompressedSerializer { /// <summary> /// Decompresses the specified compressed data. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="compressedData">The compressed data.</param> /// <returns></returns> public static T Decompress<T>(byte[] compressedData) where T : class { T result = null; using (MemoryStream memory = new MemoryStream()) { memory.Write(compressedData, 0, compressedData.Length); memory.Position = 0L; using (GZipStream zip= new GZipStream(memory, CompressionMode.Decompress, true)) { zip.Flush(); var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); result = formatter.Deserialize(zip) as T; } } return result; } /// <summary> /// Compresses the specified data. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data">The data.</param> /// <returns></returns> public static byte[] Compress<T>(T data) { byte[] result = null; using (MemoryStream memory = new MemoryStream()) { using (GZipStream zip= new GZipStream(memory, CompressionMode.Compress, true)) { var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(zip, data); } result = memory.ToArray(); } return result; } } then i just had my services take in a byte array as an input, like such void ReceiveData(byte[] data); Worked out well for me. A: If you are using IIS7, take a look at the Compression Module. This allows you to configure compression for HTTP requests to your server.
{ "language": "en", "url": "https://stackoverflow.com/questions/10006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Animation in javascript, a starting point I understand how JS is run and I think I understand most of the DOM but I've no idea about animation. Does anybody here know of a good guide that can explain to me how it's done in Javascript? In addition, should I even consider Javascript for animation? Should I instead be looking to learn flash? A: Avoid flash, its a horrible requirement, uncrawlable by Google, unsopported by a bunch of browsers and systems (eg iPhone) and most importantly: it forces you to reinvent web standards (e.g. scroll bars and whatnot), Javascript on the other hand is easier to maintain and code for in the noscript case. try scriptaculous for your animations; * *here's a quickie 3-line tutorial so you can see it working *here's a more complete tutorial *here's the scriptaculous wiki note that there are a gazillion JS animation libraries, some really good jQuery comes to mind. Usually they're just a script tag and an onclick event to setup. Good luck! /mp A: if your animation is simple, change colors over time, move from x to y in 3 seconds. Javascript is fine. If you want all kinds of wizbang buttons and coordinated rotation of the screen, straight up js + dhtml will be clunky at best. Silverlight vs Flash are you questions at that point. Interestingly enough, you program Silverlight with javascript, and that would be the major benefit to simply upgrading to a faster and more dynamic DOM that is implemented in Silverlight but still writing the same code. Flash programmability is very limited in my experience, you can do anything, but it will be slow and take thousands of lines of code to get there. For simple JS animations look at jQuery or Scriptaculous. A: Check out a JS animation framework like Bernard Sumption's Animator.js. It's pretty light-weight and has some excellent examples. Personally, I wouldn't be animating things in JS. Flash FTW. A: If you aren't concerned with IE support, you could also try experimenting with the canvas element: MOZILLA DEVELOPER NETWORK Basic animations
{ "language": "en", "url": "https://stackoverflow.com/questions/10038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do I create a Linked List Data Structure in Java? What's the best way to make a linked list in Java? A: //slightly improved code without using collection framework package com.test; public class TestClass { private static Link last; private static Link first; public static void main(String[] args) { //Inserting for(int i=0;i<5;i++){ Link.insert(i+5); } Link.printList(); //Deleting Link.deletefromFirst(); Link.printList(); } protected static class Link { private int data; private Link nextlink; public Link(int d1) { this.data = d1; } public static void insert(int d1) { Link a = new Link(d1); a.nextlink = null; if (first != null) { last.nextlink = a; last = a; } else { first = a; last = a; } System.out.println("Inserted -:"+d1); } public static void deletefromFirst() { if(null!=first) { System.out.println("Deleting -:"+first.data); first = first.nextlink; } else{ System.out.println("No elements in Linked List"); } } public static void printList() { System.out.println("Elements in the list are"); System.out.println("-------------------------"); Link temp = first; while (temp != null) { System.out.println(temp.data); temp = temp.nextlink; } } } } A: Java has a LinkedList implementation, that you might wanna check out. You can download the JDK and it's sources at java.sun.com. A: The obvious solution to developers familiar to Java is to use the LinkedList class already provided in java.util. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. Enhancements to this implementation include making it a double-linked list, adding methods to insert and delete from the middle or end, and by adding get and sort methods as well. Note: In the example, the Link object doesn't actually contain another Link object - nextLink is actually only a reference to another link. class Link { public int data1; public double data2; public Link nextLink; //Link constructor public Link(int d1, double d2) { data1 = d1; data2 = d2; } //Print Link data public void printLink() { System.out.print("{" + data1 + ", " + data2 + "} "); } } class LinkList { private Link first; //LinkList constructor public LinkList() { first = null; } //Returns true if list is empty public boolean isEmpty() { return first == null; } //Inserts a new Link at the first of the list public void insert(int d1, double d2) { Link link = new Link(d1, d2); link.nextLink = first; first = link; } //Deletes the link at the first of the list public Link delete() { Link temp = first; if(first == null){ return null; //throw new NoSuchElementException(); // this is the better way. } first = first.nextLink; return temp; } //Prints list data public void printList() { Link currentLink = first; System.out.print("List: "); while(currentLink != null) { currentLink.printLink(); currentLink = currentLink.nextLink; } System.out.println(""); } } class LinkListTest { public static void main(String[] args) { LinkList list = new LinkList(); list.insert(1, 1.01); list.insert(2, 2.02); list.insert(3, 3.03); list.insert(4, 4.04); list.insert(5, 5.05); list.printList(); while(!list.isEmpty()) { Link deletedLink = list.delete(); System.out.print("deleted: "); deletedLink.printLink(); System.out.println(""); } list.printList(); } } A: Use java.util.LinkedList. Like this: list = new java.util.LinkedList() A: The above linked list display in opposite direction. I think the correct implementation of insert method should be public void insert(int d1, double d2) { Link link = new Link(d1, d2); if(first==null){ link.nextLink = null; first = link; last=link; } else{ last.nextLink=link; link.nextLink=null; last=link; } } A: Its much better to use java.util.LinkedList, because it's probably much more optimized, than the one that you will write.
{ "language": "en", "url": "https://stackoverflow.com/questions/10042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "136" }
Q: .NET: How do I find the Desktop path when Folder Redirection is on? I have been using Environment.GetFolderPath(Environment.SpecialFolder.Desktop) to get the path to the user's desktop for ages now, but since we changed our setup here at work so we use Folder Redirection to map our users' Desktop and My Documents folders to the server, it no-longer works. It still points to the Desktop folder in C:\Documents and Settings, which is not where my desktop lives. Any ideas on how to fix this? Burns A: You need to use the DesktopDirectory special folder instead: Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) should give you the redirected directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/10043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Removing icon from Windows title bars without ditching close button or system menu? I'm developing an MFC application and I've recently been searching for a good method to remove the icon from a Windows title bar, but retain the close button. The two obvious candidate solutions are turning off the system menu style or using the tool window style, but I would prefer not to disable the system menu or use the shrunken tool window title bar. Many MFC applications have this functionality, so I wonder: am I missing some standard way of doing this? A: Set WS_EX_DLGMODALFRAME extended style. A: You can use WM_NCRBUTTONDOWN to detect if the user has right-clicked on your caption and then bring up the system menu. A: You could use a fully transparent icon. A: what about getting rid of the system menu and then putting it back in another place yourseld (say next to the close button etc.)? A: Without the icon, the only method I could imagine for users to access the system menu is via right-click of the titlebar. If that's what you had in mind, you could handle WM_RBUTTONDOWN on your main frame and then calculate if the right-click was on the titlebar. int clickX = GET_X_LPARAM(lParam); int clickY = GET_Y_LPARAM(lParam); CRect frameRect; mainFrame.GetWindowRect(&frameRect); int titleBarHeight = GetSystemMetrics(SM_CYCAPTION); if (clickX >= frameRect.left && clickX <= frameRect.right && clickY >= frameRect.top && clickY <= frameRect.top + titleBarHeight) { TrackPopupMenu(m_systemMenu); } A: A sample code in Delphi which removes icon: const WM_ResetIcon = WM_APP - 1; type TForm1 = class(TForm) procedure FormShow(Sender: TObject); protected procedure WMResetIcon(var Message: TMessage); message WM_ResetIcon; end; implementation procedure TForm1.FormShow(Sender: TObject); begin PostMessage(Handle, WM_ResetIcon, 0, 0); end; procedure TForm1.WMResetIcon(var Message: TMessage); const ICON_SMALL = 0; ICON_BIG = 1; begin DestroyIcon(SendMessage(Handle, WM_SETICON, ICON_BIG, 0)); DestroyIcon(SendMessage(Handle, WM_SETICON, ICON_SMALL, 0)); end; A similar code should work for MFC. Basically, you just need to WM_SETICON to NULL in the right place.
{ "language": "en", "url": "https://stackoverflow.com/questions/10059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: looking for a GPS with a good API I'm looking for a GPS with a good API. I would like to be able to send an address to it, and tell it to navigate to that address. I also need to pull the current location from the GPS. I'd like to be able to do this with the GPS hooked up to a laptop by bluetooth or even just a USB cable. I've looked at the Dash a little, but the monthly subscription is a downside. Also, I would like to keep the location and addresses on our private network. I'm a .NET programmer, so a .NET friendly API is best for me. Bonus points if you can show me some examples of using an API to push and pull data to and from the GPS. A: If you want to talk to a Garmin GPS, you can check out their developer website. They've got resources ranging from talking to Web Services all the way to doing low-level Serial & USB I/O to interface directly with the devices. A: What about using a GPS enabled phone running WM? I have the Motorola Q9c. I'm working on a GPS Data Logger so I can map my flights. The windows mobile SDK has a great C# sample to work with. A: GPS Devices normally don't normally provide turn-by-turn information. Almost all GPS devices (internal, linked via bluetooth or whatever) conform to the NMEA standard, which simply provides a latitude, longitude and elevation encapsulated in a simple text-based protocol. Almost all of these communicate over a simple serial port, which you can get access to in about 4 lines of code using .NET. Turn-By-Turn directions are computed by the device which the GPS is attached to - your PDA, Phone or computer. If there's an internet connection available, the Google Maps or Windows Live Local APIs are really easy to use (especially from .NET using a WebRequest or Sockets) and would probably be the best solution to your problem! A: I presume that by GPS you mean Satellite Navigation? Most GPS units don't offer the turn-by-turn capability required to navigate effectively on roads, or the underlying road map data for that matter. updated: OK, since Garmin are by far the biggest dog in the yard, I'd recommend taking a look at Garmin's Location Based Services Toolkit, Fleet Management Toolkit and their Communicator API (specifically the DeviceControl module). A: Have a peek at routes.tomtom.com, they can send addresses to a TomTom. (Warning: patent pending !)
{ "language": "en", "url": "https://stackoverflow.com/questions/10061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Compact Framework/Threading - MessageBox displays over other controls after option is chosen I'm working on an app that grabs and installs a bunch of updates off an an external server, and need some help with threading. The user follows this process: * *Clicks button *Method checks for updates, count is returned. *If greater than 0, then ask the user if they want to install using MessageBox.Show(). *If yes, it runs through a loop and call BeginInvoke() on the run() method of each update to run it in the background. *My update class has some events that are used to update a progress bar etc. The progress bar updates are fine, but the MessageBox is not fully cleared from the screen because the update loop starts right after the user clicks yes (see screenshot below). * *What should I do to make the messagebox disappear instantly before the update loop starts? *Should I be using Threads instead of BeginInvoke()? *Should I be doing the initial update check on a separate thread and calling MessageBox.Show() from that thread? Code // Button clicked event handler code... DialogResult dlgRes = MessageBox.Show( string.Format("There are {0} updates available.\n\nInstall these now?", um2.Updates.Count), "Updates Available", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2 ); if (dlgRes == DialogResult.Yes) { ProcessAllUpdates(um2); } // Processes a bunch of items in a loop private void ProcessAllUpdates(UpdateManager2 um2) { for (int i = 0; i < um2.Updates.Count; i++) { Update2 update = um2.Updates[i]; ProcessSingleUpdate(update); int percentComplete = Utilities.CalculatePercentCompleted(i, um2.Updates.Count); UpdateOverallProgress(percentComplete); } } // Process a single update with IAsyncResult private void ProcessSingleUpdate(Update2 update) { update.Action.OnStart += Action_OnStart; update.Action.OnProgress += Action_OnProgress; update.Action.OnCompletion += Action_OnCompletion; //synchronous //update.Action.Run(); // async IAsyncResult ar = this.BeginInvoke((MethodInvoker)delegate() { update.Action.Run(); }); } Screenshot A: Your UI isn't updating because all the work is happening in the user interface thread. Your call to: this.BeginInvoke((MethodInvoker)delegate() {update.Action.Run(); }) is saying invoke update.Action.Run() on the thread that created "this" (your form), which is the user interface thread. Application.DoEvents() will indeed give the UI thread the chance to redraw the screen, but I'd be tempted to create new delegate, and call BeginInvoke on that. This will execute the update.Action.Run() function on a seperate thread allocated from the thread pool. You can then keep checking the IAsyncResult until the update is complete, querying the update object for its progress after every check (because you can't have the other thread update the progress bar/UI), then calling Application.DoEvents(). You also are supposed to call EndInvoke() afterwards otherwise you may end up leaking resources I would also be tempted to put a cancel button on the progress dialog, and add a timeout, otherwise if the update gets stuck (or takes too long) then your application will have locked up forever. A: Have you tried putting a Application.DoEvents() in here if (dlgRes == DialogResult.Yes) { Application.DoEvents(); ProcessAllUpdates(um2); } A: @ John Sibly You can get away with not calling EndInvoke when dealing with WinForms without any negative consequences. The only documented exception to the rule that I'm aware of is in Windows Forms, where you are officially allowed to call Control.BeginInvoke without bothering to call Control.EndInvoke. However in all other cases when dealing with the Begin/End Async pattern you should assume it will leak, as you stated.
{ "language": "en", "url": "https://stackoverflow.com/questions/10071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Personalized icon next to the URL address in the browser's address bar? How do I write code where a company icon appears on the left side next to the URL address in the browser's address bar? A: You are looking for a Favicon. A: it loads www.whateveryouron.com/favicon.ico if your domain is robermyers.com, just put a favicon.ico 16px icon thats accessible, and you're in like flint. just try this googles or stackoverflows A: You need to create a favicon. The favicon uses a standard (in Windows, at least) .ico file. If you have a logo, you can convert it at sites like http://www.favicongenerator.com/ In the <head> of your html page, use the <link> tag to define the location of the favicon like this: <link type="image/x-icon" rel="shortcut icon" href="favicon.ico" /> You may need to refresh the page for the icon to display. A: load a file on the webserver called favicon.ico A: In modern browsers other fileformats than .ico works aswell. You can even put animated gif's in there! A: DynamicDrive has an easy favicon maker too. Different pages/directories can also call a different .ico with code similar to y0mbo's example (this is what Mint uses): <link href="sc/ph645.43/images/icons/mint.ico" rel="icon" type="text/x-icon" /> This is a good article on favicons in detail. I suspect animated favicons have the potential to go the way of the blink tag. Mint is using theirs to match their overall design, if you visit in FF3, you'll see that it matches the green color that FF uses to designate a recognized SSL cert.
{ "language": "en", "url": "https://stackoverflow.com/questions/10072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: better command for Windows? While I grew up using MSWindows, I transitioned to my much-loved Mac years ago. I don't want to start a flame war here on operating systems. I do, however, want a terminal a litle closer to what I'm used to. I'm not asking for full POSIX support - I don't have the patience to install Cygwin - but I miss tabbed terminals, being able to easily cut and paste, and my good friends ls, mkdir, rm, et al. (For these last ones, I could always put .bat files on my path, but that's going to get old fast.) Anybody have a terminal application for MSWindows XP ? A: I'm using powershell, its awesome to keep you from going crazy, and it has rm and mkdir and ls. Tabbed terminals is still not in powershell, and copy paste is similar to cmd, but its way better than cmd.exe. A: Some more options: MSYS: a Minimal SYStem providing a POSIX compatible Bourne shell environment, with a small collection of UNIX command line tools. Primarily developed as a means to execute the configure scripts and Makefiles used to build Open Source software, but also useful as a general purpose command line interface to replace Windows cmd.exe. GNU utilities for Win32: ports of common GNU utilities to native Win32. In this context, native means the executables do only depend on the Microsoft C-runtime (msvcrt.dll) and not an emulation layer like that provided by Cygwin tools. A: PowerCmd is great, with a ton of features including tabs, cut/copy/past, etc. Console is also a great replacement and is a bit more stripped down than PowerCmd (which can sometimes be a little too feature rich. Also, with both of these, if you have powershell installed, it is possible to run powershell from withing either. A: If you are a bit of a Pythonista then iPython is tough to beat. It has some of the more common shell commands coded in (i.e. ls, pwd, cd etc.), can also run any other shell command by prefixing with '!' (i.e. !latex file.tex) but also is a full Python shell with history, tab-complete, multiline editor support, logging etc. etc. Moreover, you can install iPython back on your UNIX boxes as well as Windows meaning your environment can follow wherever you go. A: There is a new-ish open source Console Emulator called cmder. It looks really nice and has some advanced features that make it nicer to use. You can also use powershell with it. Best of all, it's portable! A: I've never found anything I like more than Cygwin. I also went ahead and installed Cygwin/X w/ Openbox so I can get something like this: It's got multiple workspaces inside the main Openbox window so I can easily have up to 20 non-overlapping xterms that I can easily cycle through. A: I know you said you don't want to install anything, but I strongly suggest you give Services For Unix a shot: http://technet.microsoft.com/en-us/interopmigration/bb380242.aspx A: I use Console with unxutils Console for the tabs and easier to manage select/copy/paste unxutils for ls, rm, grep, uniq, sort ... and other goodness. A: PowerShell is amazing, however for anything other than the most basic commands there is a learning curve when switching from bash etc. I went back to using cygwin. A: PowerShell is worth looking into.
{ "language": "en", "url": "https://stackoverflow.com/questions/10083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Where is TFS work item help text displayed? I'm creating some custom work items in TFS and the helptext field seems handy but I don't see where it is being displayed in Team Explorer or Team System Web Access. Where is this information displayed? A: When you hover over the type of the field. For instance create a new bug and hover over the "rank" and you should see "Stack rank used to prioritize work"
{ "language": "en", "url": "https://stackoverflow.com/questions/10088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best mock framework that can do both WebForms and MVC? I'm getting into more of a TDD workflow, and have a mix of MVC and asp.net Web Forms apps. MOQ is recommended for MVC. I've used Rhino for Web Forms. Does anyone have a best practice for having 1 framework mock for both? A: This is sort of a silly question, but I prefer Rhino Mocks as it represents a more complete understanding of mocks vs. stubs. Look deep into TypeMock before committing to the price. Also, there is no recommended mocking framework for ASP.NET MVC. Finally - I'd suggest you stick to one mocking framework in your project (and even in your team) - the differences, while not huge, can lead to confusion that is unwarranted on such a "polishing-the-rock" decision. By that I mean the decision should not be a long one, just pick what works and get on with creating value. A: Rhino's latest release includes much of the sweet sweet 3.5 love that MoQ has. I'm a fan of MoQ, so that's what I'm using. But I also have Rhino, in case it does something that MoQ doesn't do. TL;DR: MoQ it baby. A: TypeMock is insanely powerful. When I needed to unit test a web forms app that wasn't designed for testability TypeMock saved my life. But when I take the time to pick an architectural pattern (MVC) or design one that allows for Mockability (you know, public virtualize state changing methods) I use Moq. It is so simple to use and so simple to teach others. TypeMock's record replay syntax still confuses me, but it saved me plenty of time in a tight release schedule. Moq's API is almost self explanatory which is an amazing achievement given the mock library history. A: I would just go ahead and use my favourite framework for both. I don't think there's any reason that I would choose one framework for web forms and another for MVC. A far bigger problem is how I would unit test my web forms pages at all, since it's notoriously hard to seperate the page from the rest of the HttpRequest stack. My favourite is Moq. I've also used TypeMock. It costs money, but it's really powerful - it lets you mock concrete classes and constructors, so you could potentially mock things like HttpContext or HttpRequest. A: Look into Ivonna for faking HTTPContext and traditional webforms. http://sm-art.biz/Ivonna.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/10098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I treat an integer as an array of bytes in Python? I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs: a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet: (pid,status) = os.wait() (exitstatus, signum) = decode(status) A: You can get break your int into a string of unsigned bytes with the struct module: import struct i = 3235830701 # 0xC0DEDBAD s = struct.pack(">L", i) # ">" = Big-endian, "<" = Little-endian print s # '\xc0\xde\xdb\xad' print s[0] # '\xc0' print ord(s[0]) # 192 (which is 0xC0) If you couple this with the array module you can do this more conveniently: import struct i = 3235830701 # 0xC0DEDBAD s = struct.pack(">L", i) # ">" = Big-endian, "<" = Little-endian import array a = array.array("B") # B: Unsigned bytes a.fromstring(s) print a # array('B', [192, 222, 219, 173]) A: exitstatus, signum= divmod(status, 256) A: This will do what you want: signum = status & 0xff exitstatus = (status & 0xff00) >> 8 A: To answer your general question, you can use bit manipulation pid, status = os.wait() exitstatus, signum = status & 0xFF, (status & 0xFF00) >> 8 However, there are also built-in functions for interpreting exit status values: pid, status = os.wait() exitstatus, signum = os.WEXITSTATUS( status ), os.WTERMSIG( status ) See also: * *os.WCOREDUMP() *os.WIFCONTINUED() *os.WIFSTOPPED() *os.WIFSIGNALED() *os.WIFEXITED() *os.WSTOPSIG() A: You can unpack the status using bit-shifting and masking operators. low = status & 0x00FF high = (status & 0xFF00) >> 8 I'm not a Python programmer, so I hope got the syntax correct. A: The folks before me've nailed it, but if you really want it on one line, you can do this: (signum, exitstatus) = (status & 0xFF, (status >> 8) & 0xFF) EDIT: Had it backwards. A: import amp as amp import status signum = status &amp; 0xff exitstatus = (status &amp; 0xff00) &gt;&gt; 8
{ "language": "en", "url": "https://stackoverflow.com/questions/10123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How do I bind a regular expression to a key combination in emacs? For context, I am something of an emacs newbie. I haven't used it for very long, but have been using it more and more (I like it a lot). Also I'm comfortable with lisp, but not super familiar with elisp. What I need to do is bind a regular expression to a keyboard combination because I use this particular regex so often. What I've been doing: M-C-s ^.*Table\(\(.*\n\)*?GO\) Note, I used newline above, but I've found that for isearch-forward-regexp, you really need to replace the \n in the regular expression with the result of C-q Q-j. This inserts a literal newline (without ending the command) enabling me to put a newline into the expression and match across lines. How can I bind this to a key combination? I vaguely understand that I need to create an elisp function which executes isearch-forward-regexp with the expression, but I'm fuzzy on the details. I've searched google and found most documentation to be a tad confusing. How can I bind a regular expression to a key combination in emacs? Mike Stone had the best answer so far -- not exactly what I was looking for but it worked for what I needed Edit - this sort of worked, but after storing the macro, when I went back to use it later, I couldn't use it with C-x e. (i.e., if I reboot emacs and then type M-x macro-name, and then C-x e, I get a message in the minibuffer like 'no last kbd macro' or something similar) @Mike Stone - Thanks for the information. I tried creating a macro like so: C-x( M-C-s ^.*Table\(\(.*C-q C-J\)*?GO\) C-x) This created my macro, but when I executed my macro I didn't get the same highlighting that I ordinarily get when I use isearch-forward-regexp. Instead it just jumped to the end of the next match of the expression. So that doesn't really work for what I need. Any ideas? Edit: It looks like I can use macros to do what I want, I just have to think outside the box of isearch-forward-regexp. I'll try what you suggested. A: You can use macros, just do C-x ( then do everything for the macro, then C-x ) to end the macro, then C-x e will execute the last defined macro. Then, you can name it using M-x name-last-kbd-macro which lets you assign a name to it, which you can then invoke with M-x TESTIT, then store the definition using M-x insert-kbd-macro which will put the macro into your current buffer, and then you can store it in your .emacs file. Example: C-x( abc *return* C-x) Will define a macro to type "abc" and press return. C-xeee Executes the above macro immediately, 3 times (first e executes it, then following 2 e's will execute it twice more). M-x name-last-kbd-macro testit Names the macro to "testit" M-x testit Executes the just named macro (prints "abc" then return). M-x insert-kbd-macro Puts the following in your current buffer: (fset 'testit [?a ?b ?c return]) Which can then be saved in your .emacs file to use the named macro over and over again after restarting emacs. A: I've started with solving your problem literally, (defun search-maker (s) `(lambda () (interactive) (let ((regexp-search-ring (cons ,s regexp-search-ring)) ;add regexp to history (isearch-mode-map (copy-keymap isearch-mode-map))) (define-key isearch-mode-map (vector last-command-event) 'isearch-repeat-forward) ;make last key repeat (isearch-forward-regexp)))) ;` (global-set-key (kbd "C-. t") (search-maker "^.*Table\\(\\(.*\\n\\)*?GO\\)")) (global-set-key (kbd "<f6>") (search-maker "HELLO WORLD")) The keyboard sequence from (kbd ...) starts a new blank search. To actually search for your string, you press last key again as many times as you need. So C-. t t t or <f6> <f6> <f6>. The solution is basically a hack, but I'll leave it here if you want to experiment with it. The following is probably the closest to what you need, (defmacro define-isearch-yank (key string) `(define-key isearch-mode-map ,key (lambda () (interactive) (isearch-yank-string ,string)))) ;` (define-isearch-yank (kbd "C-. t") "^.*Table\\(\\(.*\\n\\)*?GO\\)") (define-isearch-yank (kbd "<f6>") "HELLO WORLD") The key combos now only work in isearch mode. You start the search normally, and then press key combos to insert your predefined string. A: @Justin: When executing a macro, it's a little different... incremental searches will just happen once, and you will have to execute the macro again if you want to search again. You can do more powerful and complex things though, such as search for a keyword, jump to the beginning of the line, mark, go to end of the line, M-w (to copy), then jump to another buffer, then C-y (paste), then jump back to the other buffer and end your macro. Then, each time you execute the macro you will be copying a line to the next buffer. The really cool thing about emacs macros is it will stop when it sees the bell... which happens when you fail to match an incremental search (among other things). So the above macro, you can do C-u 1000 C-x e which will execute the macro 1000 times... but since you did a search, it will only copy 1000 lines, OR UNTIL THE SEARCH FAILS! Which means if there are 100 matches, it will only execute the macro 100 times. EDIT: Check out C-hf highlight-lines-matching-regexp which will show the help of a command that highlights everything matching a regex... I don't know how to undo the highlighting though... anyways you could use a stored macro to highlight all matching the regex, and then another macro to find the next one...? FURTHER EDIT: M-x unhighlight-regexp will undo the highlighting, you have to enter the last regex though (but it defaults to the regex you used to highlight) A: In general, to define a custom keybinding in Emacs, you'd write (define-key global-map (kbd "C-c C-f") 'function-name) define-key is, unsurprisingly, the function to define a new key. global-map is the global keymap, as opposed to individual maps for each mode. (kbd "C-c C-f") returns a string representing the key sequence C-c C-f. There are other ways of doing this, including inputting the string directly, but this is usually the most straightforward since it takes the normal written representation. 'function-name is a symbol that's the name of the function. Now, unless your function is already defined, you'll want to define it before you use this. To do that, write (defun function-name (args) (interactive) stuff ...) defun defines a function - use C-h f defun for more specific information. The (interactive) there isn't really a function call; it tells the compiler that it's okay for the function to be called by the user using M-x function-name and via keybindings. Now, for interactive searching in particular, this is tricky; the isearch module doesn't really seem to be set up for what you're trying to do. But you can use this to do something similar.
{ "language": "en", "url": "https://stackoverflow.com/questions/10149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Regex Rejecting matches because of Instr What's the easiest way to do an "instring" type function with a regex? For example, how could I reject a whole string because of the presence of a single character such as :? For example: * *this - okay *there:is - not okay because of : More practically, how can I match the following string: //foo/bar/baz[1]/ns:foo2/@attr/text() For any node test on the xpath that doesn't include a namespace? (/)?(/)([^:/]+) Will match the node tests but includes the namespace prefix which makes it faulty. A: I'm still not sure whether you just wanted to detect if the Xpath contains a namespace, or whether you want to remove the references to the namespace. So here's some sample code (in C#) that does both. class Program { static void Main(string[] args) { string withNamespace = @"//foo/ns2:bar/baz[1]/ns:foo2/@attr/text()"; string withoutNamespace = @"//foo/bar/baz[1]/foo2/@attr/text()"; ShowStuff(withNamespace); ShowStuff(withoutNamespace); } static void ShowStuff(string input) { Console.WriteLine("'{0}' does {1}contain namespaces", input, ContainsNamespace(input) ? "" : "not "); Console.WriteLine("'{0}' without namespaces is '{1}'", input, StripNamespaces(input)); } static bool ContainsNamespace(string input) { // a namspace must start with a character, but can have characters and numbers // from that point on. return Regex.IsMatch(input, @"/?\w[\w\d]+:\w[\w\d]+/?"); } static string StripNamespaces(string input) { return Regex.Replace(input, @"(/?)\w[\w\d]+:(\w[\w\d]+)(/?)", "$1$2$3"); } } Hope that helps! Good luck. A: Match on :? I think the question isn't clear enough, because the answer is so obvious: if(Regex.Match(":", input)) // reject A: I dont know regex syntax very well but could you not do: [any alpha numeric]\*:[any alphanumeric]\* I think something like that should work no? A: You might want \w which is a "word" character. From javadocs, it is defined as [a-zA-Z_0-9], so if you don't want underscores either, that may not work.... A: Yeah, my question was not very clear. Here's a solution but rather than a single pass with a regex, I use a split and perform iteration. It works as well but isn't as elegant: string xpath = "//foo/bar/baz[1]/ns:foo2/@attr/text()"; string[] nodetests = xpath.Split( new char[] { '/' } ); for (int i = 0; i < nodetests.Length; i++) { if (nodetests[i].Length > 0 && Regex.IsMatch( nodetests[i], @"^(\w|\[|\])+$" )) { // does not have a ":", we can manipulate it. } } xpath = String.Join( "/", nodetests );
{ "language": "en", "url": "https://stackoverflow.com/questions/10158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to return a page of results from SQL? Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results. What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user? Does LINQ simplify the solution? A: I'd recommend either using LINQ, or try to copy what it does. I've got an app where I use the LINQ Take and Skip methods to retrieve paged data. The code looks something like this: MyDataContext db = new MyDataContext(); var results = db.Products .Skip((pageNumber - 1) * pageSize) .Take(pageSize); Running SQL Server Profiler reveals that LINQ is converting this query into SQL similar to: SELECT [ProductId], [Name], [Cost], and so on... FROM ( SELECT [ProductId], [Name], [Cost], [ROW_NUMBER] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [Name]) AS [ROW_NUMBER], [ProductId], [Name], [Cost] FROM [Products] ) WHERE [ROW_NUMBER] BETWEEN 10 AND 20 ) ORDER BY [ROW_NUMBER] In plain English: 1. Filter your rows and use the ROW_NUMBER function to add row numbers in the order you want. 2. Filter (1) to return only the row numbers you want on your page. 3. Sort (2) by the row number, which is the same as the order you wanted (in this case, by Name). A: There are essentially two ways of doing pagination in the database (I'm assuming you're using SQL Server): Using OFFSET Others have explained how the ROW_NUMBER() OVER() ranking function can be used to perform pages. It's worth mentioning that SQL Server 2012 finally included support for the SQL standard OFFSET .. FETCH clause: SELECT first_name, last_name, score FROM players ORDER BY score DESC OFFSET 40 ROWS FETCH NEXT 10 ROWS ONLY If you're using SQL Server 2012 and backwards-compatibility is not an issue, you should probably prefer this clause as it will be executed more optimally by SQL Server in corner cases. Using the SEEK Method There is an entirely different, much faster, but less known way to perform paging in SQL. This is often called the "seek method" as described in this blog post here. SELECT TOP 10 first_name, last_name, score FROM players WHERE (score < @previousScore) OR (score = @previousScore AND player_id < @previousPlayerId) ORDER BY score DESC, player_id DESC The @previousScore and @previousPlayerId values are the respective values of the last record from the previous page. This allows you to fetch the "next" page. If the ORDER BY direction is ASC, simply use > instead. With the above method, you cannot immediately jump to page 4 without having first fetched the previous 40 records. But often, you do not want to jump that far anyway. Instead, you get a much faster query that might be able to fetch data in constant time, depending on your indexing. Plus, your pages remain "stable", no matter if the underlying data changes (e.g. on page 1, while you're on page 4). This is the best way to implement paging when lazy loading more data in web applications, for instance. Note, the "seek method" is also called keyset paging. A: LINQ combined with lambda expressions and anonymous classes in .Net 3.5 hugely simplifies this sort of thing. Querying the database: var customers = from c in db.customers join p in db.purchases on c.CustomerID equals p.CustomerID where p.purchases > 5 select c; Number of records per page: customers = customers.Skip(pageNum * pageSize).Take(pageSize); Sorting by any column: customers = customers.OrderBy(c => c.LastName); Getting only selected fields from server: var customers = from c in db.customers join p in db.purchases on c.CustomerID equals p.CustomerID where p.purchases > 5 select new { CustomerID = c.CustomerID, FirstName = c.FirstName, LastName = c.LastName }; This creates a statically-typed anonymous class in which you can access its properties: var firstCustomer = customer.First(); int id = firstCustomer.CustomerID; Results from queries are lazy-loaded by default, so you aren't talking to the database until you actually need the data. LINQ in .Net also greatly simplifies updates by keeping a datacontext of any changes you have made, and only updating the fields which you change. A: On MS SQL Server 2005 and above, ROW_NUMBER() seems to work: T-SQL: Paging with ROW_NUMBER() DECLARE @PageNum AS INT; DECLARE @PageSize AS INT; SET @PageNum = 2; SET @PageSize = 10; WITH OrdersRN AS ( SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum ,OrderID ,OrderDate ,CustomerID ,EmployeeID FROM dbo.Orders ) SELECT * FROM OrdersRN WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY OrderDate ,OrderID; A: Actually, LINQ has Skip and Take methods which can be combined to choose which records are fetched. Check those out. For DB: Pagination In SQL Server 2005 A: Oracle Solution: select * from ( select a.*, rownum rnum from ( YOUR_QUERY_GOES_HERE -- including the order by ) a where rownum <= MAX_ROW ) where rnum >= MIN_ROW A: There are a few solutions which I use with MS SQL 2005. One of them is ROW_NUMBER(). But, personally, I don't like ROW_NUMBER() because it doesn't work for big results (DB which I work on is really big -- over 1TB data running thousands of queries in second -- you know -- big social networking site). Here are my favourite solution. I will use kind of pseudo code of T-SQL. Let's find 2nd page of users sorted by forename, surname, where each page has 10 records. @page = 2 -- input parameter @size = 10 -- can be optional input parameter if @page < 1 then begin @page = 1 -- check page number end @start = (@page-1) * @size + 1 -- @page starts at record no @start -- find the beginning of page @page SELECT TOP (@start) @forename = forename, @surname = surname @id = id FROM users ORDER BY forename, surname, id -- to keep correct order in case of have two John Smith. -- select @size records starting from @start SELECT TOP (@size) id, forename, surname FROM users WHERE (forename = @forename and surname = @surname and id >= @id) -- the same name and surname, but bigger id OR (forename = @forename and surname > @surname) -- the same name, but bigger surname, id doesn't matter OR (forename > @forename) -- bigger forename, the rest doesn't matter ORDER BY forename, surname, id A: There is a discussion about this Here The technique gets page number 100,000 from a 150,000 line database in 78ms Using optimizer knowledge and SET ROWCOUNT, the first EmployeeID in the page that is requested is stored in a local variable for a starting point. Next, SET ROWCOUNT to the maximum number of records that is requested in @maximumRows. This allows paging the result set in a much more efficient manner. Using this method also takes advantage of pre-existing indexes on the table as it goes directly to the base table and not to a locally created table. I am afraid I am not able to judge if it is better than the current accepted answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/10190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Delimited string parsing? I'm looking at parsing a delimited string, something on the order of a,b,c But this is a very simple example, and parsing delimited data can get complex; for instance 1,"Your simple algorithm, it fails",True would blow your naiive string.Split implementation to bits. Is there anything I can freely use/steal/copy and paste that offers a relatively bulletproof solution to parsing delimited text? .NET, plox. Update: I decided to go with the TextFieldParser, which is part of VB.NET's pile of goodies hidden away in Microsoft.VisualBasic.DLL. A: I use this to read from a file string filename = @textBox1.Text; string[] fields; string[] delimiter = new string[] {"|"}; using (Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(filename)) { parser.Delimiters = delimiter; parser.HasFieldsEnclosedInQuotes = false; while (!parser.EndOfData) { fields = parser.ReadFields(); //Do what you need } } I am sure someone here can transform this to parser a string that is in memory. A: I am not aware of any framework, but a simple state machine works: * *State 1: Read every char until you hit a " or a , * *In case of a ": Move to State 2 *In case of a ,: Move to State 3 *In case of the end of file: Move to state 4 *State 2: Read every char until you hit a " * *In case of a ": Move to State 1 *In case of the end of the file: Either Move to State 4 or signal an error because of an unterminated string *State 3: Add the current buffer to the output array, move the cursor forward behind the , and back to State 1. *State 4: this is the final state, does nothing except returning the output array. A: Such as var elements = new List<string>(); var current = new StringBuilder(); var p = 0; while (p < internalLine.Length) { if (internalLine[p] == '"') { p++; while (internalLine[p] != '"') { current.Append(internalLine[p]); p++; } // Skip past last ', p += 2; } else { while ((p < internalLine.Length) && (internalLine[p] != ',')) { current.Append(internalLine[p]); p++; } // Skip past , p++; } elements.Add(current.ToString()); current.Length = 0; } A: A very complrehesive library can be found here: FileHelpers A: There are some good answers here: Split a string ignoring quoted sections You might want to rephrase your question to something more precise (e.g. What code snippet or library I can use to parse CSV data in .NET?). A: To do a shameless plug, I've been working on a library for a while called fotelo (Formatted Text Loader) that I use to quickly parse large amounts of text based off of delimiter, position, or regex. For a quick string it is overkill, but if you're working with logs or large amounts, it may be just what you need. It works off a control file model similar to SQL*Loader (kind of the inspiration behind it). A: Better late than never (add to the completeness of SO): http://www.codeproject.com/KB/database/CsvReader.aspx This one ff-ing rules. GJ A: I am thinking that a generic framework would need to specify between two things: 1. What are the delimiting characters. 2. Under what condition do those characters not count (such as when they are between quotes). I think it may just be better off writing custom logic for every time you need to do something like this. A: Simplest way is just to split the string into a char array and look for your string determiners and split char. It should be relatively easy to unit test. You can wrap it in an extension method similar to the basic .Spilt method.
{ "language": "en", "url": "https://stackoverflow.com/questions/10205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Run PHPUnit Tests in Certain Order Is there a way to get the tests inside of a TestCase to run in a certain order? For example, I want to separate the life cycle of an object from creation to use to destruction but I need to make sure that the object is set up first before I run the other tests. A: If you want your tests to share various helper objects and settings, you can use setUp(), tearDown() to add to the sharedFixture property. A: PHPUnit allows the use of '@depends' annotation which specifies dependent test cases and allows passing arguments between dependent test cases. A: Maybe there is a design problem in your tests. Usually each test must not depend on any other tests, so they can run in any order. Each test needs to instantiate and destroy everything it needs to run, that would be the perfect approach, you should never share objects and states between tests. Can you be more specific about why you need the same object for N tests? A: Alternative solution: Use static(!) functions in your tests to create reusable elements. For instance (I use selenium IDE to record tests and phpunit-selenium (github) to run test inside browser) class LoginTest extends SeleniumClearTestCase { public function testAdminLogin() { self::adminLogin($this); } public function testLogout() { self::adminLogin($this); self::logout($this); } public static function adminLogin($t) { self::login($t, 'john.smith@gmail.com', 'pAs$w0rd'); $t->assertEquals('John Smith', $t->getText('css=span.hidden-xs')); } // @source LoginTest.se public static function login($t, $login, $pass) { $t->open('/'); $t->click("xpath=(//a[contains(text(),'Log In')])[2]"); $t->waitForPageToLoad('30000'); $t->type('name=email', $login); $t->type('name=password', $pass); $t->click("//button[@type='submit']"); $t->waitForPageToLoad('30000'); } // @source LogoutTest.se public static function logout($t) { $t->click('css=span.hidden-xs'); $t->click('link=Logout'); $t->waitForPageToLoad('30000'); $t->assertEquals('PANEL', $t->getText("xpath=(//a[contains(text(),'Panel')])[2]")); } } Ok, and now, i can use this reusable elements in other test :) For instance: class ChangeBlogTitleTest extends SeleniumClearTestCase { public function testAddBlogTitle() { self::addBlogTitle($this,'I like my boobies'); self::cleanAddBlogTitle(); } public static function addBlogTitle($t,$title) { LoginTest::adminLogin($t); $t->click('link=ChangeTitle'); ... $t->type('name=blog-title', $title); LoginTest::logout($t); LoginTest::login($t, 'paris@gmail.com','hilton'); $t->screenshot(); // take some photos :) $t->assertEquals($title, $t->getText('...')); } public static function cleanAddBlogTitle() { $lastTitle = BlogTitlesHistory::orderBy('id')->first(); $lastTitle->delete(); } * *In this way, you can build hierarchy of you tests. *You can steel keep property that each test case is totaly separate from other (if you clean DB after each test). *And most important, if for instance, the way of login change in future, you only modify LoginTest class, and you don'n need correct login part in other tests (they should work after update LoginTest) :) When I run test my script clean up db ad the begining. Above I use my SeleniumClearTestCase class (I make screenshot() and other nice functions there) it is extension of MigrationToSelenium2 (from github, to port recorded tests in firefox using seleniumIDE + ff plugin "Selenium IDE: PHP Formatters" ) which is extension of my class LaravelTestCase (it is copy of Illuminate\Foundation\Testing\TestCase but not extends PHPUnit_Framework_TestCase) which setup laravel to have access to eloquent when we want to clean DB at the end of test) which is extension of PHPUnit_Extensions_Selenium2TestCase. To set up laravel eloquent I have also in SeleniumClearTestCase function createApplication (which is called at setUp, and I take this function from laral test/TestCase) A: The correct answer for this is a proper configuration file for tests. I had the same problem and fixed it by creating testsuite with necessary test files order: phpunit.xml: <phpunit colors="true" bootstrap="./tests/bootstrap.php" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" strict="true" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" stopOnRisky="false" > <testsuites> <testsuite name="Your tests"> <file>file1</file> //this will be run before file2 <file>file2</file> //this depends on file1 </testsuite> </testsuites> </phpunit> A: There really is a problem with your tests if they need to run in a certain order. Each test should be totally independent of the others: it helps you with defect localization, and allows you to get repeatable (and therefore debuggable) results. Checkout this site for a whole load of ideas / information, about how to factor your tests in a manner where you avoid these kinds of issues. A: In my view, take the following scenario where I need to test creation and destroying of a particular resource. Initially I had two methods, a. testCreateResource and b. testDestroyResource a. testCreateResource <?php $app->createResource('resource'); $this->assertTrue($app->hasResource('resource')); ?> b. testDestroyResource <?php $app->destroyResource('resource'); $this->assertFalse($app->hasResource('resource')); ?> I think this is a bad idea, as testDestroyResource depends upon testCreateResource. And a better practice would be to do a. testCreateResource <?php $app->createResource('resource'); $this->assertTrue($app->hasResource('resource')); $app->deleteResource('resource'); ?> b. testDestroyResource <?php $app->createResource('resource'); $app->destroyResource('resource'); $this->assertFalse($app->hasResource('resource')); ?> A: PHPUnit supports test dependencies via the @depends annotation. Here is an example from the documentation where tests will be run in an order that satisfies dependencies, with each dependent test passing an argument to the next: class StackTest extends PHPUnit_Framework_TestCase { public function testEmpty() { $stack = array(); $this->assertEmpty($stack); return $stack; } /** * @depends testEmpty */ public function testPush(array $stack) { array_push($stack, 'foo'); $this->assertEquals('foo', $stack[count($stack)-1]); $this->assertNotEmpty($stack); return $stack; } /** * @depends testPush */ public function testPop(array $stack) { $this->assertEquals('foo', array_pop($stack)); $this->assertEmpty($stack); } } However, it's important to note that tests with unresolved dependencies will not be executed (desirable, as this brings attention quickly to the failing test). So, it's important to pay close attention when using dependencies.
{ "language": "en", "url": "https://stackoverflow.com/questions/10228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "79" }
Q: Multithreading Design Best Practice Consider this problem: I have a program which should fetch (let's say) 100 records from a database, and then for each one it should get updated information from a web service. There are two ways to introduce parallelism in this scenario: * *I start each request to the web service on a new Thread. The number of simultaneous threads is controlled by some external parameter (or dynamically adjusted somehow). *I create smaller batches (let's say of 10 records each) and launch each batch on a separate thread (so taking our example, 10 threads). Which is a better approach, and why do you think so? A: Option 3 is the best: Use Async IO. Unless your request processing is complex and heavy, your program is going to spend 99% of it's time waiting for the HTTP requests. This is exactly what Async IO is designed for - Let the windows networking stack (or .net framework or whatever) worry about all the waiting, and just use a single thread to dispatch and 'pick up' the results. Unfortunately the .NET framework makes it a right pain in the ass. It's easier if you're just using raw sockets or the Win32 api. Here's a (tested!) example using C#3 anyway: using System.Net; // need this somewhere // need to declare an class so we can cast our state object back out class RequestState { public WebRequest Request { get; set; } } static void Main( string[] args ) { // stupid cast neccessary to create the request HttpWebRequest request = WebRequest.Create( "http://www.stackoverflow.com" ) as HttpWebRequest; request.BeginGetResponse( /* callback to be invoked when finished */ (asyncResult) => { // fetch the request object out of the AsyncState var state = (RequestState)asyncResult.AsyncState; var webResponse = state.Request.EndGetResponse( asyncResult ) as HttpWebResponse; // there we go; Debug.Assert( webResponse.StatusCode == HttpStatusCode.OK ); Console.WriteLine( "Got Response from server:" + webResponse.Server ); }, /* pass the request through to our callback */ new RequestState { Request = request } ); // blah Console.WriteLine( "Waiting for response. Press a key to quit" ); Console.ReadKey(); } EDIT: In the case of .NET, the 'completion callback' actually gets fired in a ThreadPool thread, not in your main thread, so you will still need to lock any shared resources, but it still saves you all the trouble of managing threads. A: Two things to consider. 1. How long will it take to process a record? If record processing is very quick, the overhead of handing off records to threads can become a bottleneck. In this case, you would want to bundle records so that you don't have to hand them off so often. If record processing is reasonably long-running, the difference will be negligible, so the simpler approach (1 record per thread) is probably the best. 2. How many threads are you planning on starting? If you aren't using a threadpool, I think you either need to manually limit the number of threads, or you need to break the data into big chunks. Starting a new thread for every record will leave your system thrashing if the number of records get large. A: The computer running the program is probably not the bottleneck, so: Remember that the HTTP protocol has a keep-alive header, that lets you send several GET requests on the same sockets, which saves you from the TCP/IP hand shake. Unfortunately I don't know how to use that in the .net libraries. (Should be possible.) There will probably also be a delay in answering your requests. You could try making sure that you allways have a given number of outstanding requests to the server. A: Get the Parallel Fx. Look at the BlockingCollection. Use a thread to feed it batches of records, and 1 to n threads pulling records off the collection to service. You can control the rate at which the collection is fed, and the number of threads that call to web services. Make it configurable via a ConfigSection, and make it generic by feeding the collection Action delegates, and you'll have a nice little batcher you can reuse to your heart's content.
{ "language": "en", "url": "https://stackoverflow.com/questions/10229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Checking for string contents? string Length Vs Empty String Which is more efficient for the compiler and the best practice for checking whether a string is blank? * *Checking whether the length of the string == 0 *Checking whether the string is empty (strVar == "") Also, does the answer depend on language? A: In languages that use C-style (null-terminated) strings, comparing to "" will be faster Actually, it may be better to check if the first char in the string is '\0': char *mystring; /* do something with the string */ if ((mystring != NULL) && (mystring[0] == '\0')) { /* the string is empty */ } In Perl there's a third option, that the string is undefined. This is a bit different from a NULL pointer in C, if only because you don't get a segmentation fault for accessing an undefined string. A: In .Net: string.IsNullOrEmpty( nystr ); strings can be null, so .Length sometimes throws a NullReferenceException A: For C strings, if (s[0] == 0) will be faster than either if (strlen(s) == 0) or if (strcmp(s, "") == 0) because you will avoid the overhead of a function call. A: String.IsNullOrEmpty() only works on .net 2.0 and above, for .net 1/1.1, I tend to use: if (inputString == null || inputString == String.Empty) { // String is null or empty, do something clever here. Or just expload. } I use String.Empty as opposed to "" because "" will create an object, whereas String.Empty wont - I know its something small and trivial, but id still rather not create objects when I dont need them! (Source) A: Yes, it depends on language, since string storage differs between languages. * *Pascal-type strings: Length = 0. *C-style strings: [0] == 0. *.NET: .IsNullOrEmpty. Etc. A: In languages that use C-style (null-terminated) strings, comparing to "" will be faster. That's an O(1) operation, while taking the length of a C-style string is O(n). In languages that store length as part of the string object (C#, Java, ...) checking the length is also O(1). In this case, directly checking the length is faster, because it avoids the overhead of constructing the new empty string. A: In Java 1.6, the String class has a new method [isEmpty] 1 There is also the Jakarta commons library, which has the [isBlank] 2 method. Blank is defined as a string that contains only whitespace. A: Assuming your question is .NET: If you want to validate your string against nullity as well use IsNullOrEmpty, if you know already that your string is not null, for example when checking TextBox.Text etc., do not use IsNullOrEmpty, and then comes in your question. So for my opinion String.Length is less perfomance than string comparison. I event tested it (I also tested with C#, same result): Module Module1 Sub Main() Dim myString = "" Dim a, b, c, d As Long Console.WriteLine("Way 1...") a = Now.Ticks For index = 0 To 10000000 Dim isEmpty = myString = "" Next b = Now.Ticks Console.WriteLine("Way 2...") c = Now.Ticks For index = 0 To 10000000 Dim isEmpty = myString.Length = 0 Next d = Now.Ticks Dim way1 = b - a, way2 = d - c Console.WriteLine("way 1 took {0} ticks", way1) Console.WriteLine("way 2 took {0} ticks", way2) Console.WriteLine("way 1 took {0} ticks more than way 2", way1 - way2) Console.Read() End Sub End Module Result: Way 1... Way 2... way 1 took 624001 ticks way 2 took 468001 ticks way 1 took 156000 ticks more than way 2 Which means comparison takes way more than string length check. A: After I read this thread, I conducted a little experiment, which yielded two distinct, and interesting, findings. Consider the following. strInstallString "1" string The above is copied from the locals window of the Visual Studio debugger. The same value is used in all three of the following examples. if ( strInstallString == "" ) === if ( strInstallString == string.Empty ) Following is the code displayed in the disassembly window of the Visual Studio 2013 debugger for these two fundamentally identical cases. if ( strInstallString == "" ) 003126FB mov edx,dword ptr ds:[31B2184h] 00312701 mov ecx,dword ptr [ebp-50h] 00312704 call 59DEC0B0 ; On return, EAX = 0x00000000. 00312709 mov dword ptr [ebp-9Ch],eax 0031270F cmp dword ptr [ebp-9Ch],0 00312716 sete al 00312719 movzx eax,al 0031271C mov dword ptr [ebp-64h],eax 0031271F cmp dword ptr [ebp-64h],0 00312723 jne 00312750 if ( strInstallString == string.Empty ) 00452443 mov edx,dword ptr ds:[3282184h] 00452449 mov ecx,dword ptr [ebp-50h] 0045244C call 59DEC0B0 ; On return, EAX = 0x00000000. 00452451 mov dword ptr [ebp-9Ch],eax 00452457 cmp dword ptr [ebp-9Ch],0 0045245E sete al 00452461 movzx eax,al 00452464 mov dword ptr [ebp-64h],eax 00452467 cmp dword ptr [ebp-64h],0 0045246B jne 00452498 if ( strInstallString == string.Empty ) Isn't Significantly Different if ( strInstallString.Length == 0 ) 003E284B mov ecx,dword ptr [ebp-50h] 003E284E cmp dword ptr [ecx],ecx 003E2850 call 5ACBC87E ; On return, EAX = 0x00000001. 003E2855 mov dword ptr [ebp-9Ch],eax 003E285B cmp dword ptr [ebp-9Ch],0 003E2862 setne al 003E2865 movzx eax,al 003E2868 mov dword ptr [ebp-64h],eax 003E286B cmp dword ptr [ebp-64h],0 003E286F jne 003E289C From the above machine code listings, generated by the NGEN module of the .NET Framework, version 4.5, I draw the following conclusions. * *Testing for equality against the empty string literal and the static string.Empty property on the System.string class are, for all practical purposes, identical. The only difference between the two code snippets is the source of the first move instruction, and both are offsets relative to ds, implying that both refer to baked-in constants. *Testing for equality against the empty string, as either a literal or the string.Empty property, sets up a two-argument function call, which indicates inequality by returning zero. I base this conclusion on other tests that I performed a couple of months ago, in which I followed some of my own code across the managed/unmanaged divide and back. In all cases, any call that required two or more arguments put the first argument in register ECX, and and the second in register EDX. I don't recall how subsequent arguments were passed. Nevertheless, the call setup looked more like __fastcall than __stdcall. Likewise, the expected return values always showed up in register EAX, which is almost universal. *Testing the length of the string sets up a one-argument function call, which returns 1 (in register EAX), which happens to be the length of the string being tested. *Given that the immediately visible machine code is almost identical, the only reason that I can imagine that would account for the better performance of the string equality over the sting length reported by Shinny is that the two-argument function that performs the comparison is significantly better optimized than the one-argument function that reads the length off the string instance. Conclusion As a matter of principle, I avoid comparing against the empty string as a literal, because the empty string literal can appear ambiguous in source code. To that end, my .NET helper classes have long defined the empty string as a constant. Though I use string.Empty for direct, inline comparisons, the constant earns its keep for defining other constants whose value is the empty string, because a constant cannot be assigned string.Empty as its value. This exercise settles, once and for all, any concern I might have about the cost, if any, of comparing against either string.Empty or the constant defined by my helper classes. However, it also raises a puzzling question to replace it; why is comparing against string.Empty more efficient than testing the length of the string? Or is the test used by Shinny invalidated because by the way the loop is implemented? (I find that hard to believe, but, then again, I've been fooled before, as I'm sure you have, too!) I have long assumed that system.string objects were counted strings, fundamentally similar to the long established Basic String (BSTR) that we have long known from COM. A: Actually, IMO the best way to determine is the IsNullOrEmpty() method of the string class. http://msdn.microsoft.com/en-us/library/system.string.isnullorempty. Update: I assumed .Net, in other languages, this might be different. A: In this case, directly checking the length is faster, because it avoids the overhead of constructing the new empty string. @DerekPark: That's not always true. "" is a string literal so, in Java, it will almost certainly already be interned. A: @Nathan Actually, it may be better to check if the first char in the string is '\0': I almost mentioned that, but ended up leaving it out, since calling strcmp() with the empty string and directly checking the first character in the string are both O(1). You basically just pay for an extra function call, which is pretty cheap. If you really need the absolute best speed, though, definitely go with a direct first-char-to-0 comparison. Honestly, I always use strlen() == 0, because I have never written a program where this was actually a measurable performance issue, and I think that's the most readable way to express the check. A: Again, without knowing the language, it's impossible to tell. However, I recommend that you choose the technique that makes the most sense to the maintenance programmer that follows and will have to maintain your work. I'd recommend writing a function that explicitly does what you want, such as #define IS_EMPTY(s) ((s)[0]==0) or comparable. Now there's no doubt at is you're checking. A: If strings in a language have an internal length property, checking the length is faster because it is an integer comparison of the property value with zero. However, when strings have no such property, the length must be determined the moment you want to test for it, and this is very fast for a string that actually has length zero, but can take a very long time if the string is huge, which you cannot know in advance, because if you knew it had size zero, why do you need to check that at all? If a strings don't store their lengths internally, comparing against an empty string is usually faster, as even if that means that the two strings will be compared character by character, this loop terminates after the very first iteration for sure, so the time is linear (O(1)) and does not depend on string length. However, even if strings do have an internal length property, comparing them to an empty string may be as fast as checking that property as in that case most implementations will do just that: They first compare lengths and if not the same, they skip comparing characters entirely as if not even the lengths match, the strings cannot be equal to begin with. Yet if the lengths do match, they usually check for the special case 0 and again skip the character comparison loop. And if a language does offer an explicit way to check if a string is empty, always use that, since no matter which way is faster, that is the way this check is using internally. E.g. to check for an empty string in a shell script, you could use [ "$var" = "" ] which would be string comparison. Or you could use [ ${#var} -eq 0 ] which uses string length comparison. Yet the most efficient way is in fact [ -z "$var" ] as the -z operation only exists for exactly this purpose. C is special in that regard, as the string internals are exposed (strings are not encapsulated objects in C) and while C strings don't have a length property and their length must be determined each time needed, it is very easy to check if a C string is empty by just checking if it's first character is NUL, as NUL is always the last character in a C string, so nothing can beat: char * string = ...; if (!*string) { /* empty */ } (note that in C *string is the same as string[0], !x is the same as x == 0, and 0 is the same '\0', so you could have written string[0] == '\0' but for the compiler that's exactly the same as what I've written above)
{ "language": "en", "url": "https://stackoverflow.com/questions/10230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How to get PNG transparency working in browsers that don't natively support it? Our (beloved) designer keeps creating PNG files with transparent backgrounds for use in our applications. I'd like to make sure that this feature of the PNG works in "older" browsers as well. What's the best solution? edits below @mabwi & @syd - Whether or not I agree about the use of a PNG is not the point. This is a problem that I need to solve! @Tim Sullivan - IE7.js looks pretty cool, but I don't think I want to introduce all of the other changes an application. I'd like a solution that fixes the PNG issue exclusively. Thanks for the link. A: I've found what looks to be a very good solution here: Unit Interactive -> Labs -> Unit PNG Fix update Unit PNG is also featured on a list of PNG fix options on NETTUTS Here are the highlights from their website: * *Very compact javascript: Under 1kb! *Fixes some interactivity problems caused by IE’s filter attribute. *Works on img objects and background-image attributes. *Runs automatically. You don’t have to define classes or call functions. *Allows for auto width and auto height elements. *Super simple to deploy. A: * *IE PNG Fix 2.0 which supports background-position and -repeat! Also paletted 8-bit PNG with full alpha transparency exist, contrary to what Photoshop and GIMP may make you believe, and they degrade better in IE6 – it just cuts down transparency to 1-bit. Use pngquant to generate such files from 24-bit PNGs. A: IE7.js will provide support for PNGs (including transparency) in IE6. A: I've messed with trying to make a site with .pngs and it just isn't worth it. The site becomes slow, and you use hacks that don't work 100%. Here's a good article on some options, but my advice is to find a way to make gifs work until you don't have to support IE6. Or just give IE6 a degraded experience. A: Using PNGs in IE6 is hardly any more difficult than any other browser. You can support all of it in your CSS without Javascript. I've seen this hack shown before... div.theImage { background : url(smile.png) top left no-repeat; height : 100px; width : 100px; } * html div.theImage { background : none; progid:DXImageTransform.Microsoft.AlphaImageLoader(src="layout/smile.png", sizingMethod="scale"); } I'm not so sure this is valid CSS, but depending on the site, it may not matter so much. (it's worth noting that the URL for the first image is based on the directory of the stylesheet, where the second is based on the directory of the page being viewed - thus why they do not match) A: @Hboss that's all fine and dandy if you know exactly all the files (and the dimensions of each) that you're going to be displaying - it'd be a royal pain to maintain that CSS file, but I suppose it'd be possible. When you want to start using transparent PNGs for some very common purposes: a) incidental graphics such as icons (perhaps of differing size) which work on any background, and b) repeating backgrounds; then you're screwed. Every workaround I've tried has hit a stumbling block at some point (can't select text when the background is transparent, sometimes the images are displayed at wacky sizes, etc etc), and I've found that for maximum reliability I'll have to revert to gifs. My advice is to give the PNG transparency hack a shot, but at the same time realise that it's definitely not perfect - and just remember, you're bending over backwards for users of a browser which is over 7 years old. What I do these days is give IE6 users a popup on their first visit to the site, with a friendly reminder that their browser is outdated and doesn't offer the features required by modern websites, and, though we'll try our best to give you the best, you'll get a better experience from our site and the internet as a whole if you BLOODY WELL UPGRADED. A: I believe all browsers support PNG-8. Its not alpha blended, but it does have transparent backgrounds. A: I might be mistaken, but I'm pretty sure IE6 and less just don't do transparency with PNG files. You sort of are, and you sort of aren't. IE6 has no support natively for them. However, IE has support for crazy custom javascript/css and COM objects (which is how they originally implemented XmlHttpRequest) All of these hacks basically do this: * *Find all the png images *Use a directx image filter to load them and produce a transparent image in some kind of format IE understands *Replace the images with the filtered copy. A: One thing to think about is Email clients. You often want PNG-24 transparency but in Outlook 2003 with a machine using IE6. Email clients won't allow CSS or JS tricks. Here is a good way to handle that. http://commadot.com/png-8-that-acts-like-png-24-without-fireworks/ A: If you export your images as PNG-8 from Fireworks then they'll act the same as gif images. So they won't look shitty and grey, transparency will be transparency but they won't have the full 24 bit loveliness that other browsers do. Might not totally solve your problem but at least you can get part way there just be re-exporting them. A: I might be mistaken, but I'm pretty sure IE6 and less just don't do transparency with PNG files. I have two "solutions" that I use. Either create GIF files with transparency and use those everywhere, or just use them for IE 6 and older with conditional style sheets. The second really only works if you are using them as backgrounds, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/10243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What are the useful new ASP.NET features in the .NET Framework 3.5? I've kept up to date with new features in the C# language as it's moved from version 1 through version 3. I haven't done such a good job keeping up to date with ASP.NET. I feel like some of the post version 1 features are not so good (e.g. the AJAX framework) or are just not that useful to me (e.g. the membership framework). Can anyone recommend any new killer ASP.NET features that might have gone unnoticed? A: For ASP.NET, you have a lot of improvements: * *split view (code and design) *faster switching between code and design view *embedded master pages (one master page in another) *javascript debugging Anyway most of the useful stuff are really in the meat of the language, and for .NET 3.5 the new language features for C# 3.0 will be (and yes, I find ALL of them useful) * *anonymous objects *automatic properties *object initializers *collection initializers (inline initialization for collections) *implicit typing (var keyword) *lambda expressions *LINQ *Extension methods I might have forgotten a few, but I think this is about most of the new cool and useful stuff. A: Check out the MVC framework which is built ontop of 3.5. Big improvement over the traditional webforms model. A: I'm still learning ASP.net so I can't tell you exactly, but if you look through http://www.asp.net/learn/ you'll probably find a few new gems, there's even a 3.5 section. A: ListView and its friend DataPager are probably worth looking at, but they're hardly "Killer" features. Things outside of ASP.NET specifically (LINQ, for example) are probably more likely to be get the "Killer" commendation. A: Its the MVC framework. Without 3.5, there is no MVC. Without MVC, ASP.NET is a PITA. A: Master Pages (of course, these are in there from version 2.0) Nested master pages are new in 3.5. I haven't used them yet, but I can only imagine they could turn into a hidious nightmare if not used very carefully. You only have to look at the order in which the events are fired in a page that uses a master page to think 'urgh'. A: I don't think the MVC Framework is quite ready for prime time yet Just an FYI, this site is built in MVC. I also have 2 apps in production on mvc, I would argue that its definitely ready for prime time. A: @IainMH Nested Master Pages were always supported by ASP.NET, just not by the designer. A: As others have said, there's a good list at www.asp.net/learn. I think the biggest ASP.NET specific changes are: * *Official ASP.NET AJAX integration *ListView (much better than the GridView / DataView in that they let you write out clean HTML) *Big improvements to the IDE for CSS / HTML editing *Javascript debugging Note that ASP.NET MVC is not released yet, and was definitely not included with ASP.NET 3.5. A: Here's a brief list of my favourites: * *LINQ *Extension Methods *Lambda Methods And I don't actually use ASP.NET, but ASP.NET AJAX is now included in 3.5 too and ASP.NET MVC is included in 3.5 SP1. A: I don't think the MVC Framework is quite ready for prime time yet, though I definitely plan to use it sometime next year. I love the clean URLs, clean XHTML (web forms can really spew out some nasty HTML) and the ability to create controller actions with no associated view. I've been using Master Pages since they were released and they've been a big help. I do really dislike the way the master pages add the nasty prefixes to the control IDs. It makes for some ugly CSS. I think the MVC Framework may eliminate this problem though. Any other killer features? A: The split design/code view is pretty cool. It's not perfect yet, but it's pretty cool. Also editing in the design view now edits your css there and then. A: also Dynamic Data have to be consider
{ "language": "en", "url": "https://stackoverflow.com/questions/10260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: When should I not use the ThreadPool in .Net? When should I not use the ThreadPool in .Net? It looks like the best option is to use a ThreadPool, in which case, why is it not the only option? What are your experiences around this? A: Thread pools make sense whenever you have the concept of worker threads. Any time you can easily partition processing into smaller jobs, each of which can be processed independently, worker threads (and therefore a thread pool) make sense. Thread pools do not make sense when you need thread which perform entirely dissimilar and unrelated actions, which cannot be considered "jobs"; e.g., One thread for GUI event handling, another for backend processing. Thread pools also don't make sense when processing forms a pipeline. Basically, if you have threads which start, process a job, and quit, a thread pool is probably the way to go. Otherwise, the thread pool isn't really going to help. A: @Eric, I'm going to have to agree with Dean. Threads are expensive. You can't assume that your program is the only one running. When everyone is greedy with resources, the problem multiplies. I prefer to create my threads manually and control them myself. It keeps the code very easy to understand. That's fine when it's appropriate. If you need a bunch of worker threads, though, all you've done is make your code more complicated. Now you have to write code to manage them. If you just used a thread pool, you'd get all the thread management for free. And the thread pool provided by the language is very likely to be more robust, more efficient, and less buggy than whatever you roll for yourself. Thread t = new Thread(new ThreadStart(DoSomething)); t.Start(); t.Join(); I hope that you would normally have some additional code in between Start() and Join(). Otherwise, the extra thread is useless, and you're wasting resources for no reason. People are way too afraid of the resources used by threads. I've never seen creating and starting a thread to take more than a millisecond. There is no hard limit on the number of threads you can create. RAM usage is minimal. Once you have a few hundred threads, CPU becomes an issue because of context switches, so at that point you might want to get fancy with your design. A millisecond is a long time on modern hardware. That's 3 million cycles on a 3GHz machine. And again, you aren't the only one creating threads. Your threads compete for the CPU along with every other program's threads. If you use not-quite-too-many threads, and so does another program, then together you've used too many threads. Seriously, don't make life more complex than it needs to be. Don't use the thread pool unless you need something very specific that it offers. Indeed. Don't make life more complex. If your program needs multiple worker threads, don't reinvent the wheel. Use the thread pool. That's why it's there. Would you roll your own string class? A: I'm not speaking as someone with only theoretical knowledge here. I write and maintain high volume applications that make heavy use of multithreading, and I generally don't find the thread pool to be the correct answer. Ah, argument from authority - but always be on the look out for people who might be on the Windows kernel team. Neither of us were arguing with the fact that if you have some specific requirements then the .NET ThreadPool might not be the right thing. What we're objecting to is the trivialisation of the costs to the machine of creating a thread. The significant expense of creating a thread at the raison d'etre for the ThreadPool in the first place. I don't want my machines to be filled with code written by people who have been misinformed about the expense of creating a thread, and don't, for example, know that it causes a method to be called in every single DLL which is attached to the process (some of which will be created by 3rd parties), and which may well hot-up a load of code which need not be in RAM at all and almost certainly didn't need to be in L1. The shape of the memory hierarchy in a modern machine means that 'distracting' a CPU is about the worst thing you can possibly do, and everybody who cares about their craft should work hard to avoid it. A: The only reason why I wouldn't use the ThreadPool for cheap multithreading is if I need to… * *interract with the method running (e.g., to kill it) *run code on a STA thread (this happened to me) *keep the thread alive after my application has died (ThreadPool threads are background threads) *in case I need to change the priority of the Thread. We can not change priority of threads in ThreadPool which is by default Normal. P.S.: The MSDN article "The Managed Thread Pool" contains a section titled, "When Not to Use Thread Pool Threads", with a very similar but slightly more complete list of possible reasons for not using the thread pool. There are lots of reasons why you would need to skip the ThreadPool, but if you don't know them then the ThreadPool should be good enough for you. Alternatively, look at the new Parallel Extensions Framework, which has some neat stuff in there that may suit your needs without having to use the ThreadPool. A: To quarrelsome's answer, I would add that it's best not to use a ThreadPool thread if you need to guarantee that your thread will begin work immediately. The maximum number of running thread-pooled threads is limited per appdomain, so your piece of work may have to wait if they're all busy. It's called "queue user work item", after all. Two caveats, of course: * *You can change the maximum number of thread-pooled threads in code, at runtime, so there's nothing to stop you checking the current vs maximum number and upping the maximum if required. *Spinning up a new thread comes with its own time penalty - whether it's worthwhile for you to take the hit depends on your circumstances. A: When you're going to perform an operation that is going to take a long time, or perhaps a continuous background thread. I guess you could always push the amount of threads available in the pool up but there would be little point in incurring the management costs of a thread that is never going to be given back to the pool. A: Threadpool threads are appropriate for tasks that meet both of the following criteria: * *The task will not have to spend any significant time waiting for something to happen *Anything that's waiting for the task to finish will likely be waiting for many tasks to finish, so its scheduling priority isn't apt to affect things much. Using a threadpool thread instead of creating a new one will save a significant but bounded amount of time. If that time is significant compared with the time it will take to perform a task, a threadpool task is likely appropriate. The longer the time required to perform a task, however, the smaller the benefit of using the threadpool and the greater the likelihood of the task impeding threadpool efficiency. A: MSDN has a list some reasons here: http://msdn.microsoft.com/en-us/library/0ka9477y.aspx There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads: * *You require a foreground thread. *You require a thread to have a particular priority. *You have tasks that cause the thread to block for long periods of time. The thread pool has a maximum number of threads, so a large number of blocked thread pool threads might prevent tasks from starting. *You need to place threads into a single-threaded apartment. All ThreadPool threads are in the multithreaded apartment. *You need to have a stable identity associated with the thread, or to dedicate a thread to a task. A: @Eric @Derek, I don't exactly agree with the scenario you use as an example. If you don't know exactly what's running on your machine and exactly how many total threads, handles, CPU time, RAM, etc, that your app will use under a certain amount of load, you are in trouble. Are you the only target customer for the programs you write? If not, you can't be certain about most of that. You generally have no idea when you write a program whether it will execute effectively solo, or if it will run on a webserver being hammered by a DDOS attack. You can't know how much CPU time you are going to have. Assuming your program's behavior changes based on input, it's rare to even know exactly how much memory or CPU time your program will consume. Sure, you should have a pretty good idea about how your program is going to behave, but most programs are never analyzed to determine exactly how much memory, how many handles, etc. will be used, because a full analysis is expensive. If you aren't writing real-time software, the payoff isn't worth the effort. In general, claiming to know exactly how your program will behave is far-fetched, and claiming to know everything about the machine approaches ludicrous. And to be honest, if you don't know exactly what method you should use: manual threads, thread pool, delegates, and how to implement it to do just what your application needs, you are in trouble. I don't fully disagree, but I don't really see how that's relevant. This site is here specifically because programmers don't always have all the answers. If your application is complex enough to require throttling the number of threads that you use, aren't you almost always going to want more control than what the framework gives you? No. If I need a thread pool, I will use the one that's provided, unless and until I find that it is not sufficient. I will not simply assume that the provided thread pool is insufficient for my needs without confirming that to be the case. I'm not speaking as someone with only theoretical knowledge here. I write and maintain high volume applications that make heavy use of multithreading, and I generally don't find the thread pool to be the correct answer. Most of my professional experience has been with multithreading and multiprocessing programs. I have often needed to roll my own solution as well. That doesn't mean that the thread pool isn't useful, or appropriate in many cases. The thread pool is built to handle worker threads. In cases where multiple worker threads are appropriate, the provided thread pool should should generally be the first approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/10274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: Has anyone used Jaxer in production? Has anyone used Jaxer in a production environment, I am curious as to how it holds up compared to something like php, ruby, etc. and if anyone knows of any pitfalls to using it that are well known. A: @Stu: Not necessarily, maybe there's a bunch of people using it and having no issues. I love the concept having to only write validations once, using one language for everything both client and server side sounds like a interesting approach. A: As a rule, if you have to ask this question, it is a bad idea. A: I'll add this Url to my post I found it today, it has some information regarding the subject but no real "performance" information. A: I've posted a similar question and gotten a response... Not much information out there to be had yet. I did come across this set of performance benchmarks, and I've also posted a question about object-oriented development in Jaxer which I think might leave something to be desired. A: I figured I would put an answer on this, as to not leave it hanging. This answer is not directly related to Jaxer, but since this question was asked. Technologies such as Node.JS have came out, bringing with it the same ideas and technology Jaxer was proposing and showing that Javascript can be viable on the backend of the web technology stack just as it is on the front end.
{ "language": "en", "url": "https://stackoverflow.com/questions/10293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Validating posted form data in the ASP.NET MVC framework I've been playing around with the ASP.NET MVC Framework and the one thing that's really confusing me is how I'm meant to do server side validation of posted form data. I presume I don't post back to the same URL, but if I don't, how do I redisplay the form with the entered data and error messages? Also, where should the validation logic go? In the model or the controller? This seems to be one of the few areas where web forms are much stronger (I miss the validation controls). A: You might want to take a look at ScottGu's latest post for ASP.Net prev 5. It walks through a validation sample that is very interesting: http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx A: As far as I can tell everyone is still trying to figure out the "standard" way of doing it. That said definitely check out Phil Haack and Scott Guthrie's latest posts on MVC and you'll find some interesting info on how they did. When I was just playing around with it for myself I created a ModelBinder for the LinqToSql data class that I had generated. You can check out this post to find out how to put together a basic ModelBinder: ASP.Net MVC Model Binder The in your action if you had created a "Product" ModelBinder you would just declare the action like so: public ActionResult New(Product prod) And the model binder will take care of assigning posted data to the objects properties as long as you've built it right anyway. After that within your GetValue() method you can implement whatever validation you want, whether using exception's, regex's, or whatever you can make a call like: (ModelStateDictionary_name).AddModelError("form_element_id", "entered_value", "error_message"); Then you can just throw a <%= Html.ValidationSummary() %> in your view to display all your errors. For client-side validation I just used jQuery. After you get a basic sample set up though you can start doing some interesting things combining all that with Partial Views and Ajax calls. A: Have you taken a look at this? http://www.codeplex.com/MvcValidatorToolkit Quoted from the page The Validator Toolkit provides a set of validators for the new ASP.NET MVC framework to validate HTML forms on the client and server-side using validation sets. I'm afraid that someone more MVC-savvy than me would have to speak to where in the architecture you should put things. A: Here's an overview of the flow in MVC: * */new - render your "New" view containing a form for the user to fill out * *User fills out form and it is posted to /create *The post is routed to the Create action on your controller *In your action method, update the model with the data that was posted. *Your Model should validate itself. *Your Controller should read if the model is valid. *If the Model is valid, save it to your db. Redirect to /show to render the show View for your object. *If the Model is invalid, save the form values and error messages in the TempData, and redirect to the New action again. Fill your form fields with the data from TempData and show the error message(s). The validation frameworks will help you along in this process. Also, I think the ASP.NET MVC team is planning a validation framework for the next preview. A: I'm just learning the MVC framework too so I'm not sure how off this is, but from what I understand you would have a form on a View such as Edit.aspx. This form would then post to the controller to another action method such as Update() passing in the contents of the form that you set in Edit.aspx as parameters. Update(int id, string name, string foo) You could do the validation within that method. If all is ok, return View("Item", yourObject) A: There is Castle.Components.Validator module in Castle project. It's very agile and powerfull. It generates validation rules based on model attributes (or any other source) and even able to generate JS validation using jQuery, Prototype Validation, fValidate and other. Of course it's wise to abstract validator away behind IValidationEngine interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/10300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: What FoxPro data tools can I use to find corrupted data? I have some SQL Server DTS packages that import data from a FoxPro database. This was working fine until recently. Now the script that imports data from one of the FoxPro tables bombs out about 470,000 records into the import. I'm just pulling the data into a table with nullable varchar fields so I'm thinking it must be a weird/corrupt data problem. What tools would you use to track down a problem like this? FYI, this is the error I'm getting: Data for source column 1 ('field1') is not available. Your provider may require that all Blob columns be rightmost in the source result set. There should not be any blob columns in this table. Thanks for the suggestions. I don't know if it a corruption problem for sure. I just started downloading FoxPro from my MSDN Subscription, so I'll see if I can open the table. SSRS opens the table, it just chokes before running through all the records. I'm just trying to figure out which record it's having a problem with. A: Cmrepair is an excellent freeware utility to repair corrupted .DBF files. A: Have you tried writing a small program that just copies the existing data to a new table? Also, http://fox.wikis.com/wc.dll?Wiki~TableCorruptionRepairTools~VFP A: My company uses Foxpro to store quite a bit of data... In my experience, data corruption is very obvious, with the table failing to open in the first place. Do you have a copy of foxpro to open the table with? A: At 470,000 records you might want to check to see if you're approaching the 2 gigabyte limit on FoxPro table size. As I understand it, the records can still be there, but become inaccessible after the 2 gig point. A: @Lance: if you have access to Visual FoxPro command line window, type: SET TABLEVALIDATE 11 USE "YourTable" EXCLUSIVE && If the table is damaged VFP must display an error here PACK && To reindex the table and deleted "marked" records PACK MEMO && If you have memo fields After doing that, the structure of the table must ve valid, if you want to see fields with invalid data, you can try: SELECT * FROM YourTable WHERE EMPTY(YourField) && All records with YourField empty SELECT * FROM YourTable WHERE LEN(YourMemoField) > 200 && All records with a long memo field, there can be corrupted data etc. A: Use Repair Databases from my site (www.shershahsoft.com) for FREE (and Will always be FREE). I have designed this program to repair damaged Foxpro/FoxBase/Dbase files. The program is very quick. It will repair 1 GB table in less than a minute. You can asign files, and folders to the program. As you start the program it will mark all the corrupted files, and by clicking Repair or Check and Repair button, it will repair all the corrupted files. Moreover, it will create a folders "CorruptData" in the folders where the actual data exist, and will keep copies of the corrupt files there. One thing to keep in mind, always run Windows CheckDsk on the drives where you store the files. Cause, when records are being copied to a table and power failure occures, there exists lost clusters which Windows converts to files during CheckDsk. After that, the RepairDatabases will do the job for you. I have used many paid and free programs which repair tables, but all such programs leave extra records in the tables with embiguit characters (and they are time consuming too). The programer needs to find and delete such records manually. But Repair Databases actually recovers the original records, you need no further action. The only action you need is reindexing your files. In the repair process some times File Open Dialog appears which asks to locate the compact index file for a table with indeces. You may click cancel the dialog at that point, the table will be repaired, however, you will need to reindex the file later. (this dialog may appear several times depending upon the number of corrupted indeces.)
{ "language": "en", "url": "https://stackoverflow.com/questions/10303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Graphical representation of SVN branch/merge activity Are you aware of any tool that creates diagrams showing the branch/merge activity in a SVN repository? We've all seen these diagrams in various tutorials. Some good, some not so good. Can they be created automatically (or maybe with a little prodding -- you might have to tell it what if your branching philosophy is dev-test-prod, branch-per-release, etc.) I'm looking at the TortoiseSVN Revision Graph right now, but it has more detail than I want and the wrong layout. Orion, thanks for the response. I guess since branching and merging are more a convention for managing files in a repository than a "built in feature of SVN, it would be pretty tough. I'll stick with the poorly-drawn diagram at the top of the whiteboard in our team's office. A: Have a look at Subclipse from Tigris.org A: Well, you can use git and git-svn. First, clone your SVN repository into a Git repository, like this: git svn init "http://host/repo/location/trunk" Then, use the command: gitk --all From there, you'll see a nice graph of the revision history. Of course, this assumes you have git and git-svn set up correctly and are comfortable on the command line. One of the benefits of tracking source through Git is that the merging history is tracked through content modification, not chronological order or branch name. Therefore, it doesn't matter if your SVN repository has no merging history. If the gitk revision graph isn't sufficient, you may be able to pull the repo history from Git directly and make your own graph. A: Check this out SvnMapper from Tigris.org A: prior to SVN 1.5 (which has been out all of a month or so), it didn't track merges at all, so the bits where branches 'reconnect' to the trunk are impossible for it to do anyway
{ "language": "en", "url": "https://stackoverflow.com/questions/10308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Whats the best way of finding ALL your memory when developing on the Compact Framework? I've used the CF Remote Performance Monitor, however this seems to only track memory initialised in the managed world as opposed to the unmanaged world. Well, I can only presume this as the numbers listed in the profiler are way short of the maximum allowed (32mb on CE 5). Profiling a particular app with the RPM showed me that the total usage of all the caches only manages to get to about 12mb and then slowly shrinks as (I assume) something unmanaged starts to claim more memory. The memory slider in System also shows that the device is very short on memory. If I kill the process the slider shows all the memory coming back. So it must (?) be this managed process that is swallowing the memory. Is there any simple(ish?) fashion how one can track unmanaged memory usage in some way that might enable me to match it up with the corresponding P/Invoke calls? EDIT: To all you re-taggers it isn't .NET, tagging the question like this confuses things. It's .NETCF / Compact Framework. I know they appear to be similar but they're different because .NET rocks whereas CF is basically just a wrapper around NotImplementedException. A: Try enabling Interop logging. Also, if you have access to the code of the native dll you are using, check this out: http://msdn.microsoft.com/en-us/netframework/bb630228.aspx A: I've definitely been fighting with unmanaged issues in a C# managed app for a while -- it's not easy. What I've found to be most helpful is to have a regular output to a text log file. For example you can print the output of GlobalMemoryStatus every couple of minutes along with logging every time you load a new form. From there you can at least see that either memory gradually erodes, or a huge chunks of memory disappeared at specific times of the day. For us, we found a gradual memory loss all day as long as the device was being used. From there we eventually found that the barcode scanning device was being initialized for no particular reason in our Form base class (I blame the previous developer! :-) Setting up this logging may be a small hassle, but for us it paid huge dividends in the long run especially with the device in live use we can get real data, instrumentation, stack traces from exceptions, etc. A: Ok, I'm using C++ on CE, not C# so this may not be helpful, but... I use a package called Entrk toolbox which monitors memory and resource usage, leaks, and exceptions under Windows CE. Pretty much like a lightweight CE version of boundschecker. Does the trick most times.
{ "language": "en", "url": "https://stackoverflow.com/questions/10309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can I copy files to a Network Place from a script or the command line? Is it possible, in Windows XP, to copy files to a Network Place from the command line, a batch file or, even better, a PowerShell script? What sent me down this road of research was trying to publish files to a WSS 3.0 document library from a user's machine. I can't map a drive to the library in question because the WSS site is only available to authenticate via NTLM on a port other than 80 or 443. I suppose I could alternately use the WSS web services to push the files out, but I'm really curious about the answer to this question now. A: If you are referring to a windows box, just use xcopy. It is pretty standard to have xcopy available. xcopy src \\dest-machine\shared-library-name\dest xcopy \\src-machine\shared-library-name\dest src A: Powershell uses the abstraction of Providers to provide a common interface into datastores. These seem to stick with the common noun "Item", so you can get a complete list with man *item*. If you know another way to copy and otherwise work with data from a store, you might as well use it, but using the cmdlets provides a better "learn-once, use-often" approach. In your case you could: Copy-Item test.txt -Destination \\dest-machine\share Copy-item also supports the -Credential parameter if you need it. A: "Network Places" doesn't really have an API, it's just a bunch of shortcuts, and the SharePoint share uses a Shell Extension, if I recall correctly. All of that to say: accessing Sharepoint as a file system from PowerShell also requires an extension, the SharePoint Provider. A: Using a batch file, you can both log on to the resource and copy the file: The Batch File would contain the following: net use \\{dest-machine}\{destfolder} {password} /user:{username} copy {file} \\{dest-machine}\{destfolder} e.g. net use \\Development\myfolder mypassword /user:Administrator copy newfile.c \\development\myfolder A: you could use the 'net' commands to authenticate and then copy the files. copy src \\dest-machine\shared-library-name\dest I'm not really sure exactly how to handle authentication if it's needed. A: From what I'm seeing, it seems that it's not possible to directly access/ manipulate a Network Place from the command line, be it in PowerShell or the plain ol' command prompt. @slipsec (#13899): Thanks for the suggestion, but PowerShell doesn't support the port number in the destination path any more than the net use command does. So the best thing I can figure to do in my particular situation is bite the bullet and buy something like WebDrive to enable drive mapping via WebDAV on non-standard ports, or do some different configuration (e.g. separate web app with a different IP address and host headers) in SharePoint to expose the site via NTLM on a standard port. A: If it's something you need to script, you should consider NAnt. It's a mainly used for build scripts, but it's very powerful and reasonably easy to get started with. There's also NAntContrib and the nant ftp task which should help you out. A: I could be wrong about this, but I think that neither Nick's robocopy solution or Nathan's copy command solution will work. Robocopy seems to want a mapped drive, which I can't do because it's not running on port 80 or 443, and Windows can't handle a path that includes the port in a UNC-style name: copy src \\dest-machine:45000\shared-library-name\dest I didn't see a NAnt task that would handle this situation, either. I also know there are tools that will allow me to map WebDAV drives. I was more wondering if there was some way to make use of the Network Places that have been set up without using the GUI. A: Yes you can. I suggest using a tool like robocopy.
{ "language": "en", "url": "https://stackoverflow.com/questions/10313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How do you name your instance/param values? Being new to Objective-C (but a long term C/++) programmer I'm looking for advice/recommendations on naming conventions for variables. My personal preference would be to utilize a prefix for instance variables both for clarity within functions and to prevent shadowing of function parameters. However I'm a fan of properties which rules out prefixes (unless you also prefix your property names, which doesn't work too well and looks daft). Similarly I could use the "self.variable" convention, but only if I make EVERYTHING a property. So given the code below what's your preferred naming style for instance/function variables? And if you don't bother, how do you deal with shadowing on function params? @interface GridItem : NSObject { CGRect _rect; ... } @end -(void) initFromRect:(CGRect)rect { _rect = rect; ... } Cheers! A: I follow Chris Hanson's advice in regards to the underscore ivar prefix, though I admit I do use underscore's for IBOutlets as well. However, I've recently starting moving my IBOutlet declarations to the @property line, as per @mmalc's suggestion. The benefit is that all my ivars now have an underscore and standard KVC setters are called (i.e. setNameField:). Also, the outlet names don't have underscores in Interface Builder. @interface EmployeeWindowController : NSWindowController { @private // model object this window is presenting Employee *_employee; // outlets connected to views in the window NSTextField *_nameField; NSTextField *_titleField; } - (id)initWithEmployee:(Employee *)employee; @property(readwrite, retain) Employee *employee; @property(nonatomic, retain) IBOutlet NSTextField *nameField; @property(nonatomic, retain) IBOutlet NSTextField *titleField; @end A: You can use the underbar prefix on your ivars and still use the non-underbar name for your properties. For synthesized accessors, just do this: @synthesize foo = _foo; This tells the compiler to synthesize the foo property using the_foo ivar. If you write your own accessors, then you just use the underbar ivar in your implementation and keep the non-underbar method name. A: Personally, I follow the Cocoa naming conventions, using camel-casing for functions and variables, and capitalized camel-casing for object names (without the leading NS of course). I find type prefixing makes code more opaque to anyone who didn't write it (since everyone invariably uses different prefixes), and in a modern IDE it's not really that difficult to figure out something's type. A: With the introduction of properties I see no need for prefixing "_" to class instance variables. You can set a simple rule (described in your header file) that any variables to be accessed external to the class must be accessed via the property, or by using custom methods on the class to affect values. This to me seems much cleaner than having names with "_" stuck on the front of them. It also properly encapsulates the values so that you can control how they are changed. A: Most Cocoa projects use underbar as a non-IBOutlet instance variable prefix, and use no prefix for IBOutlet instance variables. The reason I don't use underbars for IBOutlet instance variables is that when a nib file is loaded, if you have a setter method for a connected outlet, that setter will be called. However this mechanism does not use Key-Value Coding, so an IBOutlet whose name is prefixed with an underbar (e.g. _myField) will not be set unless the setter is named exactly like the outlet (e.g. set_myField:), which is non-standard and gross. Also, be aware that using properties like self.myProp is not the same as accessing instance variables. You are sending a message when you use a property, just like if you used bracket notation like [self myProp]. All properties do is give you a concise syntax for specifying both the getter and setter in a single line, and allow you to synthesize their implementation; they do not actually short-circuit the message dispatch mechanism. If you want to access an instance variable directly but prefix it with self you need to treat self as a pointer, like self->myProp which really is a C-style field access. Finally, never use Hungarian notation when writing Cocoa code, and shy away from other prefixes like "f" and "m_" — that will mark the code as having been written by someone who doesn't "get it" and will cause it to be viewed by suspicion by other Cocoa developers. In general, follow the advice in the Coding Guidelines for Cocoa document at the Apple Developer Connection, and other developers will be able to pick up and understand your code, and your code will work well with all of the Cocoa features that use runtime introspection. Here's what a window controller class might look like, using my conventions: // EmployeeWindowController.h #import <AppKit/NSWindowController.h> @interface EmployeeWindowController : NSWindowController { @private // model object this window is presenting Employee *_employee; // outlets connected to views in the window IBOutlet NSTextField *nameField; IBOutlet NSTextField *titleField; } - (id)initWithEmployee:(Employee *)employee; @property(readwrite, retain) Employee *employee; @end // EmployeeWindowController.m #import "EmployeeWindowController.h" @implementation EmployeeWindowController @synthesize employee = _employee; - (id)initWithEmployee:(Employee *)employee { if (self = [super initWithWindowNibName:@"Employee"]) { _employee = [employee retain]; } return self; } - (void)dealloc { [_employee release]; [super dealloc]; } - (void)windowDidLoad { // populates the window's controls, not necessary if using bindings [nameField setStringValue:self.employee.name]; [titleField setStringValue:self.employee.title]; } @end You'll see that I'm using the instance variable that references an Employee directly in my -init and -dealloc method, while I'm using the property in other methods. That's generally a good pattern with properties: Only ever touch the underlying instance variable for a property in initializers, in -dealloc, and in the getter and setter for the property. A: I don't like using underscores as prefixes for any identifiers, because C and C++ both reserve certain underscore prefixes for use by the implementation. I think using "self.variable" is ugly. In general, I use unadorned identifiers (that is, no prefixes nor suffixes) for instance variables. If your class is so complicated that you can't remember the instance variables, you're in trouble. So for your example, I'd use "rect" as the name of the instance variable and "newRect" or "aRect" as the parameter name. A: Andrew: There actually are plenty of Cocoa developers who don't use instance variable prefixes at all. It's also extremely common in the Smalltalk world (in fact, I'd say it's nearly unheard-of in Smalltalk to use prefixes on instance variables). Prefixes on instance variables have always struck me as a C++-ism that was brought over to Java and then to C#. Since the Objective-C world was largely parallel to the C++ world, where as the Java and C# worlds are successors to it, that would explain the "cultural" difference you might see on this between the different sets of developers. A: My style is hybrid and really a holdover from PowerPlant days: THe most useful prefixes I use are "in" and "out" for function/method parameters. This helps you know what the parameters are for at a glance and really helps prevent conflicts between method parameters and instance variables (how many times have you seen the parameter "table" conflict with an instance variable of the same name). E.g.: - (void)doSomethingWith:(id)inSomeObject error:(NSError **)outError; Then I use the bare name for instance variables and property names: Then I use "the" as a prefix for local variables: theTable, theURL, etc. Again this helps differentiate between local and and instance variables. Then following PowerPlant styling I use a handful of other prefixes: k for constants, E for enums, g for globals, and s for statics. I've been using this style for something like 12 years now. A: While I love using the underscore prefix for ivars, I loathe writing @synthesize lines because of all the duplication (it's not very DRY). I created a macro to help do this and reduce code duplication. Thus, instead of: @synthesize employee = _employee; I write this: ddsynthesize(employee); It's a simple macro using token pasting to add an underscore to the right hand side: #define ddsynthesize(_X_) @synthesize _X_ = _##_X_ The only downside is that it will confuse Xcode's refactoring tool, and it won't get renamed, if you rename the property by refactoring. A: Along with what's been said here, be sure to read the Cocoa documentation on Key Value Observing compliant naming. Strictly following this pattern will help you greatly in the long run.
{ "language": "en", "url": "https://stackoverflow.com/questions/10314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why doesn't Ruby have a real StringBuffer or StringIO? I recently read a nice post on using StringIO in Ruby. What the author doesn't mention, though, is that StringIO is just an "I." There's no "O." You can't do this, for example: s = StringIO.new s << 'foo' s << 'bar' s.to_s # => should be "foo\nbar" # => really is ''` Ruby really needs a StringBuffer just like the one Java has. StringBuffers serve two important purposes. First, they let you test the output half of what Ruby's StringIO does. Second, they are useful for building up long strings from small parts -- something that Joel reminds us over and over again is otherwise very very slow. Is there a good replacement? It's true that Strings in Ruby are mutable, but that doesn't mean we should always rely on that functionality. If stuff is large, the performance and memory requirements of this, for example, is really bad. result = stuff.map(&:to_s).join(' ') The "correct" way to do this in Java is: result = StringBuffer.new("") for(String s : stuff) { result.append(s); } Though my Java is a bit rusty. A: Like other IO-type objects in Ruby, when you write to an IO, the character pointer advances. >> s = StringIO.new => #<StringIO:0x3659d4> >> s << 'foo' => #<StringIO:0x3659d4> >> s << 'bar' => #<StringIO:0x3659d4> >> s.pos => 6 >> s.rewind => 0 >> s.read => "foobar" A: Well, a StringBuffer is not quite as necessary in Ruby, mainly because Strings in Ruby are mutable... thus you can build up a string by modifying the existing string instead of constructing new strings with each concat. As a note, you can also use special string syntax where you can build a string which references other variables within the string, which makes for very readable string construction. Consider: first = "Mike" last = "Stone" name = "#{first} #{last}" These strings can also contain expressions, not just variables... such as: str = "The count will be: #{count + 1}" count = count + 1 A: I did some benchmarks and the fastest approach is using the String#<< method. Using StringIO is a little bit slower. s = ""; Benchmark.measure{5000000.times{s << "some string"}} => 3.620000 0.100000 3.720000 ( 3.970463) >> s = StringIO.new; Benchmark.measure{5000000.times{s << "some string"}} => 4.730000 0.120000 4.850000 ( 5.329215) Concatenating strings using the String#+ method is the slowest approach by many orders of magnitude: s = ""; Benchmark.measure{10000.times{s = s + "some string"}} => 0.700000 0.560000 1.260000 ( 1.420272) s = ""; Benchmark.measure{10000.times{s << "some string"}} => 0.000000 0.000000 0.000000 ( 0.005639) So I think the right answer is that the equivalent to Java's StringBuffer is simply using String#<< in Ruby. A: I looked at the ruby documentation for StringIO, and it looks like what you want is StringIO#string, not StringIO#to_s Thus, change your code to: s = StringIO.new s << 'foo' s << 'bar' s.string A: Your example works in Ruby - I just tried it. irb(main):001:0> require 'stringio' => true irb(main):002:0> s = StringIO.new => #<StringIO:0x2ced9a0> irb(main):003:0> s << 'foo' => #<StringIO:0x2ced9a0> irb(main):004:0> s << 'bar' => #<StringIO:0x2ced9a0> irb(main):005:0> s.string => "foobar" Unless I'm missing the reason you're using to_s - that just outputs the object id.
{ "language": "en", "url": "https://stackoverflow.com/questions/10323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: Convert a hexadecimal string to an integer efficiently in C? In C, what is the most efficient way to convert a string of hex digits into a binary unsigned int or unsigned long? For example, if I have 0xFFFFFFFE, I want an int with the base10 value 4294967294. A: For AVR Microcontrollers I wrote the following function, including relevant comments to make it easy to understand: /** * hex2int * take a hex string and convert it to a 32bit number (max 8 hex digits) */ uint32_t hex2int(char *hex) { uint32_t val = 0; while (*hex) { // get current character then increment char byte = *hex++; // transform hex character to the 4bit equivalent number, using the ascii table indexes if (byte >= '0' && byte <= '9') byte = byte - '0'; else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10; else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10; // shift 4 to make space for new digit, and add the 4 bits of the new digit val = (val << 4) | (byte & 0xF); } return val; } Example: char *z ="82ABC1EF"; uint32_t x = hex2int(z); printf("Number is [%X]\n", x); Will output: A: If you don't have the stdlib then you have to do it manually. unsigned long hex2int(char *a, unsigned int len) { int i; unsigned long val = 0; for(i=0;i<len;i++) if(a[i] <= 57) val += (a[i]-48)*(1<<(4*(len-1-i))); else val += (a[i]-55)*(1<<(4*(len-1-i))); return val; } Note: This code assumes uppercase A-F. It does not work if len is beyond your longest integer 32 or 64bits, and there is no error trapping for illegal hex characters. A: As if often happens, your question suffers from a serious terminological error/ambiguity. In common speech it usually doesn't matter, but in the context of this specific problem it is critically important. You see, there's no such thing as "hex value" and "decimal value" (or "hex number" and "decimal number"). "Hex" and "decimal" are properties of representations of values. Meanwhile, values (or numbers) by themselves have no representation, so they can't be "hex" or "decimal". For example, 0xF and 15 in C syntax are two different representations of the same number. I would guess that your question, the way it is stated, suggests that you need to convert ASCII hex representation of a value (i.e. a string) into a ASCII decimal representation of a value (another string). One way to do that is to use an integer representation as an intermediate one: first, convert ASCII hex representation to an integer of sufficient size (using functions from strto... group, like strtol), then convert the integer into the ASCII decimal representation (using sprintf). If that's not what you need to do, then you have to clarify your question, since it is impossible to figure it out from the way your question is formulated. A: You want strtol or strtoul. See also the Unix man page A: Edit: Now compatible with MSVC, C++ and non-GNU compilers (see end). The question was "most efficient way." The OP doesn't specify platform, he could be compiling for a RISC based ATMEL chip with 256 bytes of flash storage for his code. For the record, and for those (like me), who appreciate the difference between "the easiest way" and the "most efficient way", and who enjoy learning... static const long hextable[] = { [0 ... 255] = -1, // bit aligned access into this table is considerably ['0'] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // faster for most modern processors, ['A'] = 10, 11, 12, 13, 14, 15, // for the space conscious, reduce to ['a'] = 10, 11, 12, 13, 14, 15 // signed char. }; /** * @brief convert a hexidecimal string to a signed long * will not produce or process negative numbers except * to signal error. * * @param hex without decoration, case insensitive. * * @return -1 on error, or result (max (sizeof(long)*8)-1 bits) */ long hexdec(unsigned const char *hex) { long ret = 0; while (*hex && ret >= 0) { ret = (ret << 4) | hextable[*hex++]; } return ret; } It requires no external libraries, and it should be blindingly fast. It handles uppercase, lowercase, invalid characters, odd-sized hex input (eg: 0xfff), and the maximum size is limited only by the compiler. For non-GCC or C++ compilers or compilers that will not accept the fancy hextable declaration. Replace the first statement with this (longer, but more conforming) version: static const long hextable[] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; A: As written before, the efficiency basically depends on what one is optimizing for. When optiming for lines of code, or just working in environment without fully-equipped standard library one quick and dirty option could be: // makes a number from two ascii hexa characters int ahex2int(char a, char b){ a = (a <= '9') ? a - '0' : (a & 0x7) + 9; b = (b <= '9') ? b - '0' : (b & 0x7) + 9; return (a << 4) + b; } ... more in similar thread here: https://stackoverflow.com/a/58253380/5951263 A: Try this: #include <stdio.h> int main() { char s[] = "fffffffe"; int x; sscanf(s, "%x", &x); printf("%u\n", x); } A: @Eric Why is a code solution that works getting voted down? Sure, it's ugly and might not be the fastest way to do it, but it's more instructive that saying "strtol" or "sscanf". If you try it yourself you will learn something about how things happen under the hood. I don't really think your solution should have been voted down, but my guess as to why it's happening is because it's less practical. The idea with voting is that the "best" answer will float to the top, and while your answer might be more instructive about what happens under the hood (or a way it might happen), it's definitely not the best way to parse hex numbers in a production system. Again, I don't think there's anything wrong with your answer from an educational standpoint, and I certainly wouldn't (and didn't) vote it down. Don't get discouraged and stop posting just because some people didn't like one of your answers. It happens. I doubt my answer makes you feel any better about yours being voted down, but I know it's especially not fun when you ask why something's being voted down and no one answers. A: @Eric I was actually hoping to see a C wizard post something really cool, sort of like what I did but less verbose, while still doing it "manually". Well, I'm no C guru, but here's what I came up with: unsigned int parseHex(const char * str) { unsigned int val = 0; char c; while(c = *str++) { val <<= 4; if (c >= '0' && c <= '9') { val += c & 0x0F; continue; } c &= 0xDF; if (c >= 'A' && c <= 'F') { val += (c & 0x07) + 9; continue; } errno = EINVAL; return 0; } return val; } I originally had more bitmasking going on instead of comparisons, but I seriously doubt bitmasking is any faster than comparison on modern hardware. A: For larger Hex strings like in the example I needed to use strtoul. A: Hexadecimal to decimal. Don't run it on online compilers, because it won't work. #include<stdio.h> void main() { unsigned int i; scanf("%x",&i); printf("%d",i); } A: Why is a code solution that works getting voted down? Sure, it's ugly ... Perhaps because as well as being ugly it isn't educational and doesn't work. Also, I suspect that like me, most people don't have the power to edit at present (and judging by the rank needed - never will). The use of an array can be good for efficiency, but that's not mentioned in this code. It also takes no account of upper and lower case so it does not work for the example supplied in the question. FFFFFFFE A: #include "math.h" #include "stdio.h" /////////////////////////////////////////////////////////////// // The bits arg represents the bit say:8,16,32... ///////////////////////////////////////////////////////////// volatile long Hex_To_Int(long Hex,char bits) { long Hex_2_Int; char byte; Hex_2_Int=0; for(byte=0;byte<bits;byte++) { if(Hex&(0x0001<<byte)) Hex_2_Int+=1*(pow(2,byte)); else Hex_2_Int+=0*(pow(2,byte)); } return Hex_2_Int; } /////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////// void main (void) { int Dec; char Hex=0xFA; Dec= Hex_To_Int(Hex,8); //convert an 8-bis hexadecimal value to a number in base 10 printf("the number is %d",Dec); } A: Try this to Convert from Decimal to Hex #include<stdio.h> #include<conio.h> int main(void) { int count=0,digit,n,i=0; int hex[5]; clrscr(); printf("enter a number "); scanf("%d",&n); if(n<10) { printf("%d",n); } switch(n) { case 10: printf("A"); break; case 11: printf("B"); break; case 12: printf("B"); break; case 13: printf("C"); break; case 14: printf("D"); break; case 15: printf("E"); break; case 16: printf("F"); break; default:; } while(n>16) { digit=n%16; hex[i]=digit; i++; count++; n=n/16; } hex[i]=n; for(i=count;i>=0;i--) { switch(hex[i]) { case 10: printf("A"); break; case 11: printf("B"); break; case 12: printf("C"); break; case 13: printf("D"); break; case 14: printf("E"); break; case 15: printf("F"); break; default: printf("%d",hex[i]); } } getch(); return 0; } A: This currently only works with lower case but its super easy to make it work with both. cout << "\nEnter a hexadecimal number: "; cin >> hexNumber; orighex = hexNumber; strlength = hexNumber.length(); for (i=0;i<strlength;i++) { hexa = hexNumber.substr(i,1); if ((hexa>="0") && (hexa<="9")) { //cout << "This is a numerical value.\n"; } else { //cout << "This is a alpabetical value.\n"; if (hexa=="a"){hexa="10";} else if (hexa=="b"){hexa="11";} else if (hexa=="c"){hexa="12";} else if (hexa=="d"){hexa="13";} else if (hexa=="e"){hexa="14";} else if (hexa=="f"){hexa="15";} else{cout << "INVALID ENTRY! ANSWER WONT BE CORRECT\n";} } //convert from string to integer hx = atoi(hexa.c_str()); finalhex = finalhex + (hx*pow(16.0,strlength-i-1)); } cout << "The hexadecimal number: " << orighex << " is " << finalhex << " in decimal.\n"; A: In C you can convert a hexadecimal number to decimal in many ways. One way is to cast the hexadecimal number to an integer. I personally found this to be simple and small. Here is an sample code for converting a Hexadecimal number to a Decimal number with the help of casting. #include <stdio.h> int main(){ unsigned char Hexadecimal = 0x6D; //example hex number int Decimal = 0; //decimal number initialized to 0 Decimal = (int) Hexadecimal; //conversion printf("The decimal number is %d\n", Decimal); //output return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/10324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: In WinForms, why can't you update UI controls from other threads? I'm sure there is a good (or at least decent) reason for this. What is it? A: Because you can easily end up with a deadlock (among other issues). For exmaple, your secondary thread could be trying to update the UI control, but the UI control will be waiting for a resource locked by the secondary thread to be released, so both threads end up waiting for each other to finish. As others have commented this situation is not unique to UI code, but is particularly common. In other languages such as C++ you are free to try and do this (without an exception being thrown as in WinForms), but your application may freeze and stop responding should a deadlock occur. Incidentally, you can easily tell the UI thread that you want to update a control, just create a delegate, then call the (asynchronous) BeginInvoke method on that control passing it your delegate. E.g. myControl.BeginInvoke(myControl.UpdateFunction); This is the equivalent to doing a C++/MFC PostMessage from a worker thread A: Although it sounds reasonable Johns answer isn't correct. In fact even when using Invoke you're still not safe not running into dead-lock situations. When dealing with events fired on a background thread using Invoke might even lead to this problem. The real reason has more to do with race conditions and lays back in ancient Win32 times. I can't explain the details here, the keywords are message pumps, WM_PAINT events and the subtle differences between "SEND" and "POST". Further information can be found here here and here. A: I think this is a brilliant question - and I think there is need of a better answer. Surely the only reason is that there is something in a framework somewhere that isn't very thread-safe. That "something" is almost every single instance member on every single control in System.Windows.Forms. The MSDN documentation for many controls in System.Windows.Forms, if not all of them, say "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." This means that instance members such as TextBox.Text {get; set;} are not reentrant. Making each of those instance members thread safe could introduce a lot of overhead that most applications do not need. Instead the designers of the .Net framework decided, and I think correctly, that the burden of synchronizing access to forms controls from multiple threads should be put on the programmer. [Edit] Although this question only asks "why" here is a link to an article that explains "how": How to: Make Thread-Safe Calls to Windows Forms Controls on MSDN http://msdn.microsoft.com/en-us/library/ms171728.aspx A: Back in 1.0/1.1 no exception was thrown during debugging, what you got instead was an intermittent run-time hanging scenario. Nice! :) Therefore with 2.0 they made this scenario throw an exception and quite rightly so. The actual reason for this is probably (as Adam Haile states) some kind of concurrency/locky issue. Note that the normal .NET api (such as TextBox.Text = "Hello";) wraps SEND commands (that require immediate action) which can create issues if performed on separate thread from the one that actions the update. Using Invoke/BeginInvoke uses a POST instead which queues the action. More information on SEND and POST here. A: It is so that you don't have two things trying to update the control at the same time. (This could happen if the CPU switches to the other thread in the middle of a write/read) Same reason you need to use mutexes (or some other synchronization) when accessing shared variables between multiple threads. Edit: In other languages such as C++ you are free to try and do this (without an exception being thrown as in WinForms), but you'll end up learning the hard way! Ahh yes...I switch between C/C++ and C# and therefore was a little more generic then I should've been, sorry... He is correct, you can do this in C/C++, but it will come back to bite you! A: There would also be the need to implement synchronization within update functions that are sensitive to being called simultaneously. Doing this for UI elements would be costly at both application and OS levels, and completely redundant for the vast majority of code. Some APIs provide a way to change the current thread ownership of a system so you can temporarily (or permanently) update systems from other threads without needing to resort to inter-thread communication. A: Hmm I'm not pretty sure but I think that when we have a progress controls like waiting bars, progress bars we can update their values from another thread and everything works great without any glitches.
{ "language": "en", "url": "https://stackoverflow.com/questions/10349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Style display not working in Firefox, Opera, Safari - (IE7 is OK) I have an absolutely positioned div that I want to show when the user clicks a link. The onclick of the link calls a js function that sets the display of the div to block (also tried: "", inline, table-cell, inline-table, etc). This works great in IE7, not at all in every other browser I've tried (FF2, FF3, Opera 9.5, Safari). I've tried adding alerts before and after the call, and they show that the display has changed from none to block but the div does not display. I can get the div to display in FF3 if I change the display value using Firebug's HTML inspector (but not by running javascript through Firebug's console) - so I know it's not just showing up off-screen, etc. I've tried everything I can think of, including: * *Using a different doctype (XHTML 1, HTML 4, etc) *Using visibility visible/hidden instead of display block/none *Using inline javascript instead of a function call *Testing from different machines Any ideas about what could cause this? A: Can you provide some markup that reproduce the error? Your situation must have something to do with your code since I can get this to work on IE, FF3 and Opera 9.5: function show() { var d = document.getElementById('testdiv'); d.style.display = 'block'; } #testdiv { position: absolute; height: 20px; width: 20px; display: none; background-color: red; } <div id="testdiv"></div> <a href="javascript:show();">Click me</a> A: Since setting the properties with javascript never seemed to work, but setting using Firebug's inspect did, I started to suspect that the javascript ID selector was broken - maybe there were multiple items in the DOM with the same ID? The source didn't show that there were, but looping through all divs using javascript I found that that was the case. Here's the function I ended up using to show the popup: function openPopup(popupID) { var divs = getObjectsByTagAndClass('div','popupDiv'); if (divs != undefined && divs != null) { for (var i = 0; i < divs.length; i++) { if (divs[i].id == popupID) divs[i].style.display = 'block'; } } } (utility function getObjectsByTagAndClass not listed) Ideally I'll find out why the same item is being inserted multiple times, but I don't have control over the rendering platform, just its inputs. So when debugging issues like this, remember to check for duplicate IDs in the DOM, which can break getElementById. To everyone who answered, thanks for your help! A: Found the answer : I need to use the following to make it work on both browsers : document.getElementById('editRow').style.display = ''; A: Actually I was experiencing the same problem you're describing here. What actually fixed my issue was changing the document properties. Old DOCTYPE/html spec <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> Replaced with <html> A: Check the error console (Tools Menu > Error Console in Firefox 3) to make sure that there isn't another error happening that you're not seeing, which is stopping your script from working. A: Try setting the height and width of the div, and make sure it is on top by setting its z-index higher than everything else. If the absolutely positioned div is inside an element that is relatively positioned, it's top and left location is based off the top and left of the relatively positioned element. Try putting your div just under the body element. A: You must write a window.onload method: window.onload = document.getElementById('testdiv').style.display='inline'; Or you can also make a variable: var d = document.getElementById('testdiv'); window.onload = d.style.display = 'inline'; A: There is an annoying display error on Firefox 3.5 but not on IE7 or Firefox 2.0.9 I have 3 DIV's position absolute - the first with plain text; the second with a CSS menu (sucklefish type with UL and LI) and the third ditto. The third will not display at all even though the coding has been checked and found to be perfect with W3C's HTML validator. As a temporary measure, I have merged the second and third DIV's contents. Things must be bad at Mozilla when IE7 and FF2 display OK but not FF 3.5 A: I'll give you a BIG hint: <div style="..." class="..."> ... </div> If you have something in style, then document.style will work! If you have something in class, it will not show up in document.style and class="..." will OVERRIDE it! Think about this and this will clear up SO MANY ISSUES. Just this one little understanding will RID you of this MIND VIRUS. Have a good day. Cheers, Ron Lentjes, LC CLS.
{ "language": "en", "url": "https://stackoverflow.com/questions/10366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How can a Word document be created in C#? I have a project where I would like to generate a report export in MS Word format. The report will include images/graphs, tables, and text. What is the best way to do this? Third party tools? What are your experiences? A: To generate Word documents with Office Automation within .NET, specifically in C# or VB.NET: * *Add the Microsoft.Office.Interop.Word assembly reference to your project. The path is \Visual Studio Tools for Office\PIA\Office11\Microsoft.Office.Interop.Word.dll. *Follow the Microsoft code example you can find here: http://support.microsoft.com/kb/316384/en-us. A: The answer is going to depend slightly upon if the application is running on a server or if it is running on the client machine. If you are running on a server then you are going to want to use one of the XML based office generation formats as there are know issues when using Office Automation on a server. However, if you are working on the client machine then you have a choice of either using Office Automation or using the Office Open XML format (see links below), which is supported by Microsoft Office 2000 and up either natively or through service packs. One draw back to this though is that you might not be able to embed some kinds of graphs or images that you wish to show. The best way to go about things will all depend sightly upon how much time you have to invest in development. If you go the route of Office Automation there are quite a few good tutorials out there that can be found via Google and is fairly simple to learn. However, the Open Office XML format is fairly new so you might find the learning curve to be a bit higher. Office Open XML Iinformation * *Office Open XML - http://en.wikipedia.org/wiki/Office_Open_XML *OpenXML Developer - http://openxmldeveloper.org/default.aspx *Introducing the Office (2007) Open XML File Formats - http://msdn.microsoft.com/en-us/library/aa338205.aspx A: Schmidty, if you want to generate Word documents on a web server you will need a licence for each client (not just the web server). See this section in the first link Rob posted: "Besides the technical problems, you must also consider licensing issues. Current licensing guidelines prevent Office applications from being used on a server to service client requests, unless those clients themselves have licensed copies of Office. Using server-side Automation to provide Office functionality to unlicensed workstations is not covered by the End User License Agreement (EULA)." If you meet the licensing requirements, I think you will need to use COM Interop - to be specific, the Office XP Primary Interop Assemblies. A: Check out VSTO (Visual Studio Tools for Office). It is fairly simple to create a Word template, inject an xml data island into it, then send it to the client. When the user opens the doc in Word, Word reads the xml and transforms it into WordML and renders it. You will want to look at the ServerDocument class of the VSTO library. No extra licensing is required from my experience. A: I faced this problem and created a small library for this. It was used in several projects and then I decided to publish it. It is free and very very simple but I'm sure it will help with you with the task. Invoke the Office Open XML Library, http://invoke.co.nz/products/docx.aspx. A: I have had good success using the Syncfusion Backoffice DocIO which supports doc and docx formats. In prior releases it did not support everything in word, but accoriding to your list we tested it with tables and text as a mail merge approach and it worked fine. Not sure about the import of images though. On their blurb page http://www.syncfusion.com/products/DocIO/Backoffice/features/default.aspx it says Blockquote Essential DocIO has support for inserting both Scalar and Vector images into the document, in almost all formats. Bitmap, gif, png and tiff are some of the common image types supported. So its worth considering. As others have mentioned you can build up a RTF document, there are some good RTF libraries around for .net like http://www.codeproject.com/KB/string/nrtftree.aspx A: I've written a blog post series on Open XML WordprocessingML document generation. My approach is that you create a template document that contains content controls, and in each content control you write an XPath expression that defines how to retrieve the content from an XML document that contains the data that drives the document generation process. The code is free, and is licensed under the the Microsoft Reciprocal License (Ms-RL). In that same blog post series, I also explore an approach where you write C# code in content controls. The document generation process then processes the template document and generates a C# program that generates the desired documents. One advantage of this approach is that you can use any data source as the source of data for the document generation process. That code is also licenced under the Microsoft Reciprocal License. A: I currently do this exact thing. If the document isn't very big, doesn't contain images and such, then I store it as an RTF with #MergeFields# in it and simply replace them with content, sending the result down to the user as an RTF. For larger documents, including images and dynamically inserted images, I save the initial Word document as a Single Webpage *.mht file containing the #MergeFields# again. I then do the same as above. Using this, I can easily render a DataTable with some basic Html table tags and replace one of the #MergeFields# with a whole table. Images can be stored on your server and the url embedded into the document too. Interestingly, the new Office 2007 file formats are actually zip files - if you rename the extension to .zip you can open them up and see their contents. This means you should be able to switch content such as images in and out using a simple C# zip library. A: DocX free library for creating DocX documents, actively developed and very easy and intuitive to use. Since CodePlex is dying, project has moved to github. A: I have spent the last week or so getting up to speed on Office Open XML. We have a database application that stores survey data that we want to report in Microsoft Word. You can actually create Word 2007 (docx) files from scratch in C#. The Open XML SDK version 2 includes a cool application called the Document Reflector that will actually provide the C# code to fully recreate a Word document. You can use parts or all of the code, and substitute the bits you want to change on the fly. The help file included with the SDK has some good code samples as well. There is no need for the Office Interop or any other Office software on the server - the new formats are 100% XML. A: Have you considered using .RTF as an alternative? It supports embedding images and tables as well as text, opens by default using Microsoft Word and whilst it's featureset is more limited (count out any advanced formatting) for something that looks and feels and opens like a Word document it's not far off. Your end users probably won't notice. A: I have found Aspose Words to be the best as not everybody can open Office Open XML/*.docx format files and the Word interop and Word automation can be buggy. Aspose Words supports most document file types from Word 97 upwards. It is a pay-for component but has great support. The other alternative as already suggested is RTF. A: @Dale Ragan: That will work for the Office 2003 XML format, but that's not portable (as, say, .doc or .docx files would be). To read/write those, you'll need to use the Word Object Library ActiveX control: http://www.codeproject.com/KB/aspnet/wordapplication.aspx A: @Danny Smurf: Actually this article describes what will become the Office Open XML format which Rob answered with. I will pay more attention to the links I post for now on to make sure there not obsolete. I actually did a search on WordML, which is what it was called at the time. I believe that the Office Open XML format is the best way to go. A: LibreOffice also supports headless interaction via API. Unfortunately there's currently not much information about this feature yet.. :( A: You could also use Word document generator. It can be used for client-side or server-side deployment. From the project description: WordDocumentGenerator is an utility to generate Word documents from templates using Visual Studio 2010 and Open XML 2.0 SDK. WordDocumentGenerator helps generate Word documents both non-refresh-able as well as refresh-able based on predefined templates using minimum code changes. Content controls are used as placeholders for document generation. It supports Word 2007 and Word 2010. Grab it: http://worddocgenerator.codeplex.com/ Download SDK: http://www.microsoft.com/en-us/download/details.aspx?id=5124 A: Another alternative is Windward Docgen (disclaimer - I'm the founder). With Windward you design the template in Word, including images, tables, graphs, gauges, and anything else you want. You can set tags where data from an XML or SQL datasource is inserted (including functionality like forEach loops, import, etc). And then generate the report to DOCX, PDF, HTML, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/10412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "74" }
Q: Impersonation in IIS 7.0 I have a website that works correctly under IIS 6.0: It authenticates users with windows credentials, and then when talking to the service that hits the DB, it passes the credentials. In IIS 7.0, the same config settings do not pass the credentials, and the DB gets hit with NT AUTHORITY\ANONYMOUS. Is there something I'm missing? I've turned ANONYMOUS access off in my IIS 7.0 website, but I can't get the thing to work. These are the settings that I'm using on both IIS 6.0 and 7.0: <authentication mode="Windows"> <identity impersonate="true"> What changed from 6.0 to 7.0? A: There has been changes between IIS7 and IIS6.0. I found for you one blog post that might actually help you (click here to see it). Are you running your application in Integrated Mode or in Classic Mode? From what I saw, putting the Impersonate attribute at true should display you a 500 error with the following error message: Internal Server Error. This is HTTP Error 500.19: The requested page cannot be accessed because the related configuration data for the page is invalid. Here is the workaround that is proposed: Workaround: 1) If your application does not rely on impersonating the requesting user in the BeginRequest and AuthenticateRequest stages (the only stages where impersonation is not possible in Integrated mode), ignore this error by adding the following to your application’s web.config: <validation validateIntegratedModeConfiguration="false" /> 2) If your application does rely on impersonation in BeginRequest and AuthenticateRequest, or you are not sure, move to classic mode. I hoped that was useful to understand how IIS 7.0 now works. A: Is your IIS server set up to be trusted for delegation by the SQLServer? I've run into this before with WebDAV where we've had to have the server running IIS trusted by the file server to authenticate on the file server's behalf. A: Interesting... I have the opposite problem - Not being able to get the authentication to be passed from the client browser, through the webserver and onto the database within a large corporate network over firewalls. I also feel that "end to end user" authentication to the database is a bad idea and a potential security risk. There is nothing to stop the end user from loading up SQL Query and connecting directly to your database, so you'd better have your schema locked down! @Esteban - Clarified my not very useful in helping you answer. A: Typically if you are doing double hop authentication like this, Kerberos is typically involved unless the first authentication is Basic. I would check the authentication on the IIS 6 servers and make sure that it's the same on IIS 7. If the IIS 6 box is set to Windows Integrated, then you need to verify the kerberos settings - SPNs, Delegation etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/10435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Send messages to program through command line I have this program, we'll call it Host. Host does all kinds of good stuff, but it needs to be able to accept input through the command line while it's running. This means it has to somehow send its other process data and then quit. For example, I need to be able to do this: ./Host --blahblah 3 6 3 5 This should somehow end up calling some function in Host called handleBlahBlah(int x1, int y1, int x2, int y2){ //do some more sweet stuff } Host is a C program, and does not need to support multiple instances. An example of this is Amarok music player. With Amarok running and playing, you can type "amarok --pause" and it will pause the music. I need to be able to do this in Linux or Windows. Preferably Linux. What is the cleanest way to implement this? A: If it needs to be cross-platform, you might want to consider making the running instance listen on a TCP port, and have the instance you fire up from the command-line send a message to that port. A: I suggest using either a Unix socket or D-Bus. Using a socket might be faster if you're familiar with Unix sockets programming and only want a few operations, whereas D-Bus might make it easier to concentrate on implementing the functionality in a familiar object-oriented way. Take a look at Beej's Guide to Unix IPC, particularly the chapter on Unix sockets. A: If you were on Windows, I'd tell you to use a hidden window to receive the messages, but since you used ./, I assume you want something Unix-based. In that case, I'd go with a named pipe. Sun has a tutorial about named pipes that might be useful. The program would probably create the pipe and listen. You could have a separate command-line script which would open the pipe and just echo its command-line arguments to it. You could modify your program to support the command-line sending instead of using a separate script. You'd do the same basic thing in that case. Your program would look at it's command-line arguments, and if applicable, open the pipe to the "main" instance of the program, and send the arguments through. A: What no one has said here is this: "you can't get there from here". The command line is only available as it was when your program was invoked. The example of invoking "fillinthename arguments ..." to communicate with fillinthename once fillinthename is running can only be accomplished by using two instances of the program which communicate with each other. The other answers suggest ways to achieve the communication. An amarok like program needs to detect the existence of another instance of itself in order to know which role it must play, the major role of persistent message receiver/server, or the minor role of one shot message sender. edited to make the word fillinthename actually be displayed. A: One technique I have seen is to have your Host program be merely a "shell" for your real program. For example when you launch your application normally (e.g.: ./Host), the program will fork into the "main app" part of your code. When you launch your program in a way that suggests you want to signal the running instance (e.g.: ./Host --send-message restart), the program will fork into the "message sender" part of your code. It's like having two apps in one. Another option that doesn't use fork is to make Host purely a "message sender" app and have your "main app" as a separate executable (e.g.: Host_core) that Host can launch separately. The "main app" part of your program will need to open up some kind of a communication channel to receive messages, and the "message sender" part will need to connect to that channel and use it to send messages. There are several different options available for sending messages between processes. Some of the more common methods are pipes and sockets. Depending on your OS, you may have additional options available; for instance, QNX has channels and BeOS/Haiku have BMessages. You may also be able to find a library that neatly wraps up this functionality, such as lcm. A: So, I may be missing the point here, but by deafult a C program's main function takes two arguments; argc, a count of the number of arguments (at least one), and argv (or arg vector), the argument list. You could just parse through the arguments and call the correct method. For example: int main(int argc, *argv[]) { /*loop through each argument and take action*/ while (--argc > 0) { printf(%s%s, *++argv, (argc > 1) ? " " : ""); } } would print all of the arguments to screen. I am no C guru, so I hope I haven't made any mistakes. EDIT: Ok, he was after something else, but it wasn't really clear before the question was edited. Don't have to jump on my rep...
{ "language": "en", "url": "https://stackoverflow.com/questions/10443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: HowTo Disable WebBrowser 'Click Sound' in your app only The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus. Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta. using System; using Microsoft.Win32; namespace HowTo { class WebClickSound { /// <summary> /// Enables or disables the web browser navigating click sound. /// </summary> public static bool Enabled { get { RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current"); string keyValue = (string)key.GetValue(null); return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\""; } set { string keyValue; if (value) { keyValue = "%SystemRoot%\\Media\\"; if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0) { // XP keyValue += "Windows XP Start.wav"; } else if (Environment.OSVersion.Version.Major == 6) { // Vista keyValue += "Windows Navigation Start.wav"; } else { // Don't know the file name so I won't be able to re-enable it return; } } else { keyValue = "\"\""; } // Open and set the key that points to the file RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true); key.SetValue(null, keyValue, RegistryValueKind.ExpandString); isEnabled = value; } } } } Then in the main form we use the above code in these 3 events: * *Activated *Deactivated *FormClosing private void Form1_Activated(object sender, EventArgs e) { // Disable the sound when the program has focus WebClickSound.Enabled = false; } private void Form1_Deactivate(object sender, EventArgs e) { // Enable the sound when the program is out of focus WebClickSound.Enabled = true; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Enable the sound on app exit WebClickSound.Enabled = true; } The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that. What do you guys think? Is this a good solution? What improvements can be made? A: const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21; const int SET_FEATURE_ON_PROCESS = 0x00000002; [DllImport("urlmon.dll")] [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] static extern int CoInternetSetFeatureEnabled(int FeatureEntry, [MarshalAs(UnmanagedType.U4)] int dwFlags, bool fEnable); static void DisableClickSounds() { CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS, SET_FEATURE_ON_PROCESS, true); } A: I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen. So instead of this: webBrowser1.DocumentText = "<h1>Hello, world!</h1>"; try this: webBrowser1.Document.OpenNew(true); webBrowser1.Document.Write("<h1>Hello, world!</h1>"); A: You disable it by changing Internet Explorer registry value of navigating sound to "NULL": Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","NULL"); And enable it by changing Internet Explorer registry value of navigating sound to "C:\Windows\Media\Cityscape\Windows Navigation Start.wav": Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","C:\Windows\Media\Cityscape\Windows Navigation Start.wav"); A: Definitely feels like a hack, but having done some research on this a long time ago and not finding any other solutions, probably your best bet. Better yet would be designing your application so it doesn't require many annoying page reloads.. for example, if you're refreshing an iframe to check for updates on the server, use XMLHttpRequest instead. (Can you tell that I was dealing with this problem back in the days before the term "AJAX" was coined?) A: If you want to use replacing Windows Registry, use this: // backup value RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current"); string BACKUP_keyValue = (string)key.GetValue(null); // write nothing key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true); key.SetValue(null, "", RegistryValueKind.ExpandString); // do navigation ... // write backup key RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true); key.SetValue(null, BACKUP_keyValue, RegistryValueKind.ExpandString);
{ "language": "en", "url": "https://stackoverflow.com/questions/10456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Is there a "Set" data structure in .Net? Ideally, I'm looking for a templated logical Set class. It would have all of the standard set operations such as Union, Intersection, Etc., and collapse duplicated items. I ended up creating my own set class based on the C# Dictionary<>- just using the Keys. A: I don't think c# has anything built in, but I know there are a couple of implementations floating around on the net. There are also some good articles around on this sort of thing: This is part 6 of a series on efficiently representing data structure. This part focuses on representing sets in C#. An implementation of a set collection An implementation of a set class Yet another implementation of a set class And finally... I've actually used this library myself as the basis of a set implementation that I did a year or so ago. A: HashSet<T> is about the closest you'll get, I think. A: The best set implementation I have seen is part of the wonderful Wintellect's Power Collections: http://www.codeplex.com/PowerCollections. The set implementation can be found here: http://www.codeplex.com/PowerCollections/SourceControl/FileView.aspx?itemId=101886&changeSetId=6259 It has all the expected set operations (union, intersect, etc). Hope this helps! A: No, there is not one natively in the framework. There is an open source implementation that most projects use, (i.e. nHibernate) called Iesi.Collections. Here's a CodeProject article about it: http://www.codeproject.com/KB/recipes/sets.aspx A: Have you checked out the HashSet in 3.5? A: Here's a simple implementation: public sealed class MathSet<T> : HashSet<T>, IEquatable<MathSet<T>> { public override int GetHashCode() => this.Select(elt => elt.GetHashCode()).Sum().GetHashCode(); public bool Equals(MathSet<T> obj) => SetEquals(obj); public override bool Equals(object obj) => Equals(obj as MathSet<T>); public static bool operator ==(MathSet<T> a, MathSet<T> b) => ReferenceEquals(a, null) ? ReferenceEquals(b, null) : a.Equals(b); public static bool operator !=(MathSet<T> a, MathSet<T> b) => !(a == b); } Example usage: var a = new MathSet<int> { 1, 2, 3 }; var b = new MathSet<int> { 3, 2, 1 }; var c = a.Equals(b); // true var d = new MathSet<MathSet<int>> { a, b }; // contains one element var e = a == b; // true See this question for why this approach was considered over HashSet.
{ "language": "en", "url": "https://stackoverflow.com/questions/10458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: Touch Typing Software recommendations Since the keyboard is the interface we use to the computer, I've always thought touch typing should be something I should learn, but I've always been, well, lazy is the word. So, anyone recommend any good touch typing software? It's easy enough to google, but I'ld like to hear recommendations. A: Find a long document on the web, using Firefox Press CTRL+F Type along with the document. Try it, it works. A: Mavis Beacon. Although not nearly as fun as Typing of the Dead! A: I've been touchtyping since I was 10 years old (on a real typewriter at that!) but one thing that helped my sister learn touchtyping is hanging out in IRC channels. You want to be able to "talk" as fast as you can speak and that trained her in typing a lot faster. I know it's a lame answer and not really a software solution or what, but it worked for a lot of people I know. :) A: Try http://keybr.com/? It is a little different from the usual format of free typing tutors. If you create an account, it keeps track of your progress as well. No add-ware and no pop-ups, or other useless junk. A: Typing of the Dead! It's a good few years old so you may have to hunt around, but it's a lot of fun and as well as the main game there are numerous minigames to practice specific areas you may be weak on. A: If you want to learn by getting thrown in the deep end... DasKeyboard ultimate will have you touch typing in no time :) A: I use Rapid Typing to learn touch typing. It has excellent visuals and it's even somewhat relaxing to type. A: I trained my typing on GNU Typist. It comes with exercises for various languages and keyboard layouts, if you're so inclined. One of the most fun typing programs I used is dvorak7min. It has a nastiness mode where for each typo you make, the cursor goes back by 1. So if you don't watch your typing, you'll be back to square 1…. A: If you want some motivation to learn to touch type read Steve Yegge's Blog rant: Programming's Dirtiest Little Secret A: About the recommendation to use the DasKeyboard, I just started using one today! But be aware that it makes a lot of noise. I was mortified how much noise it was making in my super quiet office filled with other people, who are engineers but mostly not developers. I asked the person across from me if it was too noisy. She hesitated for a fraction of a second before insisting it was fine, and when I said I would put it away she barely protested. So I packed it up. Maybe if you are just surrounded by other devs it would be OK. I'd love to hear of contrary experiences. I'm banging away from home right now though, as loud as possible, and loving it! Oh, and you will definitely learn to touch type! Right now I have a picture of a labeled keyboard as my desktop image, but am referring to it less and less. Mike A: I have a really weird habitual way of typing where I use several fingers on my left hand but only one or two on the right. This has served me for years and apparently gives me 80+ words per minute, but it does seem an incredibly weird way to type. This is touch typing but not using the "standard" finger arrangement. While it's probably not a great idea to try and fix something that already works, I thought I'd try and relearn to type the proper way (left fingers on asdf and right fingers on jkl;). I've been trying out Mavis Beacon and it seems alright, it slowly adds more and more letters to your repertoire allowing you to gain the muscle memory or whatever, and then focuses on speed. The "games" seem a little pointless (is this program designed for kids?), but I guess for someone who doesn't know where the keys are it does a good job showing you which fingers to use and where to move them. As I already knew where the keys are most of the program didn't really aid me. Once you know where the keys are you probably just want to practice typing out text and a program like that won't really aid any more than notepad apart from counting your words per minute and giving you something to type. I agree with Typing of the dead being pretty awesome though, and will definitely help with your speed once you've got the finger arrangement down. Do all you touch typers use the standard finger arrangement or do you just do your own thing? I think I've come to the conclusion I'll just stick with what I know, it seems to work anyway. A: For the sake of completeness, my wife used KP Typing Tutor, worked great. +1 on chatting more A: I used the TTCoach plugin for Vim and have been very happy with it. It doesnt come with any exercises for numbers and symbols however, but it is easy to just make some text files yourself and write :TTCustom file.txt to use it for exercising. Just learn a couple of characters at a time and when you got them nailed, learn a couple more and so on... A: I've been using TypeFaster. It's not pretty, but one nice feature is that it can load lessons in different keyboard layouts, like Colemak (layout files here) or Dvorak.
{ "language": "en", "url": "https://stackoverflow.com/questions/10475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Equidistant points across Bezier curves Currently, I'm attempting to make multiple beziers have equidistant points. I'm currently using cubic interpolation to find the points, but because the way beziers work some areas are more dense than others and proving gross for texture mapping because of the variable distance. Is there a way to find points on a bezier by distance rather than by percentage? Furthermore, is it possible to extend this to multiple connected curves? A: This is called "arc length" parameterization. I wrote a paper about this several years ago: http://www.saccade.com/writing/graphics/RE-PARAM.PDF The idea is to pre-compute a "parameterization" curve, and evaluate the curve through that. A: distance between P_0 and P_3 (in cubic form), yes, but I think you knew that, is straight forward. Distance on a curve is just arc length: fig 1 http://www.codecogs.com/eq.latex?%5Cint_%7Bt_0%7D%5E%7Bt_1%7D%20%7B%20|P'(t)|%20dt where: fig 2 http://www.codecogs.com/eq.latex?P%27(t)%20=%20[%7Bx%27,y%27,z%27%7D]%20=%20[%7B%5Cfrac%7Bdx(t)%7D%7Bdt%7D,%5Cfrac%7Bdy(t)%7D%7Bdt%7D,%5Cfrac%7Bdz(t)%7D%7Bdt%7D%7D] (see the rest) Probably, you'd have t_0 = 0, t_1 = 1.0, and dz(t) = 0 (2d plane). A: I know this is an old question but I recently ran into this problem and created a UIBezierPath extention to solve for an X coordinate given a Y coordinate and vise versa. Written in swift. https://github.com/rkotzy/RKBezierMath extension UIBezierPath { func solveBezerAtY(start: CGPoint, point1: CGPoint, point2: CGPoint, end: CGPoint, y: CGFloat) -> [CGPoint] { // bezier control points let C0 = start.y - y let C1 = point1.y - y let C2 = point2.y - y let C3 = end.y - y // The cubic polynomial coefficients such that Bez(t) = A*t^3 + B*t^2 + C*t + D let A = C3 - 3.0*C2 + 3.0*C1 - C0 let B = 3.0*C2 - 6.0*C1 + 3.0*C0 let C = 3.0*C1 - 3.0*C0 let D = C0 let roots = solveCubic(A, b: B, c: C, d: D) var result = [CGPoint]() for root in roots { if (root >= 0 && root <= 1) { result.append(bezierOutputAtT(start, point1: point1, point2: point2, end: end, t: root)) } } return result } func solveBezerAtX(start: CGPoint, point1: CGPoint, point2: CGPoint, end: CGPoint, x: CGFloat) -> [CGPoint] { // bezier control points let C0 = start.x - x let C1 = point1.x - x let C2 = point2.x - x let C3 = end.x - x // The cubic polynomial coefficients such that Bez(t) = A*t^3 + B*t^2 + C*t + D let A = C3 - 3.0*C2 + 3.0*C1 - C0 let B = 3.0*C2 - 6.0*C1 + 3.0*C0 let C = 3.0*C1 - 3.0*C0 let D = C0 let roots = solveCubic(A, b: B, c: C, d: D) var result = [CGPoint]() for root in roots { if (root >= 0 && root <= 1) { result.append(bezierOutputAtT(start, point1: point1, point2: point2, end: end, t: root)) } } return result } func solveCubic(a: CGFloat?, var b: CGFloat, var c: CGFloat, var d: CGFloat) -> [CGFloat] { if (a == nil) { return solveQuadratic(b, b: c, c: d) } b /= a! c /= a! d /= a! let p = (3 * c - b * b) / 3 let q = (2 * b * b * b - 9 * b * c + 27 * d) / 27 if (p == 0) { return [pow(-q, 1 / 3)] } else if (q == 0) { return [sqrt(-p), -sqrt(-p)] } else { let discriminant = pow(q / 2, 2) + pow(p / 3, 3) if (discriminant == 0) { return [pow(q / 2, 1 / 3) - b / 3] } else if (discriminant > 0) { let x = crt(-(q / 2) + sqrt(discriminant)) let z = crt((q / 2) + sqrt(discriminant)) return [x - z - b / 3] } else { let r = sqrt(pow(-(p/3), 3)) let phi = acos(-(q / (2 * sqrt(pow(-(p / 3), 3))))) let s = 2 * pow(r, 1/3) return [ s * cos(phi / 3) - b / 3, s * cos((phi + CGFloat(2) * CGFloat(M_PI)) / 3) - b / 3, s * cos((phi + CGFloat(4) * CGFloat(M_PI)) / 3) - b / 3 ] } } } func solveQuadratic(a: CGFloat, b: CGFloat, c: CGFloat) -> [CGFloat] { let discriminant = b * b - 4 * a * c; if (discriminant < 0) { return [] } else { return [ (-b + sqrt(discriminant)) / (2 * a), (-b - sqrt(discriminant)) / (2 * a) ] } } private func crt(v: CGFloat) -> CGFloat { if (v<0) { return -pow(-v, 1/3) } return pow(v, 1/3) } private func bezierOutputAtT(start: CGPoint, point1: CGPoint, point2: CGPoint, end: CGPoint, t: CGFloat) -> CGPoint { // bezier control points let C0 = start let C1 = point1 let C2 = point2 let C3 = end // The cubic polynomial coefficients such that Bez(t) = A*t^3 + B*t^2 + C*t + D let A = CGPointMake(C3.x - 3.0*C2.x + 3.0*C1.x - C0.x, C3.y - 3.0*C2.y + 3.0*C1.y - C0.y) let B = CGPointMake(3.0*C2.x - 6.0*C1.x + 3.0*C0.x, 3.0*C2.y - 6.0*C1.y + 3.0*C0.y) let C = CGPointMake(3.0*C1.x - 3.0*C0.x, 3.0*C1.y - 3.0*C0.y) let D = C0 return CGPointMake(((A.x*t+B.x)*t+C.x)*t+D.x, ((A.y*t+B.y)*t+C.y)*t+D.y) } // TODO: - future implementation private func tangentAngleAtT(start: CGPoint, point1: CGPoint, point2: CGPoint, end: CGPoint, t: CGFloat) -> CGFloat { // bezier control points let C0 = start let C1 = point1 let C2 = point2 let C3 = end // The cubic polynomial coefficients such that Bez(t) = A*t^3 + B*t^2 + C*t + D let A = CGPointMake(C3.x - 3.0*C2.x + 3.0*C1.x - C0.x, C3.y - 3.0*C2.y + 3.0*C1.y - C0.y) let B = CGPointMake(3.0*C2.x - 6.0*C1.x + 3.0*C0.x, 3.0*C2.y - 6.0*C1.y + 3.0*C0.y) let C = CGPointMake(3.0*C1.x - 3.0*C0.x, 3.0*C1.y - 3.0*C0.y) return atan2(3.0*A.y*t*t + 2.0*B.y*t + C.y, 3.0*A.x*t*t + 2.0*B.x*t + C.x) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/10477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }