text
stringlengths
8
267k
meta
dict
Q: How to discover USB storage devices and writable CD/DVD drives (C#) How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0). I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive. A: using System.IO; DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { if (d.IsReady && d.DriveType == DriveType.Removable) { // This is the drive you want... } } The DriveInfo class documentation is here: http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx A: this is VB.NET code to check for any removable drives or CDRom drives attached to the computer: Me.lstDrives.Items.Clear() For Each item As DriveInfo In My.Computer.FileSystem.Drives If item.DriveType = DriveType.Removable Or item.DriveType = DriveType.CDRom Then Me.lstDrives.Items.Add(item.Name) End If Next it won't be that hard to modify this code into a c# equivalent, and more driveType's are available. From MSDN: * *Unknown: The type of drive is unknown. *NoRootDirectory: The drive does not have a root directory. *Removable: The drive is a removable storage device, such as a floppy disk drive or a USB flash drive. *Fixed: The drive is a fixed disk. *Network: The drive is a network drive. *CDRom: The drive is an optical disc device, such as a CD or DVD-ROM. *Ram: The drive is a RAM disk. A: in c# you can get the same by using the System.IO.DriveInfo class using System.IO; public static class GetDrives { public static IEnumerable<DriveInfo> GetCDDVDAndRemovableDevices() { return DriveInfo.GetDrives(). Where(d => d.DriveType == DriveType.Removable && d.DriveType == DriveType.CDRom); } } A: This is a complete module for VB.NET : Imports System.IO Module GetDriveNamesByType Function GetDriveNames(Optional ByVal DType As DriveType = DriveType.Removable) As ListBox For Each DN As System.IO.DriveInfo In My.Computer.FileSystem.Drives If DN.DriveType = DType Then GetDriveNames.Items.Add(DN.Name) End If Next End Function End Module 'Drive Types <br> 'Unknown: The type of drive is unknown. <br> 'NoRootDirectory: The drive does not have a root directory. <br> 'Removable: The drive is a removable storage device, such as a floppy disk drive or a USB flash drive. <br> 'Fixed: The drive is a fixed disk. <br> 'Network: The drive is a network drive. <br> 'CDRom: The drive is an optical disc device, such as a CD or DVD-ROM. <br> 'Ram: The drive is a RAM disk. <br>
{ "language": "en", "url": "https://stackoverflow.com/questions/51645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How does off-the-shelf software fit in with agile development? Maybe my understanding of agile development isn't as good as it should be, but I'm curious how an agile developer would potentially use off-the-shelf (OTS) software when the requirements and knowledge of what the final system should be are changing as rapidly as I understand them to (often after each iteration of development). I see two situations that are of particular interest to me: (1) An OTS system meets the initial set of requirements with little to no modification, other than potential integration into an existing system. However, within a few iterations of development, this system no longer meets the needs without rewriting the core code. The developers must choose to either spend additional time learning the core code behind this OTS software or throw it away and build from scratch. Either would have a drastic impact on development time and project cost. (2) The initial needs are not like any existing OTS system available, however, in the end when the customer accepts the product, it ends up being much like existing solutions due to requirement additions and subtractions. If the developers had more requirements and spent more time working on them up front, this solution could have been used instead of building again. The project was delivered, but later and at a higher cost than necessary. As a software engineer, part of my responsibilities (as I have been taught), are to deliver high-quality software to the customer on time at the lowest possible cost (among other things). Agile development allows for high-quality software, but in some cases, it might not be apparent that there are better alternatives until it is too late and too much money has been spent. My questions are: * *How does off-the-shelf software fit in with agile development? *How do the agile manager and agile developer deal with these cases? *What do the agile paradigms say about these cases? A: Scenario1: This can occur regardless off the OTS nature of the component. Agile does not mean near-sighted.. you'd need to know the big chunks.. the framework bits and spend thinking time on it beforehand. That said, you can only build to what you know .. Delay only till the last responsible moment.Then you need to pick one of the alternatives and start on it. (I'd Avoid third party application unless the cost of developing it in-house is infeasible.. but that's just me). Prototype multiple solutions to check feasibility with list of known requirements. Keep things loosely coupled (replacable), easy to change and full tested. If you reach the fork of keep hacking or rewrite, you'd need to think of which has better value for the business and pick that option. It's comes down 'Now that we're here, what's the best we can do now?' Scenario2: This can happen although the chances are slim compared to the team spending 2-3 months trying to get the requirements 'finalized' only to find that the market needs or customer minds have changed and 'Now we want it this way'. Once again, its a question of what is the point of time till which you are prepared to investigate and explore before committing on a path of action. Decide wisely with whatever information you have upto that point.. Hindsight is always 20-20 but the customers wont wait forever. You can't wait till the point of time where the requirements coalesce to fit a known OTS component :) Agile says Do whatever makes sense and strip out the non-value-adding activities :) Agile is no magic bullet. just my 2 agile cents :) A: Not a strict answer per se, but I think that using off the shelf software as a component in a software solution can be very beneficial if: * *It's data is open, e.g. an open database or a web service to interact with it *The off the shelf system can customised easily using a similar programming paradigm to the rest of your solution *It can be seamlessly adapted to the rest of your work-flow I'm a big fan of not re-inventing the wheel, and using your development skills to design the 'glue' between off-the-shelf solutions can be a big win. Remember 'open' is the important part, and a vendor will often tout their solution as open when it isn't really. A: I think I read somewhere that if during an iteration you discover that you have more than 20% more work that you initially thought then you should abandon the sprint and start planning a new one taking into account the additional work. So this would mean replanning with the business to see if they still want to go ahead with the original requirements now that you know more. At our company we also make use of prototyping before the sprint to try and identify these kind of situations before they arise on a sprint. Although of course that still may not identify the kind of situation that you describe. A: C2 wiki discussion: http://c2.com/cgi/wiki?BuyDontBuild
{ "language": "en", "url": "https://stackoverflow.com/questions/51649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What to do with queries which don´t have a representation in a domain model? This is not specific to any language, it´s just about best practices. I am using JPA/Hibernate (but it could be any other ORM solution) and I would like to know how do you guys deal with this situation: Let´s suppose that you have a query returning something that is not represented by any of your domain classes. Do you create a specific class to represent that specific query? Do you return the query in some other kind of object (array, map...) Some other solutions? I would like to know about your experiences and best practices. P.S. Actually I am creating specific objetcs for specific queries. A: We have a situation that sounds similar to yours. We use separate objects for reporting data that spans several domain objects. Our convention is that these will be backed by a view in the database, so we have come to call them view objects. We generally use them for summarising complex data into a flat format. A: I typically write a function that performs a query using SQL and then puts the results into either a list or dictionary (in Java, I'd use either an ArrayList or a HashMap). If I found myself doing this a lot, I'd probably create a new file to hold all of these queries. Otherwise I'd just make them functions in whatever file they were needed/used. Since we're talking Java specifically, I would certainly not create a new class in a separate file. However, for queries needed in only one class, you could create a private static inner class with only the function(s) needed to generate the query(s) needed by that class. A: The idea of wrapping that up the functionality in some sort of manager is always nice. It allows for better testing, and management therefore of schema changes. Also allows for easier reuse in the application. NEVER just put the sql in directly!!!. For Hibernate I have found HQL great for just this. In particular , if you can use Named queries. Also be careful of adding an filter values etc use "string append", use parameters (can we say SQL injection ?). Even if the SQL is dynamic in terms of the join or where criteria, have a function in some sort of manager is always best. A: @DrPizza I will be more specific. We have three tables in a database USER PROJECT TASK USER to TASK 1:n PROJECT to TASK 1:n I have a query that returns a list of all projects but showing also some grouped information (all tasks, open tasks, closed tasks). When returned, the query looks like this PROJECTID: 1 NAME: New Web Site ALLTASK: 10 OPENTASK: 7 CLOSEDTASK: 3 I don´t have any domain class that could represent this information and I don´t want to create specific methods in Project class (like getAllTasks, getOpenTasks) because each of these methods would trigger a new query. So the question is: I create a new class (somenthing like ProjectTasksQuery) just to hold that information? I return information within array or map? Something else? A: You might feel better after reading about Data Transfer Objects. Some people plain don't like them, but if it feels like a good fit to you, it probably is.
{ "language": "en", "url": "https://stackoverflow.com/questions/51653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: (N)Hibernate - is it possible to dynamically map multiple tables to the one class I have the situation where i use GIS software which stores the information about GIS objects into separate database table for each type/class of GIS object (road, river, building, sea, ...) and keeps the metadata table in which it stores info about the class name and its DB table. Those GIS objects of different classes share some parameters, i.e. Description and ID. I'd like to represent all of these different GIS classes with one common C# class (let's call it GisObject), which is enough for what i need to do from the non-GIS part of the application which lists GIS objects of the given GIS class. The problem for me is how to map those objects using NHibernate to explain to the NHibernate when creating a C# GisObject to receive and use the table name as a parameter which will be read from the meta table (it can be in two steps, i can manually fetch the table name in first step and then pass it down to the NHibernate when pulling GisObject data). Has anybody dealt with this kind of situation, and can it be done at all? A: It sounds like the simplest thing to do here may be to create an abstract base class with all of the common GIS members and then to inherit the other X classes that will have nothing more than the necessary NHibernate mappings. I would then use the Factory pattern to create the object of the specific type using your metadata. A: @Brian Chiasson Unfortunately, it's not an option to create all classes of GIS data because classes are created dynamically in the application. Every GIS data of the same type should be a class, but my user has the possibility to get new set of data and put it in the database. I can't know in front which classes my user will have in the application. Therefore, the in-front per-class mapping model doesn't work because tomorrow there will be another new database table, and a need to create new class with new mapping. @all There might be a possibility to write my own custom query in the XML config file of my GisObject class, then in the data access class fetching that query using the string qs = getSession().getNamedQuery(queryName); and use the string replace to inject database name (by replacing some placeholder string) which i will pass as a parameter. qs = qs.replace(":tablename:", tableName); How do you feel about that solution? I know it might be a security risk in an uncontrolled environment where the table name would be fetched as the user input, but in this case, i have a meta table containing right and valid table names for the GIS data classes which i will read before calling the query for fetching data for the specific class of GIS objects. A: one way you could do it is to declare an interface say IGisObject that has the common properties declared on the interface. Then implement a concrete class which maps to each table. That way they'll still be all of type IGisObject. A: You can have a look at what Ayende is saying here : MultiTable Entities. But since you have separate tables , i don't think it will work. You can also check out nhuser group A: I guess I'd ask the question to why you are going after the GIS data directly in the database and not using what API that is typically provided as an abstraction for you. If this is an ESRI system there are tools that allow you to create static database views into their GIS objects and then maybe from that point it might be appropriate for data extract. A: From the NHibernate documentation, you could use one of the inheritance mappings. You might also have a separate class for each table, but have them all implement some common interface
{ "language": "en", "url": "https://stackoverflow.com/questions/51654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cross-platform space remaining on volume using python I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way? A: import ctypes import os import platform import sys def get_free_space_mb(dirname): """Return folder/drive free space (in megabytes).""" if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes)) return free_bytes.value / 1024 / 1024 else: st = os.statvfs(dirname) return st.f_bavail * st.f_frsize / 1024 / 1024 Note that you must pass a directory name for GetDiskFreeSpaceEx() to work (statvfs() works on both files and directories). You can get a directory name from a file with os.path.dirname(). Also see the documentation for os.statvfs() and GetDiskFreeSpaceEx. A: From Python 3.3 you can use shutil.disk_usage("/").free from standard library for both Windows and UNIX :) A: A good cross-platform way is using psutil: http://pythonhosted.org/psutil/#disks (Note that you'll need psutil 0.3.0 or above). A: Install psutil using pip install psutil. Then you can get the amount of free space in bytes using: import psutil print(psutil.disk_usage(".").free) A: You could use the wmi module for windows and os.statvfs for unix for window import wmi c = wmi.WMI () for d in c.Win32_LogicalDisk(): print( d.Caption, d.FreeSpace, d.Size, d.DriveType) for unix or linux from os import statvfs statvfs(path) A: You can use df as a cross-platform way. It is a part of GNU core utilities. These are the core utilities which are expected to exist on every operating system. However, they are not installed on Windows by default (Here, GetGnuWin32 comes in handy). df is a command-line utility, therefore a wrapper required for scripting purposes. For example: from subprocess import PIPE, Popen def free_volume(filename): """Find amount of disk space available to the current user (in bytes) on the file system containing filename.""" stats = Popen(["df", "-Pk", filename], stdout=PIPE).communicate()[0] return int(stats.splitlines()[1].split()[3]) * 1024 A: If you're running python3: Using shutil.disk_usage()with os.path.realpath('/') name-regularization works: from os import path from shutil import disk_usage print([i / 1000000 for i in disk_usage(path.realpath('/'))]) Or total_bytes, used_bytes, free_bytes = disk_usage(path.realpath('D:\\Users\\phannypack')) print(total_bytes / 1000000) # for Mb print(used_bytes / 1000000) print(free_bytes / 1000000) giving you the total, used, & free space in MB. A: If you dont like to add another dependency you can for windows use ctypes to call the win32 function call directly. import ctypes free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'c:\\'), None, None, ctypes.pointer(free_bytes)) if free_bytes.value == 0: print 'dont panic' A: The os.statvfs() function is a better way to get that information for Unix-like platforms (including OS X). The Python documentation says "Availability: Unix" but it's worth checking whether it works on Windows too in your build of Python (ie. the docs might not be up to date). Otherwise, you can use the pywin32 library to directly call the GetDiskFreeSpaceEx function. A: Below code returns correct value on windows import win32file def get_free_space(dirname): secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname) return secsPerClus * bytesPerSec * nFreeClus A: I Don't know of any cross-platform way to achieve this, but maybe a good workaround for you would be to write a wrapper class that checks the operating system and uses the best method for each. For Windows, there's the GetDiskFreeSpaceEx method in the win32 extensions. A: Most previous answers are correct, I'm using Python 3.10 and shutil. My use case was Windows and C drive only ( but you should be able to extend this for you Linux and Mac as well (here is the documentation) Here is the example for Windows: import shutil total, used, free = shutil.disk_usage("C:/") print("Total: %d GiB" % (total // (2**30))) print("Used: %d GiB" % (used // (2**30))) print("Free: %d GiB" % (free // (2**30)))
{ "language": "en", "url": "https://stackoverflow.com/questions/51658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: Metamodelling tools What tools are available for metamodelling? Especially for developing diagram editors, at the moment trying out Eclipse GMF Wondering what other options are out there? Any comparison available? A: Your question is simply too broad for a single answer - due to many aspects. First, meta-modelling is not a set term, but rather a very fuzzy thing, including modelling models of models and reaching out to terms like MDA. Second, there are numerous options to developing diagram editors - going the Eclipse way is surely a nice option. To get you at least started in the Eclipse department: * *have a look at MOF, that is architecture for "meta-modelling" from the OMG (the guys, that maintain UML) *from there approach EMOF, a sub set which is supported by the Eclipse Modelling Framework in the incarnation of Ecore. *building something on top of GMF might be indeed a good idea, because that's the way existing diagram editors for the Eclipse platform take (e.g. Omondo's EclipseUML) *there are a lot of tools existing in the Eclipse environment, that can utilize Ecore - I simply hope, that GMF builts on top of Ecore itself. A: Dia has an API for this - I was able to fairly trivially frig their UML editor into a basic ER modelling tool by changing the arrow styles. With a DB reversengineering tool I found in sourceforge (took the schema and spat out dia files) you could use this to document databases. While what I did was fairly trivial, the API was quite straightforward and it didn't take me that long to work out how to make the change. If you're of a mind to try out Smalltalk There used to be a Smalltalk meta-case framework called DOME which does this sort of thing. If you download VisualWorks, DOME is one of the contributed packages. A: GMF is a nice example. At the core of this sits EMF/Ecore, like computerkram sais. Ecore is also used for the base of Eclipse's UML2 . The prestige use case and proof of concept for GMF is certainly UML2 Tools. A: Although generally a UML tool, I would look at StarUML. It supports additional modules beyond what are already built in. If it doesn't have what you need built in or as a module, I supposed you could make your own, but I don't know how difficult that is. A: Meta-modeling is mostly done in Smalltalk. You might want to take a look at MOOSE (http://moose.unibe.ch). There are a lot of tools being developed for program understanding. Most are Smalltalk based. There is also some java and c++ work. Two of the most impressive tools are CodeCity and Mondrian. CodeCity can visualize code development over time, Mondrian provides scriptable visualization technology. And of course there is the classic HotDraw, which is also available in java. For web development there is also Magritte, providing meta-descriptions for Seaside. A: I would strongly recommend you look into DSM (Domain Specific Modeling) as a general topic, meta-modeling is directly related. There are eclipse based tools like GMF that currently require java coding, but integrate nicely with other eclipse tools and UML. However there are two other classes out there. * *MetaCase which I will call a pure DSM tool as it focuses on allowing a developer/modeler with out nearly as much coding create a usable graphical model. Additionally it can be easily deployed for others to use. GMF and Microsoft's Beta software factory/DSM tool fall into this category. *Pure Meta-modeling tools which are not intended for DSM tooling, code generation, and the like. I do not follow these tools as closely as I am interested in applications that generate tooling for SMEs, Domain Experts, and others to use and contribute value to an active project not modeling for models sake, or just documentation and theory. If you want to learn more about number 1, the tooling applications for DSMs/Meta-modeling, then check out my post "DSMForum.org great resources, worth a look." or just navigate directly to the DSMForum.org A: In case you are interested in something that is related to modelling and not generation of code, have a look at adoxx.org. As a metamodelling platform it does provide functionalities and mechanisms to quickly develop your own DSL and allows you to focus on the models needs (business requirements, conceptual level design/specification). There is an active community from academia and practice involved developing prototypical as well as commercial application based on the platform. Could be interesting ...
{ "language": "en", "url": "https://stackoverflow.com/questions/51660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Best Tips for documenting code using doxygen? My team is starting to document our C code using doxygen, paying particular attention to our public API headers. There appears to be a lot of flexibility and different special commands in doxygen, which is great, but it's not clear what's a good thing and what's a bad thing without trial and error. What are your favourite ways to mark up your code, what are your MUST DOs and DO NOTs? Please provide your top tips, one per answer to facilitate voting. I am looking to define our whole approach to API documentation, including providing a template to get the rest of the team started. So far I have something like this: /** * @file example_action.h * @Author Me ([email protected]) * @date September, 2008 * @brief Brief description of file. * * Detailed description of file. */ /** * @name Example API Actions * @brief Example actions available. * @ingroup example * * This API provides certain actions as an example. * * @param [in] repeat Number of times to do nothing. * * @retval TRUE Successfully did nothing. * @retval FALSE Oops, did something. * * Example Usage: * @code * example_nada(3); // Do nothing 3 times. * @endcode */ boolean example(int repeat); A: You don't need and should not write the name of the file in the @file directive, doxygen reads the name of the file automatically. The problem with writing the name of the file is that when you rename the file you will have to change the @file directive as well. Providing @author and @date information is also useless most of the time since the source control system does it a lot better than someone editing the files manually. You also don't have to write @brief if you use the following Doxygen syntax and enable JAVADOC_AUTOBRIEF in doxygen's configuration: /*! Short Description on the first line Detailed description... ... */ void foo(void) {} The @name directive for functions is also 100% redundant most of the time and completely useless. It only brings errors when someone modifies the name of the function and not the doxygen @name. A: Automatically build and publish your documentation. As part of automatically building the documentation, pay attention to the warnings, its very easy to write badly structure doxygen comments. A: Use \example as much as you can. It auto-links API elements to example code. A: Don't bother with @author or @date (@date was mentioned in another post). These are both handled by a revision control system. A: Always include a description with your classes. Try to say how a class is used, or why it is used, not just what it is (which usually just reflects the name anyway). A: Write a descriptive home page using @mainpage (in a separate header file just for this purpose). Consider, as shown in my example, making it a guide to your main classes/functions and modules. Another Sample Whilst I was getting the above-linked main oofile doxygen content back online, here's an example from some current client work using Markdown format. Using Markdown you can refer to a mainpage in markdown (in the Doxygen settings) which is great for the typical readme.md file included in open-source projects. Lingopal ======== Developer Documentation started when Andy Dent took over support in May 2014. There are a number of pages in Markdown format which explain key aspects: - @ref doc/LingopalBuilding.md - @ref doc/LingopalSigning.md - @ref doc/LingopalDatabases.md - @ref doc/LingopalExternals.md See the <a href="pages.html">Related Pages list for more.</a> ------------- _Note_ These pages, whilst readable by themselves, are designed to be run through the [Doxygen](http://www.doxygen.com) code documentation engine which builds an entire local cross-referenced set of docs. It uses a minor [extension of Markdown formatting.](http://www.stack.nl/~dimitri/doxygen/manual/markdown.html) The settings to generate the documentation are `Lingopal.doxy` and `LingopalDocOnly.doxy`. The latter is used for quick re-generation of just these additional pages. A: Use Groups to organise your code into modules. Remember that you can put almost everything into multiple groups so they can be used to provide semantic tagging like the tags in Stack Overflow. For example, you might tag things as specific to a given platform. You can also use groups to match a folder hierarchy within an IDE, as shown in my RB2Doxy sample output. Groups work well when nested - I have a large example for the OOFILE source. A: Some commands i use in my code : * *\todo { paragraph describing what is to be done } Useful to keep track of todos, a page will be created in final documentation containing your todo list. *\c <word> Displays the argument using a typewriter font. Use this to refer to a word of code. I would use it before "TRUE" and "FALSE" in your example. *\a , \warning , \see : see http://www.stack.nl/~dimitri/doxygen/commands.html#cmdc for description A: Group your member functions and fields if it makes sense to do so with \defgroup. This is very helpful, even if you don't say much. A: If you are worried that some team members will avoid documenting or you just want a working minimal sets of documentation, you can enable these in your doxygen configuration. WARNINGS = YES WARN_IF_UNDOCUMENTED = YES WARN_IF_DOC_ERROR = YES As part of your doxygen build process save the warnings to a file and try to get and keep the warning count as low as possible (0 if that is reasonable). If you do this, every public and protected class member will need at least an @brief, @param for each function argument and an @return. This is good enough to describe most APIs and not too much to encumber other living codebases. You should, of course, encourage people to document as much as they feel is required on a case by case basis, as long as they meet the minimum project standards. Don't set the minimum too high though, then you may not get useful documentation in the end. For example, in our project, everything another coder is likely to touch should be documented. Enabling the warnings let see how close that goal we are. We also try to use @internal to describe what/why we do what we do with some of our private members. A: A good "best practice" (though not always achievable) is to provide short, working examples for every API, and pull them into the help using \includelineno (or \include for no line numbers). These can be unit tests, if they're written so users can understand them (ie, not hooked into a larger test harness). As a nice side effect, changes to the API will break the samples, so they have to be kept up to date. You can describe an API in words, but there's nothing like seeing the actual code to understand how to use it. A: If you find that the configuration directive INLINE_SOURCES puts too much code in the documentation, you can manually quote specific portions of the code using the \snippet command. /** * Requirment XYZ is implemented by the following code. * * \snippet file.c CODE_LABEL */ int D() { //[CODE_LABEL] if( A ) { B= C(); } //[CODE_LABEL] } note: snippet gets its files from the EXAMPLE_PATH, not where the source path is. You will have to put the same list of files and paths from INPUT directive on the EXAMPLE_PATH directive. A: As I find myself editing code on higher-resolution screens I've moved from using the backslash to the @ prefix on Doxygen commands. Not so noisy backslash has found itself now too damned hard to make out the Doxygen commands. A: If you are sure your team will follow such a heavyweight template, fine, use it as shown. Otherwise, it looks like JavaDoc. One of the nice things about Doxygen is how good a job it does without having to use use such strong markup. You don't need to use @name and with the JAVADOC_AUTOBRIEF setting you can skip @brief - just make sure the first line of the comment is a reasonable brief description. I prefer descriptive names over enforcing documentation and encouraging people to add comments only when they add significant value. That way, the valuable comments aren't drowned out by all the noise. A: If you have bugs located in the code or you find bugs you can also tag in the code like this: /** @bug The text explaining the bug */ When you then run doxygen you get a seperate Bug List alongside lists like Todo List A: For larger projects taking 5+min to generate, I found it useful to quicly be able to generate doxygen for a single file and view it in a web browser. While references to anything outside the file won't resolve, it can still useful to see the basic formatting is ok. This script takes a single file and the projects doxy config and runs doxygen, I've set this up to run from my IDE. #!/usr/bin/env python3 """ This script takes 2-3 args: [--browse] <Doxyfile> <sourcefile> --browse will open the resulting docs in a web browser. """ import sys import os import subprocess import tempfile doxyfile, sourcefile = sys.argv[-2:] tempfile = tempfile.NamedTemporaryFile(mode='w+b') doxyfile_tmp = tempfile.name tempfile.write(open(doxyfile, "r+b").read()) tempfile.write(b'\n\n') tempfile.write(b'INPUT=' + os.fsencode(sourcefile) + b'\n') tempfile.flush() subprocess.call(("doxygen", doxyfile_tmp)) del tempfile # Maybe handy, but also annoying as default. if "--browse" in sys.argv: import webbrowser webbrowser.open("html/files.html") A: If you have a really, really big project -- big enough that Doxygen runs take over an hour -- you can cut it up into multiple modules that Doxygen later links together using tag files. For example, if you have a big MSVC solution with twenty projects in it, you can make directory be its own Doxygen run, and then use tag-files to glue together the output the same way a linker glues together .libs to make an executable. You can even take the linking metaphor more literally and make each Doxy config file correspond to a .vcproj file, so that each project (eg .lib or .dll) gets its own Doxy output. A: I use a subversion post-commit hook to pull out the directories that have changed, write them to a file and then every night I automatically re-generate the doxygen html on our webserver so we always have up-to-date docco. Every project I want documented has a little project.doxy file that contains the per-project settings and an include to the main doxygen settings - eg: PROJECT_NAME = "AlertServer" PROJECT_NUMBER = 8.1.2 INPUT = "C:/Dev/src/8.1.2/Common/AlertServer" HTML_OUTPUT = "AlertServer" @INCLUDE = "c:\dev\CommonConfig.doxy" For Windows SVN server, use the hook: @echo off for /F "eol=¬ delims=¬" %%A in ('svnlook dirs-changed %1 -r %2') do echo %%A >> c:\svn_exports\export.txt and then run this nightly: @echo off rem --------------- rem remove duplicates. type nul> %TEMP%.\TEMP.txt for /F "eol=¬ delims=¬" %%a in (c:\svn_exports\export.txt) do ( findstr /L /C:"%%a" < %TEMP%.\TEMP.txt > nul if errorlevel=1 echo %%a>> %TEMP%.\TEMP.txt ) copy /y %TEMP%.\TEMP.txt export_uniq.cmd >nul if exist %TEMP%.\TEMP.txt del %TEMP%.\TEMP.txt rem --------------- rem fetch all the recently changed directories into the svn_exports directory for /F "eol=¬ delims=¬" %%A in (c:\svn_exports\export_uniq.cmd) do ( svn export "file:///d:/repos/MyRepo/%%A" "c:/svn_exports/%%A" --force ) rem --------------- rem search through all dirs for any config files, if found run doxygen for /R c:\svn_exports %%i in (*.doxy) do c:\tools\doxygen\bin\doxygen.exe "%i" rem --------------- rem now remove the directories to be generated. del /F c:\svn_exports this removes duplicate entries, finds all projects that have a .doxy project file, and runs doxygen on them. Voila: fully documented, always up-to-date code on a webserver. A: For complex projects it may be useful to have a separate file for module management, which controls the groups and subgroups. The whole hierarchy can be in one place and then each file can simply stuff to the child groups. e.g.: /** * @defgroup example Top Level Example Group * @brief The Example module. * * @{ */ /** * @defgroup example_child1 First Child of Example * @brief 1st of 2 example children. */ /** * @defgroup example_child2 Second Child of Example * @brief 2nd of 2 example children. */ // @} Simply including the definition of a group within the { } of another group makes it a child of that group. Then in the code and header files functions can just be tagged as part of whatever group they are in and it all just works in the finished documentation. It makes refactoring the documentation to match the refactor code much easier. A: Uses lots and lots of links. This can be done using see also links (\see or @see if you prefer), and making sure that you use any references to other class names in documentation by their correct class name. For example if you refer to class FUZZYObject as an "object", then write immediately after it the name of the class (e.g. "frazzle the objects (FUZZYObject)").
{ "language": "en", "url": "https://stackoverflow.com/questions/51667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "308" }
Q: What is the easiest way to copy a database from one Informix IDS 11 Server to another The source database is quite large. The target database doesn't grow automatically. They are on different machines. I'm coming from a MS SQL Server, MySQL background and IDS11 seems overly complex (I am sure, with good reason). A: One way to move data from one server to another is to backup the database using the dbexport command. Then after copying the backup files to the destination server run the dbimport command. To create a new database you need to create the DBSpace for the new database using the onmonitor tool, at this point you could use the existing files from the other server. You will then need to create the database on the destination server using the dbaccess tool. The dbaccess tool has a database option that allows you to create a database. When creating the database you specify what DBSpace to use. The source database may be made up of many chunks which you will also need to copy and attach to the new database. A: The easiest way is dbexport/dbimport, as others have mentioned. The fastest way is using onpload, the High Performance Loader. If you have lots of data, but not a ridiculous number of tables, this is definitely worth pursuing. There are some bits and pieces on the IIUG site that may be of assistance in scripting the HPL to generate all the config you'll need. A: You have a few choices. dbexport/dbimport onunload/onload HPL (high performance loader) options. I have personally used onunload/onload and dbexport/dbimport. I have not used HPL. I'm using IDS 10. onunload/onload IBM docs *Back up the raw database to disk or tape in page size chunks *faster (especially if you go to disk) *Issues if the the database servers are on different operating systems or hardware or if they just have different page sizes. dbexport/dbimport IBM docs *backup the database in delimited ascii files *writes an ascii schema of the database including all users, tables, views, indexes, etc. Everything about the structure of the database into one huge plain text file. *separate plain text files for each table of the database as well *not so fast *issues on dbimport on any table that has bad data, any view with incorrect syntax, etc. (This can be a good thing, an opportunity to identify and clean) *DO NOT LEAVE THIS TAPE ON THE FRONT SEAT OF YOUR CAR WHEN YOU RUN INTO THE STORE FOR AN ICE CREAM (or you'll be on the news). Also read ... Not a very secure way to be moving data around. :) *Limitation: Requires exclusive access to the source database. Here is a good place to start in the docs --> Migration of Data Between Database Servers A: have you used the export tool ? There used to be a way if you first put the db's into quiescent mode and then you could actually copy the DBSpaces across (dbspaces tool I think... its been a few years now). Because with informix you used to be able to specify the DBSpaces(s) to used for the table (maybe even in the alter table ?). Check - dbaccess tool - there is an export command. Put the DB's into quiesent mode or shut down, copy the dbspaces and then attach table telling it to point to the new dbspaces file. (the dbspaces tool could be worth while looking at.. I have manuals around here. they are 9.2, but it shouldn't have changed too much). A: If both the machines use the same version of IDS then another option would be to use ontape to take a backup on one machine one machine and restore on another. You can use the STDIO option and then just stream the backup onto the other machine where the restore could just restore from the STDIO. From the "Data Replication for High Availability and Distribution" redbook: ontape -s -L 0 -F | rsh secondary_server "ontape –p" You could also create a passwordless ssh connection b/w the hosts and transfer in a more secure way.
{ "language": "en", "url": "https://stackoverflow.com/questions/51673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Graph (Chart) Algorithm Does anyone have a decent algorithm for calculating axis minima and maxima? When creating a chart for a given set of data items, I'd like to be able to give the algorithm: * *the maximum (y) value in the set *the minimum (y) value in the set *the number of tick marks to appear on the axis *an optional value that must appear as a tick (e.g. zero when showing +ve and -ve values) The algorithm should return * *the largest axis value *the smallest axis value (although that could be inferred from the largest, the interval size and the number of ticks) *the interval size The ticks should be at a regular interval should be of a "reasonable" size (e.g. 1, 3, 5, possibly even 2.5, but not any more sig figs). The presence of the optional value will skew this, but without that value the largest item should appear between the top two tick marks, the lowest value between the bottom two. This is a language-agnostic question, but if there's a C#/.NET library around, that would be smashing ;) A: OK, here's what I came up with for one of our applications. Note that it doesn't deal with the "optional value" scenario you mention, since our optional value is always 0, but it shouldn't be hard for you to modify. Data is continually added to the series so we just keep the range of y values up to date by inspecting each data point as its added; this is very inexpensive and easy to keep track of. Equal minimum and maximum values are special cased: a spacing of 0 indicates that no markers should be drawn. This solution isn't dissimilar to Andrew's suggestion above, except that it deals, in a slightly kludgy way with some arbitrary fractions of the exponent multiplier. Lastly, this sample is in C#. Hope it helps. private float GetYMarkerSpacing() { YValueRange range = m_ScrollableCanvas. TimelineCanvas.DataModel.CurrentYRange; if ( range.RealMinimum == range.RealMaximum ) { return 0; } float absolute = Math.Max( Math.Abs( range.RealMinimum ), Math.Abs( range.RealMaximum ) ), spacing = 0; for ( int power = 0; power < 39; ++power ) { float temp = ( float ) Math.Pow( 10, power ); if ( temp <= absolute ) { spacing = temp; } else if ( temp / 2 <= absolute ) { spacing = temp / 2; break; } else if ( temp / 2.5 <= absolute ) { spacing = temp / 2.5F; break; } else if ( temp / 4 <= absolute ) { spacing = temp / 4; break; } else if ( temp / 5 <= absolute ) { spacing = temp / 5; break; } else { break; } } return spacing; } A: I've been using the jQuery flot graph library. It's open source and does axis/tick generation quite well. I'd suggest looking at it's code and pinching some ideas from there. A: I can recommend the following: * *Set a visually appealing minimum number of major lines. This will depend on the nature of the data that you're presenting and the size of the plot you're doing, but 7 is a pretty good number *Choose the exponent and the multiplier based on a progression of 1, 2, 5, 10, etc. that will give you at least the minimum number of major lines. (ie. (max-min)/(scale x 10^exponent) >= minimum_tick_marks) *Find the minimum integer multiple of your exponent and multiplier that fits within your range. This will be the first major tick. The rest of the ticks are derived from this. This was used for an application that allowed arbitrary scaling of data an seemed to work well.
{ "language": "en", "url": "https://stackoverflow.com/questions/51680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Name of the process with highest cpu usage I have a Samurize config that shows a CPU usage graph similar to Task manager. How do I also display the name of the process with the current highest CPU usage percentage? I would like this to be updated, at most, once per second. Samurize can call a command line tool and display it's output on screen, so this could also be an option. Further clarification: I have investigated writing my own command line c# .NET application to enumerate the array returned from System.Diagnostics.Process.GetProcesses(), but the Process instance class does not seem to include a CPU percentage property. Can I calculate this in some way? A: What you want to get its the instant CPU usage (kind of)... Actually, the instant CPU usage for a process does not exists. Instead you have to make two measurements and calculate the average CPU usage, the formula is quite simple: AvgCpuUsed = [TotalCPUTime(process,time2) - TotalCPUTime(process,time1)] / [time2-time1] The lower Time2 and Time1 difference is, the more "instant" your measurement will be. Windows Task Manager calculate the CPU use with an interval of one second. I've found that is more than enough and you might even consider doing it in 5 seconds intervals cause the act of measuring itself takes up CPU cycles... So, first, to get the average CPU time using System.Diagnostics; float GetAverageCPULoad(int procID, DateTme from, DateTime, to) { // For the current process //Process proc = Process.GetCurrentProcess(); // Or for any other process given its id Process proc = Process.GetProcessById(procID); System.TimeSpan lifeInterval = (to - from); // Get the CPU use float CPULoad = (proc.TotalProcessorTime.TotalMilliseconds / lifeInterval.TotalMilliseconds) * 100; // You need to take the number of present cores into account return CPULoad / System.Environment.ProcessorCount; } now, for the "instant" CPU load you'll need an specialized class: class ProcLoad { // Last time you checked for a process public Dictionary<int, DateTime> lastCheckedDict = new Dictionary<int, DateTime>(); public float GetCPULoad(int procID) { if (lastCheckedDict.ContainsKey(procID)) { DateTime last = lastCheckedDict[procID]; lastCheckedDict[procID] = DateTime.Now; return GetAverageCPULoad(procID, last, lastCheckedDict[procID]); } else { lastCheckedDict.Add(procID, DateTime.Now); return 0; } } } You should call that class from a timer (or whatever interval method you like) for each process you want to monitor, if you want all the processes just use the Process.GetProcesses static method A: Building on Frederic's answer and utilizing the code at the bottom of the page here (for an example of usage see this post) to join the full set of processes gotten from Get-Process, we get the following: $sampleInterval = 3 $process1 = Get-Process |select Name,Id, @{Name="Sample1CPU"; Expression = {$_.CPU}} Start-Sleep -Seconds $sampleInterval $process2 = Get-Process | select Id, @{Name="Sample2CPU"; Expression = {$_.CPU}} $samples = Join-Object -Left $process1 -Right $process2 -LeftProperties Name,Sample1CPU -RightProperties Sample2CPU -Where {$args[0].Id -eq $args[1].Id} $samples | select Name,@{Name="CPU Usage";Expression = {($_.Sample2CPU-$_.Sample1CPU)/$sampleInterval * 100}} | sort -Property "CPU Usage" -Descending | select -First 10 | ft -AutoSize Which gives an example output of Name CPU Usage ---- --------- firefox 20.8333333333333 powershell_ise 5.72916666666667 Battle.net 1.5625 Skype 1.5625 chrome 1.5625 chrome 1.04166666666667 chrome 1.04166666666667 chrome 1.04166666666667 chrome 1.04166666666667 LCore 1.04166666666667 A: You might be able to use Pmon.exe for this. You can get it as part of the Windows Resource Kit tools (the link is to the Server 2003 version, which can apparently be used in XP as well). A: Process.TotalProcessorTime http://msdn.microsoft.com/en-us/library/system.diagnostics.process.totalprocessortime.aspx A: Somehow Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName,TotalProcessorTime -hidetableheader wasn't getting the CPU information from the remote machine. I had to come up with this. Get-Counter '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| Sort-Object -Property cookedvalue -Descending| Select-Object -First 10| ft -AutoSize A: Thanks for the formula, Jorge. I don't quite understand why you have to divide by the number of cores, but the numbers I get match the Task Manager. Here's my powershell code: $procID = 4321 $time1 = Get-Date $cpuTime1 = Get-Process -Id $procID | Select -Property CPU Start-Sleep -s 2 $time2 = Get-Date $cpuTime2 = Get-Process -Id $procID | Select -Property CPU $avgCPUUtil = ($cpuTime2.CPU - $cpuTime1.CPU)/($time2-$time1).TotalSeconds *100 / [System.Environment]::ProcessorCount A: You can also do it this way :- public Process getProcessWithMaxCPUUsage() { const int delay = 500; Process[] processes = Process.GetProcesses(); var counters = new List<PerformanceCounter>(); foreach (Process process in processes) { var counter = new PerformanceCounter("Process", "% Processor Time", process.ProcessName); counter.NextValue(); counters.Add(counter); } System.Threading.Thread.Sleep(delay); //You must wait(ms) to ensure that the current //application process does not have MAX CPU int mxproc = -1; double mxcpu = double.MinValue, tmpcpu; for (int ik = 0; ik < counters.Count; ik++) { tmpcpu = Math.Round(counters[ik].NextValue(), 1); if (tmpcpu > mxcpu) { mxcpu = tmpcpu; mxproc = ik; } } return processes[mxproc]; } Usage:- static void Main() { Process mxp=getProcessWithMaxCPUUsage(); Console.WriteLine(mxp.ProcessName); } A: With PowerShell: Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName -hidetableheader returns somewhat like: 16.8641632 System 12.548072 csrss 11.9892168 powershell
{ "language": "en", "url": "https://stackoverflow.com/questions/51684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is it possible to deploy a native Delphi application with ClickOnce Is it possible to deploy a native Delphi application with ClickOnce without a stub C# exe that would be used to launch the Delphi application? The same question applies to VB6, C++ and other native Windows applications. A: Personally, I build my own mechanism to kick off self update process when my application timestamp is out of sync with the server. Not too difficult, but it's not a simple task. By the way, for Delphi you can use some thirdparty help: http://www.tmssoftware.com/site/wupdate.asp UPDATED: For my implementation: MyApp.EXE will run in 3 different modes * *MyApp.EXE without any argument. This will start the application typically. 1.1 The very first thing it does is to validate its own file-time with the server. 1.2 If update is required then it will download the updated file to the file named "MyApp-YYYY-MM-DD-HH-MM-SS.exe" 1.3 Then it invoke "MyApp-YYYY-MM-DD-HH-MM-SS.exe" with command argument MyApp-YYYY-MM-DD-HH-MM-SS.exe --update MyApp.EXE 1.4 Terminate this application. 1.5 If there is no update required then the application will start normally from 1.1 *MyApp.EXE --update "FILENAME". 2.1 Try copying itself to "FILENAME" every 100ms until success. 2.2 Invoke "FILENAME" when it success 2.3 Invoke "FILNAME --delete MyApp-YYYY-MM-DD-HH-MM-SS.exe" to delete itself. 2.4 Terminate *MyApp.EXE --delete "FILENAME" 3.1 Try deleting the file "FILENAME" every 500ms until success. 3.2 Terminate I've already been using this scheme for my application for 7 years and it works well. It could be quite painful to debug when things goes wrong since the steps involve many processes. I suggest you make a lot of trace logging to allow simpler trouble-shooting. Good Luck A: No, the entry point to your app needs to be managed code. This is from a blog post by Brian Noyes, one of the main authorites on ClickOnce and author of Smart Client Deployment with ClickOnce. If you app is REALLY legacy (i.e. VB6, MFC, ATL, etc.), as in an unmanaged code executable, then no, you cannot deploy it as an executable through ClickOnce. The accepted workaround seems to be a managed code stub exe that launches the main exe. A: I'm not 100% sure if this can be accomplished without the stub, but this article may provide some insight: How To: ClickOnce deployment for unmanaged app with COM component in managed assembly
{ "language": "en", "url": "https://stackoverflow.com/questions/51686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Lightbox style dialogs in MFC App Has anyone implemented Lightbox style background dimming on a modal dialog box in a MFC/non .net app. I think the procedure would have to be something like: steps: * *Get dialog parent HWND or CWnd* *Get the rect of the parent window and draw an overlay with a translucency over that window *allow the dialog to do it's modal draw routine, e.g DoModal() Are there any existing libraries/frameworks to do this, or what's the best way to drop a translucent overlay in MFC? edit Here's a mockup of what i'm trying to achieve if you don't know what 'lightbox style' means Some App: with a lightbox dialog box A: Here's what I did* based on Brian's links First create a dialog resource with the properties: * *border FALSE *3D look FALSE *client edge FALSE *Popup style *static edge FALSE *Transparent TRUE *Title bar FALSE and you should end up with a dialog window with no frame or anything, just a grey box. override the Create function to look like this: BOOL LightBoxDlg::Create(UINT nIDTemplate, CWnd* pParentWnd) { if(!CDialog::Create(nIDTemplate, pParentWnd)) return false; RECT rect; RECT size; GetParent()->GetWindowRect(&rect); size.top = 0; size.left = 0; size.right = rect.right - rect.left; size.bottom = rect.bottom - rect.top; SetWindowPos(m_pParentWnd,rect.left,rect.top,size.right,size.bottom,NULL); HWND hWnd=m_hWnd; SetWindowLong (hWnd , GWL_EXSTYLE ,GetWindowLong (hWnd , GWL_EXSTYLE ) | WS_EX_LAYERED ) ; typedef DWORD (WINAPI *PSLWA)(HWND, DWORD, BYTE, DWORD); PSLWA pSetLayeredWindowAttributes; HMODULE hDLL = LoadLibrary (_T("user32")); pSetLayeredWindowAttributes = (PSLWA) GetProcAddress(hDLL,"SetLayeredWindowAttributes"); if (pSetLayeredWindowAttributes != NULL) { /* * Second parameter RGB(255,255,255) sets the colorkey * to white LWA_COLORKEY flag indicates that color key * is valid LWA_ALPHA indicates that ALphablend parameter * is valid - here 100 is used */ pSetLayeredWindowAttributes (hWnd, RGB(255,255,255), 100, LWA_COLORKEY|LWA_ALPHA); } return true; } then create a small black bitmap in an image editor (say 48x48) and import it as a bitmap resource (in this example IDB_BITMAP1) override the WM_ERASEBKGND message with: BOOL LightBoxDlg::OnEraseBkgnd(CDC* pDC) { BOOL bRet = CDialog::OnEraseBkgnd(pDC); RECT rect; RECT size; m_pParentWnd->GetWindowRect(&rect); size.top = 0; size.left = 0; size.right = rect.right - rect.left; size.bottom = rect.bottom - rect.top; CBitmap cbmp; cbmp.LoadBitmapW(IDB_BITMAP1); BITMAP bmp; cbmp.GetBitmap(&bmp); CDC memDc; memDc.CreateCompatibleDC(pDC); memDc.SelectObject(&cbmp); pDC->StretchBlt(0,0,size.right,size.bottom,&memDc,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY); return bRet; } Instantiate it in the DoModal of the desired dialog, Create it like a Modal Dialog i.e. on the stack(or heap if desired), call it's Create manually, show it then create your actual modal dialog over the top of it: INT_PTR CAboutDlg::DoModal() { LightBoxDlg Dlg(m_pParentWnd);//make sure to pass in the parent of the new dialog Dlg.Create(LightBoxDlg::IDD); Dlg.ShowWindow(SW_SHOW); BOOL ret = CDialog::DoModal(); Dlg.ShowWindow(SW_HIDE); return ret; } and this results in something exactly like my mock up above *there are still places for improvment, like doing it without making a dialog box to begin with and some other general tidyups. A: I think you just need to create a window and set the transparency. There is an MFC CGlassDialog sample on CodeProject that might help you. There is also an article on how to do this with the Win32 APIs.
{ "language": "en", "url": "https://stackoverflow.com/questions/51687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Vista BEX error Recently I got IE7 crashed on Vista on jar loading (presumably) with the following error: Problem signature: Problem Event Name: BEX Application Name: iexplore.exe Application Version: 7.0.6001.18000 Application Timestamp: 47918f11 Fault Module Name: ntdll.dll Fault Module Version: 6.0.6001.18000 Fault Module Timestamp: 4791a7a6 Exception Offset: 00087ba6 Exception Code: c000000d Exception Data: 00000000 OS Version: 6.0.6001.2.1.0.768.3 Locale ID: 1037 Additional Information 1: fd00 Additional Information 2: ea6f5fe8924aaa756324d57f87834160 Additional Information 3: fd00 Additional Information 4: ea6f5fe8924aaa756324d57f87834160 Googling revealed this sort of problems is common for Vista and relates to Java (although SUN negates). Also I think it has something to do with DEP. I failed to find official Microsoft Kb. So, the questions are: * *What BEX stands for? *What is it about? *How to deal with such kind of errors? A: BEX=Buffer overflow exception. See http://technet.microsoft.com/en-us/library/cc738483.aspx for details. However, c000000d is STATUS_INVALID_PARAMETER; the technet article talks primarily about status c0000005 or c0000409 (access violation/DEP) A: Java and IE7 do not like to play together nicely. Just turn off DEP, it will work fine then. http://www.tech-recipes.com/rx/1261/vista_disable_dep_noexecute_protection_fix_explorer_crashing/ A: go to internet explorer options/ advanced /security/ uncheck the box that says enable memory protection to mitigate attacks this will work it did for me go to internet explorer options/ advanced /security/ uncheck the box that says enable memory protection to mitigate attacks this will work it did for me A: Most likely there is an addon that is messing with IE. You can try this. 1. Open IE 2. Switch to the Advanced tab. 3. Click the Reset Internet Explorer Settings button. 4. Click Reset to confirm the operation. 5. Click Close when the resetting process finished. 6. Uncheck Enable third-party browser extensions option in the Settings box. 7. Click Apply, click OK. After this, check to see if it works and if it does, enable one addon at a time until you find the culprit. Then uninstall it and reinstall it if you need it. A: just try disabling the bing or msn toolbar - should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/51690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Property default values using Properties.Settings.Default I am using .Net 2 and the normal way to store my settings. I store my custom object serialized to xml. I am trying to retrieve the default value of the property (but without reseting other properties). I use: ValuationInput valuationInput = (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue; But it seems to return a string instead of ValuationInput and it throws an exception. I made a quick hack, which works fine: string valuationInputStr = (string) Settings.Default.Properties["ValuationInput"].DefaultValue; XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValuationInput)); ValuationInput valuationInput = (ValuationInput) xmlSerializer.Deserialize(new StringReader(valuationInputStr)); But this is really ugly - when I use all the tool to define a strongly typed setting, I don't want to serialize the default value myself, I would like to read it the same way as I read the current value: ValuationInput valuationInput = Settings.Default.ValuationInput; A: At some point, something, somewhere is going to have to use Xml Deserialization, whether it is you or a wrapper inside the settings class. You could always abstract it away in a method to remove the "ugly" code from your business logic. public static T FromXml<T>(string xml) { XmlSerializer xmlser = new XmlSerializer(typeof(T)); using (System.IO.StringReader sr = new System.IO.StringReader(xml)) { return (T)xmlser.Deserialize(sr); } } http://www.vonsharp.net/PutDownTheXmlNodeAndStepAwayFromTheStringBuilder.aspx A: @Grzenio, Why don't you use your object type directly? You can set type of your setting on Project Properties->Settings tab. You can select your type by clicking on Browse in drop down for Type column. Citation from MSDN: Application settings can be stored as any data type that is XML serializable or has a TypeConverter that implements ToString/FromString That way you can have strongly typed settings, i.e. (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue; will return an object instead of string.
{ "language": "en", "url": "https://stackoverflow.com/questions/51700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mail Message Link Handling I have written an AppleScript which when supplied with a Windows network link, will convert it to the correct smb:// equivalent for the server in our office, mount the network drive, and open the requested folder in Finder. I have this built in an application which just takes a pasted network path. Ideally I need this to trigger on clicking a link in a Mail.app email message so that it can check if the link is in the correct format, and if so run the script and attempt to mount the drive and load the folder in Finder. How would I go about doing this? A: In order to do this I think you'd need to create a Cocoa application that was registered with OS X Launch Services as the default role handler for smb:// links. I've written some stuff about how to do this on another question: How do you set your Cocoa application as the default web browser? If there's a pure AppleScript solution or a way of only handling links within Mail.app I'm not aware of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/51701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue reading XML file into C# DataSet I was given an .xml file that I needed to read into my code as a DataSet (as background, the file was created by creating a DataSet in C# and calling dataSet.WriteXml(file, XmlWriteMode.IgnoreSchema), but this was done by someone else). The .xml file was shaped like this: <?xml version="1.0" standalone="yes"?> <NewDataSet> <Foo> <Bar>abcd</Bar> <Foo>efg</Foo> </Foo> <Foo> <Bar>hijk</Bar> <Foo>lmn</Foo> </Foo> </NewDataSet> Using C# and .NET 2.0, I read the file in using the code below: DataSet ds = new DataSet(); ds.ReadXml(file); Using a breakpoint, after this line ds.Tables[0] looked like this (using dashes in place of underscores that I couldn't get to format properly): Bar Foo-Id Foo-Id-0 abcd 0 null null 1 0 hijk 2 null null 3 2 I have found a workaround (I know there are many) and have been able to successfully read in the .xml, but what I would like to understand why ds.ReadXml(file) performed in this manner, so I will be able to avoid the issue in the future. Thanks. A: This appears to be correct for your nested Foo tags: <NewDataSet> <Foo> <!-- Foo-Id: 0 --> <Bar>abcd</Bar> <Foo>efg</Foo> <!-- Foo-Id: 1, Parent-Id: 0 --> </Foo> <Foo> <!-- Foo-Id: 2 --> <Bar>hijk</Bar> <Foo>lmn</Foo> <!-- Foo-Id: 3, Parent-Id: 2 --> </Foo> </NewDataSet> So this correctly becomes 4 records in your result, with a parent-child key of "Foo-Id-0" Try: <NewDataSet> <Rec> <!-- Rec-Id: 0 --> <Bar>abcd</Bar> <Foo>efg</Foo> </Rec> <Rec> <!-- Rec-Id: 1 --> <Bar>hijk</Bar> <Foo>lmn</Foo> </Rec> </NewDataSet> Which should result in: Bar Foo Rec-Id abcd efg 0 hijk lmn 1 A: These are my observations rather than a full answer: My guess (without trying to re-produce it myself) is that a couple of things may be happening as the DataSet tries to 'flatten' a hierarchical structure to a relational data structure. 1) thinking about the data from a relational database perspective; there is no obvious primary key field for identifying each of the Foo elements in the collection so the DataSet has automatically used the ordinal position in the file as an auto-generated field called Foo-Id. 2) There are actually two elements called 'Foo' so that probably explains the generation of a strange name for the column 'Foo-Id-0' (it has auto-generated a unique name for the column - I guess you could think of this as a fault-tolerant behaviour in the DataSet).
{ "language": "en", "url": "https://stackoverflow.com/questions/51741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: HTTP Errors with .Net 3.5 SP1 I have a ASP.Net website that is failing on AJAX postbacks (both with ASP.Net AJAX and a 3rd part control) in IE. FireFox works fine. If I install the website on another machine without .Net 3.5 SP1, it works as expected. When it fails, Fiddler shows that I'm getting a 405 "Method Not Allowed". The form seems to be posting to pages other than page I'm viewing. The form's action is "#" for the page on the broken website (with SP1). The form's action is "Default.aspx" for the same page on a website without SP1. Any ideas? A: Check out the following Microsoft Knowledge base article: http://support.microsoft.com/kb/216493 If you're using IIS4 or IIS5 this may be the problem. A: SP1 changes the HtmlForm control so that it honors the action attribute, where previous versions ignored it. It sounds like you have something like this on the broken pages: <form runat="server" action="#"> Remove the action, and it should be fine: <form runat="server"> More info here: http://forums.asp.net/t/1305800.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/51751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SpecialCells in VSTO I'm trying to use the SpecialCells method in a VSTO project using c# against the 3.5 framework and Excel2007. Here's my code: Excel.Worksheet myWs = (Excel.Worksheet)ModelWb.Worksheets[1]; Range myRange = myWs.get_Range("A7", "A800"); //Range rAccounts = myRange.SpecialCells(XlCellType.xlCellTypeConstants, XlSpecialCellsValue.xlTextValues); Range rAccounts = myWs.Cells.SpecialCells(XlCellType.xlCellTypeConstants, XlSpecialCellsValue.xlTextValues); When I run this, it throws an exception... System.Exception._COMPlusExceptionCode with a value of -532459699 Note that I get the same exception if I switch (uncomment one and comment the other) the above Range rAccounts line. A: I figured it out... the worksheet was protected! myWs.Unprotect(Properties.Settings.Default.PasswordSheet); fixes it...for those playing along at home...don't forget to protect the sheet when you're done. myWs.Protect(Properties.Settings.Default.PasswordSheet, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
{ "language": "en", "url": "https://stackoverflow.com/questions/51754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Print stack trace information from C# As part of some error handling in our product, we'd like to dump some stack trace information. However, we experience that many users will simply take a screenshot of the error message dialog instead of sending us a copy of the full report available from the program, and thus I'd like to make some minimal stack trace information available in this dialog. A .NET stack trace on my machine looks like this: at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) at System.IO.StreamReader..ctor(String path) at LVKWinFormsSandbox.MainForm.button1_Click(Object sender, EventArgs e) in C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36 I have this question: The format looks to be this: at <class/method> [in file:line ##] However, the at and in keywords, I assume these will be localized if they run, say, a norwegian .NET runtime instead of the english one I have installed. Is there any way for me to pick apart this stack trace in a language-neutral manner, so that I can display only the file and line number for those entries that have this? In other words, I'd like this information from the above text: C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36 Any advice you can give will be helpful. A: Or there is even shorter version.. Console.Write(exception.StackTrace); A: You should be able to get a StackTrace object instead of a string by saying var trace = new System.Diagnostics.StackTrace(exception); You can then look at the frames yourself without relying on the framework's formatting. See also: StackTrace reference A: Here is the code I use to do this without an exception public static void LogStack() { var trace = new System.Diagnostics.StackTrace(); foreach (var frame in trace.GetFrames()) { var method = frame.GetMethod(); if (method.Name.Equals("LogStack")) continue; Log.Debug(string.Format("{0}::{1}", method.ReflectedType != null ? method.ReflectedType.Name : string.Empty, method.Name)); } } A: Just to make this a 15 sec copy-paste answer: static public string StackTraceToString() { StringBuilder sb = new StringBuilder(256); var frames = new System.Diagnostics.StackTrace().GetFrames(); for (int i = 1; i < frames.Length; i++) /* Ignore current StackTraceToString method...*/ { var currFrame = frames[i]; var method = currFrame.GetMethod(); sb.AppendLine(string.Format("{0}:{1}", method.ReflectedType != null ? method.ReflectedType.Name : string.Empty, method.Name)); } return sb.ToString(); } (based on Lindholm answer) A: As alternative, log4net, though potentially dangerous, has given me better results than System.Diagnostics. Basically in log4net, you have a method for the various log levels, each with an Exception parameter. So, when you pass the second exception, it will print the stack trace to whichever appender you have configured. example: Logger.Error("Danger!!!", myException ); The output, depending on configuration, looks something like System.ApplicationException: Something went wrong. at Adapter.WriteToFile(OleDbCommand cmd) in C:\Adapter.vb:line 35 at Adapter.GetDistributionDocument(Int32 id) in C:\Adapter.vb:line 181 ...
{ "language": "en", "url": "https://stackoverflow.com/questions/51768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: The best way to validate XML in a unit test? I have a class with a ToString method that produces XML. I want to unit test it to ensure it is producing valid xml. I have a DTD to validate the XML against. Should I include the DTD as a string within the unit test to avoid a dependency on it, or is there a smarter way to do this? A: If your program validates the XML against the DTD during normal execution, then you should just get the DTD from wherever your program will get it. If not and the DTD is extremely short (only a few lines), then storing it as a string in your code is probably okay. Otherwise, I'd put it in an external file and have your unit test read it from that file. A: I've used XmlUnit in the past and found it to be useful. It can be used to validate XML against a schema or compare your XML against a string. It is clever enough to understand XML's parsing rules. For example it knows that "<e1/>" is equivalent to "<e1></e1>" and can be configured to ignore or include whitespace. A: Using a DTD in the unit test to test its validity is one thing, testing for the correct content is another. You can use the DTD to check for the validity of the generated xml which I would simply read the way you do in your program. I personally would not include it inline (as a String); there is always a dependency between you application code and the unit test. When the generated xml changes, the DTD will also change. To test for the correct content I would go for XMLUnit. Asserting xml using XMLUnit: XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true); Diff diff = new Diff(expectedDocument, obtainedDocument); XMLAssert.assertXMLIdentical("xml invalid", diff, true); One thing you might come across is the fact that the generated xml might contain changing identifiers (id/uid attributes or alike). This can be solved by using a DifferenceListener when asserting the generated xml. Example implementation of such DifferenceListener: public class IgnoreVariableAttributesDifferenceListener implements DifferenceListener { private final List<String> IGNORE_ATTRS; private final boolean ignoreAttributeOrder; public IgnoreVariableAttributesDifferenceListener(List<String> attributesToIgnore, boolean ignoreAttributeOrder) { this.IGNORE_ATTRS = attributesToIgnore; this.ignoreAttributeOrder = ignoreAttributeOrder; } @Override public int differenceFound(Difference difference) { // for attribute value differences, check for ignored attributes if (difference.getId() == DifferenceConstants.ATTR_VALUE_ID) { if (IGNORE_ATTRS.contains(difference.getControlNodeDetail().getNode().getNodeName())) { return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; } } // attribute order mismatch (optionally ignored) else if (difference.getId() == DifferenceConstants.ATTR_SEQUENCE_ID && ignoreAttributeOrder) { return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; } // attribute missing / not expected else if (difference.getId() == DifferenceConstants.ATTR_NAME_NOT_FOUND_ID) { if (IGNORE_ATTRS.contains(difference.getTestNodeDetail().getValue())) { return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; } } return RETURN_ACCEPT_DIFFERENCE; } @Override public void skippedComparison(Node control, Node test) { // nothing to do } } using DifferenceListener: XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true); Diff diff = new Diff(expectedDocument, obtainedDocument); diff.overrideDifferenceListener(new IgnoreVariableAttributesDifferenceListener(Arrays.asList("id", "uid"), true)); XMLAssert.assertXMLIdentical("xml invalid", diff, true);
{ "language": "en", "url": "https://stackoverflow.com/questions/51771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Haxe iteration on Dynamic I have a variable of type Dynamic and I know for sure one of its fields, lets call it a, actually is an array. But when I'm writing var d : Dynamic = getDynamic(); for (t in d.a) { } I get a compilation error on line two: You can't iterate on a Dynamic value, please specify Iterator or Iterable How can I make this compilable? A: Haxe can't iterate over Dynamic variables (as the compiler says). You can make it work in several ways, where this one is probably easiest (depending on your situation): var d : {a:Array<Dynamic>} = getDynamic(); for (t in d.a) { ... } You could also change Dynamic to the type of the contents of the array. A: Another way to do the same is to use an extra temp variable and explicit typing: var d = getDynamic(); var a: Array<Dynamic> = d.a; for (t in a) { ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/51781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I export the code documentation in C# / VisualStudio 2008? I have always made a point of writing nice code comments for classes and methods with the C# xml syntax. I always expected to easily be able to export them later on. Today I actually have to do so, but am having trouble finding out how. Is there something I'm missing? I want to go Menu->Build->Build Code Documentation, but there is no option to do that, there. A: You could try NDOC or SandCastle if you dont mind using 3rd party tools. A: Actually it's in the project properties. Build tab, Output section, XML documentation file, and enter the filename. It will be built on every build of the project. After that you can build the actual help with Sandcastle. A: Sandcastle works pretty well for generating documentation and it supports a couple different formats for the generation. As far as I know, there isn't any Visual Studio integration for it, but there is a SandcastleGUI for it that is available. A: Be careful if you're using LINQ to SQL as you won't be able to easily add sustainable comments to the auto-generated objects. A: Late comment, but worth adding that even though Sandcastle is mothballed, the Sandcastle Help File Builder remains in active development, and I found it very powerful and straightforward to dive into when dealing with just this situation--install to rich .chm and .html/.asp output in a couple hours. A: The previous answers are really out of date. Here are some more modern options: * *DocFX: This is probably your best bet because it runs on Linux, macOS, and Windows and it's supported by the .NET Foundation. *Sandcastle Help File Builder (SHFB): This one is still supported but it might not be as active. A: The original NDoc project (mentioned by others) is dead, but there is a new project called NDoc3. NDoc3 supports .NET 2.0 - 3.5. It is currently available as a beta version and worked great for me. I'm not sure if the project is still active - the last beta was release in april 2009.
{ "language": "en", "url": "https://stackoverflow.com/questions/51782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How to serialize a graph structure? Flat files and relational databases give us a mechanism to serialize structured data. XML is superb for serializing un-structured tree-like data. But many problems are best represented by graphs. A thermal simulation program will, for instance, work with temperature nodes connected to each others through resistive edges. So what is the best way to serialize a graph structure? I know XML can, to some extent, do it---in the same way that a relational database can serialize a complex web of objects: it usually works but can easily get ugly. I know about the dot language used by the graphviz program, but I'm not sure this is the best way to do it. This question is probably the sort of thing academia might be working on and I'd love to have references to any papers discussing this. A: Typically relationships in XML are shown by the parent/child relationship. XML can handle graph data but not in this manner. To handle graphs in XML you should use the xs:ID and xs:IDREF schema types. In an example, assume that node/@id is an xs:ID type and that link/@ref is an xs:IDREF type. The following XML shows the cycle of three nodes 1 -> 2 -> 3 -> 1. <data> <node id="1"> <link ref="2"/> </node> <node id="2"> <link ref="3"/> </node> <node id="3"> <link ref="1"/> </node> </data> Many development tools have support for ID and IDREF too. I have used Java's JAXB (Java XML Binding. It supports these through the @XmlID and the @XmlIDREF annotations. You can build your graph using plain Java objects and then use JAXB to handle the actual serialization to XML. A: XML is very verbose. Whenever I do it, I roll my own. Here's an example of a 3 node directed acyclic graph. It's pretty compact and does everything I need it to do: 0: foo 1: bar 2: bat ---- 0 1 0 2 1 2 A: Adjacency lists and adjacency matrices are the two common ways of representing graphs in memory. The first decision you need to make when deciding between these two is what you want to optimize for. Adjacency lists are very fast if you need to, for example, get the list of a vertex's neighbors. On the other hand, if you are doing a lot of testing for edge existence or have a graph representation of a markov chain, then you'd probably favor an adjacency matrix. The next question you need to consider is how much you need to fit into memory. In most cases, where the number of edges in the graph is much much smaller than the total number of possible edges, an adjacency list is going to be more efficient, since you only need to store the edges that actually exist. A happy medium is to represent the adjacency matrix in compressed sparse row format in which you keep a vector of the non-zero entries from top left to bottom right, a corresponding vector indicating which columns the non-zero entries can be found in, and a third vector indicating the start of each row in the column-entry vector. [[0.0, 0.0, 0.3, 0.1] [0.1, 0.0, 0.0, 0.0] [0.0, 0.0, 0.0, 0.0] [0.5, 0.2, 0.0, 0.3]] can be represented as: vals: [0.3, 0.1, 0.1, 0.5, 0.2, 0.3] cols: [2, 3, 0, 0, 1, 4] rows: [0, 2, null, 4] Compressed sparse row is effectively an adjacency list (the column indices function the same way), but the format lends itself a bit more cleanly to matrix operations. A: How do you represent your graph in memory? Basically you have two (good) options: * *an adjacency list representation *an adjacency matrix representation in which the adjacency list representation is best used for a sparse graph, and a matrix representation for the dense graphs. If you used suchs representations then you could serialize those representations instead. If it has to be human readable you could still opt for creating your own serialization algorithm. For example you could write down the matrix representation like you would do with any "normal" matrix: just print out the columns and rows, and all the data in it like so: 1 2 3 1 #t #f #f 2 #f #f #t 3 #f #t #f (this is a non-optimized, non weighted representation, but can be used for directed graphs) A: One example you might be familiar is Java serialization. This effectively serializes by graph, with each object instance being a node, and each reference being an edge. The algorithm used is recursive, but skipping duplicates. So the pseudo code would be: serialize(x): done - a set of serialized objects if(serialized(x, done)) then return otherwise: record properties of x record x as serialized in done for each neighbour/child of x: serialize(child) Another way of course is as a list of nodes and edges, which can be done as XML, or in any other preferred serialization format, or as an adjacency matrix. A: On a less academic, more practical note, in CubicTest we use Xstream (Java) to serialize tests to and from xml. Xstream handles graph-structured object relations, so you might learn a thing or two from looking at it's source and the resulting xml. You're right about the ugly part though, the generated xml files don't look pretty.
{ "language": "en", "url": "https://stackoverflow.com/questions/51783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How to generate UML diagrams (especially sequence diagrams) from Java code? How can I generate UML diagrams (especially sequence diagrams) from existing Java code? A: How about PlantUML? It's not for reverse engineering!!! It's for engineering before you code. A: I developed a maven plugin that can both, be run from CLI as a plugin goal, or import as dependency and programmatically use the parser, @see Main#main() to get the idea on how. It renders PlantUML src code of desired packages recursively that you can edit manually if needed (hopefully you won't). Then, by pasting the code in the plantUML page, or by downloading plant's jar you can render the UML diagram as a png image. Check it out here https://github.com/juanmf/Java2PlantUML Example output diagram: Any contribution is more than welcome. It has a set of filters that customize output but I didn't expose these yet in the plugin CLI params. It's important to note that it's not limited to your *.java files, it can render UML diagrams src from you maven dependencies as well. This is very handy to understand libraries you depend on. It actually inspects compiled classes with reflection so no source needed Be the 1st to star it at GitHub :P A: EDIT: If you're a designer then Papyrus is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then ObjectAid is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !. UPDATE Oct 11th, 2013 My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer. I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway. The Answer (Oct 11th, 2013) Tools * *Download Papyrus *Go to Help -> Install New Software... *In the Work with: drop-down, select --All Available Sites-- *In the filter, type in Papyrus *After installation finishes restart Eclipse *Repeat steps 1-3 and this time, install Modisco Steps * *In your java project (assume it's called MyProject) create a folder e.g UML *Right click over the project name -> Discovery -> Discoverer -> Discover Java and inventory model from java project, a file called MyProject_kdm.xmi will be generated. *Right click project name file --> new --> papyrus model -> and call it MyProject. *Move the three generated files MyProject.di , MyProject.notation, MyProject.uml to the UML folder *Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml *Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one. *ALT+W -> show view -> papyrus -> model explorer *In that view, you'll find your classes like in the picture *In the view Right click root model -> New diagram *Then start grabbing classes to the diagram from the view Some features * *To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !! *You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram *one very important setting is Arrange when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All *Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc *After all of that your settings will show diagrams like *Synchronization isn't available as far as I know you'll need to manually import any new classes. That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something. Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools. A: What is your codebase? Java or C++? eUML2 for Java is a powerful UML modeler designed for Java developper in Eclipse. The free edition can be used for commercial use. It supports the following features: * *CVS and Team Support *Designed for large project with multiple and customizable model views *Helios Compliant *Real-time code/model synchronization *UML2.1 compliant and support of OMG XMI *JDK 1.4 and 1.5 support *The commercial edition provides: *Advanced reversed engineering *Powerful true dependency analyze tools *UML Profile and MDD *Database tools *Customizable template support A: I would recommend EclipseUML from Omondo for general usage, although I did experience some problems a few months back, with my web projects. They had a free edition at one point in time, but that is supposedly no longer promoted. If you are really keen on reverse engineering sequence diagrams from source code, I would recommend jTracert. As far as Eclipse projects themselves are concerned, the Eclipse UML2 Tools project might support reverse engineering, although I've have never seen its use in practice. The MoDisco (Model Discovery) project Eclipse GMT project seems to be clearer in achieving your objective. The list of technology specific tools would be a good place to start with. A: You could also give the netbeans UML modeller a try. I have used it to generate javacode that I used in my eclipse projects. You can even import eclipse projects in netbeans and keep the eclipse settings synced with the netbeans project settings. I tried several UML modellers for eclipse and wasn't satisfied with them. They were either unstable, complicated or just plain ugly. ;-) A: I found Green plugin very simple to use and to generate class diagram from source code. Give it a try :). Just copy the plugin to your plugin dir. A: Using IntelliJ IDEA. To generate class diagram select package and press Ctrl + Alt + U: By default, it displays only class names and not all dependencies. To change it: right click -> Show Categories... and Show dependencies: To genarate dependencies diagram (UML Deployment diagram) and you use maven go View -> Tool Windows -> Maven Projects and press Ctrl + Alt + U: The result: Also it is possible to generate more others diagrams. See documentation. A: ObjectAid UML Explorer Is what I used. It is easily installed from the repository: Name: ObjectAid UML Explorer Location: http://www.objectaid.com/update/current And produces quite nice UML diagrams: Description from the website: The ObjectAid UML Explorer is different from other UML tools. It uses the UML notation to show a graphical representation of existing code that is as accurate and up-to-date as your text editor, while being very easy to use. Several unique features make this possible: * *Your source code and libraries are the model that is displayed, they are not reverse engineered into a different format. *If you update your code in Eclipse, your diagram is updated as well; there is no need to reverse engineer source code. *Refactoring updates your diagram as well as your source code. When you rename a field or move a class, your diagram simply reflects the changes without going out of sync. *All diagrams in your Eclipse workspace are updated with refactoring changes as appropriate. If necessary, they are checked out of your version control system. *Diagrams are fully integrated into the Eclipse IDE. You can drag Java classes from any other view onto the diagram, and diagram-related information is shown in other views wherever applicable. A: You can use the 30 days evaluation build of EclipseUML for Eclipse 3.5 : http://www.uml2.org/eclipse-java-galileo-SR2-win32_eclipseUML2.2_package_may2010.zip This is not the latest 3.6 build, but is pretty good and don't require you purchase it for testing and reverse engineering. Reverse engineering : http://www.forum-omondo.com/documentation_eclipseuml_2008/reverse/reverse/reverse_engineering_example.html Live flash demo: http://www.ejb3.org/reverse.swf EclipseUML Omondo is the best tool in the world for Java. Only eUML seems to compete with it on this live java synchronization market, but eUML adds model tags in the code which is really very very bad and a definitive no go for me. A: I am one of the authors, so the answer can be biased. It is open-source (Apache 2.0), but the plugin is not free. You don't have to pay (obviously) if you clone and build it locally. On Intellij IDEA, ZenUML can generate sequence diagram from Java code. Check it out at https://plugins.jetbrains.com/plugin/12437-zenuml-support Source code: https://github.com/ZenUml/jetbrains-zenuml A: By far the best tool I have used for reverse engineering, and round tripping java -> UML is Borland's Together. It is based on Eclipse (not just a single plugin) and really works well. A: I've noticed SequenceDiagram plugin for Intellij is also a good option. A: Another modelling tool for Java is (my) website GitUML. Generate UML diagrams from Java or Python code stored in GitHub repositories. One key idea with GitUML is to address one of the problems with "documentation": that diagrams are always out of date. With GitUML, diagrams automatically update when you push code using git. Browse through community UML diagrams, there are some Java design patterns there. Surf through popular GitHub repositories and visualise the architectures and patterns in them. Create diagrams using point and click. There is no drag drop editor, just click on the classes in the repository tree that you want to visualise: The underlying technology is PlantUML based, which means you can refine your diagrams with additional PlantUML markup. A: There is a Free tool named binarydoc which can generate UML Sequence Diagram, or Control Flow Graph (CFG) from the bytecode (instead of source code) of a Java method. Here is an sample diagram binarydoc generated for the java method java.net.AbstractPlainSocketImpl.getInputStream: * *Control Flow Graph of method java.net.AbstractPlainSocketImpl.getInputStream: * *UML Sequence Diagram of method java.net.AbstractPlainSocketImpl.getInputStream: A: I suggest PlantUML. this tools is very usefull and easy to use. PlantUML have a plugin for Netbeans that you can create UML diagram from your java code. you can install PlantUML plugin in the netbeans by this method: Netbeans Menu -> Tools -> Plugin Now select Available Plugins and then find PlantUML and install it. For more information go to website: www.plantuml.com
{ "language": "en", "url": "https://stackoverflow.com/questions/51786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "447" }
Q: How can you set the SMTP envelope MAIL FROM using System.Net.Mail? When you send an email using C# and the System.Net.Mail namespace, you can set the "From" and "Sender" properties on the MailMessage object, but neither of these allows you to make the MAIL FROM and the from address that goes into the DATA section different from each other. MAIL FROM gets set to the "From" property value, and if you set "Sender" it only adds another header field in the DATA section. This results in "From [email protected] on behalf of [email protected]", which is not what you want. Am I missing something? The use case is controlling the NDR destination for newsletters, etc., that are sent on behalf of someone else. I am currently using aspNetEmail instead of System.Net.Mail, since it allows me to do this properly (like most other SMTP libraries). With aspNetEmail, this is accomplished using the EmailMessage.ReversePath property. A: MailMessage.Sender will always insert a Sender header (interpreted as on behalf of in your e-mail client). If you use the Network delivery method on the SmtpClient, .Sender will also change the sender in the envelope. Using the PickupDirectoryFromIis delivery method will leave it to IIS to determine the envelope sender, and IIS will use the From address, not the Sender address. There's a similar question on MSDN here. A: I just found how to do it: * *mail.From specify the email from visible to the final user *mail.Sender specifies the envelope MAIL FROM That's it (even if it took me a while to figure it out) A: If you add the following lines the Return-Path and the Reply-To headers are set in the mail header. Dim strReplyTo As String = "[email protected]" message.ReplyToList.Add(strReplyTo) message.Headers.Add("Return-Path", strReplyTo) And if you click on reply the e-mail set to the Reply-To address A: Do you mean this?: //create the mail message MailMessage mail = new MailMessage(); //set the addresses mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]"); //set the content mail.Subject = "This is an email"; mail.Body = "this is a sample body with html in it. <b>This is bold</b> <font color=#336699>This is blue</font>"; mail.IsBodyHtml = true; //send the message SmtpClient smtp = new SmtpClient("127.0.0.1"); smtp.Send(mail); From http://www.systemnetmail.com/faq/3.1.2.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/51793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Edit control on stack overflow Is the edit control I'm typing in now, with all its buttons and rules freely available for use? My web project is also .Net based. A: It's the WMD Markdown editor which is free and seems to be pretty easy to use. Just include the javascript for it and (in the easiest case), it just attaches to the first textarea it finds. Here's some info about the Perl implementation of Markdown which, according to the site, WMD is 100% compatible with. @Chris Upchurch Technically the current release isn't open-source, just free to use. The next version is supposed to be released with an MIT license though. "now completely free to use. The next release will be open source under an MIT-style license." A: I don't know about this control, but TinyMCE is: http://tinymce.moxiecode.com/ It's what wordpress etc use. A: The WMD editor is completely free (in the speech and beer senses of the word). It's available under an MIT-style license.
{ "language": "en", "url": "https://stackoverflow.com/questions/51808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there a standard approach to generating sql dynamically? I want to ask how other programmers are producing Dynamic SQL strings for execution as the CommandText of a SQLCommand object. I am producing parameterized queries containing user-generated WHERE clauses and SELECT fields. Sometimes the queries are complex and I need a lot of control over how the different parts are built. Currently, I am using many loops and switch statements to produce the necessary SQL code fragments and to create the SQL parameters objects needed. This method is difficult to follow and it makes maintenance a real chore. Is there a cleaner, more stable way of doing this? Any Suggestions? EDIT: To add detail to my previous post: * *I cannot really template my query due to the requirements. It just changes too much. *I have to allow for aggregate functions, like Count(). This has consequences for the Group By/Having clause. It also causes nested SELECT statements. This, in turn, effects the column name used by *Some Contact data is stored in an XML column. Users can query this data AS WELL AS and the other relational columns together. Consequences are that xmlcolumns cannot appear in Group By clauses[sql syntax]. *I am using an efficient paging technique that uses Row_Number() SQL Function. Consequences are that I have to use a Temp table and then get the @@rowcount, before selecting my subset, to avoid a second query. I will show some code (the horror!) so that you guys have an idea of what I'm dealing with. sqlCmd.CommandText = "DECLARE @t Table(ContactId int, ROWRANK int" + declare + ")INSERT INTO @t(ContactId, ROWRANK" + insertFields + ")"//Insert as few cols a possible + "Select ContactID, ROW_NUMBER() OVER (ORDER BY " + sortExpression + " " + sortDirection + ") as ROWRANK" // generates a rowrank for each row + outerFields + " FROM ( SELECT c.id AS ContactID" + coreFields + from // sometimes different tables are required + where + ") T " // user input goes here. + groupBy+ " " + havingClause //can be empty + ";" + "select @@rowcount as rCount;" // return 2 recordsets, avoids second query + " SELECT " + fields + ",field1,field2" // join onto the other cols n the table +" FROM @t t INNER JOIN contacts c on t.ContactID = c.id" +" WHERE ROWRANK BETWEEN " + ((pageIndex * pageSize) + 1) + " AND " + ( (pageIndex + 1) * pageSize); // here I select the pages I want In this example, I am querying XML data. For purely relational data, the query is much more simple. Each of the section variables are StringBuilders. Where clauses are built like so: // Add Parameter to SQL Command AddParamToSQLCmd(sqlCmd, "@p" + z.ToString(), SqlDbType.VarChar, 50, ParameterDirection.Input, qc.FieldValue); // Create SQL code Fragment where.AppendFormat(" {0} {1} {2} @p{3}", qc.BooleanOperator, qc.FieldName, qc.ComparisonOperator, z); A: I had the need to do this on one of my recent projects. Here is the scheme that I am using for generating the SQL: * *Each component of the query is represented by an Object (which in my case is a Linq-to-Sql entity that maps to a table in the DB). So I have the following classes: Query, SelectColumn, Join, WhereCondition, Sort, GroupBy. Each of these classes contains all details relating to that component of the query. *The last five classes are all related to a Query object. So the Query object itself has collections of each class. *Each class has a method that can generate the SQL for the part of the query that it represents. So creating the overall query ends up calling Query.GenerateQuery() which in turn enumerates through all of the sub-collections and calls their respective GenerateQuery() methods It is still a bit complicated, but in the end you know where the SQL generation for each individual part of the query originates (and I don't think that there are any big switch statements). And don't forget to use StringBuilder. A: We created our own FilterCriteria object that is kind of a black-box dynamic query builder. It has collection properties for SelectClause, WhereClause, GroupByClause and OrderByClause. It also contains a properties for CommandText, CommandType, and MaximumRecords. We then jut pass our FilterCriteria object to our data logic and it executes it against the database server and passes parameter values to a stored procedure that executes the dynamic code. Works well for us ... and keeps the SQL generation nicely contained in an object. A: You could try the approach used by code generation tools like CodeSmith. Create a SQL template with placeholders. At runtime, read the template into a string and substitute the placeholders with actual values. This is only useful if all the SQL code follow a pattern. A: Gulzar and Ryan Lanciaux make good points in mentioning CodeSmith and ORM. Either of those might reduce or eliminate your current burden when it comes to generating dynamic SQL. Your current approach of using parameterized SQL is wise, simply because it protects well against SQL injection attacks. Without an actual code sample to comment on, it's difficult to provide an informed alternative to the loops and switch statements you're currently using. But since you mention that you're setting a CommandText property, I would recommend the use of string.Format in your implementation (if you aren't already using it). I think it may make your code easier to restructure, and therefore improve readability and understanding. A: Usually it's something like this: string query= "SELECT {0} FROM .... WHERE {1}" StringBuilder selectclause = new StringBuilder(); StringBuilder wherecaluse = new StringBuilder(); // .... the logic here will vary greatly depending on what your system looks like MySqlcommand.CommandText = String.Format(query, selectclause.ToString(), whereclause.ToString()); I'm also just getting started out with ORMs. You might want to take a look at one of those. ActiveRecord / Hibernate are some good keywords to google. A: If you really need to do this from code, then an ORM is probably the way to go to try to keep it clean. But I'd like to offer an alternative that works well and could avoid the performance problems that accompany dynamic queries, due to changing SQL that requires new query plans to be created, with different demands on indexes. Create a stored procedure that accepts all possible parameters, and then use something like this in the where clause: where... and (@MyParam5 is null or @MyParam5 = Col5) then, from code, it's much simpler to set the parameter value to DBNull.Value when it is not applicable, rather than changing the SQL string you generate. Your DBAs will be much happier with you, because they will have one place to go for query tuning, the SQL will be easy to read, and they won't have to dig through profiler traces to find the many different queries being generated by your code. A: Out of curiousity, have you considered using an ORM for managing your data access. A lot of the functionality you're trying to implement could already be there. It may be something to look at because its best not to re-invent the wheel. A: ORMs have already solved the problem of dynamic SQL generation (I prefer NHibernate/ActiveRecord). Using these tools you can create a query with an unknown number of conditions by looping across user input and generating an array of Expression objects. Then execute the built-in query methods with that custom expression set. List<Expression> expressions = new List<Expression>(userConditions.Count); foreach(Condition c in userConditions) { expressions.Add(Expression.Eq(c.Field, c.Value)); } SomeTable[] records = SomeTable.Find(expressions); There are more 'Expression' options: non-equality, greater/less than, null/not-null, etc. The 'Condition' type I just made up, you can probably stuff your user input into a useful class.
{ "language": "en", "url": "https://stackoverflow.com/questions/51827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Open one of a series of files using a batch file I have up to 4 files based on this structure (note the prefixes are dates) * *0830filename.txt *0907filename.txt *0914filename.txt *0921filename.txt I want to open the the most recent one (0921filename.txt). how can i do this in a batch file? Thanks. A: This method uses the actual file modification date, to figure out which one is the latest file: @echo off for /F %%i in ('dir /B /O:-D *.txt') do ( call :open "%%i" exit /B 0 ) :open start "dummy" "%~1" exit /B 0 This method, however, chooses the last file in alphabetic order (or the first one, in reverse-alphabetic order), so if the filenames are consistent - it will work: @echo off for /F %%i in ('dir /B *.txt^|sort /R') do ( call :open "%%i" exit /B 0 ) :open start "dummy" "%~1" exit /B 0 You actually have to choose which method is better for you. A: Sorry, for spamming this question, but I just really feel like posting The Real Answer. If you want your BATCH script to parse and compare the dates in filenames, then you can use something like this: @echo off rem Enter the ending of the filenames. rem Basically, you must specify everything that comes after the date. set fn_end=filename.txt rem Do not touch anything bellow this line. set max_month=00 set max_day=00 for /F %%i in ('dir /B *%fn_end%') do call :check "%%i" call :open %max_month% %max_day% exit /B 0 :check set name=%~1 set date=%name:~0,4% set month=%date:~0,2% set day=%date:~2,2% if /I %month% GTR %max_month% ( set max_month=%month% set max_day=%day% ) else if /I %month% EQU %max_month% ( set max_month=%month% if /I %day% GTR %max_day% ( set max_day=%day% ) ) exit /B 0 :open set date=%~1 set month=%~2 set name=%date%%month%%fn_end% start "dummy" "%name%" exit /B 0 A: One liner, using EXIT trick: FOR /F %%I IN ('DIR *.TXT /B /O:-D') DO NOTEPAD %%I & EXIT EDIT: @pam: you're right, I was assuming that the files were in date order, but you can change the command to: FOR /F %%I IN ('DIR *.TXT /B /O:-N') DO NOTEPAD %%I & EXIT then you have the file list sorted by name in reverse order. A: Here you go... (hope no-one beat me to it...) (You'll need to save the file as lasttext.bat or something) This will open up / run the oldest .txt file dir *.txt /b /od > systext.bak FOR /F %%i in (systext.bak) do set sysRunCommand=%%i call %sysRunCommand% del systext.bak /Y Probably XP only. BEHOLD The mighty power of DOS. Although this takes the latest filename by date - NOT by filename.. If you want to get the latest filename, change /od to /on . If you want to sort on something else, add a "sort" command to the second line. A: Use regular expression to parse the relevant integer out and compare them.
{ "language": "en", "url": "https://stackoverflow.com/questions/51837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can MS Visual Studio compile projects using 2 or 4 cores on CPU? Is it any compilator option of flag? A: You can if you setup an external tool pointing to MsBuild to build the solution with the multiple process flag /m. Scott Hanselman wrote a nice post on how to accomplish this, so I won't repeat what he has already done. A: MSDN answers your question: Using Multiple Processors to Build Projects A: In case anyone comes across this, VS2012 introduced parallel builds as a standard feature. Quote from the article: Visual Studio 2010 included an option for "maximum number of parallel project builds." Although there was no indication of any restriction, this IDE option only worked for C++ projects. Fortunately, this restriction no longer applies to Visual Studio 11. Rather, there's now full support for parallel builds in other languages as well. To view this, run a copy of Process Explorer at the same time a solution with numerous projects is building. You'll see that multiple MSBuild instances are created -- as many as specified in the "maximum number of parallel project builds."
{ "language": "en", "url": "https://stackoverflow.com/questions/51845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Using Makefile instead of Solution/Project files under Visual Studio (2005) Does anyone have experience using makefiles for Visual Studio C++ builds (under VS 2005) as opposed to using the project/solution setup. For us, the way that the project/solutions work is not intuitive and leads to configuruation explosion when you are trying to tweak builds with specific compile time flags. Under Unix, it's pretty easy to set up a makefile that has its default options overridden by user settings (or other configuration setting). But doing these types of things seems difficult in Visual Studio. By way of example, we have a project that needs to get build for 3 different platforms. Each platform might have several configurations (for example debug, release, and several others). One of my goals on a newly formed project is to have a solution that can have all platform build living together, which makes building and testing code changes easier since you aren't having to open 3 different solutions just to test your code. But visual studio will require 3 * (number of base configurations) configurations. i.e. PC Debug, X360 Debug, PS3 Debug, etc. It seems like a makefile solution is much better here. Wrapped with some basic batchfiles or scripts, it would be easy to keep the configuration explotion to a minimum and only maintain a small set of files for all of the different builds that we have to do. However, I have no experience with makefiles under visual studio and would like to know if others have experiences or issues that they can share. Thanks. (post edited to mention that these are C++ builds) A: I've found some benefits to makefiles with large projects, mainly related to unifying the location of the project settings. It's somewhat easier to manage the list of source files, include paths, preprocessor defines and so on, if they're all in a makefile or other build config file. With multiple configurations, adding an include path means you need to make sure you update every config manually through Visual Studio's fiddly project properties, which can get pretty tedious as a project grows in size. Projects which use a lot of custom build tools can be easier to manage too, such as if you need to compile pixel / vertex shaders, or code in other languages without native VS support. You'll still need to have various different project configurations however, since you'll need to differentiate the invocation of the build tool for each config (e.g. passing in different command line options to make). Immediate downsides that spring to mind: * *Slower builds: VS isn't particularly quick at invoking external tools, or even working out whether it needs to build a project in the first place. *Awkward inter-project dependencies: It's fiddly to set up so that a dependee causes the base project to build, and fiddlier to make sure that they get built in the right order. I've had some success getting SCons to do this, but it's always a challenge to get working well. *Loss of some useful IDE features: Edit & Continue being the main one! In short, you'll spend less time managing your project configurations, but more time coaxing Visual Studio to work properly with it. A: Visual studio is being built on top of the MSBuild configurations files. You can consider *proj and *sln files as makefiles. They allow you to fully customize build process. A: While it's technically possible, it's not a very friendly solution within Visual Studio. It will be fighting you the entire time. I recommend you take a look at NAnt. It's a very robust build system where you can do basically anything you need to. Our NAnt script does this on every build: * *Migrate the database to the latest version *Generate C# entities off of the database *Compile every project in our "master" solution *Run all unit tests *Run all integration tests Additionally, our build server leverages this and adds 1 more task, which is generating Sandcastle documentation. If you don't like XML, you might also take a look at Rake (ruby), Bake/BooBuildSystem (Boo), or Psake (PowerShell) A: You can use nant to build the projects individually thus replacing the solution and have 1 coding solution and no build solutions. 1 thing to keep in mind, is that the solution and csproj files from vs 2005 and up are msbuild scripts. So if you get acquainted with msbuild you might be able to wield the existing files, to make vs easier, and to make your deployment easier. A: We have a similar set up as the one you are describing. We support at least 3 different platforms, so the we found that using CMake to mange the different Visual Studio solutions. Set up can be a bit painful, but it pretty much boils down to reading the docs and a couple of tutorials. You should be able to do virtually everything you can do by going to the properties of the projects and the solution. Not sure if you can have all three platforms builds living together in the same solution, but you can use CruiseControl to take care of your builds, and running your testing scripts as often as needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/51859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: VC++ and MapPoint OCX control dialog issue I am writing a VC++ MFC dialog based app which requires Microsoft MapPoint embedding in it. To do this I'm using MS VC++ .NET 2003 and MapPoint Europe 2006 to do this but am having problems as when I select "Insert ActiveX Control" no MapPoint control appears in the list of options. I have tried manually registering mappointcontrol.ocx with regsvr32 which appears to succeed but still the control doesn't appear on the list. Can anyone suggest what I am doing wrong here, and any possible solutions. Thanks Ian A: Have you tried using the ActiveX control test container? Is it in the list of controls? How about using the register button in the test container? Also check the registry to see if it is registered. You should have an entry in HKEY-CLASSES-ROOT\controlName that has a CLSID element that points to a UUID. That UUID should also be in HKEY-CLASSES-ROOT\CLSID\uuid and have a LocalServer32 entry that points to the DLL and ProgID that points back to controlName. A: I have now got the Mappoint control working but in a slightly different way. The control does appear on the list of controls the test container can use. I have tried reregistering it and unregistering it but still it doesn't appear on the list of controls when I try a "Insert ActiveX Control". However if I use "Add/Remove Toolbox Items" I can add it to the toolbox and then drag it into my app where it works fine. I'm not sure why this method works but it does and I can get on with my coding. Many thanks for all your help with this.
{ "language": "en", "url": "https://stackoverflow.com/questions/51866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to force my ASP.net 2.0 app to recompile I have a ASP.net 2.0 app and I have made some changes the the source file ( cs files ). I uploaded the changes with the belief that it would auto-recompile. I also have the compiled dll in MY_APP/bin. I checked it and noticed that it did not recompile. Please understand I am new to this. A: I use a similar method to ChanChan, but instead of whitespace I put a comment in the web.config to indicate when/why the config was edited. A: my #1 way to do this, add white space to the top of the web config file, after the xml declaration tag. It forces the node to re-cache and recompile. We even have a page deep in the admin called Flush.aspx that does it for us. A: It's always best to just actually run a build after making .cs changes. Where are you running it? Is this for debugging or production? A: In VS menu you have Build -> Rebuild Solution
{ "language": "en", "url": "https://stackoverflow.com/questions/51870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What is the best Visual Studio Plugin for Printing Code Some of the features I think it must include are: * *Print Entire Solution *Ability to print line numbers *Proper choice of coding font and size to improve readability *Nice Header Information *Ability to print regions collapsed Couple feature additions: * *Automatically insert page breaks after methods/classes *Keep long lines readable (nearly all current implementations are broken) Note: There are many reasons to need to print code... One very good one is escrow. A: Try StarPrint's VSNETcodePrint A: I use PrettyCode.Print for .NET. It does everything on your list, and more. (I use it for printing code excerpts for copyright registration paperwork, which is similar to your escrow case.) It is a little slow to open a really big solution, but not unbearably so, and the output quality is excellent. A: Couple feature additions: * *Automatically insert page breaks after methods/classes *Keep long lines readable (nearly all current implementations are broken)
{ "language": "en", "url": "https://stackoverflow.com/questions/51871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Use cases for regular expression find/replace I recently discussed editors with a co-worker. He uses one of the less popular editors and I use another (I won't say which ones since it's not relevant and I want to avoid an editor flame war). I was saying that I didn't like his editor as much because it doesn't let you do find/replace with regular expressions. He said he's never wanted to do that, which was surprising since it's something I find myself doing all the time. However, off the top of my head I wasn't able to come up with more than one or two examples. Can anyone here offer some examples of times when they've found regex find/replace useful in their editor? Here's what I've been able to come up with since then as examples of things that I've actually had to do: * *Strip the beginning of a line off of every line in a file that looks like: Line 25634 : Line 632157 : *Taking a few dozen files with a standard header which is slightly different for each file and stripping the first 19 lines from all of them all at once. *Piping the result of a MySQL select statement into a text file, then removing all of the formatting junk and reformatting it as a Python dictionary for use in a simple script. *In a CSV file with no escaped commas, replace the first character of the 8th column of each row with a capital A. *Given a bunch of GDB stack traces with lines like #3 0x080a6d61 in _mvl_set_req_done (req=0x82624a4, result=27158) at ../../mvl/src/mvl_serv.c:850 strip out everything from each line except the function names. Does anyone else have any real-life examples? The next time this comes up, I'd like to be more prepared to list good examples of why this feature is useful. A: Just last week, I used regex find/replace to convert a CSV file to an XML file. Simple enough to do really, just chop up each field (luckily it didn't have any escaped commas) and push it back out with the appropriate tags in place of the commas. A: Regex make it easy to replace whole words using word boundaries. (\b\w+\b) So you can replace unwanted words in your file without disturbing words like Scunthorpe A: Yesterday I took a create table statement I made for an Oracle table and converted the fields to setString() method calls using JDBC and PreparedStatements. The table's field names were mapped to my class properties, so regex search and replace was the perfect fit. Create Table text: ... field_1 VARCHAR2(100) NULL, field_2 VARCHAR2(10) NULL, field_3 NUMBER(8) NULL, field_4 VARCHAR2(100) NULL, .... My Regex Search: /([a-z_])+ .*?,?/ My Replacement: pstmt.setString(1, \1); The result: ... pstmt.setString(1, field_1); pstmt.setString(1, field_2); pstmt.setString(1, field_3); pstmt.setString(1, field_4); .... I then went through and manually set the position int for each call and changed the method to setInt() (and others) where necessary, but that worked handy for me. I actually used it three or four times for similar field to method call conversions. A: I like to use regexps to reformat lists of items like this: int item1 double item2 to public void item1(int item1){ } public void item2(double item2){ } This can be a big time saver. A: I use it all the time when someone sends me a list of patient visit numbers in a column (say 100-200) and I need them in a '0000000444','000000004445' format. works wonders for me! I also use it to pull out email addresses in an email. I send out group emails often and all the bounced returns come back in one email. So, I regex to pull them all out and then drop them into a string var to remove from the database. I even wrote a little dialog prog to apply regex to my clipboard. It grabs the contents applies the regex and then loads it back into the clipboard. A: One thing I use it for in web development all the time is stripping some text of its HTML tags. This might need to be done to sanitize user input for security, or for displaying a preview of a news article. For example, if you have an article with lots of HTML tags for formatting, you can't just do LEFT(article_text,100) + '...' (plus a "read more" link) and render that on a page at the risk of breaking the page by splitting apart an HTML tag. Also, I've had to strip img tags in database records that link to images that no longer exist. And let's not forget web form validation. If you want to make a user has entered a correct email address (syntactically speaking) into a web form this is about the only way of checking it thoroughly. A: I've just pasted a long character sequence into a string literal, and now I want to break it up into a concatenation of shorter string literals so it doesn't wrap. I also want it to be readable, so I want to break only after spaces. I select the whole string (minus the quotation marks) and do an in-selection-only replace-all with this regex: /.{20,60} / ...and this replacement: /$0"¶ + "/ ...where the pilcrow is an actual newline, and the number of spaces varies from one incident to the next. Result: String s = "I recently discussed editors with a co-worker. He uses one " + "of the less popular editors and I use another (I won't say " + "which ones since it's not relevant and I want to avoid an " + "editor flame war). I was saying that I didn't like his " + "editor as much because it doesn't let you do find/replace " + "with regular expressions."; A: The first thing I do with any editor is try to figure out it's Regex oddities. I use it all the time. Nothing really crazy, but it's handy when you've got to copy/paste stuff between different types of text - SQL <-> PHP is the one I do most often - and you don't want to fart around making the same change 500 times. A: Regex is very handy any time I am trying to replace a value that spans multiple lines. Or when I want to replace a value with something that contains a line break. I also like that you can match things in a regular expression and not replace the full match using the $# syntax to output the portion of the match you want to maintain. A: I agree with you on points 3, 4, and 5 but not necessarily points 1 and 2. In some cases 1 and 2 are easier to achieve using a anonymous keyboard macro. By this I mean doing the following: * *Position the cursor on the first line *Start a keyboard macro recording *Modify the first line *Position the cursor on the next line *Stop record. Now all that is needed to modify the next line is to repeat the macro. I could live with out support for regex but could not live without anonymous keyboard macros.
{ "language": "en", "url": "https://stackoverflow.com/questions/51884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Operating System Overheads while profiling? I am doing profiling of a C code in Microsoft VS 2005 on a Intel Core-2Duo platform. I measure the time(secs:millisecs) counsumed by my function. But i have some doubts about the accuracy of this measurement as the operating system will not continuously run my application, but instead schedule others apps/services in between the execution of my code.(Although i have no major applications running while i do the profile run, still windows will have lot of code of its own which it will run by preempting my app.). Because of all this i believe the profiling number(time taken by my app to run) is not accurate. So my question is there any way to find out the Operating system overheads, scheduling overhead on a typical windows system(I run Windows XP)e.g. if my applications says it ran for 60 milliseconds, out of that 60 msec, how much time really was used by my app. and how much time it was sitting idle, due to being pre-empted by some other task scheduled by the OS? or Atleast is there any ball-park number to get such OS overhead, based on your experience you came across while doing something similar? A: @Kogus: Even if i run outside debugger(standalone app. from a command prompt) it still could be preempted by OS and cause a incorrect measurement of the time consumed by my app. Is'nt it? -AD A: I think you are going to have some problems with the granularity. See similar questions GetLocalTime() API time resolution and Is gettimeofday() guaranteed to be of microsecond resolution? Also, you may want to take a look at the Windows Resource Kits Tools which include timeit.exe (similar to time on unix/linux) to give you elapsed and process times. A: Suggestion Try run on multi CPU systems. A: 1 - Put some debug logging in your code (include timestamps of course), and run it outside of the debugger 2 - Run again in the debugger 3 - Repeat many times, to get statistically valid data. 4 - Compare. If there is a significant difference in the average execution time of the standalone vs. the debugger, then you are right to be suspicious of the OS (or the overhead of the debugger hooks themselves...). If no difference, then don't sweat it. Edit0: Obviously the debug messages have some overhead of their own. You may want to leave those in the code even when you are running from the debugger. That way, both the standalone and the debugger are running the very same code. Edit1: I misunderstood the question. I thought your concern was that --while debugging--, the OS might interrupt your app more frequently than in a normal mode of execution. If you want to know how much time your app actually spent working, just compare the time taken to the "CPU Time" in the Task Manager. Edit2: Compare the time returned by GetProcessTimes for your process to the actual execution time. The difference is the time spent by the CPU on somebody else. A: The best way of doing this is a dedicated profiling tool. There are lots out there. I haven't used one for C for a few years, someone else will hopefully be able to give better advice. As you are using Visual Studio 2005 this might be a good place to start: AQ, but I've never used it.
{ "language": "en", "url": "https://stackoverflow.com/questions/51887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Activating the main form of a single instance application In a C# Windows Forms application I want to detect if another instance of the application is already running. If so, activate the main form of the running instance and exit this instance. What is the best way to achieve this? A: Scott Hanselman answers on you question in details. A: Here is what I'm currently doing in the application's Program.cs file. // Sets the window to be foreground [DllImport("User32")] private static extern int SetForegroundWindow(IntPtr hwnd); // Activate or minimize a window [DllImportAttribute("User32.DLL")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); private const int SW_RESTORE = 9; static void Main() { try { // If another instance is already running, activate it and exit Process currentProc = Process.GetCurrentProcess(); foreach (Process proc in Process.GetProcessesByName(currentProc.ProcessName)) { if (proc.Id != currentProc.Id) { ShowWindow(proc.MainWindowHandle, SW_RESTORE); SetForegroundWindow(proc.MainWindowHandle); return; // Exit application } } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } catch (Exception ex) { } } A: You can use such detection and activate your instance after it: // Detect existing instances string processName = Process.GetCurrentProcess().ProcessName; Process[] instances = Process.GetProcessesByName(processName); if (instances.Length > 1) { MessageBox.Show("Only one running instance of application is allowed"); Process.GetCurrentProcess().Kill(); return; } // End of detection A: Aku, that is a good resource. I answered a question similar to this one a while back. You can check my answer here. Even though this was for WPF, you can use the same logic in WinForms.
{ "language": "en", "url": "https://stackoverflow.com/questions/51898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Recommendations regarding Continuous Integration systems We are currently evaluating different applications that interface with Visual Studio 2008 (C#) and Subversion to do automated builds of our core libraries. We are hoping to have nightly builds performed and either email the list of changes made to each developer or have the latest versions be pushed to each workstation. What has been your experience with these tools and what are some recommendations? Suggested software * *Cruise Control .NET *Hudson *TeamCity Suggested articles * *Continuous Integration: From Theory to Practice 2nd Edition (CC.net) *Automating Your ASP.NET Build and Deploy Process with Hudson A: Hudson is the easiest continuous-integration / daily-build tool I've seen. Not sure if it meets all your requirements. A: Take a look at the JetBrain's (guys behind ReSharper) TeamCity A: I've used cc.net with nant and msbuild with great success, would highly recommend it. A: Cruise Control.net (ccnet) does everything you are looking for. Its pretty easy to use, just make sure if you are going to run it as a service, you give it an account and don't make it run as network service, that way you can give it rights on intranet boxes and have it do xcopy deploys. It has all kinds of email modes, on failure, on all, on fix after failure, and many many more. A: At my last employer I set up a buildserver with cc.net. Expect at least one or two days work to set it up. I used cc.net together with nant and msbuild. These projects have a lot of overlap in functionality so it might be a good idea to think about how you want to set everything up. The setup I eventually settled with was cc.net on the server to retrieve the project from subversion and fire off the nant scripts. nant was used to call msbuild to build the visual studio .sln files and do all the other build steps like running tests etc. I had a quick look at teamcity too. On first sight it looks a lot better than cc.net but I didn't have time to try it out yet. It's certainly worth checking out. A: I use CC.Net along with SubVersion and MSBuild to accomplish this. Here is a great guide for implementing this which I followed on found very helpful. A: A couple of tidbits about working with cc.net and msbuild. If you are building C/C+= projects, msbuild is, um, unreliable at least with VS 2005 (and perhaps earlier). I have not tested with VS 2008. We found that sometimes msbuild would work properly, sometimes not. In trying to solve the problem, we found vcbuild.exe which seems to work well in place of msbuild when building C/C++ solutions. A: If you are using trac for issue tracking, the bitten plug-in works well. It's not platform specific (we run it on both Windows and Linux at work, with msbuild/mstest and make/gcc/cpptest respectively). A: I am using hudsons Jenkins for getting daily build. It really very easy to setup and maintain. And it have a lot of plugins which full fill our requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/51925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to check if element in groovy array/hash/collection/list? How do I figure out if an array contains an element? I thought there might be something like [1, 2, 3].includes(1) which would evaluate as true. A: If you really want your includes method on an ArrayList, just add it: ArrayList.metaClass.includes = { i -> i in delegate } A: You can use Membership operator: def list = ['Grace','Rob','Emmy'] assert ('Emmy' in list) Membership operator Groovy A: For lists, use contains: [1,2,3].contains(1) == true A: IMPORTANT Gotcha for using .contains() on a Collection of Objects, such as Domains. If the Domain declaration contains a EqualsAndHashCode, or some other equals() implementation to determine if those Ojbects are equal, and you've set it like this... import groovy.transform.EqualsAndHashCode @EqualsAndHashCode(includes = "settingNameId, value") then the .contains(myObjectToCompareTo) will evaluate the data in myObjectToCompareTo with the data for each Object instance in the Collection. So, if your equals method isn't up to snuff, as mine was not, you might see unexpected results. A: Some syntax sugar 1 in [1,2,3] A: def fruitBag = ["orange","banana","coconut"] def fruit = fruitBag.collect{item -> item.contains('n')} I did it like this so it works if someone is looking for it. A: .contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue() [a:1,b:2,c:3].containsValue(3) [a:1,b:2,c:3].containsKey('a') A: You can also use matches with regular expression like this: boolean bool = List.matches("(?i).*SOME STRING HERE.*")
{ "language": "en", "url": "https://stackoverflow.com/questions/51927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "153" }
Q: TypeLoadException on System.Xml.Linq.XDocument when running T4 template on build server I'm having a problem running a T4 template using TextTransform.exe on my build server. On my dev machine the template works perfectly. The error message is as follows. error : Running transformation: System.TypeLoadException: Could not instantiate type System.Xml.Linq.XDocument The build server has the windows 2008 SDK on it, my machine has VS 2008. I thought mayve it couldn't find System.Data.Xml so I ensure the dll was present in the same directory, but no luck. Any ideas? A: Sounds like your server may not have .NET 3.5 installed. A: I installed .NET 3.5 SP1 and it corrected the problem
{ "language": "en", "url": "https://stackoverflow.com/questions/51931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I create a status dialog box in Excel I have created a database report generator in Excel. I am trying to create a dialog box that displays status information as the program runs. When I generate the report, although the dialog box appears, I cannot refresh/update the information it displays. Most of the time, the dialog box only partially appears. I have tried using the .repaint method, but I still get the same results. I only see the complete dialog box, after the report is generated. A: I have used Excel's own status bar (in bottom left of window) to display progress information for a similar application I developed in the past. It works out very well if you just want to display textual updates on progress, and avoids the need for an updating dialog at all. Ok @JonnyGold, here's an example of the kind of thing I used... Sub StatusBarExample() Application.ScreenUpdating = False ' turns off screen updating Application.DisplayStatusBar = True ' makes sure that the statusbar is visible Application.StatusBar = "Please wait while performing task 1..." ' add some code for task 1 that replaces the next sentence Application.Wait Now + TimeValue("00:00:02") Application.StatusBar = "Please wait while performing task 2..." ' add some code for task 2 that replaces the next sentence Application.Wait Now + TimeValue("00:00:02") Application.StatusBar = False ' gives control of the statusbar back to the programme End Sub Hope this helps! A: Try adding a DoEvents call in your loop. That should allow the form to repaint & accept other requests. A: The code below works well when performing actions within Excel (XP or later). For actions that take place outside Excel, for example connecting to a database and retrieving data the best this offers is the opportunity to show dialogs before and after the action (e.g. "Getting data", "Got data") Create a form called "frmStatus", put a label on the form called "Label1". Set the form property 'ShowModal' = false, this allows the code to run while the form is displayed. Sub ShowForm_DoSomething() Load frmStatus frmStatus.Label1.Caption = "Starting" frmStatus.Show frmStatus.Repaint 'Load the form and set text frmStatus.Label1.Caption = "Doing something" frmStatus.Repaint 'code here to perform an action frmStatus.Label1.Caption = "Doing something else" frmStatus.Repaint 'code here to perform an action frmStatus.Label1.Caption = "Finished" frmStatus.Repaint Application.Wait (Now + TimeValue("0:00:01")) frmStatus.Hide Unload frmStatus 'hide and unload the form End Sub A: Insert a blank sheet in your workbook Rename the Sheet eg. "information" Sheets("information").Select Range("C3").Select ActiveCell.FormulaR1C1 = "Updating Records" Application.ScreenUpdating = False Application.Wait Now + TimeValue("00:00:02") Continue Macro Sheets("information").Select Range("C3").Select Application.ScreenUpdating = True ActiveCell.FormulaR1C1 = "Preparing Information" Application.ScreenUpdating = False Application.Wait Now + TimeValue("00:00:02") Continue Macro Etc Alternatively select a blank cell somewhere on the existing sheet instead of inserting a new sheet Range("C3").Select ActiveCell.FormulaR1C1 = "Updating Records" Application.ScreenUpdating = False Application.Wait Now + TimeValue("00:00:02") Etc A: The dialog box is also running on the same UI thread. So, it is too busy to repaint itself. Not sure if VBA has good multi-threading capabilities.
{ "language": "en", "url": "https://stackoverflow.com/questions/51941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Do you know of a good program for editing/translating resource (.rc) files? I'm building a C++/MFC program in a multilingual environment. I have one main (national) language and three international languages. Every time I add a feature to the program I have to keep the international languages up-to-date with the national one. The resource editor in Visual Studio is not very helpful because I frequently end up leaving a string, dialog box, etc., untranslated. I wonder if you guys know of a program that can edit resource (.rc) files and * *Build a file that includes only the strings to be translated and their respective IDs and accepts the same (or similar) file in another language (this would be helpful since usually the translation is done by someone else), or *Handle the translations itself, allowing to view the same string in different languages at the same time. A: In my experience, internationalization requires a little more than translating strings. Many strings when translated, require more space on a dialog. Because of this it's useful to be able to customize the dialogs for each language. Otherwise you have to create dialogs with extra space for the translated strings which then looks less than optimal when displayed in English. Quite a while back I was using a translation tool for an MFC application but the company that produced the software stopped selling it. When I tried to find a reasonably priced replacement I did not find one. A: Check out Lingobit Localizer. Expensive, but well worth it. A: Here's a script I use to generate resource files for testing in different languages. It just parses a response from babelfish so clearly the translation will be about as high quality as that done by a drunken monkey, but it's useful for testing and such for i in $trfile do key=`echo $i | sed 's/^\(.*\)=\(.*\)$/\1/g'` value=`echo $i | sed 's/^\(.*\)=\(.*\)$/\2/g'` url="http://babelfish.altavista.com/tr?doit=done&intl=1&tt=urltext&lp=$langs&btnTrTxt=Translate&trtext=$value" wget -O foo.html -A "$agent" "$url" *&> /dev/null tx=`grep "<td bgcolor=white class=s><div style=padding:10px;>" foo.html` tx=`echo $tx | iconv -f latin1 -t utf-8 | sed 's/<td bgcolor=white class=s><div style=padding:10px;>\(.*\)<\/div><\/td>/\1/g'` echo $key=$tx done rm foo.html A: Check out appTranslator, its relatively cheap and works rather well. The guy developing it is really responsive to enhancement requests and bug report, so you get really good support. A: You might take a look at Sisulizer http://www.sisulizer.com. Expensive though. We're evaluating it for use at my company to manage the headache of ongoing translation. I read on their About page that the company was founded by people who left Multilizer and other similar companies. A: If there isn't one, it would be pretty easy to loop through all the strings in a resource a compare them to the international resources. You could probably do this with a simple grid. A: In the end we have ended up building our own external tools to manage this. Our devs work in the english string table and every automated build sends our strings that have been added/changed and deleted to translation manager. He can also run a report at anytime from an old build to determine what is required for translation. A: Check out RC-WinTrans. Its a commercial tool that my company uses. It basically imports our .RC files (or .resx files) into a database which we send to a different office for translation. The tool can then export a translated .RC file (or .resx file) for each language from the database. It even has a basic dialog box editor so the translator can adjust the size of various controls in the dialog box to be sure the translated text fits. It also accepts a number of command line arguments and has a COM automation interface so you can integrate it into a build process more easily. It works quite well for us and we literally have thousands and thousands of strings and dialog boxes, etc. (We currently have version 7 so what I've said might be a little bit different than their latest version 8.) A: Also try AppTranslator: http://www.apptranslator.com/. It has a build-in resource editor so that translators can, for example, enlargen a text box when need bo. It has separate versions for developers and translators and much more. A: We are using Multilizer (http://www.multilizer.com/) and although sometimes it's a bit tricky to use, at the end with a bit of patient it works pretty well. We even have a translation web site where translators can download our projects and then upload the translations using Multilizer command-line features. A: Managing localization and translations using .rc files and Visual Studio is not a good idea. It's much smarter (though counter-intuitive) to start localization through the exe. Read here why: http://www.apptranslator.com/misconceptions.html A: I've written this recently, which integrates into VS: https://github.com/ekkis/Powershell/blob/master/MT.ps1 largely because I was unsatisfied with the solutions out there. you'll need to get a client id from M$ (but they give you 2M words/month translation free - not bad) A: ResxCrunch will be out soon, it will edit multiple resource files in multiple languages in one single table.
{ "language": "en", "url": "https://stackoverflow.com/questions/51948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to get file extension from string in C++ Given a string "filename.conf", how to I verify the extension part? I need a cross platform solution. A: Actually, the easiest way is char* ext; ext = strrchr(filename,'.') One thing to remember: if '.' doesn't exist in filename, ext will be NULL. A: I've stumbled onto this question today myself, even though I already had a working code I figured out that it wouldn't work in some cases. While some people already suggested using some external libraries, I prefer to write my own code for learning purposes. Some answers included the method I was using in the first place (looking for the last "."), but I remembered that on linux hidden files/folders start with ".". So if file file is hidden and has no extension, the whole file name would be taken for extension. To avoid that I wrote this piece of code: bool getFileExtension(const char * dir_separator, const std::string & file, std::string & ext) { std::size_t ext_pos = file.rfind("."); std::size_t dir_pos = file.rfind(dir_separator); if(ext_pos>dir_pos+1) { ext.append(file.begin()+ext_pos,file.end()); return true; } return false; } I haven't tested this fully, but I think that it should work. A: The best way is to not write any code that does it but call existing methods. In windows, the PathFindExtension method is probably the simplest. So why would you not write your own? Well, take the strrchr example, what happens when you use that method on the following string "c:\program files\AppleGate.Net\readme"? Is ".Net\readme" the extension? It is easy to write something that works for a few example cases, but can be much harder to write something that works for all cases. A: I'd go with boost::filesystem::extension (std::filesystem::path::extension with C++17) but if you cannot use Boost and you just have to verify the extension, a simple solution is: bool ends_with(const std::string &filename, const std::string &ext) { return ext.length() <= filename.length() && std::equal(ext.rbegin(), ext.rend(), filename.rbegin()); } if (ends_with(filename, ".conf")) { /* ... */ } A: With C++17 and its std::filesystem::path::extension (the library is the successor to boost::filesystem) you would make your statement more expressive than using e.g. std::string. #include <iostream> #include <filesystem> // C++17 namespace fs = std::filesystem; int main() { fs::path filePath = "my/path/to/myFile.conf"; if (filePath.extension() == ".conf") // Heed the dot. { std::cout << filePath.stem() << " is a valid type."; // Output: "myFile is a valid type." } else { std::cout << filePath.filename() << " is an invalid type."; // Output: e.g. "myFile.cfg is an invalid type" } } See also std::filesystem::path::stem, std::filesystem::path::filename. A: You have to make sure you take care of file names with more then one dot. example: c:\.directoryname\file.name.with.too.many.dots.ext would not be handled correctly by strchr or find. My favorite would be the boost filesystem library that have an extension(path) function A: Assuming you have access to STL: std::string filename("filename.conf"); std::string::size_type idx; idx = filename.rfind('.'); if(idx != std::string::npos) { std::string extension = filename.substr(idx+1); } else { // No extension found } Edit: This is a cross platform solution since you didn't mention the platform. If you're specifically on Windows, you'll want to leverage the Windows specific functions mentioned by others in the thread. A: Using std::string's find/rfind solves THIS problem, but if you work a lot with paths then you should look at boost::filesystem::path since it will make your code much cleaner than fiddling with raw string indexes/iterators. I suggest boost since it's a high quality, well tested, (open source and commercially) free and fully portable library. A: Someone else mentioned boost but I just wanted to add the actual code to do this: #include <boost/filesystem.hpp> using std::string; string texture = foo->GetTextureFilename(); string file_extension = boost::filesystem::extension(texture); cout << "attempting load texture named " << texture << " whose extensions seems to be " << file_extension << endl; // Use JPEG or PNG loader function, or report invalid extension A: _splitpath, _wsplitpath, _splitpath_s, _wsplitpath_w This is Windows (Platform SDK) only A: For char array-type strings you can use this: #include <ctype.h> #include <string.h> int main() { char filename[] = "apples.bmp"; char extension[] = ".jpeg"; if(compare_extension(filename, extension) == true) { // ..... } else { // ..... } return 0; } bool compare_extension(char *filename, char *extension) { /* Sanity checks */ if(filename == NULL || extension == NULL) return false; if(strlen(filename) == 0 || strlen(extension) == 0) return false; if(strchr(filename, '.') == NULL || strchr(extension, '.') == NULL) return false; /* Iterate backwards through respective strings and compare each char one at a time */ for(int i = 0; i < strlen(filename); i++) { if(tolower(filename[strlen(filename) - i - 1]) == tolower(extension[strlen(extension) - i - 1])) { if(i == strlen(extension) - 1) return true; } else break; } return false; } Can handle file paths in addition to filenames. Works with both C and C++. And cross-platform. A: A NET/CLI version using System::String System::String^ GetFileExtension(System::String^ FileName) { int Ext=FileName->LastIndexOf('.'); if( Ext != -1 ) return FileName->Substring(Ext+1); return ""; } A: If you use Qt library, you can give a try to QFileInfo's suffix() A: Good answers but I see most of them has some problems: First of all I think a good answer should work for complete file names which have their path headings, also it should work for linux or windows or as mentioned it should be cross platform. For most of answers; file names with no extension but a path with a folder name including dot, the function will fail to return the correct extension: examples of some test cases could be as follow: const char filename1 = {"C:\\init.d\\doc"}; // => No extention const char filename2 = {"..\\doc"}; //relative path name => No extention const char filename3 = {""}; //emputy file name => No extention const char filename4 = {"testing"}; //only single name => No extention const char filename5 = {"tested/k.doc"}; // normal file name => doc const char filename6 = {".."}; // parent folder => No extention const char filename7 = {"/"}; // linux root => No extention const char filename8 = {"/bin/test.d.config/lx.wize.str"}; // ordinary path! => str "brian newman" suggestion will fail for filename1 and filename4. and most of other answers which are based on reverse find will fail for filename1. I suggest including the following method in your source: which is function returning index of first character of extension or the length of given string if not found. size_t find_ext_idx(const char* fileName) { size_t len = strlen(fileName); size_t idx = len-1; for(size_t i = 0; *(fileName+i); i++) { if (*(fileName+i) == '.') { idx = i; } else if (*(fileName + i) == '/' || *(fileName + i) == '\\') { idx = len - 1; } } return idx+1; } you could use the above code in your c++ application like below: std::string get_file_ext(const char* fileName) { return std::string(fileName).substr(find_ext_idx(fileName)); } The last point in some cases the a folder is given to file name as argument and includes a dot in the folder name the function will return folder's dot trailing so better first to user check that the given name is a filename and not folder name. A: This is a solution I came up with. Then, I noticed that it is similar to what @serengeor posted. It works with std::string and find_last_of, but the basic idea will also work if modified to use char arrays and strrchr. It handles hidden files, and extra dots representing the current directory. It is platform independent. string PathGetExtension( string const & path ) { string ext; // Find the last dot, if any. size_t dotIdx = path.find_last_of( "." ); if ( dotIdx != string::npos ) { // Find the last directory separator, if any. size_t dirSepIdx = path.find_last_of( "/\\" ); // If the dot is at the beginning of the file name, do not treat it as a file extension. // e.g., a hidden file: ".alpha". // This test also incidentally avoids a dot that is really a current directory indicator. // e.g.: "alpha/./bravo" if ( dotIdx > dirSepIdx + 1 ) { ext = path.substr( dotIdx ); } } return ext; } Unit test: int TestPathGetExtension( void ) { int errCount = 0; string tests[][2] = { { "/alpha/bravo.txt", ".txt" }, { "/alpha/.bravo", "" }, { ".alpha", "" }, { "./alpha.txt", ".txt" }, { "alpha/./bravo", "" }, { "alpha/./bravo.txt", ".txt" }, { "./alpha", "" }, { "c:\\alpha\\bravo.net\\charlie.txt", ".txt" }, }; int n = sizeof( tests ) / sizeof( tests[0] ); for ( int i = 0; i < n; ++i ) { string ext = PathGetExtension( tests[i][0] ); if ( ext != tests[i][1] ) { ++errCount; } } return errCount; } A: You can use strrchr() to find last occurence of .(dot) and get .(dot) based extensions files. Check the below code for example. #include<stdio.h> void GetFileExtension(const char* file_name) { int ext = '.'; const char* extension = NULL; extension = strrchr(file_name, ext); if(extension == NULL){ printf("Invalid extension encountered\n"); return; } printf("File extension is %s\n", extension); } int main() { const char* file_name = "c:\\.directoryname\\file.name.with.too.many.dots.ext"; GetFileExtension(file_name); return 0; } A: actually the STL can do this without much code, I advise you learn a bit about the STL because it lets you do some fancy things, anyways this is what I use. std::string GetFileExtension(const std::string& FileName) { if(FileName.find_last_of(".") != std::string::npos) return FileName.substr(FileName.find_last_of(".")+1); return ""; } this solution will always return the extension even on strings like "this.a.b.c.d.e.s.mp3" if it cannot find the extension it will return "". A: Is this too simple of a solution? #include <iostream> #include <string> int main() { std::string fn = "filename.conf"; if(fn.substr(fn.find_last_of(".") + 1) == "conf") { std::cout << "Yes..." << std::endl; } else { std::cout << "No..." << std::endl; } } A: Here's a function that takes a path/filename as a string and returns the extension as a string. It is all standard c++, and should work cross-platform for most platforms. Unlike several other answers here, it handles the odd cases that windows' PathFindExtension handles, based on PathFindExtensions's documentation. wstring get_file_extension( wstring filename ) { size_t last_dot_offset = filename.rfind(L'.'); // This assumes your directory separators are either \ or / size_t last_dirsep_offset = max( filename.rfind(L'\\'), filename.rfind(L'/') ); // no dot = no extension if( last_dot_offset == wstring::npos ) return L""; // directory separator after last dot = extension of directory, not file. // for example, given C:\temp.old\file_that_has_no_extension we should return "" not "old" if( (last_dirsep_offset != wstring::npos) && (last_dirsep_offset > last_dot_offset) ) return L""; return filename.substr( last_dot_offset + 1 ); } A: I use these two functions to get the extension and filename without extension: std::string fileExtension(std::string file){ std::size_t found = file.find_last_of("."); return file.substr(found+1); } std::string fileNameWithoutExtension(std::string file){ std::size_t found = file.find_last_of("."); return file.substr(0,found); } And these regex approaches for certain extra requirements: std::string fileExtension(std::string file){ std::regex re(".*[^\\.]+\\.([^\\.]+$)"); std::smatch result; if(std::regex_match(file,result,re))return result[1]; else return ""; } std::string fileNameWithoutExtension(std::string file){ std::regex re("(.*[^\\.]+)\\.[^\\.]+$"); std::smatch result; if(std::regex_match(file,result,re))return result[1]; else return file; } Extra requirements that are met by the regex method: * *If filename is like .config or something like this, extension will be an empty string and filename without extension will be .config. *If filename doesn't have any extension, extention will be an empty string, filename without extension will be the filename unchanged. EDIT: The extra requirements can also be met by the following: std::string fileExtension(const std::string& file){ std::string::size_type pos=file.find_last_of('.'); if(pos!=std::string::npos&&pos!=0)return file.substr(pos+1); else return ""; } std::string fileNameWithoutExtension(const std::string& file){ std::string::size_type pos=file.find_last_of('.'); if(pos!=std::string::npos&&pos!=0)return file.substr(0,pos); else return file; } Note: Pass only the filenames (not path) in the above functions. A: Try to use strstr char* lastSlash; lastSlash = strstr(filename, "."); A: Or you can use this: char *ExtractFileExt(char *FileName) { std::string s = FileName; int Len = s.length(); while(TRUE) { if(FileName[Len] != '.') Len--; else { char *Ext = new char[s.length()-Len+1]; for(int a=0; a<s.length()-Len; a++) Ext[a] = FileName[s.length()-(s.length()-Len)+a]; Ext[s.length()-Len] = '\0'; return Ext; } } } This code is cross-platform A: So, using std::filesystem is the best answer, but if for whatever reason you don't have C++17 features available, this will work even if the input string includes directories: string getextn (const string &fn) { int sep = fn.find_last_of(".\\/"); return (sep >= 0 && fn[sep] == '.') ? fn.substr(sep) : ""; } I'm adding this because the rest of the answers here are either strangely complicated or fail if the path to the file contains a dot and the file doesn't. I think the fact that find_last_of can look for multiple characters is often overlooked. It works with both / and \ path separators. It fails if the extension itself contains a slash but that's usually too rare to matter. It doesn't do any filtering for filenames that start with a dot and contain no other dots -- if this matters to you then this is the least unreasonable answer here. Example input / output: / => '' ./ => '' ./pathname/ => '' ./path.name/ => '' pathname/ => '' path.name/ => '' c:\path.name\ => '' /. => '.' ./. => '.' ./pathname/. => '.' ./path.name/. => '.' pathname/. => '.' path.name/. => '.' c:\path.name\. => '.' /.git_ignore => '.git_ignore' ./.git_ignore => '.git_ignore' ./pathname/.git_ignore => '.git_ignore' ./path.name/.git_ignore => '.git_ignore' pathname/.git_ignore => '.git_ignore' path.name/.git_ignore => '.git_ignore' c:\path.name\.git_ignore => '.git_ignore' /filename => '' ./filename => '' ./pathname/filename => '' ./path.name/filename => '' pathname/filename => '' path.name/filename => '' c:\path.name\filename => '' /filename. => '.' ./filename. => '.' ./pathname/filename. => '.' ./path.name/filename. => '.' pathname/filename. => '.' path.name/filename. => '.' c:\path.name\filename. => '.' /filename.tar => '.tar' ./filename.tar => '.tar' ./pathname/filename.tar => '.tar' ./path.name/filename.tar => '.tar' pathname/filename.tar => '.tar' path.name/filename.tar => '.tar' c:\path.name\filename.tar => '.tar' /filename.tar.gz => '.gz' ./filename.tar.gz => '.gz' ./pathname/filename.tar.gz => '.gz' ./path.name/filename.tar.gz => '.gz' pathname/filename.tar.gz => '.gz' path.name/filename.tar.gz => '.gz' c:\path.name\filename.tar.gz => '.gz' A: If you happen to use Poco libraries you can do: #include <Poco/Path.h> ... std::string fileExt = Poco::Path("/home/user/myFile.abc").getExtension(); // == "abc" A: If you consider the extension as the last dot and the possible characters after it, but only if they don't contain the directory separator character, the following function returns the extension starting index, or -1 if no extension found. When you have that you can do what ever you want, like strip the extension, change it, check it etc. long get_extension_index(string path, char dir_separator = '/') { // Look from the end for the first '.', // but give up if finding a dir separator char first for(long i = path.length() - 1; i >= 0; --i) { if(path[i] == '.') { return i; } if(path[i] == dir_separator) { return -1; } } return -1; } A: I used PathFindExtension() function to know whether it is a valid tif file or not. #include <Shlwapi.h> bool A2iAWrapperUtility::isValidImageFile(string imageFile) { char * pStrExtension = ::PathFindExtension(imageFile.c_str()); if (pStrExtension != NULL && strcmp(pStrExtension, ".tif") == 0) { return true; } return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/51949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "94" }
Q: How do I allow assembly (unit testing one) to access internal properties of another assembly? I would like my Core assembly to not expose a certain class and I would still like to be able to test it. How can I do that ? A: I put my unit tests in the same assembly as the code that it's testing. This makes sense to me, because I think of "test yourself" as a feature of a class, along with things like "initialize yourself" and "describe yourself". I've heard some objections to this approach, but few of them have been convincing. It hurts performance Bah, I say! Don't optimize without hard data! Perhaps if you are planning your assemblies to be downloaded over slow links, then minimizing assembly size would be worthwhile. It's a security risk. Only if you have secrets in your tests. Don't do that. Now, your situation is different from mine, so maybe it'll make sense for you, and maybe it won't. You'll have to figure that out yourself. Aside: In C#, I once tried putting my unit tests in a class named "Tests" that was nested inside the class that it was testing. This made the correct organization of things obvious. It also avoided the duplication of names that occurs when tests for the class "Foo" are in a class called "FooTests". However, the unit testing frameworks that I had access to refused to accept tests that weren't marked "public". This means that the class that you're testing can't be "private". I can't think of any good reason to require tests to be "public", since no one really calls them as public methods - everything is through reflection. If you ever write a unit testing framework for .Net, please consider allowing non-public tests, for my sake! A: With InternalsVisible if your assemblies are strongly named you need to specify the public key (note: the full key not the public key token) for example... [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("BoardEx_BusinessObjects.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fb3a2d8 etc etc")] and the following trick is really useful for getting the public key without resorting to the cmd line... http://www.andrewconnell.com/blog/archive/2006/09/15/4587.aspx A: You can use reflection (as the MS Test items do), or you can declare the unit test assembly a friend of the core assembly. The other option is to put the unit tests in the same assembly. A: I would suggest not going to such troubles ... if you really want to unit test your "internal" classes, just hide them away in a namespace that only your internal code would end up using. Unless you're writing a framework on the scale of the .NET framework, you don't really need that level of hiding. A: InternalsVisibleTo attribute to the rescue! Just add: [assembly:InternalsVisibleToAttribute("UnitTestAssemblyName")] to your Core classes AssemblyInfo.cs file See Friend Assemblies (C# Programming Guide) for best practices. A: Let's start with an example class: using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("App.Infrastructure.UnitTests")] namespace App.Infrastructure.Data.Repositories { internal class UserRepository : IUserRepository { // internal members that you want to test/access } } The [assembly: InternalsVisibleTo("Input_The_Assembly_That_Can_Access_Your_Internals_Here")] attribute allows all of your internal classes and members to be accessed by another assembly, but the InternalsVisibleTo attribute is not only applied to a single class (on where you declared it), rather on the WHOLE assembly itself. In the example code - App.Infrastructure.UnitTests can access all internals in the assembly that you declared (InternalsVisibleTo attribute) it even if you didn't explicitly declare it to other classes that belong to the same assembly. I found out in this youtube video: That there are 2 approaches to make your internals accessible to certain assemblies (or assembly) 1. Creating your own AssemblyInfo.cs file These are the only lines you'll need in your AssemblyInfo.cs (delete all "default" code, and replace with the code below) using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("App.Infrastructure.UnitTests"), InternalsVisibleTo("Another.Assembly")] 2. Adding the InternalsVisibleTo attribute in the project's .csproj (double click the project that you want its internals to be exposed) <ItemGroup> <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo"> <_Parameter1>The_Assembly_That_Can_Access_Your_Internals</_Parameter1> </AssemblyAttribute> <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo"> <_Parameter1>Another_Assembly_Or_Project</_Parameter1> </AssemblyAttribute> </ItemGroup> Note: watch the whole youtube video for a more detailed explanation on Assembly-Level Attributes A: in dotnet core we can add AssembyAttribute in the .csproj file just add this into your .csproj <!-- Make internals available for Unit Testing --> <ItemGroup> <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo"> <_Parameter1>Myproject.Tests</_Parameter1> </AssemblyAttribute> </ItemGroup> <!-- End Unit test Internals -->
{ "language": "en", "url": "https://stackoverflow.com/questions/51950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "82" }
Q: How do I remove items from the query string for redirection? In my base page I need to remove an item from the query string and redirect. I can't use Request.QueryString.Remove("foo") because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it? A: You'd have to reconstruct the url and then redirect. Something like this: string url = Request.RawUrl; NameValueCollection params = Request.QueryString; for (int i=0; i<params.Count; i++) { if (params[i].GetKey(i).ToLower() == "foo") { url += string.Concat((i==0 ? "?" : "&"), params[i].GetKey(i), "=", params.Get(i)); } } Response.Redirect(url); Anyway, I didn't test that or anything, but it should work (or at least get you in thye right direction) A: Response.Redirect(String.Format("nextpage.aspx?{0}", Request.QueryString.ToString().Replace("foo", "mangledfoo"))); I quick hack, saves you little. But foo will not be present for the code awaiting it in nextpge.aspx :) A: Interesting question. I don't see any real viable alternative to manually copying the collection since CopyTo will only allow you to get the values (and not the keys). I think HollyStyles' Hack would work (although I would be nervous about putting a Replace in a QueryString - obv. dependant on use case), but there is one thing thats bothering me.. If the target page is not reading it, why do you need to remove it from the QueryString? It will just be ignored? Failing that, I think you would just need to bite the bullet and create a util method to alter the collection for you. UPDATE - Following Response from OP Ahhhh! I see now, yes, I have had similar problems with SiteMap performing full comparison of the string. Since changing the other source code (i.e. the search) is out of the question, I would probably say it may be best to do a Replace on the string. Although to be fair, if you often encounter code similar to this, it would equally be just as quick to set up a utility function to clone the collection, taking an array of values to filter from it. This way you would never have to worry about such issues again :) A: HttpUtility.ParseQueryString(Request.Url.Query) return isQueryStringValueCollection. It is inherit from NameValueCollection. var qs = HttpUtility.ParseQueryString(Request.Url.Query); qs.Remove("foo"); string url = "~/Default.aspx"; if (qs.Count > 0) url = url + "?" + qs.ToString(); Response.Redirect(url); A: You can avoid touching the original query string by working on a copy of it instead. You can then redirect the page to the a url containing your modified query string like so: var nvc = new NameValueCollection(); nvc.Add(HttpUtility.ParseQueryString(Request.Url.Query)); nvc.Remove("foo"); string url = Request.Url.AbsolutePath; for (int i = 0; i < nvc.Count; i++) url += string.Format("{0}{1}={2}", (i == 0 ? "?" : "&"), nvc.Keys[i], nvc[i]); Response.Redirect(url); Update: Turns out we can simplify the code like so: var nvc = HttpUtility.ParseQueryString(Request.Url.Query); nvc.Remove("foo"); string url = Request.Url.AbsolutePath + "?" + nvc.ToString(); Response.Redirect(url); A: The search page appends "&terms=" to the query string for highlighting, so it messes it up. Only other option is a regex replace. If you know for sure that &terms is in the middle of the collection somewhere leave the trailing & in the regex, if you know for sure it's on the end then drop the trailing & and change the replacement string "&" to String.Empty Response.Redirect(String.Format("nextpage.aspx?{0}", Regex.Replace(Request.QueryString.ToString(), "&terms=.*&", "&")); A: Request.Url.GetLeftPart(UriPartial.Path) should do this A: I found this was a more elegant solution var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString()); qs.Remove("item"); Console.WriteLine(qs.ToString()); A: Here is a solution that uses LINQ against the Request.QueryString which allows for complex filtering of qs params if required. The example below shows me filtering out the uid param to create a relative url ready for redirection. Before: http://www.domain.com/home.aspx?color=red&uid=1&name=bob After: ~/home.aspx?color=red&name=bob Remove QS param from url var rq = this.Request.QueryString; var qs = string.Join("&", rq.Cast<string>().Where(k => k != "uid").Select(k => string.Format("{0}={1}", k, rq[k])).ToArray()); var url = string.Concat("~", Request.RawUrl.Split('?')[0], "?", qs); A: Can you clone the collection and then redirect to the page with the cloned (and modified) collection? I know it's not much better than iterating...
{ "language": "en", "url": "https://stackoverflow.com/questions/51964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to detect READ_COMMITTED_SNAPSHOT is enabled? In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command ALTER DATABASE <database> SET READ_COMMITTED_SNAPSHOT ON;? I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI. A: * *As per DBCC USEROPTIONS (Transact-SQL): DBCC USEROPTIONS reports an isolation level of 'read committed snapshot' when the database option READ_COMMITTED_SNAPSHOT is set to ON and the transaction isolation level is set to 'read committed'. The actual isolation level is read committed. *Also in SQL Server Management Studio, in database properties under Options->Miscellaneous there is "Is Read Committed Snapshot On" option status A: SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name= 'YourDatabase' Return value: * *1: READ_COMMITTED_SNAPSHOT option is ON. Read operations under the READ COMMITTED isolation level are based on snapshot scans and do not acquire locks. *0 (default): READ_COMMITTED_SNAPSHOT option is OFF. Read operations under the READ COMMITTED isolation level use Shared (S) locks. A: Neither on SQL2005 nor 2012 does DBCC USEROPTIONS show is_read_committed_snapshot_on: Set Option Value textsize 2147483647 language us_english dateformat mdy datefirst 7 lock_timeout -1 quoted_identifier SET arithabort SET ansi_null_dflt_on SET ansi_warnings SET ansi_padding SET ansi_nulls SET concat_null_yields_null SET isolation level read committed
{ "language": "en", "url": "https://stackoverflow.com/questions/51969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "142" }
Q: What work has been done on cross-platform mobile development? Have any well-documented or open source projects targeted iPhone, Blackberry, and Android ? Are there other platforms which are better-suited to such an endeavor ? Note that I am particularly asking about client-side software, not web apps, though any information about the difficulties of using web apps across multiple mobile platforms is also interesting. A: XMLVM (via Coke and Code) and EdgeLib currently seem to be the most mature options. EdgeLib is aimed primarily at game developers, and according to Coke and Code, the XMLVM developers are difficult to contact. A: The iPhone uses Objective C, the Blackberry Java SE with RIM functionality and Android another custom version of Java. I could possibly see how you could combine the latter two but there is no functionality (without jailbreaking) of running Java applications on an iPhone. The best bet I've seen so far is something like Qt that will run on Windows CE, almost certainly shortly Symbian, some Java platforms and the three major desktop OSs. A: redfivelabs have implemented the .Net compact framework for the S60 platform Titanium Mobile from Appcelerator looks interesting. You develop your app in HTML & Javascript and upload to their server where it is compiled into a native application of the target platform (currently iPhone & Android) A: For the iPhone there's currently no such notion as Open Source as the Apple iPhone SDK NDA forbids publishing code. They also forbid posting code on any non-Apple site or even non-Apple discussion forums on iPhone development. As soon as the NDA expires (will it ever?) we'll start having Open Source iPhone apps. A: Suprised MoSync hasn't been mentioned here already. Update (2014 January - present): the project is abandoned. A: The HTML5 standard has support for releasing stand-alone HTML5 apps. Essentially a HTML5 app is a bundle of HTML5, JavaScript and CSS files that will run stand-alone in the browser of the desktop or device. You can distribute them like any other program, including selling them on the iStore for the iPhone. The support for this is patchy at the moment but is likely to improve tremendously in the next year or two. Google for HTML5 apps for information and resources. A good introduction to HTML5 is the online book "Dive Into HTML5" by Mark Pilgrim. This is a work in progress, but sufficiently complete to be useful. A: There are 2 [newish] solutions to exactly this issue: rhomobile and phonegap A: I started to use a really cool cross-platform SDK called EdgeLib. It allows you to use a simple API and you can compile your projects to a variety of platforms: Windows Mobile Pocket PC, Windows Mobile Smartphone, Symbian Series 60, Series 80, Series 90, Symbian UIQ, Gamepark Holdings GP2X, Gizmondo and Windows desktop. I know iPhone, Blackberry, and Android are not on that list but the developers mentioned that these platforms are on their roadmap. A: EdgeLib looks promising and has an iPhone beta announced but not open yet. A: jQuery Mobile Alpha 2 Released Nimblekit Sencha Phonegap Appcelerator A: Well BlackBerrys don't really have Java SE, they have Java ME, with a lot of additional librarys provided by RIM. Same goes for Android. The only cross-platform apps you'll ever see on mobile devices are probably written in strict Java ME, which runs on most devices. However, just like JavaScript between different browser, Java ME has is quirks across different devices, so source code changes may be necessary. A: I found one game engine for dat MoMinis games are available for distribution and are supported on Android, Blackberry, Symbian and J2me devices. MoMinis games include a wide range of casual games – including arcade, puzzle, time management, strategy and brain-training mobile games. mominis A: I think there best chance for cross-platform mobile success is the Web. Just write a very simple Web application for what you want to achieve. It should work on the Nokia S60browser, Iphone and Android. That's already a lot of mobile devices... A: Appcelerator, PhoneGap (acquired by Adobe, plus it's now standardized as Apache Cordova), Intel XDK (formerly called appMobi) and Rhodes (acquired by Motorola Solutions) are all open source and create hybrid apps (natively packed with html ui, with the possibility to add some of your native controls). If it's a game, your only professional choice for a free engine that can be used for commercial development is Unity3D. For 2D games, cocos2d-x is also available. Additionally, Vuforia can be used for AR and LiquidFun for physics. A: S60 on Symbian OS has alot of interesting projects happening relating to desktop/server languages to move applications mobile. Some interesting ones:- Python: sourceforge Ruby: ruby-symbian Mozilla: mozilla S60Webkit: S60browser POSIX: openc_cpp A: We have a cross platform mobile development platform called RAMP. It covers both feature and smart phones from midp 1 to Android. The platform is mostly aimed at secure commercial applications but it is pluggable so you can do almost anything with it. For more information and access to the platform have a look at: virtual mobile tech A: Phonsai is new in the market for cross-platform mobile develeopment "without coding" It is mixture of do-it-yourself mobile development and content management You can customize all applications. No templates. It is SaaS. Totally web based with java web start. Work with 2000 mobile phone models. Very simple GUI and no coding. Just copy and paste. It has create, send and report modules. And at last it has 4 emulators inside so that it is a WYSIWYG concept. You can reach Phonsai at http://phonsai.com
{ "language": "en", "url": "https://stackoverflow.com/questions/51988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "89" }
Q: How to check if the given string is palindrome? Definition: A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction How to check if the given string is a palindrome? This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C. Looking for solutions in any and all languages possible. A: Here's a python way. Note: this isn't really that "pythonic" but it demonstrates the algorithm. def IsPalindromeString(n): myLen = len(n) i = 0 while i <= myLen/2: if n[i] != n[myLen-1-i]: return False i += 1 return True A: Delphi function IsPalindrome(const s: string): boolean; var i, j: integer; begin Result := false; j := Length(s); for i := 1 to Length(s) div 2 do begin if s[i] <> s[j] then Exit; Dec(j); end; Result := true; end; A: EDIT: from the comments: bool palindrome(std::string const& s) { return std::equal(s.begin(), s.end(), s.rbegin()); } The c++ way. My naive implementation using the elegant iterators. In reality, you would probably check and stop once your forward iterator has past the halfway mark to your string. #include <string> #include <iostream> using namespace std; bool palindrome(string foo) { string::iterator front; string::reverse_iterator back; bool is_palindrome = true; for(front = foo.begin(), back = foo.rbegin(); is_palindrome && front!= foo.end() && back != foo.rend(); ++front, ++back ) { if(*front != *back) is_palindrome = false; } return is_palindrome; } int main() { string a = "hi there", b = "laval"; cout << "String a: \"" << a << "\" is " << ((palindrome(a))? "" : "not ") << "a palindrome." <<endl; cout << "String b: \"" << b << "\" is " << ((palindrome(b))? "" : "not ") << "a palindrome." <<endl; } A: I'm seeing a lot of incorrect answers here. Any correct solution needs to ignore whitespace and punctuation (and any non-alphabetic characters actually) and needs to be case insensitive. A few good example test cases are: "A man, a plan, a canal, Panama." "A Toyota's a Toyota." "A" "" As well as some non-palindromes. Example solution in C# (note: empty and null strings are considered palindromes in this design, if this is not desired it's easy to change): public static bool IsPalindrome(string palindromeCandidate) { if (string.IsNullOrEmpty(palindromeCandidate)) { return true; } Regex nonAlphaChars = new Regex("[^a-z0-9]"); string alphaOnlyCandidate = nonAlphaChars.Replace(palindromeCandidate.ToLower(), ""); if (string.IsNullOrEmpty(alphaOnlyCandidate)) { return true; } int leftIndex = 0; int rightIndex = alphaOnlyCandidate.Length - 1; while (rightIndex > leftIndex) { if (alphaOnlyCandidate[leftIndex] != alphaOnlyCandidate[rightIndex]) { return false; } leftIndex++; rightIndex--; } return true; } A: PHP sample: $string = "A man, a plan, a canal, Panama"; function is_palindrome($string) { $a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string)); return $a==strrev($a); } Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words. A: boolean isPalindrome(String str1) { //first strip out punctuation and spaces String stripped = str1.replaceAll("[^a-zA-Z0-9]", ""); return stripped.equalsIgnoreCase((new StringBuilder(stripped)).reverse().toString()); } Java version A: Windows XP (might also work on 2000) or later BATCH script: @echo off call :is_palindrome %1 if %ERRORLEVEL% == 0 ( echo %1 is a palindrome ) else ( echo %1 is NOT a palindrome ) exit /B 0 :is_palindrome set word=%~1 set reverse= call :reverse_chars "%word%" set return=1 if "$%word%" == "$%reverse%" ( set return=0 ) exit /B %return% :reverse_chars set chars=%~1 set reverse=%chars:~0,1%%reverse% set chars=%chars:~1% if "$%chars%" == "$" ( exit /B 0 ) else ( call :reverse_chars "%chars%" ) exit /B 0 A: Language agnostic meta-code then... rev = StringReverse(originalString) return ( rev == originalString ); A: Here's my solution in c# static bool isPalindrome(string s) { string allowedChars = "abcdefghijklmnopqrstuvwxyz"+ "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string compareString = String.Empty; string rev = string.Empty; for (int i = 0; i <= s.Length - 1; i++) { char c = s[i]; if (allowedChars.IndexOf(c) > -1) { compareString += c; } } for (int i = compareString.Length - 1; i >= 0; i--) { char c = compareString[i]; rev += c; } return rev.Equals(compareString, StringComparison.CurrentCultureIgnoreCase); } A: Here's my solution, without using a strrev. Written in C#, but it will work in any language that has a string length function. private static bool Pal(string s) { for (int i = 0; i < s.Length; i++) { if (s[i] != s[s.Length - 1 - i]) { return false; } } return true; } A: Here's a Python version that deals with different cases, punctuation and whitespace. import string def is_palindrome(palindrome): letters = palindrome.translate(string.maketrans("",""), string.whitespace + string.punctuation).lower() return letters == letters[::-1] Edit: Shamelessly stole from Blair Conrad's neater answer to remove the slightly clumsy list processing from my previous version. A: An obfuscated C version: int IsPalindrome (char *s) { char*a,*b,c=0; for(a=b=s;a<=b;c=(c?c==1?c=(*a&~32)-65>25u?*++a,1:2:c==2?(*--b&~32)-65<26u?3:2:c==3?(*b-65&~32)-(*a-65&~32)?*(b=s=0,a),4:*++a,1:0:*++b?0:1)); return s!=0; } A: C++ std::string a = "god"; std::string b = "lol"; std::cout << (std::string(a.rbegin(), a.rend()) == a) << " " << (std::string(b.rbegin(), b.rend()) == b); Bash function ispalin { [ "$( echo -n $1 | tac -rs . )" = "$1" ]; } echo "$(ispalin god && echo yes || echo no), $(ispalin lol && echo yes || echo no)" Gnu Awk /* obvious solution */ function ispalin(cand, i) { for(i=0; i<length(cand)/2; i++) if(substr(cand, length(cand)-i, 1) != substr(cand, i+1, 1)) return 0; return 1; } /* not so obvious solution. cough cough */ { orig = $0; while($0) { stuff = stuff gensub(/^.*(.)$/, "\\1", 1); $0 = gensub(/^(.*).$/, "\\1", 1); } print (stuff == orig); } Haskell Some brain dead way doing it in Haskell ispalin :: [Char] -> Bool ispalin a = a == (let xi (y:my) = (xi my) ++ [y]; xi [] = [] in \x -> xi x) a Plain English "Just reverse the string and if it is the same as before, it's a palindrome" A: Ruby: class String def is_palindrome? letters_only = gsub(/\W/,'').downcase letters_only == letters_only.reverse end end puts 'abc'.is_palindrome? # => false puts 'aba'.is_palindrome? # => true puts "Madam, I'm Adam.".is_palindrome? # => true A: C# in-place algorithm. Any preprocessing, like case insensitivity or stripping of whitespace and punctuation should be done before passing to this function. boolean IsPalindrome(string s) { for (int i = 0; i < s.Length / 2; i++) { if (s[i] != s[s.Length - 1 - i]) return false; } return true; } Edit: removed unnecessary "+1" in loop condition and spent the saved comparison on removing the redundant Length comparison. Thanks to the commenters! A: This Java code should work inside a boolean method: Note: You only need to check the first half of the characters with the back half, otherwise you are overlapping and doubling the amount of checks that need to be made. private static boolean doPal(String test) { for(int i = 0; i < test.length() / 2; i++) { if(test.charAt(i) != test.charAt(test.length() - 1 - i)) { return false; } } return true; } A: Three versions in Smalltalk, from dumbest to correct. In Smalltalk, = is the comparison operator: isPalindrome: aString "Dumbest." ^ aString reverse = aString The message #translateToLowercase returns the string as lowercase: isPalindrome: aString "Case insensitive" |lowercase| lowercase := aString translateToLowercase. ^ lowercase reverse = lowercase And in Smalltalk, strings are part of the Collection framework, you can use the message #select:thenCollect:, so here's the last version: isPalindrome: aString "Case insensitive and keeping only alphabetic chars (blanks & punctuation insensitive)." |lowercaseLetters| lowercaseLetters := aString select: [:char | char isAlphabetic] thenCollect: [:char | char asLowercase]. ^ lowercaseLetters reverse = lowercaseLetters A: Another C++ one. Optimized for speed and size. bool is_palindrome(const std::string& candidate) { for(std::string::const_iterator left = candidate.begin(), right = candidate.end(); left < --right ; ++left) if (*left != *right) return false; return true; } A: Lisp: (defun palindrome(x) (string= x (reverse x))) A: Note that in the above C++ solutions, there was some problems. One solution was inefficient because it passed an std::string by copy, and because it iterated over all the chars, instead of comparing only half the chars. Then, even when discovering the string was not a palindrome, it continued the loop, waiting its end before reporting "false". The other was better, with a very small function, whose problem was that it was not able to test anything else than std::string. In C++, it is easy to extend an algorithm to a whole bunch of similar objects. By templating its std::string into "T", it would have worked on both std::string, std::wstring, std::vector and std::deque. But without major modification because of the use of the operator <, the std::list was out of its scope. My own solutions try to show that a C++ solution won't stop at working on the exact current type, but will strive to work an anything that behaves the same way, no matter the type. For example, I could apply my palindrome tests on std::string, on vector of int or on list of "Anything" as long as Anything was comparable through its operator = (build in types, as well as classes). Note that the template can even be extended with an optional type that can be used to compare the data. For example, if you want to compare in a case insensitive way, or even compare similar characters (like è, é, ë, ê and e). Like king Leonidas would have said: "Templates ? This is C++ !!!" So, in C++, there are at least 3 major ways to do it, each one leading to the other: Solution A: In a c-like way The problem is that until C++0X, we can't consider the std::string array of chars as contiguous, so we must "cheat" and retrieve the c_str() property. As we are using it in a read-only fashion, it should be ok... bool isPalindromeA(const std::string & p_strText) { if(p_strText.length() < 2) return true ; const char * pStart = p_strText.c_str() ; const char * pEnd = pStart + p_strText.length() - 1 ; for(; pStart < pEnd; ++pStart, --pEnd) { if(*pStart != *pEnd) { return false ; } } return true ; } Solution B: A more "C++" version Now, we'll try to apply the same solution, but to any C++ container with random access to its items through operator []. For example, any std::basic_string, std::vector, std::deque, etc. Operator [] is constant access for those containers, so we won't lose undue speed. template <typename T> bool isPalindromeB(const T & p_aText) { if(p_aText.empty()) return true ; typename T::size_type iStart = 0 ; typename T::size_type iEnd = p_aText.size() - 1 ; for(; iStart < iEnd; ++iStart, --iEnd) { if(p_aText[iStart] != p_aText[iEnd]) { return false ; } } return true ; } Solution C: Template powah ! It will work with almost any unordered STL-like container with bidirectional iterators For example, any std::basic_string, std::vector, std::deque, std::list, etc. So, this function can be applied on all STL-like containers with the following conditions: 1 - T is a container with bidirectional iterator 2 - T's iterator points to a comparable type (through operator =) template <typename T> bool isPalindromeC(const T & p_aText) { if(p_aText.empty()) return true ; typename T::const_iterator pStart = p_aText.begin() ; typename T::const_iterator pEnd = p_aText.end() ; --pEnd ; while(true) { if(*pStart != *pEnd) { return false ; } if((pStart == pEnd) || (++pStart == pEnd)) { return true ; } --pEnd ; } } A: A simple Java solution: public boolean isPalindrome(String testString) { StringBuffer sb = new StringBuffer(testString); String reverseString = sb.reverse().toString(); if(testString.equalsIgnoreCase(reverseString)) { return true; else { return false; } } A: C#: LINQ var str = "a b a"; var test = Enumerable.SequenceEqual(str.ToCharArray(), str.ToCharArray().Reverse()); A: A more Ruby-style rewrite of Hal's Ruby version: class String def palindrome? (test = gsub(/[^A-Za-z]/, '').downcase) == test.reverse end end Now you can call palindrome? on any string. A: Unoptimized Python: >>> def is_palindrome(s): ... return s == s[::-1] A: Java solution: public class QuickTest { public static void main(String[] args) { check("AmanaplanacanalPanama".toLowerCase()); check("Hello World".toLowerCase()); } public static void check(String aString) { System.out.print(aString + ": "); char[] chars = aString.toCharArray(); for (int i = 0, j = (chars.length - 1); i < (chars.length / 2); i++, j--) { if (chars[i] != chars[j]) { System.out.println("Not a palindrome!"); return; } } System.out.println("Found a palindrome!"); } } A: Using a good data structure usually helps impress the professor: Push half the chars onto a stack (Length / 2). Pop and compare each char until the first unmatch. If the stack has zero elements: palindrome. *in the case of a string with an odd Length, throw out the middle char. A: C in the house. (not sure if you didn't want a C example here) bool IsPalindrome(char *s) { int i,d; int length = strlen(s); char cf, cb; for(i=0, d=length-1 ; i < length && d >= 0 ; i++ , d--) { while(cf= toupper(s[i]), (cf < 'A' || cf >'Z') && i < length-1)i++; while(cb= toupper(s[d]), (cb < 'A' || cb >'Z') && d > 0 )d--; if(cf != cb && cf >= 'A' && cf <= 'Z' && cb >= 'A' && cb <='Z') return false; } return true; } That will return true for "racecar", "Racecar", "race car", "racecar ", and "RaCe cAr". It would be easy to modify to include symbols or spaces as well, but I figure it's more useful to only count letters(and ignore case). This works for all palindromes I've found in the answers here, and I've been unable to trick it into false negatives/positives. Also, if you don't like bool in a "C" program, it could obviously return int, with return 1 and return 0 for true and false respectively. A: Many ways to do it. I guess the key is to do it in the most efficient way possible (without looping the string). I would do it as a char array which can be reversed easily (using C#). string mystring = "abracadabra"; char[] str = mystring.ToCharArray(); Array.Reverse(str); string revstring = new string(str); if (mystring.equals(revstring)) { Console.WriteLine("String is a Palindrome"); } A: In Ruby, converting to lowercase and stripping everything not alphabetic: def isPalindrome( string ) ( test = string.downcase.gsub( /[^a-z]/, '' ) ) == test.reverse end But that feels like cheating, right? No pointers or anything! So here's a C version too, but without the lowercase and character stripping goodness: #include <stdio.h> int isPalindrome( char * string ) { char * i = string; char * p = string; while ( *++i ); while ( i > p && *p++ == *--i ); return i <= p && *i++ == *--p; } int main( int argc, char **argv ) { if ( argc != 2 ) { fprintf( stderr, "Usage: %s <word>\n", argv[0] ); return -1; } fprintf( stdout, "%s\n", isPalindrome( argv[1] ) ? "yes" : "no" ); return 0; } Well, that was fun - do I get the job ;^) A: Perl: sub is_palindrome($) { $s = lc(shift); # ignore case $s =~ s/\W+//g; # consider only letters, digits, and '_' $s eq reverse $s; } It ignores case and strips non-alphanumeric characters (it locale- and unicode- neutral). A: Using Java, using Apache Commons String Utils: public boolean isPalindrome(String phrase) { phrase = phrase.toLowerCase().replaceAll("[^a-z]", ""); return StringUtils.reverse(phrase).equals(phrase); } A: I had to do this for a programming challenge, here's a snippet of my Haskell: isPalindrome :: String -> Bool isPalindrome n = (n == reverse n) A: Python: if s == s[::-1]: return True Java: if (s.Equals(s.Reverse())) { return true; } PHP: if (s == strrev(s)) return true; Perl: if (s == reverse(s)) { return true; } Erlang: string:equal(S, lists:reverse(S)). A: Perl: sub is_palindrome { my $s = lc shift; # normalize case $s =~ s/\W//g; # strip non-word characters return $s eq reverse $s; } A: c++: bool is_palindrome(const string &s) { return equal( s.begin(), s.begin()+s.length()/2, s.rbegin()); } A: My 2c. Avoids overhead of full string reversal everytime, taking advantage of shortcircuiting to return as soon as the nature of the string is determined. Yes, you should condition your string first, but IMO that's the job of another function. In C# /// <summary> /// Tests if a string is a palindrome /// </summary> public static bool IsPalindrome(this String str) { if (str.Length == 0) return false; int index = 0; while (index < str.Length / 2) if (str[index] != str[str.Length - ++index]) return false; return true; } A: Prolog palindrome(B, R) :- palindrome(B, R, []). palindrome([], R, R). palindrome([X|B], [X|R], T) :- palindrome(B, R, [X|T]). A: Erlang is awesome palindrome(L) -> palindrome(L,[]). palindrome([],_) -> false; palindrome([_|[]],[]) -> true; palindrome([_|L],L) -> true; palindrome(L,L) -> true; palindrome([H|T], Acc) -> palindrome(T, [H|Acc]). A: No solution using JavaScript yet? function palindrome(s) { var l = 0, r = s.length - 1; while (l < r) if (s.charAt(left++) !== s.charAt(r--)) return false; return true } A: Simple JavaScript solution. Run code snippet for demo. function checkPalindrome(line){ reverse_line=line.split("").reverse().join(""); return line==reverse_line; } alert("checkPalindrome(radar): "+checkPalindrome("radar")); A: Another one from Delphi, which I think is a little more rigorous than the other Delphi example submitted. This can easily turn into a golfing match, but I've tried to make mine readable. Edit0: I was curious about the performance characteristics, so I did a little test. On my machine, I ran this function against a 60 character string 50 million times, and it took 5 seconds. function TForm1.IsPalindrome(txt: string): boolean; var i, halfway, len : integer; begin Result := True; len := Length(txt); { special cases: an empty string is *never* a palindrome a 1-character string is *always* a palindrome } case len of 0 : Result := False; 1 : Result := True; else begin halfway := Round((len/2) - (1/2)); //if odd, round down to get 1/2way pt //scan half of our string, make sure it is mirrored on the other half for i := 1 to halfway do begin if txt[i] <> txt[len-(i-1)] then begin Result := False; Break; end; //if we found a non-mirrored character end; //for 1st half of string end; //else not a special case end; //case end; And here is the same thing, in C#, except that I've left it with multiple exit points, which I don't like. private bool IsPalindrome(string txt) { int len = txt.Length; /* Special cases: An empty string is *never* a palindrome A 1-character string is *always* a palindrome */ switch (len) { case 0: return false; case 1: return true; } //switch int halfway = (len / 2); //scan half of our string, make sure it is mirrored on the other half for (int i = 0; i < halfway; ++i) { if (txt.Substring(i,1) != txt.Substring(len - i - 1,1)) { return false; } //if } //for return true; } A: C#3 - This returns false as soon as a char counted from the beginning fails to match its equivalent at the end: static bool IsPalindrome(this string input) { char[] letters = input.ToUpper().ToCharArray(); int i = 0; while( i < letters.Length / 2 ) if( letters[i] != letters[letters.Length - ++i] ) return false; return true; } A: If we're looking for numbers and simple words, many correct answers have been given. However, if we're looking for what we generally see as palindromes in written language (e.g., "A dog, a panic, in a pagoda!"), the correct answer would be to iterate starting from both ends of the sentence, skipping non-alphanumeric characters individually, and returning false if any mismatches are found. i = 0; j = length-1; while( true ) { while( i < j && !is_alphanumeric( str[i] ) ) i++; while( i < j && !is_alphanumeric( str[j] ) ) j--; if( i >= j ) return true; if( tolower(string[i]) != tolower(string[j]) ) return false; i++; j--; } Of course, stripping out non-valid characters, reversing the resulting string and comparing it to the original one also works. It comes down to what type of language you're working on. A: OCaml: let rec palindrome s = s = (tailrev s) source A: boolean IsPalindrome(string s) { return s = s.Reverse(); } A: There isn't a single solution on here which takes into account that a palindrome can also be based on word units, not just character units. Which means that none of the given solutions return true for palindromes like "Girl, bathing on Bikini, eyeing boy, sees boy eyeing bikini on bathing girl". Here's a hacked together version in C#. I'm sure it doesn't need the regexes, but it does work just as well with the above bikini palindrome as it does with "A man, a plan, a canal-Panama!". static bool IsPalindrome(string text) { bool isPalindrome = IsCharacterPalindrome(text); if (!isPalindrome) { isPalindrome = IsPhrasePalindrome(text); } return isPalindrome; } static bool IsCharacterPalindrome(string text) { String clean = Regex.Replace(text.ToLower(), "[^A-z0-9]", String.Empty, RegexOptions.Compiled); bool isPalindrome = false; if (!String.IsNullOrEmpty(clean) && clean.Length > 1) { isPalindrome = true; for (int i = 0, count = clean.Length / 2 + 1; i < count; i++) { if (clean[i] != clean[clean.Length - 1 - i]) { isPalindrome = false; break; } } } return isPalindrome; } static bool IsPhrasePalindrome(string text) { bool isPalindrome = false; String clean = Regex.Replace(text.ToLower(), @"[^A-z0-9\s]", " ", RegexOptions.Compiled).Trim(); String[] words = Regex.Split(clean, @"\s+"); if (words.Length > 1) { isPalindrome = true; for (int i = 0, count = words.Length / 2 + 1; i < count; i++) { if (words[i] != words[words.Length - 1 - i]) { isPalindrome = false; break; } } } return isPalindrome; } A: I haven't seen any recursion yet, so here goes... import re r = re.compile("[^0-9a-zA-Z]") def is_pal(s): def inner_pal(s): if len(s) == 0: return True elif s[0] == s[-1]: return inner_pal(s[1:-1]) else: return False r = re.compile("[^0-9a-zA-Z]") return inner_pal(r.sub("", s).lower()) A: This is all good, but is there a way to do better algorithmically? I was once asked in a interview to recognize a palindrome in linear time and constant space. I couldn't think of anything then and I still can't. (If it helps, I asked the interviewer what the answer was. He said you can construct a pair of hash functions such that they hash a given string to the same value if and only if that string is a palindrome. I have no idea how you would actually make this pair of functions.) A: The solutions which strip out any chars that don't fall between A-Z or a-z are very English centric. Letters with diacritics such as à or é would be stripped! According to Wikipedia: The treatment of diacritics varies. In languages such as Czech and Spanish, letters with diacritics or accents (except tildes) are not given a separate place in the alphabet, and thus preserve the palindrome whether or not the repeated letter has an ornamentation. However, in Swedish and other Nordic languages, A and A with a ring (å) are distinct letters and must be mirrored exactly to be considered a true palindrome. So to cover many other languages it would be better to use collation to convert diacritical marks to their equivalent non diacritic or leave alone as appropriate and then strip whitespace and punctuation only before comparing. A: set l = index of left most character in word set r = index of right most character in word loop while(l < r) begin if letter at l does not equal letter at r word is not palindrome else increase l and decrease r end word is palindrome A: Efficient C++ version: template< typename Iterator > bool is_palindrome( Iterator first, Iterator last, std::locale const& loc = std::locale("") ) { if ( first == last ) return true; for( --last; first < last; ++first, --last ) { while( ! std::isalnum( *first, loc ) && first < last ) ++first; while( ! std::isalnum( *last, loc ) && first < last ) --last; if ( std::tolower( *first, loc ) != std::tolower( *last, loc ) ) return false; } return true; } A: Here are two more Perl versions, neither of which uses reverse. Both use the basic algorithm of comparing the first character of the string to the last, then discarding them and repeating the test, but they use different methods of getting at the individual characters (the first peels them off one at a time with a regex, the second splits the string into an array of characters). #!/usr/bin/perl my @strings = ("A man, a plan, a canal, Panama.", "A Toyota's a Toyota.", "A", "", "As well as some non-palindromes."); for my $string (@strings) { print is_palindrome($string) ? "'$string' is a palindrome (1)\n" : "'$string' is not a palindrome (1)\n"; print is_palindrome2($string) ? "'$string' is a palindrome (2)\n" : "'$string' is not a palindrome (2)\n"; } sub is_palindrome { my $str = lc shift; $str =~ tr/a-z//cd; while ($str =~ s/^(.)(.*)(.)$/\2/) { return unless $1 eq $3; } return 1; } sub is_palindrome2 { my $str = lc shift; $str =~ tr/a-z//cd; my @chars = split '', $str; while (@chars && shift @chars eq pop @chars) {}; return scalar @chars <= 1; } A: Easy mode in C#, only using Base Class Libraries Edit: just saw someone did Array.Reverse also public bool IsPalindrome(string s) { if (String.IsNullOrEmpty(s)) { return false; } else { char[] t = s.ToCharArray(); Array.Reverse(t); string u = new string(t); if (s.ToLower() == u.ToLower()) { return true; } } return false; } A: Here's another for C# that I used when doing a sample server control. It can be found in the book ASP.NET 3.5 Step by Step (MS Press). It's two methods, one to strip non-alphanumerics, and another to check for a palindrome. protected string StripNonAlphanumerics(string str) { string strStripped = (String)str.Clone(); if (str != null) { char[] rgc = strStripped.ToCharArray(); int i = 0; foreach (char c in rgc) { if (char.IsLetterOrDigit(c)) { i++; } else { strStripped = strStripped.Remove(i, 1); } } } return strStripped; } protected bool CheckForPalindrome() { if (this.Text != null) { String strControlText = this.Text; String strTextToUpper = null; strTextToUpper = Text.ToUpper(); strControlText = this.StripNonAlphanumerics(strTextToUpper); char[] rgcReverse = strControlText.ToCharArray(); Array.Reverse(rgcReverse); String strReverse = new string(rgcReverse); if (strControlText == strReverse) { return true; } else { return false; } } else { return false; } } A: Const-correct C/C++ pointer solution. Minimal operations in loop. int IsPalindrome (const char *str) { const unsigned len = strlen(str); const char *end = &str[len-1]; while (str < end) if (*str++ != *end--) return 0; return 1; } A: Scala def pal(s:String) = Symbol(s) equals Symbol(s.reverse) A: public bool IsPalindrome(string s) { string formattedString = s.Replace(" ", string.Empty).ToLower(); for (int i = 0; i < formattedString.Length / 2; i++) { if (formattedString[i] != formattedString[formattedString.Length - 1 - i]) return false; } return true; } This method will work for sting like "Was it a rat I saw". But I feel we need to eliminate special character through Regex. A: C# Version: Assumes MyString to be a char[], Method return after verification of the string, it ignores space and <,>, but this can be extended to ignore more, probably impleemnt a regex match of ignore list. public bool IsPalindrome() if (MyString.Length == 0) return false; int len = MyString.Length - 1; int first = 0; int second = 0; for (int i = 0, j = len; i <= len / 2; i++, j--) { while (i<j && MyString[i] == ' ' || MyString[i] == ',') i++; while(j>i && MyString[j] == ' ' || MyString[j] == ',') j--; if ((i == len / 2) && (i == j)) return true; first = MyString[i] >= 97 && MyString[i] <= 122 ? MyString[i] - 32 : MyString[i]; second = MyString[j] >= 97 && MyString[j] <= 122 ? MyString[j] - 32 : MyString[j]; if (first != second) return false; } return true; } Quick test cases negative 1. ABCDA 2. AB CBAG 3. A#$BDA 4. NULL/EMPTY positive 1. ABCBA 2. A, man a plan a canal,,Panama 3. ABC BA 4. M 5. ACCB let me know any thoghts/errors. A: How about this PHP example: function noitcnuf( $returnstrrevverrtsnruter, $functionnoitcnuf) { $returnstrrev = "returnstrrevverrtsnruter"; $verrtsnruter = $functionnoitcnuf; return (strrev ($verrtsnruter) == $functionnoitcnuf) ; } A: public static boolean isPalindrome( String str ) { int count = str.length() ; int i, j = count - 1 ; for ( i = 0 ; i < count ; i++ ) { if ( str.charAt(i) != str.charAt(j) ) return false ; if ( i == j ) return true ; j-- ; } return true ; } A: If you can use Java APIs and additional storage: public static final boolean isPalindromeWithAdditionalStorage(String string) { String reversed = new StringBuilder(string).reverse().toString(); return string.equals(reversed); } In can need an in-place method for Java: public static final boolean isPalindromeInPlace(String string) { char[] array = string.toCharArray(); int length = array.length-1; int half = Math.round(array.length/2); char a,b; for (int i=length; i>=half; i--) { a = array[length-i]; b = array[i]; if (a != b) return false; } return true; } A: Regular Approach: flag = True // Assume palindrome is true for i from 0 to n/2 { compare element[i] and element[n-i-1] // 0 to n-1 if not equal set flag = False break } return flag There is a better machine optimized method which uses XORs but has the same complexity XOR approach: n = length of string mid_element = element[n/2 +1] for i from 0 to n { t_xor = element[i] xor element[i+1] } if n is odd compare mid_element and t_xor else check t_xor is zero A: public class palindrome { public static void main(String[] args) { StringBuffer strBuf1 = new StringBuffer("malayalam"); StringBuffer strBuf2 = new StringBuffer("malayalam"); strBuf2.reverse(); System.out.println(strBuf2); System.out.println((strBuf1.toString()).equals(strBuf2.toString())); if ((strBuf1.toString()).equals(strBuf2.toString())) System.out.println("palindrome"); else System.out.println("not a palindrome"); } } A: A case-insensitive, const-friendly version in plain C that ignores non-alphanumeric characters (e.g. whitespace / punctuation). It therefore will actually pass on classics like "A man, a plan, a canal, Panama". int ispalin(const char *b) { const char *e = b; while (*++e); while (--e >= b) { if (isalnum(*e)) { while (*b && !isalnum(*b)) ++b; if (toupper(*b++) != toupper(*e)) return 0; } } return 1; } A: The interviewer will be looking for some logic on how you will be approaching this problem: Please consider the following java code: * *always check if the input string is null *check your base cases. *format your string accordingly (remove anything that is not a character/digit *Most likely they do not want to see if you know the reverse function, and a comparison, but rather if you are able to answer the question using a loop and indexing. *shortcut return as soon as you know your answer and do not waste resources for nothing. public static boolean isPalindrome(String s) { if (s == null || s.length() == 0 || s.length() == 1) return false; String ss = s.toLowerCase().replaceAll("/[^a-z]/", ""); for (int i = 0; i < ss.length()/2; i++) if (ss.charAt(i) != ss.charAt(ss.length() - 1 - i)) return false; return true; } A: Java with stacks. public class StackPalindrome { public boolean isPalindrome(String s) throws OverFlowException,EmptyStackException{ boolean isPal=false; String pal=""; char letter; if (s==" ") return true; else{ s=s.toLowerCase(); for(int i=0;i<s.length();i++){ letter=s.charAt(i); char[] alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; for(int j=0; j<alphabet.length;j++){ /*removing punctuations*/ if ((String.valueOf(letter)).equals(String.valueOf(alphabet[j]))){ pal +=letter; } } } int len=pal.length(); char[] palArray=new char[len]; for(int r=0;r<len;r++){ palArray[r]=pal.charAt(r); } ArrayStack palStack=new ArrayStack(len); for(int k=0;k<palArray.length;k++){ palStack.push(palArray[k]); } for (int i=0;i<len;i++){ if ((palStack.topAndpop()).equals(palArray[i])) isPal=true; else isPal=false; } return isPal; } } public static void main (String args[]) throws EmptyStackException,OverFlowException{ StackPalindrome s=new StackPalindrome(); System.out.println(s.isPalindrome("“Ma,” Jerome raps pot top, “Spare more jam!”")); } A: //Single program for Both String or Integer to check palindrome //In java with out using string functions like reverse and equals method also and display matching characters also package com.practice; import java.util.Scanner; public class Pallindrome { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int i=0,j=0,k,count=0; String input,temp; System.out.println("Enter the String or Integer"); input=sc.nextLine(); temp=input; k=temp.length()-1; for(i=0;i<=input.length()-1;i++) { if(input.charAt(j)==temp.charAt(k)) { count++; } //For matching characters j++; k--; } System.out.println("Matching Characters = "+count); if(count==input.length()) { System.out.println("It's a pallindrome"); } else { System.out.println("It's not a pallindrome"); } } } A: public static boolean isPalindrome(String str) { return str.equals(new StringBuilder(str).reverse().toString()); } for versions of Java earlier than 1.5, public static boolean isPalindrome(String str) { return str.equals(new StringBuffer().append(str).reverse().toString()); } or public static boolean istPalindrom(char[] word){ int i1 = 0; int i2 = word.length - 1; while (i2 > i1) { if (word[i1] != word[i2]) { return false; } ++i1; --i2; } return true; } A: // JavaScript Version. function isPalindrome(str) { str = str.replace(/[^a-zA-Z]/g, '') return str.split('').reverse().join('').toUpperCase() === str.toUpperCase() }
{ "language": "en", "url": "https://stackoverflow.com/questions/52002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: Options for PivotTables in Excel I need to design a small project for generating excel reports in .NET, which will be sent to users to use. The excel reports will contain PivotTables. I don't have much experience with them, but I can think of three implementation alternatives: * *Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data. *Generate a small access database and send it along with the excel file, connect to it. *Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think. What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about? A: Do you have to keep the data "offline"? What I usually do in these cases, where you have quite a bit of data, is to use an existing SQL server already on the network. If it is to be used at the office, the users will be online anyway. Just remember to create a dedicated user with restricted access on the SQL server for this report and don't store the "sa" password in the excel file. If you mean users outside of the office by "sent to the users", this would not be a good solution. If that is the case, I would try to include the data in the excel sheet and see how big it will become. That will be the most user friendly solution if the file is not too big. Also, I found this online: Different Ways of Using Web Queries in Microsoft Office Excel 2003. This will let you store the data on a public website (with a secret URL if you want) and then let Excel pull the data. That way you do not have to fill the users' inbox with large files, and you can also update the data later without resending the excel file. A: @Espo No, the users will not have access to the original datasource, that's why I'm considering creating a small access database with the data subset required for the report A: Option 3 sounds the simplest and I would have thought Excel is as if not more efficient than Access for storing the data. The trouble with two files is getting the links between them to work even in a different location. A: @paulmorriss Maybe... the problem with that is that there are limitations as to how much data a single sheet can contain... I'm thinking option 2, unless someone tells me it is not a good idea in regards to performance A: Since it's a small project, you can rely on Excel for data storage from the application. It'll be easier to develop and test, and simpler to maintain.
{ "language": "en", "url": "https://stackoverflow.com/questions/52008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting a list of assemblies needed by application Is there a way of getting all required assemblies (excluding the .net framework) for a .net project into a folder ready to be packaged into an nsis as setup file? I've tried writing a small console app that uses reflection to get a list of dlls but have got stuck with finding a foolproof way of determining if a dll is from the .net framework or not. The answer could be a simple switch in Visual Studio to output all dependencies, or a standalone app that can do it, or a plugin for Nsis, or some information on reflection that I've missed. A: In Visual Studio (2005 at least - what I'm using right now), each reference that you have associated to a project has a property called "Copy Local", this can be set to true/false. When true it will copy the dll's for you into the current configuration directory. A: You can use NDepend for this. Download it, build a new NDepend project, drag&drop your assemblies in the Application Assemblies data grid view, and you'll see NDepend resolving instantly the tier assemblies needed by your set of Application Assemblies. You can also provide a list of folders to tell NDepend where to look. If a tier assembly can't be found, then NDepend will mark it as not found, which I think is a valuable information. A: Dependency Walker is what you need. Or maybe Depends.Net
{ "language": "en", "url": "https://stackoverflow.com/questions/52022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accessing a web service in a Flash CS3 AS3 project Since CS3 doesn't have a web service component, as previous versions had, is there a good, feature-complete, AS3-only (no Flex dependencies) library for accessing web services with AS3? A: You may want to check out http://alducente.wordpress.com/2007/10/27/web-service-in-as3-release-10/ A: What type of service are you trying to consume? URLLoader can handle soap requests (urlRequest.requestHeaders.push(new URLRequestHeader("Content-Type", "application/soap+xml"));) and NetConnection can handle most other stuff (AMF/Remoting).
{ "language": "en", "url": "https://stackoverflow.com/questions/52046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the best source for information on COM error codes? I'm at a loss for where to get the best information about the meaning, likely causes, and possible solutions to resolve COM errors when all you have is the HRESULT. Searching Google for terms like '80004027' is just about useless as it sends you to random discussion groups where 90% of the time, the question 'What does 80004027 mean?' is not answered. What is a good resource for this? Why isn't MSDN the top Google result? A: I always use WinError.h. That has the vast majority of Windows error codes of all sorts. A key indicator to look out for is the Facility part of the code: the second most-significant byte. That is, 0x80nnmmmm, where nn is the Facility. That tells you which component generated the code. Anything with a facility of 7 is a Windows error code repackaged as an HRESULT, and you should convert the low word to decimal and look it up in WinError.h. There are also error ranges that appear in their own headers (e.g. anything from 12000 - 12999 is a WinInet error code and you should look it up in WinInet.h). Looking up the error code will give you the symbolic name, which might be found in more documentation than the code itself or the wording of the error message. FACILITY_ITF (which has the value 4, so these HRESULTs start 0x8004) indicates that the error is defined by the interface you're using; you'll have to check with that interface to find out what it means. Finally, COM also offers the interface IErrorInfo to retrieve extended error information: call GetErrorInfo to retrieve the error object. You'll have to query for ISupportErrorInfo and call that interface's InterfaceSupportsErrorInfo method to determine whether the interface you called actually set the error object (and of course, if it was template code, it could be lying). A: Error Lookup (ErrLook.exe) in your %PROGRAMFILES%[Some version of Visual Studio]\Tools Common7\ folder will give you the error message often, but not always: |---------------------------------------------------| | [] Error Lookup | |---------------------------------------------------| | Value: [0x80004027] | | | | Error Message | | +---------------------------------------------+ | | |The component or application containing the | | | |component has been disabled | | | | | | | +---------------------------------------------+ | | [Modules...] [Look up] [Close] [Help] | |---------------------------------------------------- If this doesn't work, you might follow some ideas from here: http://blogs.msdn.com/oldnewthing/archive/2008/09/01/8914664.aspx (Error Lookup simply calls FormatMessage() with the FORMAT_MESSAGE_FROM_SYSTEM flag) If the COM error is not a system error, you might also have to check the documentation of the component that threw the error. If you are catching the error in code, you can hope that the component implements rich errors (GetErrorInfo(), same as the Err object in VB) so you can get a full message describing the problem. A: Structure of COM Error Code Second in Google results for COM Error Code. A: Good link from Prakash (I wasn't aware of the RCNr stuff - I thought those bytes were part of the facility - but that's only true in 16 bit Windows it seems.) Often these unknown codes are specific to the interface/component you're using. The facility would be set to FACILITY_ITF. I have an old program HRPlus (link?) that parses HRESULTs.
{ "language": "en", "url": "https://stackoverflow.com/questions/52059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Dynamic regex for date-time formats Is there an existing solution to create a regular expressions dynamically out of a given date-time format pattern? The supported date-time format pattern does not matter (Joda DateTimeFormat, java.text.SimpleDateTimeFormat or others). As a specific example, for a given date-time format like dd/MM/yyyy hh:mm, it should generate the corresponding regular expression to match the date-times within the specified formats. A: I guess you have a limited alphabet that your time formats can be constructed of. That means, "HH" would always be "hours" on the 24-hour clock, "dd" always the day with leading zero, and so on. Because of the sequential nature of a time format, you could try to tokenize a format string of "dd/mm/yyyy HH:nn" into an array ["dd", "/", "mm", "/", "yyyy", " ", "HH", ":", "nn"]. Then go ahead and form a pattern string from that array by replacing "HH" with "([01][0-9]|2[0-3])" and so on. Preconstruct these pattern atoms into a lookup table/array. All parts of your array that are not in the lookup table are literals. Escape them to according regex rules and append them to you pattern string. EDIT: As a side effect for a regex based solution, when you put all regex "atoms" of your lookup table into parens and keep track of their order in a given format string, you would be able to use sub-matches to extract the required components from a match and feed them into a CreateDate function, thus skipping the ParseDate part altogether. A: If you are looking for basic date checking, this code matches this data. \b(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}\b 10/07/2008 10.07.2008 1-01/2008 10/07/08 10.07.2008 1-01/08 Code via regexbuddy A: SimpleDateFormat already does this with the parse() method. If you need to parse multiple dates from a single string, start with a regex (even if it matches too leniently), and use parse() on all the potential matches found by the regex. A: The below given js / jQuery code is for dynamically generated RegEx for the Date format only, not for DateTime (Development version not fully tested yet.) Date Format should be in "D M Y". E.g. * *DD-MM-YY *DD-MM-YYYY *YYYY-MM-DD *YYYY-DD-MM *MM-DD-YYYY *MM-DD-YY *DD/MM/YY *DD/MM/YYYY *YYYY/MM/DD *YYYY/DD/MM *MM/DD/YYYY *MM/DD/YY Or other formats but created with "D M Y" characters: var dateFormat = "DD-MM-YYYY"; var order = []; var position = {"D":dateFormat.search('D'),"M":dateFormat.search('M'),"Y":dateFormat.search('Y')}; var count = {"D":dateFormat.split("D").length - 1,"M":dateFormat.split("M").length - 1,"Y":dateFormat.split("Y").length - 1}; var seprator =''; for(var i=0; i<dateFormat.length; i++){ if(["Y","M","D"].indexOf(dateFormat.charAt(i))<0){ seprator = dateFormat.charAt(i); }else{ if(order.indexOf(dateFormat.charAt(i)) <0 ){ order.push(dateFormat.charAt(i)); } } } var regEx = "^"; $(order).each(function(ok,ov){ regEx += '(\d{'+count[ov]+'})'+seprator; }); regEx = regEx.substr(0,(regEx.length)-1); regEx +="$"; var re = new RegExp(regEx); console.log(re); NOTE: There is no validation check for months / days e.g. month should be in 01-12 or date should be in 01-31
{ "language": "en", "url": "https://stackoverflow.com/questions/52066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: .NET path manipulation library Does anyone know of any good library that abstracts the problem of path manipulation in a nice way? I'd like to be able to combine and parse paths with arbitrary separators ('/' or ':' for example) without reinventing the wheel. It's a shame that System.IO.Path isn't more reusable. Thanks A: System.IO.Path.Combine will work great for many different types of paths: http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx System.IO.Path.Combine uses the current platform standard separators to combine paths. That means on Windows it uses "\" and on unix/linux (mono) it uses "/". Can you give some samples of what paths you are trying to combine and on what platform? A: Check Patrick's library to handle path operations link text This is the codeplex project A: You're describing regular expressions! Use that as the underpinning for what you need to do. A: I can't tell what environment you might be using based off of your separators, but I have never seen a library like this before. So using reflector and System.IO.Path as a basis it isn't difficult to reinvent the wheel. * *Create an instance of this class *Supply your separator characters in the CTor *Optionally change the InvalidPathChars if needed. This is pretty much the code that is used by the framework so it should be just as fast or only a negligible difference. May or may not be faster than RegEx, it is probably worth a test though. class ArbitraryPath { private readonly char _directorySeparatorChar; private readonly char _altDirectorySeparatorChar; private readonly char _volumeSeparatorChar; public ArbitraryPath(char directorySeparatorChar, char altDirectorySeparatorChar, char volumeSeparatorChar) { _directorySeparatorChar = directorySeparatorChar; _altDirectorySeparatorChar = altDirectorySeparatorChar; _volumeSeparatorChar = volumeSeparatorChar; } public string Combine(string path1, string path2) { if ((path1 == null) || (path2 == null)) { throw new ArgumentNullException((path1 == null) ? "path1" : "path2"); } CheckInvalidPathChars(path1); CheckInvalidPathChars(path2); if (path2.Length == 0) { return path1; } if (path1.Length == 0) { return path2; } if (IsPathRooted(path2)) { return path2; } char ch = path1[path1.Length - 1]; if (ch != _directorySeparatorChar && ch != _altDirectorySeparatorChar && ch != _volumeSeparatorChar) { return (path1 + _directorySeparatorChar + path2); } return (path1 + path2); } public bool IsPathRooted(string path) { if (path != null) { CheckInvalidPathChars(path); int length = path.Length; if (length >= 1 && (path[0] == _directorySeparatorChar || path[0] == _altDirectorySeparatorChar) || length >= 2 && path[1] == _volumeSeparatorChar) { return true; } } return false; } internal static void CheckInvalidPathChars(string path) { for (int i = 0; i < path.Length; i++) { int num2 = path[i]; if (num2 == 0x22 || num2 == 60 || num2 == 0x3e || num2 == 0x7c || num2 < 0x20) { throw new ArgumentException("Argument_InvalidPathChars"); } } } } A: I'm afraid you'll have to implement a path class yourself, as I did. It gives the following advantages: * *you can profit from type safety *you can override operator/, which makes concatenation easier *you can add convenience member functions such as GetParentPath() and GetLeafPart()
{ "language": "en", "url": "https://stackoverflow.com/questions/52071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Inversion of Control Container for PHP? I am trying to code TDD style in PHP and one of my biggest stumbling blocks (other than lack of a decent IDE) is that I have to make my own hacked together IoC container just to inject all my mock objects properly. Has anyone used an Ioc container in PHP? All I've been able to find is PHP IOC on the ever-annoying phpclasses.org and it seems to have almost no documentation and not much of a following. A: I played with some DI Frameworks for PHP, but I haven't used one in production. Have some links: * *http://www.stubbles.net/ which I think is the oldest I tried *http://php.xjconf.net/ *FLOW3 - I belive this one will become a very nice framework (its beta right now) You mentioned you would use it for TDD - so maybe have a look at Dependency Injection for Unit Tests in PHP A: Phemto is being developed again, and looks quite promising IMHO. A few other similar projects, that you might want to look at: bucket (Disclaimer: I'm the principal author of this one) The php-port of picocontainer, has been around for a long time. I don't think it's being actively deveoped any more, but on the other hand, I believe that it's quite stable. It's been a long time since I looked at it though. A rather new project, I recently stumbled upon is Crafty. Not sure how many people uses it though. I'm also watching sphicy, which looks interesting. A: You might also want to try Ding (http://marcelog.github.com/Ding) which is modeled after Spring(tm) for Java. It is a complete inversion of control and dependency injection container, which also supports AOP A: What about the Symfony Dependency Injection or the PHP 5.3+ equivalent component from the symfony 2.0 project. A: PHP-DI is another dependency injection container. It features dependency injection through annotations and minimal configuration, here is an example: class Foo { /** * @Inject * @var Bar */ private $bar; } It's very easy to use, and it integrates with Zend Framework for example. (yes I do work on this framework) A: I have been working on a PHP IoC/DI Container named Substrate for the last six months. It is still very much a work in progress but it has been deployed in production for a month and a half and has been working pretty well so far. Substrate is inspired by Spring Framework, but written with the strengths and limitations of PHP in mind. The documentation is pretty minimal at this point, but there is some sample code, including a unit testing example. Is this something that you think you might be able to use for TDD? A: Laravel 4 has the best IoC and DI framework. if you dont mind using a framework the Laravel 4 is the way to go
{ "language": "en", "url": "https://stackoverflow.com/questions/52072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: How do I build a loop in JavaScript? How can I build a loop in JavaScript? A: For loops for (i = startValue; i <= endValue; i++) { // Before the loop: i is set to startValue // After each iteration of the loop: i++ is executed // The loop continues as long as i <= endValue is true } For...in loops for (i in things) { // If things is an array, i will usually contain the array keys *not advised* // If things is an object, i will contain the member names // Either way, access values using: things[i] } It is bad practice to use for...in loops to itterate over arrays. It goes against the ECMA 262 standard and can cause problems when non-standard attributes or methods are added to the Array object, e.g. by Prototype. (Thanks to Chase Seibert for pointing this out in the comments) While loops while (myCondition) { // The loop will continue until myCondition is false } A: Here is an example of a for loop: We have an array of items nodes. for(var i = 0; i< nodes.length; i++){ var node = nodes[i]; alert(node); } A: Aside form the build-in loops (while() ..., do ... while(), for() ...), there is a structure of self calling function, also known as recursion to create a loop without the three build-in loop structures. Consider the following: // set the initial value var loopCounter = 3; // the body of the loop function loop() { // this is only to show something, done in the loop document.write(loopCounter + '<br>'); // decrease the loopCounter, to prevent running forever loopCounter--; // test loopCounter and if truthy call loop() again loopCounter && loop(); } // invoke the loop loop(); Needless to say that this structure is often used in combination with a return value, so this is a small example how to deal with value that is not in the first time available, but at the end of the recursion: function f(n) { // return values for 3 to 1 // n -n ~-n !~-n +!~-n return // conv int neg bitnot not number // 3 -3 2 false 0 3 * f(2) // 2 -2 1 false 0 2 * f(1) // 1 -1 0 true 1 1 // so it takes a positive integer and do some conversion like changed sign, apply // bitwise not, do logical not and cast it to number. if this value is then // truthy, then return the value. if not, then return the product of the given // value and the return value of the call with the decreased number return +!~-n || n * f(n - 1); } document.write(f(7)); A: A loop in JavaScript looks like this: for (var = startvalue; var <= endvalue; var = var + increment) { // code to be executed }
{ "language": "en", "url": "https://stackoverflow.com/questions/52080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Querying XML columns in SQLServer 2005 There is a field in my company's "Contacts" table. In that table, there is an XML type column. The column holds misc data about a particular contact. EG. <contact> <refno>123456</refno> <special>a piece of custom data</special> </contact> The tags below contact can be different for each contact, and I must query these fragments alongside the relational data columns in the same table. I have used constructions like: SELECT c.id AS ContactID,c.ContactName as ForeName, c.xmlvaluesn.value('(contact/Ref)[1]', 'VARCHAR(40)') as ref, INNER JOIN ParticipantContactMap pcm ON c.id=pcm.contactid AND pcm.participantid=2140 WHERE xmlvaluesn.exist('/contact[Ref = "118985"]') = 1 This method works ok but, it takes a while for the Server to respond. I have also investigated using the nodes() function to parse the XML nodes and exist() to test if a nodes holds the value I'm searching for. Does anyone know a better way to query XML columns?? A: If you are doing one write and a lot of reads, take the parsing hit at write time, and get that data into some format that is more query-able. A first suggestion would be to parse them into a related but separate table, with name/value/contactID columns. A: I've found the msdn xml best practices helpful for working with xml blob columns, might provide some inspiration... http://msdn.microsoft.com/en-us/library/ms345115.aspx#sql25xmlbp_topic4 A: In addition to the page mentioned by @pauljette, this page has good performance optimization advice: http://msdn.microsoft.com/en-us/library/ms345118.aspx There's a lot you can do to speed up the performance of XML queries, but it will never be as good as properly indexed relational data. If you are selecting one document and then querying inside just that one, you can do pretty well, but when your query needs to scan through a bunch of similar documents looking for something, it's sort of like a key lookup in a relational query plan (that is, slow). A: If you have a XSD for your Xml then you can import that into your database and you can then build indexes for your Xml data. A: Try this SELECT * FROM conversionupdatelog WHERE convert(XML,colName).value('(/leads/lead/@LeadID=''[email protected]'')[1]', 'varchar(max)')='true'
{ "language": "en", "url": "https://stackoverflow.com/questions/52084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why the claim that C# people don't get object-oriented programming? (vs class-oriented) This caught my attention last night. On the latest ALT.NET Podcast Scott Bellware discusses how as opposed to Ruby, languages like C#, Java et al. are not truly object oriented rather opting for the phrase "class-oriented". They talk about this distinction in very vague terms without going into much detail or discussing the pros and cons much. What is the real difference here and how much does it matter? What are other languages then are "object-oriented"? It sounded pretty interesting but I don't want to have to learn Ruby just to know what if anything I am missing. Update After reading some of the answers below it seems like people generally agree that the reference is to duck-typing. What I'm not sure I understand still though is the claim that this ultimately changes all that much. Especially if you are already doing proper TDD with loose coupling etc. Can someone show me an example of a specific thing I could do with Ruby that I cannot do with C# and that exemplifies this different OOP approach? A: There are three pillars of OOP * *Encapsulation *Inheritance *Polymorphism If a language can do those three things it is a OOP language. I am pretty sure the argument of language X does OOP better than language A will go on forever. A: OO is sometimes defined as message oriented. The idea is that a method call (or property access) is really a message sent to another object. How the recieveing object handles the message is completely encapsulated. Often the message corresponds to a method which is then executed, but that is just an implementation detail. You can for example create a catch-all handler which is executed regardless of the method name in the message. Static OO like in C# does not have this kind of encapsulation. A massage has to correspond to an existing method or property, otherwise the compiler will complain. Dynamic languages like Smalltalk, Ruby or Python does however support "message-based" OO. So in this sense C# and other statically typed OO languages are not true OO, sine thay lack "true" encapsulation. A: Update: Its the new wave.. which suggest everything that we've been doing till now is passe.. Seems to be propping up quite a bit in podcasts and books.. Maybe this is what you heard. Till now we've been concerned with static classes and not unleashed the power of object oriented development. We've been doing 'class based dev.' Classes are fixed/static templates to create objects. All objects of a class are created equal. e.g. Just to illustrate what I've been babbling about... let me borrow a Ruby code snippet from PragProg screencast I just had the privilege of watching. 'Prototype based development' blurs the line between objects and classes.. there is no difference. animal = Object.new # create a new instance of base Object def animal.number_of_feet=(feet) # adding new methods to an Object instance. What? @number_of_feet = feet end def animal.number_of_feet @number_of_feet end cat = animal.clone #inherits 'number_of_feet' behavior from animal cat.number_of_feet = 4 felix = cat.clone #inherits state of '4' and behavior from cat puts felix.number_of_feet # outputs 4 The idea being its a more powerful way to inherit state and behavior than traditional class based inheritance. It gives you more flexibility and control in certain "special" scenarios (that I've yet to fathom). This allows things like Mix-ins (re using behavior without class inheritance).. By challenging the basic primitives of how we think about problems, 'true OOP' is like 'the Matrix' in a way... You keep going WTF in a loop. Like this one.. where the base class of Container can be either an Array or a Hash based on which side of 0.5 the random number generated is. class Container < (rand < 0.5 ? Array : Hash) end Ruby, javascript and the new brigade seem to be the ones pioneering this. I'm still out on this one... reading up and trying to make sense of this new phenomenon. Seems to be powerful.. too powerful.. Useful? I need my eyes opened a bit more. Interesting times.. these. A: In an object-oriented language, objects are defined by defining objects rather than classes, although classes can provide some useful templates for specific, cookie-cutter definitions of a given abstraction. In a class-oriented language, like C# for example, objects must be defined by classes, and these templates are usually canned and packaged and made immutable before runtime. This arbitrary constraint that objects must be defined before runtime and that the definitions of objects are immutable is not an object-oriented concept; it's class oriented. A: Maybe they are alluding to the difference between duck typing and class hierarchies? if it walks like a duck and quacks like a duck, just pretend it's a duck and kick it. In C#, Java etc. the compiler fusses a lot about: Are you allowed to do this operation on that object? Object Oriented vs. Class Oriented could therefore mean: Does the language worry about objects or classes? For instance: In Python, to implement an iterable object, you only need to supply a method __iter__() that returns an object that has a method named next(). That's all there is to it: No interface implementation (there is no such thing). No subclassing. Just talking like a duck / iterator. EDIT: This post was upvoted while I rewrote everything. Sorry, won't ever do that again. The original content included advice to learn as many languages as possible and to nary worry about what the language doctors think / say about a language. A: I've only listened to the first 6-7 minutes of the podcast that sparked your question. If their intent is to say that C# isn't a purely object-oriented language, that's actually correct. Everything in C# isn't an object (at least the primitives aren't, though boxing creates an object containing the same value). In Ruby, everything is an object. Daren and Ben seem to have covered all the bases in their discussion of "duck-typing", so I won't repeat it. Whether or not this difference (everything an object versus everything not an object) is material/significant is a question I can't readily answer because I don't have sufficient depth in Ruby to compare it to C#. Those of you who on here who know Smalltalk (I don't, though I wish I did) have probably been looking at the Ruby movement with some amusement since it was the first pure OO language 30 years ago. A: The duck typing comments here are more attributing to the fact that Ruby and Python are more dynamic than C#. It doesn't really have anything to do with it's OO Nature. What (I think) Bellware meant by that is that in Ruby, everything is an object. Even a class. A class definition is an instance of an object. As such, you can add/change/remove behavior to it at runtime. Another good example is that NULL is an object as well. In ruby, everything is LITERALLY an object. Having such deep OO in it's entire being allows for some fun meta-programming techniques such as method_missing. A: IMO, it's really overly defining "object-oriented", but what they are referring to is that Ruby, unlike C#, C++, Java, et al, does not make use of defining a class -- you really only ever work directly with objects. Conversely, in C# for example, you define classes that you then must instantiate into object by way of the new keyword. The key point being you must declare a class in C# or describe it. Additionally, in Ruby, everything -- even numbers, for example -- is an object. In contrast, C# still retains the concept of an object type and a value type. This in fact, I think illustrates the point they make about C# and other similar languages -- object type and value type imply a type system, meaning you have an entire system of describing types as opposed to just working with objects. Conceptually, I think OO design is what provides the abstraction for use to deal complexity in software systems these days. The language is a tool use to implement an OO design -- some make it more natural than others. I would still argue that from a more common and broader definition, C# and the others are still object-oriented languages. A: That was an abstract-podcast indeed! But I see what they're getting at - they just dazzled by Ruby Sparkle. Ruby allows you to do things that C-based and Java programmers wouldn't even think of + combinations of those things let you achieve undreamt of possibilities. Adding new methods to a built-in String class coz you feel like it, passing around unnamed blocks of code for others to execute, mixins... Conventional folks are not used to objects changing too far from the class template. Its a whole new world out there for sure.. As for the C# guys not being OO enough... dont take it to heart.. Just take it as the stuff you speak when you are flabbergasted for words. Ruby does that to most people. If I had to recommend one language for people to learn in the current decade.. it would be Ruby. I'm glad I did.. Although some people may claim Python. But its like my opinion.. man! :D A: I don't think this is specifically about duck typing. For instance C# supports limited duck-typing already - an example would be that you can use foreach on any class that implements MoveNext and Current. The concept of duck-typing is compatible with statically typed languages like Java and C#, it's basically an extension of reflection. This is really the case of static vs dynamic typing. Both are proper-OO, in as much as there is such a thing. Outside of academia it's really not worth debating. Rubbish code can be written in either. Great code can be written in either. There's absolutely nothing functional that one model can do that the other can't. The real difference is in the nature of the coding done. Static types reduce freedom, but the advantage is that everyone knows what they're dealing with. The opportunity to change instances on the fly is very powerful, but the cost is that it becomes hard to know what you're deaing with. For instance for Java or C# intellisense is easy - the IDE can quickly produce a drop list of possibilities. For Javascript or Ruby this becomes a lot harder. For certain things, for instance producing an API that someone else will code with, there is a real advantage in static typing. For others, for instance rapidly producing prototypes, the advantage goes to dynamic. It's worth having an understanding of both in your skills toolbox, but nowhere near as important as understanding the one you already use in real depth. A: Object Oriented is a concept. This concept is based upon certain ideas. The technical names of these ideas (actually rather principles that evolved over the time and have not been there from the first hour) have already been given above, I'm not going to repeat them. I'm rather explaining this as simple and non-technical as I can. The idea of OO programming is that there are objects. Objects are small independent entities. These entities may have embedded information or they may not. If they have such information, only the entity itself can access it or change it. The entities communicate with each other by sending messages between each other. Compare this to human beings. Human beings are independent entities, having internal data stored in their brain and the interact with each other by communicating (e.g. talking to each other). If you need knowledge from someone's else brain, you cannot directly access it, you must ask him a question and he may answer that to you, telling you what you wanted to know. And that's basically it. This is real idea behind OO programming. Writing these entities, define the communication between them and have them interact together to form an application. This concept is not bound to any language. It's just a concept and if you write your code in C#, Java, or Ruby, that is not important. With some extra work this concept can even be done in pure C, even though it is a functional language but it offers everything you need for the concept. Different languages have now adopted this concept of OO programming and of course the concepts are not always equal. Some languages allow what other languages forbid, for example. Now one of the concepts that involved is the concept of classes. Some languages have classes, some don't. A class is a blueprint how an object looks like. It defines the internal data storage of an object, it defines the messages an object can understand and if there is inheritance (which is not mandatory for OO programming!), classes also defines from which other class (or classes if multiple inheritance is allowed) this class inherits (and which properties if selective inheritance exists). Once you created such a blueprint you can now generate an unlimited amount of objects build according to this blueprint. There are OO languages that have no classes, though. How are objects then build? Well, usually dynamically. E.g. you can create a new blank object and then dynamically add internal structure like instance variables or methods (messages) to it. Or you can duplicate an already existing object, with all its properties and then modify it. Or possibly merge two objects into a new one. Unlike class based languages these languages are very dynamic, as you can generate objects dynamically during runtime in ways not even you the developer has thought about when starting writing the code. Usually this dynamic has a price: The more dynamic a language is the more memory (RAM) objects will waste and the slower everything gets as program flow is extremely dynamically as well and it's hard for a compiler to generate effective code if it has no chance to predict code or data flow. JIT compilers can optimize some parts of that during runtime, once they know the program flow, however as these languages are so dynamically, program flow can change at any time, forcing the JIT to throw away all compilation results and re-compile the same code over and over again. But this is a tiny implementation detail - it has nothing to do with the basic OO principle. It is nowhere said that objects need to be dynamic or must be alterable during runtime. The Wikipedia says it pretty well: Programming techniques may include features such as information hiding, data abstraction, encapsulation, modularity, polymorphism, and inheritance. http://en.wikipedia.org/wiki/Object-oriented_programming They may or they may not. This is all not mandatory. Mandatory is only the presence of objects and that they must have ways to interact with each other (otherwise objects would be pretty useless if they cannot interact with each other). A: You asked: "Can someone show me an example of a wonderous thing I could do with ruby that I cannot do with c# and that exemplifies this different oop approach?" One good example is active record, the ORM built into rails. The model classes are dynamically built at runtime, based on the database schema. A: I'll take a stab at this. Python and Ruby are duck-typed. To generate any maintainable code in these languages, you pretty much have to use test driven development. As such, it is very important for a developer to easily inject dependencies into their code without having to create a giant supporting framework. Successful dependency-injection depends upon on having a pretty good object model. The two are sort of two sides of the same coin. If you really understand how to use OOP, then you should by default create designs where dependencies can be easily injected. Because dependency injection is easier in dynamically typed languages, the Ruby/Python developers feel like their language understands the lessons of OO much better than other statically typed counterparts. A: This is really probably getting down to what these people see others doing in c# and java as opposed to c# and java supporting OOP. Most languages cane be used in different programming paradigms. For example, you can write procedural code in c# and scheme, and you can do functional-style programming in java. It is more about what you are trying to do and what the language supports.
{ "language": "en", "url": "https://stackoverflow.com/questions/52092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How do you navigate out of a ComboBox on a Windows Mobile Device without a TAB key? I'm developing an application for Windows Mobile Devices using Visual Studio .NET 2008 whose UI requires the use of a ComboBox control. Unfortunately, for devices with neither a hardware fullsize keyboard nor a touchscreen interface, there is no way to move (tab) from the ComboBox control to another control on the same form (say, specifying a product in the ComboBox and then moving to a text field to add a quantity). I've tried creating an event handler for the ComboBox's KeyPress event and setting the focus to the next control manually whenever the user presses the Right or Left directional key but unfortunately the event handler does not capture those key presses. Any ideas? I have a strong suspicion that this is being over-engineered and that there exists a better control more suited to what I need to do; I find it a bit inconceivable that tabbing out of a Combo Box control could be that difficult. Thanks! EDIT: Apparently I can capture the KeyDown and KeyUp events on the ComboBox, which allows me to set the focus or tab to the next control. Still over-engineered - still looking for ideas! A: I believe directionals are only captured on KeyDown and KeyUp, not on KeyPress. Alternatively to using a ComboBox, you could use several RadioButtons if the numer of ListItems is static and relatively small. A: http://msdn.microsoft.com/en-us/library/bb985500.aspx#GeneralRules provides UI navigation rules.
{ "language": "en", "url": "https://stackoverflow.com/questions/52098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I use SQL Server Management Studio 2005 for 2008 DB? I am looking to manage a SQL Server 2008 DB using Management Studio 2005. The reason for this is because our server is a 64-bit machine and we only have the 64-bit version of the software. Is this possible? How about managing a SQL Server 2005 DB using Management Studio 2008? A: I'm posting this to prevent people getting false hope (as I did). Where as you may be able to use SQL Server 2005 Management Studio to connect to SQL Server 2008, you cannot use SQL Server 2005 Management Studio Express. You get an explicit error message stating: This version of Microsoft SQL Server Management Studio Express can only be used to connect to SQL Server 2000 and SQL Server 2005 servers. (Microsoft.SqlServer.Express.ConnectionDlg) Hopefully that will prevent a couple of people from wasting their time trying just-in-case. A: UPDATE: You can use Cumulative update package 5 for SQL Server 2005 Service Pack 2 to connect to 2008. FIX: 50002151 946127 (http://support.microsoft.com/kb/946127/) FIX: You may experience problems when you use SQL Server Management Studio in SQL Server 2005 to connect to an instance of SQL Server 2008 A: The other question you asked was about managing 2005 servers with SSMS 2008 - and yes, you can do that. SSMS 2008 can manage 2008, 2005, 2000. I actually recommend that everybody use the latest SSMS 2008 client regardless of what server they're connecting to, because it has some nice perks and upgrades that work with all server versions that you connect to. Be aware that SSMS 2008 has IntelliSense, but only when you connect to a SQL 2008 server. If you connect to a 2005 server, you don't get IntelliSense. A: unless I'm mistaken and things have changed, you cannot use sql server 2008 to save a backup which restores to sql server 2005. I found this out the hard way :(
{ "language": "en", "url": "https://stackoverflow.com/questions/52103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: What is the shortcut to open a file within your solution in Visual Studio 2008? What is the shortcut to open a file within your solution in Visual Studio 2008 (+ Resharper)? A: Depending on your keymap, Ctrl + Shift + N will open any file in the solution, or Ctrl + N will open any type. A: If the standard toolbar is visible the following will open any file in the solution (resharper is not necessary). Ctrl + D places you in the Find textbox. >of f will provide a dropdown with all files that start with f with path information after the filename to distinguish name collisions. Complete the filename, or arrow down to the correct one and hit enter to open it in the editor. A: Ctrl + T (ReSharper, Goto, type) will open a class file for you. Looks like Ctrl + Shift + T opens files. A: It depends on the key mapping that you have set. With default keymapping: Do Ctrl + T to open a type and Ctrl + Shift + T to open a file. With IntelliJ like mapping : Do Ctrl + N to open a type and Ctrl + Shift + N to open a file. Visit the following links for all your key mapping. ReSharper 4 Default Keymap: Visual Studio scheme http://www.jetbrains.com/resharper/docs/ReSharper40DefaultKeymap.pdf ReSharper 4 Default Keymap: ReSharper 2.x / IDEA scheme http://www.jetbrains.com/resharper/docs/ReSharper40DefaultKeymap2.pdf A: I attended a presentation recently where Kirk Jackson showed how to add aliases to the command window in Visual Studio. Bear with me, it gets better. So it went like this: * *Open Command Window and type alias fo File.FileOpen *Now in your editor window hit Ctrl + / to put the focus into the Find box on the toolbar *If you use the prefix > this is command window (sneaky huh?) so type: fo and intellisense kicks in and shows you the names of the folders and files in the solution. The alias is persistent between Visual Studio sessions. Not exactly a keyboard shortcut but using this technique you can access any command in Visual Studio from the keyboard. You should also check out Kirk's list of essential VS tips and tricks
{ "language": "en", "url": "https://stackoverflow.com/questions/52108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Extracting SVN data with Java Does anyone know a good Java lib that will hook into SVN so I can extract the data? I want the SVN comments, author, path, etc... Hopefully with this data I can build a better time management tracking system. A: You want SVNKit. It's dual-licensed, so you have to pay only if you're doing commercial work with it. A: You can try to work with SVNKit.Its easy and flexible to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/52112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Determining if an assembly is part of the .NET framework How can I tell from the assembly name, or assembly class (or others like it), whether an assembly is part of the .NET framework (that is, System.windows.Forms)? So far I've considered the PublicKeyToken, and CodeBase properties, but these are not always the same for the whole framework. The reason I want this information is to get a list of assemblies that my EXE file is using that need to be on client machines, so I can package the correct files in a setup file without using the Visual Studio setup system. The problem is, I don't want to pick up any .NET framework assemblies, and I want it to be an automatic process that is easy to roll out whenever a major update is finished. The ultimate solution would be that there is an IsFramework property... :) A: To accomplish this I'm using the Product Name embedded within the assembly through the AssemblyProductAttribute. var attribute = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0] as AssemblyProductAttribute; var isFrameworkAssembly = (attribute.Product == "Microsoft® .NET Framework"); I'm using this technique to group assemblies by product under the About screen of the application and it seems to work just fine for me. A: I have had to deal with the exact same issue. Unfortunately, all answers given so far are insufficient to safely determine if an assembly is part of the .NET Framework. Microsoft puts a class named FXAssembly into the global namespace of each framework assembly with a const string indicating the version: .class private abstract auto ansi sealed beforefieldinit FXAssembly extends [mscorlib]System.Object { .field assembly static literal string Version = string('2.0.0.0') } Use this "marker" to check if an assembly is a framework assembly. Checking the public key too won't hurt either. A: I suspect that the method both most reliable and most general is going to be the PublicKeyToken. Yes, there's more than one, but it's going to be a finite list and one that doesn't change very often. For that matter, you could just have a whitelist of assembly names -- that list, too, will be both finite and static between versions of the framework. A: When you install Visual Studio, you get the reference assemblies in various subfolders of the form C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\{FrameworkName}\{FrameworkVersion} - the most interesting thing could be the RedistList\FrameworkList.xml file that contains a list of all assembly names that were shipped with the given framework version. E.g. C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\RedistList\FrameworkList.xml seems to contain a list of all of .NET 4.0's Framework assemblies. You could easily use these files to establish static white lists of assemblies. A: No, it doesn't begin with "System". You could check "WindowsBase" which is a framework assembly. You can't also check the PublicKeyToken, because there are other Microsoft assemblies signed with the "default" keys, but they are not part of the .NET Framework (Visual Studio assemblies). The best way of doing it is to get a collection of installed .NET frameworks and check if the target assembly is part of their RedistList (RedistList\FrameworkList.xml). FrameworkList.xml can be found in: * *.NET 2.0: C:\Windows\Microsoft.NET\Framework64\v2.0.50727\RedistList *.NET 3.x: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\vVersionNumber\RedistList *.NET 4.x: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\vVersionNumber\RedistList *.NET Core: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\vVersionNumber\RedistList A: You could use reflection to look at the publisher of the assembly, and coordinate that with the assembly's path. If you find an assembly whose publisher is Microsoft, and which exists somewhere below C:\Windows\Microsoft.NET\Framework it's a safe bet it's part of the runtime. On second thought, the publisher may not even be necessary. Anything under that path should be part of the runtime (barring a misbehaving application that's diddling where it shouldn't be). A: If you know that none of your DLLs will be in the GAC you could check whether each assembly is in the GAC or not. If it is, don't copy it. If it isn't, then do copy it. There is a property on the Assembly class called GlobalAssemblyCache. This would obviously work better in some situations than in others.
{ "language": "en", "url": "https://stackoverflow.com/questions/52134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: What are the (technical) pros and cons of Flash vs AJAX/JS? We provide a web application with a frontend completely developed in Adobe Flash. When we chose Flash 6 years ago, we did so for its large number of features for user interaction, like dragging stuff, opening and closing menus, tree navigation elements, popup dialogs etc. Today it's obvious that AJAX/JS offers roughly the same possibilities and because of the number of frameworks that are readily available, it's very feasible to implement them. Is there a technical reason one should choose either technology over the other? By "technical", I mean performance, security, portability/compatibility and the like. I don't mean aspects such as the very non-programmer way development is done in Flash or whether it makes sense to switch an app from one to the other. As I just explained in another question, it seems to me that JS is way ahead in terms of market share and I'm wondering whether we are missing some important point if we stick to Flash. A: In addition to what others have said, Flash is constrained in the "rectangle" and cannot be added to a normal html page in an un-obtrusive manner. @Gulzar I think when more browsers will support the video tag like mozilla 3.1 does we'll see even more adoption of ajax/js over flash. A: * *Adobe Actionscript is a statically typed language, Javascript is dynamically typed. Depending on your point of view, this may be a good thing or a bad thing. *With Javascript/HTML/CSS you're going to be heading into cross-browser compatibility hell, especially if you want to support older browsers. This can be mitigated by the libraries that are available, but it's still a big headache. With Flash, you write the code once and it just works in all browsers. *Even with the libraries available, Flash user controls are simply more advanced than anything you can find in the world of Javascript/HTML. In Javascript, you are not going to find anything that comes close to the simplicity and power of a databound user control that Flash provides. I don't see how Javascript has more of a "market share" than Flash. Pretty much anyone with a web browser has a Flash plugin installed. I'd be curious to know how many people disable Javascript but have a Flash plugin. Also keep in mind that you're going to be in for a huge learning curve and lots of development time if you decide to switch your technology base so you'd really better have a good business reason to do it. This decision also has a lot to do with what your application does and who your install base is. Edit: I see people have mentioned that the iPhone doesn't have Flash support. I would expect this to change with the install base of the iPhone - Adobe would be crazy not to support it. A: * *Correctly designed AJAX apps are more googleable than Flash *Correctly designed AJAX apps are more easily deep linkable than Flash *AJAX doesn't require a plugin (Flash is pretty ubiquitous, so it's not really a big deal)* *AJAX isn't controlled by a single company the way Flash is Edited to add: * Except for the iPhone, as Abdu points out. A: JS and Flash both have great presence on the web with overlapping capabilities. One area JS is still lacking is in rendering video. A: Flash, used well, allows easy localization and internationalization. Furthermore, it is much easier to use Flash in an accessible manner; you can feed screen readers the right text, instead of having them iterate over all of the possible form elements. A: I think Flash should be limited to online games, videos and animation. Otherwise use html and Ajax. It's a web standard and supported by almost all devices. AFAIK, the iPhone doesn't support Flash. That's a fast growing segment you're blocking out already. Keep it simple and efficient. A: Although flash is pretty ubiquitous on desktop browsers, mobile support is very limited (flash lite? yeah, right). I get really frustrated looking up a restaurant on my phone only to find the entire site is flash based and I can't even get a phone number or address! A: One benefit of Flash is that it has a few facilities to help do cross domain type operations safely, which can be helpful. Flash also has (limited) support for some hardware, which is not possible with Javascript. Personally, I'd try to use as much Ajax as possible before turning to something like Flash. From the UI perspective, it is better in that the controls and basic authoring is a little more developed. The Sound Manager project is a good example of effectively using a small amount of Flash while keeping the remainder in Javascript. A: I suspect one of the reasons javascript is becoming more popular is that it's more easy to retrofit into an existing application. A: As I can't accept two answers, I'm going to merge Christ Upchurch's and 17 of 26's answers in my own post. I think, these two together pretty much sum up what I wanted to know. Thanks guys! A: If you're dealing a lot with polygons, then Flash is still easier to program and debug. With AJAX there are a lot of libraries to handle polygons, but the more libraries your app uses, the slower it gets.
{ "language": "en", "url": "https://stackoverflow.com/questions/52140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: VB6 Runtime Type Retrieval How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime? i.e. something like: If Typeof(foobar) = "CommandButton" Then ... /EDIT: to clarify, I need to check on Dynamically Typed objects. An example: Dim y As Object Set y = CreateObject("SomeType") Debug.Print( <The type name of> y) Where the output would be "CommandButton" A: I think what you are looking for is TypeName rather than TypeOf. If TypeName(foobar) = "CommandButton" Then DoSomething End If Edit: What do you mean Dynamic Objects? Do you mean objects created with CreateObject(""), cause that should still work. Edit: Private Sub Command1_Click() Dim oObject As Object Set oObject = CreateObject("Scripting.FileSystemObject") Debug.Print "Object Type: " & TypeName(oObject) End Sub Outputs Object Type: FileSystemObject A: TypeName is what you want... Here is some example output: VB6 Code: Private Sub cmdCommand1_Click() Dim a As Variant Dim b As Variant Dim c As Object Dim d As Object Dim e As Boolean a = "" b = 3 Set c = Me.cmdCommand1 Set d = CreateObject("Project1.Class1") e = False Debug.Print TypeName(a) Debug.Print TypeName(b) Debug.Print TypeName(c) Debug.Print TypeName(d) Debug.Print TypeName(e) End Sub Results: String Integer CommandButton Class1 Boolean A: I don't have a copy of VB6 to hand, but I think you need the Typename() function... I can see it in Excel VBA, so it's probably in the same runtime. Interestingly, the help seems to suggest that it shouldn't work for a user-defined type, but that's about the only way I ever do use it. Excerpt from the help file: TypeName Function Returns a String that provides information about a variable. Syntax TypeName(varname) The required varname argument is a Variant containing any variable except a variable of a user-defined type. A: This should prove difficult, since in VB6 all objects are COM (IDispatch) things. Thus they are only an interface. TypeOf(object) is class probably only does a COM get_interface call (I forgot the exact method name, sorry).
{ "language": "en", "url": "https://stackoverflow.com/questions/52160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: BNF grammar test case generation Does anyone have any experience with a tool that generates test strings from a BNF grammar that could then be fed into a unit test? A: I don't have an answer to the tool question, but I will say it is fairly easy in any text processing language (perl/python/etc) to randomly generate sentences from a BNF grammar, and slightly more verbose in a bigger language (Java/C/etc), but it shouldn't be too hard to roll your own. The problem with this, of course, is that it can only generate strings in the grammar, and unless your grammar is very simple, the test space is infinitely large. A: I've done exactly as hazzen commented (using an embedded DSL in a scripting language). It was a mildly interesting exercise, but except for the most basic tests of e.g. parsing, it wasn't terribly useful. Most of my most interesting tests have to do with more sophisticated relationships than one can easily express in BNF (or any other context-free grammar). A: If, say, you're developing a compiler, then you likely have an abstract syntax tree datatype. If so, then you could write a function to generate an random AST -- with that, you can print it to a string and feed that to your unit test. It's guaranteed to be a valid program this way, since you started with your AST. If I were writing a compiler in Haskell or ML, this is what I would do, using QuickCheck. A: Gramtest is one such tool that can generate strings from arbitrary user defined BNF grammars. You can read more details about the algorithm behind Gramtest here and some practical tips on the tool are available here.
{ "language": "en", "url": "https://stackoverflow.com/questions/52167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: SQL Server2005 memory locking I've noticed that SQL Server 2005 x64 does not seem to lock pages into memory the same way SQL Server 2000 did. In 2000 I could easily see from task manager that SQL had locked 8GB of ram with AWE. I'm fairly certain I've got 2005 setup in an equivalent way. Is this a normal x64 difference or am I forgetting a crucial setup option? A: SQL Server 2005 x64 certainly doesn't need, or use, AWE; AWE is only to allow it to use > 4GB on 32 bit systems. You can use the old lock-pages-in-memory trick, but as this KB shows (http://support.microsoft.com/kb/918483): "Note For 64-bit editions of SQL Server 2005, only SQL Server 2005 Enterprise Edition can use the Lock pages in memory user right." A: I've seen permissions problems crop up a lot too - if the account you're using for the SQL Server service doesn't have the right permissions, it can't lock pages in memory even if you're running Enterprise Edition. This blog entry by the PSS SQL Server Engineers is really helpful: PSS Engineers: Do I have to assign the Lock Pages in Memory privilege for Local System?
{ "language": "en", "url": "https://stackoverflow.com/questions/52169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Unmovable Files on Windows XP When I defragment my XP machine I notice that there is a block of "Unmovable Files". Is there a file attribute I can use to make my own files unmovable? Just to clarify, I want a way to programmatically tell Windows that a file that I create should be unmovable. Is this possible, and if so, how can I do it? Thanks, Terry A: A lot of system files cannot be moved after the system boots, such as the page file and registry database files. This utility runs before Windows boots to defragment those files. I have it set to run at every boot, and it works well for me on several machines. Note that the very first time you boot up with this utility set to run, it may take several minutes to defrag. After that first run though, it finishes in just 3 or 4 seconds. Edit0: To respond to your clarification- that link says windows has marked the page file and registry files as open for exclusive access. So you should be able to do the same thing with the LockFile API Call. However, that's not an attribute of the file itself. You'd have to actually run some background program that locks the file for exclusive access. A: There are no file attributes that you can place on your files to mark them as immovable. The only way that a file cannot be moved (I think) during defragmentation is to have some other process have the file open (for read or write, I'm not even sure that you need to have the file open in exclusive mode or not). Quite frankly, I cannot think of a reason that you'd want your files not to move, unless you have specific requirements about where on the disk platter your files reside. Defragmentation should generally lead to faster disk access and that seems to be desireable in all cases :-) A: This usually means that the file is in use by some process. If you're defragmenting, you'll likely see this with a lot of system files. If the file should legitimately be movable and is stuck (it's being held by a process that runs at startup but shouldn't be, for example), the most useful way of resolving the problem is to remove all permissions on the file, reboot, restore the permissions, and then get rid of the file/run the program that's trying to use it. A: I suppose the ugly way is to have an application boot on startup, check every few seconds if defrag is running and if so open the file in exclusive mode. This is really ugly and I don't recommend it unless there is no cleaner solution. A: Terry, the answers all mention ways to prevent files from becoming unmovable during defragmentation. From your question it appears that you are in fact wanting to make your personal files unmovable. Can you please clarify what is appealing about making your files unmovable. A: I assume you're using the defragger that comes with Windows. Some commercial ones like DiskKeeper can move some of these files (usually system files). You can try their trial versions. A: Contig might serve your purpose http://technet.microsoft.com/en-us/sysinternals/bb897428.aspx I'm relatively certain I ran across some methods/attributes you could access programatically to do exactly what you want. This was back in NT4 days though and my memory isn't that good. A: For a little more complete solution try Raxco's PerfectDisk. While it is a commercial product it does a very good job and supports boot time defrag of system files. The first defrag takes longer than say DiskKeeper but its a single pass defragger and supports defragging with very little free space left on the drive. Overall its a much smarter defrag program then any other I've seen and supports systems of any size. http://www.raxco.com/ A: first try to move(or delete) the files within safe mode. If can not, try to move(or delete) the files with linux. But be careful if those are the windows system files, then you are failed to boot up your windows. Some reason why the files are unmovable are : the file size is too big, the files are being in open/in use condition, insufficient security privileges, being access by other computer/s, and many other things.
{ "language": "en", "url": "https://stackoverflow.com/questions/52172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What are the core mathematical concepts a good developer should know? Since Graduating from a very small school in 2006 with a badly shaped & outdated program (I'm a foreigner & didn't know any better school at the time) I've come to realize that I missed a lot of basic concepts from a mathematical & software perspective that are mostly the foundations of other higher concepts. I.e. I tried to listen/watch the open courseware from MIT on Introduction to Algorithms but quickly realized I was missing several mathematical concepts to better understand the course. So what are the core mathematical concepts a good software engineer should know? And what are the possible books/sites you will recommend me? A: "Proof by induction" is a core mathematical concept for programmers to know. A: Big O notation in general algorithm analysis, and in relation to standard collections (sorting, retrieval insertion and deletion) A: For discrete math, here is an awesome set of 20 lectures from Arsdigita University. Each is about an hour and twenty minutes long. A: Start with what we CS folks call "discrete math". Calculus and linear algebra can come in quite handy too because they get your foot in the door to a lot of application domains. Once you've mastered those three, go for probability theory. Those 4 will get you to competency in 95% (I made that up) of application domains. A: Concrete Mathematics covers most of the major topics. A good book on Discrete Math, like Rosen's Discrete Mathematics and Its Applications, will fill in any gaps. A: Math for Programmers. A good read. A: I think it depends on your focus. A few years ago I purchased the set of Art of Computer Programming by Donald Knuth. After looking at the books I realized pretty much everything is calculus proofs. If you're interested in developing your own generic algorithms and proofs for them, then I recommend being able to understand the above books since its what you'd be dealing with in that world. On the other hand if you only want/need to use various sorting/searching/tree/etc... routines then big O notation at a minimum, boolean math, and general algebra will be fine. If you're dealing with 3D then geometry and trig as well. I tend to be more on the using side than making proofs, and while I'd like to think I've done some clever things over the years I've never sat down and developed a new sorting routine. The best advice I can give is learn what you need for your field, but expose yourself to higher levels so you know it exists and how much more there is to learn, you won't get much growth otherwise. A: I would say boolean logic. AND, OR, XOR, NOT. I found as programmer we use this more often than the rest of math concepts. A: Basic Algebra and Statistics are good starting points, and the foundation for a lot of other fields. A: Here is a simple one that baffles me when I see developers that don't understand it: - Order of Operations A: Chapter 1 of "The Art of Computer Programming" aims to provide exactly this. A: Boolean algebra is fundamental to understanding control structures and refactoring. For example, I've seen many bugs caused by programmers who didn't know (or couldn't use) deMorgan's law. As another example, how many programmers immediately recognize that if (condition-1) { if (condition-2) { action-1 } else { action-2 } else { action-2 } can be rewritten as if (condition-1 and condition-2) { action-1 } else { action-2 } Discrete mathematics and combinatorics are tremendously helpful in understanding the performance of various algorithms and data structures. As mentioned by Baltimark, mathematical induction is very useful in reasoning about loops and recursion. Set theory is the basis of relational databases and SQL. By way of analogy, let me point out that carpenters routinely use a variety of rule-of-thumb techniques in constructing things like roofs and stairs. However, a knowledge of geometry allows you to solve problems for which you don't have a "canned" rule of thumb. It's like learning to read via phonetics versus sight-recognition of a basic vocabulary. 90+% of the time there's not much difference. But when you run into an unfamiliar situation, it's VERY nice to have the tools to work out the solution yourself. Finally, the rigor/precision required by mathematics is very useful preparation for programming, regardless of specific technique. Again, many of the bugs in programming (or even specifications) that I've seen in my career have sloppy thinking at their root cause. A: I would go with the fields that Landon stated: Discrete Math, Linear Algebra, Combinatorics, Probability and Statistics, Graph Theory and add mathematical logic. This would give you a grip on most fields of CS. If you want to go into special fields, you have to dive into some areas especially: Computer graphics -> Linear Algebra Gaming -> Linear Algebra, Physics Computer Linguistics -> Statistics, Graph Theory AI -> Statistics, Stochastics, Logic, Graph Theory A: In order of importance: * *Counting (needed for loops) *Addition, subtraction, multiplication, division. *Algebra (only really required to understand the use of variables). *Boolean algebra, boolean logic and binary. *Exponents and logarithms (i.e. understand O(n) notation). Anything more advanced than that is usually algorithm-specific or domain-specific. Depending on which areas you are interested in, the following may also be relevant: * *Linear algebra and trigonometry (3D visualization) *Discrete mathematics and set theory (database design, algorithm design, compiler design). *Statistics (well, for statistical and/or scientific/economic applications. possibly also useful for algorithm design). *Physics (for simulations). Understanding functions is also useful (don't remember what the mathematical term is for that area), but if you know how to program you probably already do. My point being: A ten year old should know enough mathematics to be able to understand programming. There isn't really much math required for the basic understanding of things. It's all about the logic, really. A: There was a book that was recommended...the title was something like Concrete Mathematics. It was recommended in a few questions. A: Back in school, on of my instructors said for business applications, all you need to know know add, subtract, multiply, and divide. All other formulas the requester will know and inform you what is needed. Now realize that this is for financing reporting and application focused school. To this day, this has held true for me. I have never once needed to know more than that. A: Check the book Foundations of Computer Science This book is authored by: Al Aho and Jeff Ullman and the entire book is available online. This is what the authors say in their Preface about the goal of this book: "Foundations of Computer Science covers subjects that are often found split between a discrete mathematics course and a sophomore-level sequence in computer science in data structures. It has been our intention to select the mathematical foundations with an eye toward what the computer user really needs, rather than what a mathematician might choose." A: a site for brushing up on Math: http://www.khanacademy.org/ A: My math background is really poor (Geologist by training), but I took a discrete math class in high school and I use the concepts every day as a programmer. It is probably the most valuable class I took in all of my education as it relates to my current profession. A: Discrete Math Linear Algebra Combinatorics Probability and Statistics Graph Theory A: * *Boolean Algebra *Set Theory *Discrete Math A: Well, that depends on what you goal is. As someone said, Linear Algebra, Combinatorics, Probability and Statistics and Graph Theory are important if you're into solving hard problems. Asymptotic growth of functions (bit-Oh notation) is very important. You will also need to master summations and series if you need to work on analyzing some more complex algorithms (see the appendix on Cormen&others Intro to Algorithms). Even if you're into "Java for the enterprise" or "server-side PHP", you will find some Statistics and Algorithm Complexity (hence combinatorics, induction, summations, series, etc) useful when your boss wants you to get the server to work faster, and adding new hardware doesn't seem to help. :-) I've been through that once. A: * *Boolean Algebra *Set Theory A: Why is everybody including probability and statistics in the gold list without mentioning calculus? One cannot understand what probability and statistics are about without at least a working knowledge of limits, derivatives, integrals and series. And all in all, calculus (together with linear algebra) is the workhorse of all mathematics. A: I think algorithms and theory are of great importance. Being able to come up with a fast, and correct solution is what differentiates good programmers from the rest. Also, being able to prove your algorithm (using standard proof techniques-- induction, contradiction, etc) is equally important. A: Yeah, I would say a basic understanding of induction helps so that you understand what n represents in algorithms. Also some Logic and Discrete Structures is helpful. A: Probability and Statistics are very helpful if you ever have to do anything resembling machine learning. I cover the basics in my "Computing Your Skill" blog post where I discuss how Xbox Live's TrueSkill ranking and matchmaking algorithm works.
{ "language": "en", "url": "https://stackoverflow.com/questions/52176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: Virtual Serial Port for Linux I need to test a serial port application on Linux, however, my test machine only has one serial port. Is there a way to add a virtual serial port to Linux and test my application by emulating a device through a shell or script? Note: I cannot remap the port, it hard coded on ttys2 and I need to test the application as it is written. A: You may want to look at Tibbo VSPDL for creating a linux virtual serial port using a Kernel driver -- it seems pretty new, and is available for download right now (beta version). Not sure about the license at this point, or whether they want to make it available commercially only in the future. There are other commercial alternatives, such as http://www.ttyredirector.com/. In Open Source, Remserial (GPL) may also do what you want, using Unix PTY's. It transmits the serial data in "raw form" to a network socket; STTY-like setup of terminal parameters must be done when creating the port, changing them later like described in RFC 2217 does not seem to be supported. You should be able to run two remserial instances to create a virtual nullmodem like com0com, except that you'll need to set up port speed etc in advance. Socat (also GPL) is like an extended variant of Remserial with many many more options, including a "PTY" method for redirecting the PTY to something else, which can be another instance of Socat. For Unit tets, socat is likely nicer than remserial because you can directly cat files into the PTY. See the PTY example on the manpage. A patch exists under "contrib" to provide RFC2217 support for negotiating serial line settings. A: You can use a pty ("pseudo-teletype", where a serial port is a "real teletype") for this. From one end, open /dev/ptyp5, and then attach your program to /dev/ttyp5; ttyp5 will act just like a serial port, but will send/receive everything it does via /dev/ptyp5. If you really need it to talk to a file called /dev/ttys2, then simply move your old /dev/ttys2 out of the way and make a symlink from ptyp5 to ttys2. Of course you can use some number other than ptyp5. Perhaps pick one with a high number to avoid duplicates, since all your login terminals will also be using ptys. Wikipedia has more about ptys: http://en.wikipedia.org/wiki/Pseudo_terminal A: Using the links posted in the previous answers, I coded a little example in C++ using a Virtual Serial Port. I pushed the code into GitHub: https://github.com/cymait/virtual-serial-port-example . The code is pretty self explanatory. First, you create the master process by running ./main master and it will print to stderr the device is using. After that, you invoke ./main slave device, where device is the device printed in the first command. And that's it. You have a bidirectional link between the two process. Using this example you can test you the application by sending all kind of data, and see if it works correctly. Also, you can always symlink the device, so you don't need to re-compile the application you are testing. A: Use socat for this: For example: socat PTY,link=/dev/ttyS10 PTY,link=/dev/ttyS11 A: Would you be able to use a USB->RS232 adapter? I have a few, and they just use the FTDI driver. Then, you should be able to rename /dev/ttyUSB0 (or whatever gets created) as /dev/ttyS2 . A: I can think of three options: Implement RFC 2217 RFC 2217 covers a com port to TCP/IP standard that allows a client on one system to emulate a serial port to the local programs, while transparently sending and receiving data and control signals to a server on another system which actually has the serial port. Here's a high-level overview. What you would do is find or implement a client com port driver that would implement the client side of the system on your PC - appearing to be a real serial port but in reality shuttling everything to a server. You might be able to get this driver for free from Digi, Lantronix, etc in support of their real standalone serial port servers. You would then implement the server side of the connection locally in another program - allowing the client to connect and issuing the data and control commands as needed. It's probably non trivial, but the RFC is out there, and you might be able to find an open source project that implements one or both sides of the connection. Modify the linux serial port driver Alternately, the serial port driver source for Linux is readily available. Take that, gut the hardware control pieces, and have that one driver run two /dev/ttySx ports, as a simple loopback. Then connect your real program to the ttyS2 and your simulator to the other ttySx. Use two USB<-->Serial cables in a loopback But the easiest thing to do right now? Spend $40 on two serial port USB devices, wire them together (null modem) and actually have two real serial ports - one for the program you're testing, one for your simulator. -Adam A: $ socat -d -d pty,link=/tmp/vserial1,raw,echo=0 pty,link=/tmp/vserial2,raw,echo=0 Will generate symlinks of /tmp/vserial1 and /tmp/vserial2 for generated virtual serial ports in /dev/pts/* Resource A: Complementing the @slonik's answer. You can test socat to create Virtual Serial Port doing the following procedure (tested on Ubuntu 12.04): Open a terminal (let's call it Terminal 0) and execute it: socat -d -d pty,raw,echo=0 pty,raw,echo=0 The code above returns: 2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/2 2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/3 2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs [3,3] and [5,5] Open another terminal and write (Terminal 1): cat < /dev/pts/2 this command's port name can be changed according to the pc. it's depends on the previous output. 2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**2** 2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**3** 2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs you should use the number available on highlighted area. Open another terminal and write (Terminal 2): echo "Test" > /dev/pts/3 Now back to Terminal 1 and you'll see the string "Test". A: There is also tty0tty http://sourceforge.net/projects/tty0tty/ which is a real null modem emulator for linux. It is a simple kernel module - a small source file. I don't know why it only got thumbs down on sourceforge, but it works well for me. The best thing about it is that is also emulates the hardware pins (RTC/CTS DSR/DTR). It even implements TIOCMGET/TIOCMSET and TIOCMIWAIT iotcl commands! On a recent kernel you may get compilation errors. This is easy to fix. Just insert a few lines at the top of the module/tty0tty.c source (after the includes): #ifndef init_MUTEX #define init_MUTEX(x) sema_init((x),1) #endif When the module is loaded, it creates 4 pairs of serial ports. The devices are /dev/tnt0 to /dev/tnt7 where tnt0 is connected to tnt1, tnt2 is connected to tnt3, etc. You may need to fix the file permissions to be able to use the devices. edit: I guess I was a little quick with my enthusiasm. While the driver looks promising, it seems unstable. I don't know for sure but I think it crashed a machine in the office I was working on from home. I can't check until I'm back in the office on monday. The second thing is that TIOCMIWAIT does not work. The code seems to be copied from some "tiny tty" example code. The handling of TIOCMIWAIT seems in place, but it never wakes up because the corresponding call to wake_up_interruptible() is missing. edit: The crash in the office really was the driver's fault. There was an initialization missing, and the completely untested TIOCMIWAIT code caused a crash of the machine. I spent yesterday and today rewriting the driver. There were a lot of issues, but now it works well for me. There's still code missing for hardware flow control managed by the driver, but I don't need it because I'll be managing the pins myself using TIOCMGET/TIOCMSET/TIOCMIWAIT from user mode code. If anyone is interested in my version of the code, send me a message and I'll send it to you. A: Combining all other amazingly useful answers, I found the below command to be VERY useful for testing on different types of Linux distros where there's no guarantee you're going to get the same /dev/pts/#'s every time and/or you need to test multiple psuedo serial devices and connections at once. parallel 'i="{1}"; socat -d -d pty,raw,echo=0,link=$HOME/pty{1} pty,raw,echo=0,link=$HOME/pty$(($i+1))' ::: $(seq 0 2 3;) Breaking this down: parallel runs the same command for each argument supplied to it. So for example if we run it with the --dryrun flag it gives us: i="0"; socat -d -d pty,raw,echo=0,link=$HOME/pty0 pty,raw,echo=0,link=$HOME/pty$(($i+1)) i="2"; socat -d -d pty,raw,echo=0,link=$HOME/pty2 pty,raw,echo=0,link=$HOME/pty$(($i+1)) This is due to the $(seq x y z;) at the end, where x = start #, y = increment by, and z = end # (or # of devices you need to spawn) parallel 'i="{1}"; echo "make psuedo_devices {1} $(($i+1))"' ::: $(seq 0 2 3;) Outputs: make psuedo_devices 0 1 make psuedo_devices 2 3 Gathering all this together the final above command symlinks the proper psuedo devices together regardless of whats in /dev/pts/ to whatever directory supplied to socat via the link flag. pstree -c -a $PROC_ID gives: perl /usr/bin/parallel i="{1}"; socat -d -d pty,raw,echo=0,link=$HOME/pty{1} pty,raw,echo=0,link=$HOME/pty$(($i+1)) ::: 0 2 ├─bash -c i="0"; socat -d -d pty,raw,echo=0,link=$HOME/pty0 pty,raw,echo=0,link=$HOME/pty$(($i+1)) │ └─socat -d -d pty,raw,echo=0,link=/home/user/pty0 pty,raw,echo=0,link=/home/user/pty1 └─bash -c i="2"; socat -d -d pty,raw,echo=0,link=$HOME/pty2 pty,raw,echo=0,link=$HOME/pty$(($i+1)) └─socat -d -d pty,raw,echo=0,link=/home/user/pty2 pty,raw,echo=0,link=/home/user/pty3 ls -l $HOME/pty* yield: lrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty0 -> /dev/pts/4 lrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty1 -> /dev/pts/6 lrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty2 -> /dev/pts/7 lrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty3 -> /dev/pts/8 This was all because I was trying running tests against a platform where I needed to generated a lot of mach-serial connections and to test their input/output via containerization (Docker). Hopefully someone finds it useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/52187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "178" }
Q: Browser refresh behaviour When a user hits Refresh on their browser, it reloads the page but keeps the contents of form fields. While I can see this being a useful default, it can be annoying on some dynamic pages, leading to a broken user experience. Is there a way, in HTTP headers or equivalents, to change this behaviour? A: This should do the trick: <body onload="document.FormName.reset();"> Replace FormName with the name of your form and then all the fields will be reset when the user clicks refresh in his browser. Or if you only want to reset some fields, add this to the bottom of your page: <script type="text/javascript"> document.getElementById('field1').value =''; document.getElementById('field2').value =''; document.getElementById('field3').value =''; </script> That will reset the fields every time a user enters the page, including refreshes A: Add the autocomplete attribute set to "off" to the inputs you don't want to be refreshed. For instance: <input type="text" name="pin" autocomplete="off" /> see the W3C reference although not mentioned in the reference, it works also with checkboxes, at least on firefox. A: <input autocomplete="off"> A: You could call the reset() method of the forms object from the body load event of your html document to clear the forms. h1. References * *MSDN reset Method - http://msdn.microsoft.com/en-us/library/ms536721(VS.85).aspx *Mozilla developer center form.reset A: I wonder, if you set the page not to be cached through meta tags, will that fix the problem? http://lists.evolt.org/archive/Week-of-Mon-20030106/131984.html If it does, it'll have the benefit of working on browser's with Javascript disabled. A: The data on forms are not part of w3c specification. It's a browser feature to make your life easy. So, if you don't want to keep the data after reloads, you can set all form's values to null after loading it, as Espo said. Even if the page is not cached, it will display the data on the form, because the data aren't part of the page's html code. You can try this too (don't know if it will work): <input type="text" name="foo" value="">
{ "language": "en", "url": "https://stackoverflow.com/questions/52213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Creating a Patch with TFS Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select Create Patch. But for the life of me, I can't find this functionality in TFS. Is this possible? If not, what's the standard way to submit patches in open source TFS hosted projects (a la CodePlex)? A: tf diff /shelveset:shelveset /format:unified Edit: This writes to standard output. You can pipe the output to a file. For more options, see Difference Command. A: Because TFS doesn't natively support patch files, the most common thing I see people do on CodePlex is simply zip the modified files and upload the zip. The project coordinator then does a diff against their own checkout. However since CodePlex also supports TortoiseSVN, more and more people are using that to create their patch files. A: I wrote a blog post about a similar issue where I used the TF.exe command and 7Zip to create a TFS patch file that could then be applied on another TFS server or workspace. I posted the the Powershell scripts at Github, which can be used to Zip up any pending changes on one workspace and then apply them to a different server. It would have to be modified to use a changeset instead of pending changes, but that shouldn't be too difficult to accomplish.
{ "language": "en", "url": "https://stackoverflow.com/questions/52234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: How can I highlight a table row using Prototype? How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag? An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful. A: You can use Prototype's addClassName and removeClassName methods. Create a CSS class "hilight" that you'll apply to the hilighted <tr>'s. Then run this code on page load: var rows = $$('tbody tr'); for (var i = 0; i < rows.length; i++) { rows[i].onmouseover = function() { $(this).addClassName('hilight'); } rows[i].onmouseout = function() { $(this).removeClassName('hilight'); } } A: A little bit generic solution: Let's say I want to have a simple way to make tables with rows that will highlight when I put mouse pointer over them. In ideal world this would be very easy, with just one simple CSS rule: tr:hover { background: red; } Unfortunately, older versions of IE don't support :hover selector on elements other than A. So we have to use JavaScript. In that case, I will define a table class "highlightable" to mark tables that should have hoverable rows. I will make the background switching by adding and removing the class "highlight" on the table row. CSS table.highlightable tr.highlight { background: red; } JavaScript (using Prototype) // when document loads document.observe( 'dom:loaded', function() { // find all rows in highlightable table $$( 'table.highlightable tr' ).each( function( row ) { // add/remove class "highlight" when mouse enters/leaves row.observe( 'mouseover', function( evt ) { evt.element().addClassName( 'highlight' ) } ); row.observe( 'mouseout', function( evt ) { evt.element().removeClassName( 'highlight' ) } ); } ); } ) HTML All you have to do now is to add class "highlightable" to any table you want: <table class="highlightable"> ... </table> A: I made a slight change to @swilliams code. $$('#thetable tr:not(#headRow)').each( This lets me have a table with a header row that doesn't get highlighted. <tr id="headRow"> <th>Header 1</th> </tr> A: <table id="mytable"> <tbody> <tr><td>Foo</td><td>Bar</td></tr> <tr><td>Bork</td><td>Bork</td></tr> </tbody> </table> <script type="text/javascript"> $$('#mytable tr').each(function(item) { item.observe('mouseover', function() { item.setStyle({ backgroundColor: '#ddd' }); }); item.observe('mouseout', function() { item.setStyle({backgroundColor: '#fff' }); }); }); </script> A: You can do something to each row, like so: $('tableId').getElementsBySelector('tr').each(function (row) { ... }); So, in the body of that function, you have access to each row, one at a time, in the 'row' variable. You can then call Event.observe(row, ...) So, something like this might work: $('tableId').getElementsBySelector('tr').each(function (row) { Event.observe(row, 'mouseover', function () {...do hightlight code...}); }); A: I found ab interesting solution for Rows background, the rows highlighting on mouse over, without JS. Here is link Works in all browsers. For IE6/7/8 ... tr{ position: relative; } td{ background-image: none } And for Safari I use negative background position for each TD.
{ "language": "en", "url": "https://stackoverflow.com/questions/52238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to recover or change Oracle sysdba password We are working with an oracle database in which the person that set it up is "long gone" and thus do not know the sysdba password, but need it. We have root access to the box (its on linux). Is there any way to recover or change the sys passwords? A: Have you tried logging into Linux as your installed Oracle user then sqlplus "/ as sysdba" When you log in you'll be able to change your password. alter user sys identified by <new password>; Good luck :) A: You can connect to the database locally using the combination of environment variables: * *ORACLE_HOME *ORACLE_SID . Depending on your OS: Unix/Linux: export ORACLE_HOME=<oracle_home_directory_till_db_home> export PATH=$PATH:$ORACLE_HOME/bin export ORACLE_SID=<your_oracle_sid> SQLPLUS / AS SYSDBA Windows set ORACLE_HOME=<oracle_home_path_till_db_home> set PATH=%PATH%||%ORACLE_HOME%\bin set ORACLE_SID=<your_oracle_sid> SQLPLUS / AS SYSDBA Once connected, you could then alter the user to modify the password: ALTER USER username IDENTIFIED BY password;
{ "language": "en", "url": "https://stackoverflow.com/questions/52239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How to check if a given user is a member of the built-in Administrators group? I need to check programmatically (in .NET) whether a given user (domain account) is a member of the built-in Administrators group on a current computer (the one where the application gets executed). Is it possible? A: I don't know about .Net, but in win32, the easy way is to call IsUserAnAdmin(). If you need more control, you can open the process token and check with CheckTokenMembership for each group you need to check Edit: See pinvoke.net for .NET sample code (Thanks chopeen) A: There is a Win32 API for this you could P/Invoke: IsUserAnAdmin The question is more complex on Vista ... see this blog post. A: You could loop the groups like i did in this answer: Determining members of local groups via C# After reading some more, the easiest thing would be to use the System.DirectoryServices.AccountManagement namespace. Here is how it can be used: http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx Sample: public static bool IsUserInGroup(string username, string groupname, ContextType type) { PrincipalContext context = new PrincipalContext(type); UserPrincipal user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, username); GroupPrincipal group = GroupPrincipal.FindByIdentity( context, groupname); return user.IsMemberOf(group); } A: If you are talking about the currently running user then using System.Security.Principal; WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal wp = new WindowsPrincipal(identity); if (wp.IsInRole("BUILTIN\Administrators")) // Is Administrator else // Is Not If not then I expect its possible to set identity to a particular user but not looked into how.
{ "language": "en", "url": "https://stackoverflow.com/questions/52256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iTunes warning message on quit due to scripting Wrote the following in PowersHell as a quick iTunes demonstration: $iTunes = New-Object -ComObject iTunes.Application $LibrarySource = $iTunes.LibrarySource foreach ($PList in $LibrarySource.Playlists) { write-host $PList.name } This works well and pulls back a list of playlist names. However on trying to close iTunes a warning appears One or more applications are using the iTunes scripting interface. Are you sure you want to quit? Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it? Itunes 7.7.1, Windows XP A: Here is one thing that I did on my a Powershell script that adds podcasts to iTunes. I use Juice on a server to download all the podcasts that I listen to. The script uses .Net methods to release the COM objects. When I wrote my iTunes script I had read a couple of articles that stated you should release your COM objects using .NET. [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$LibrarySource) [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$iTunes) I also run my scripts the majority of time from a shortcut, not from the powershell prompt. Based on your comments, I did some testing and I determined that I would get the message when running against iTunes, if I ran my script in a way that leaves powershell running. iTunes seems to keep track of that. Running the script in a manner that exits it's process after running, eliminated the message. One method of running your script from powershell, is to prefix your script with powershell. powershell .\scriptname.ps1 The above command will launch your script and then exit the process that was used to run it, but still leaving you at the powershell prompt. A: You should be able to set $itunes to $null. Alternatively, $itunes should have a quit method you can call. $itunes.quit()
{ "language": "en", "url": "https://stackoverflow.com/questions/52286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Templates of Technical and Functional Specs So basically I am looking for good templates for writing both technical and functional specs on a project or work request. What do you use? How deep do you get while writing the specs? Any additional general tips you could provide would be appreciated. My company needs these badly. I work for a contractor and right now we do not use these documents at all. EDIT: I have read Joel's take about Painless Specification, I really liked it, but are there any other opinions :) A: You can buy templates from ieee and other places, but I have always ended up making my own. For a technical spec, "Code Complete" by Steve McDonnell has a good checklist, you can draw some info from that. At my last job, I just made a template out of his section headers, and tweaked it from there. As far as a functional spec, the important thing is to define all the interfaces: * *UI (screen mockups) *Software interfaces (plugins, etc.) *Hardware interfaces (if appropriate) *Communications interfaces (Services, email, messaging, etc.) There should also be a section for business rules, things that are important functionally that are not covered in any interface definition. A: If you want to purchase a book, Software Requirements by Karl Wiegers has templates for a few documents as an appendix. Unfortunately, I'm at work and that particular book is at home. If someone has it handy, they might be able to confirm that. A: I happen to like this one, among others: ReadySet. He sells a pro version too. A: This is the best one I have found: http://www.jiludwig.com/templates/FRDTemplate.doc A: On general tips; We are implementing a process of 1) Business Requirements Statement (BRS) 2) Functional Specification 3) Technical specification The BRS covers what the business problems are, and what the requirements are around solutions, testing, security, reliability and delivery. This defines what would make a successful solution. The functional spec details what is needed, how it should look, how long fields should be, etc. The technical spec details where the data comes from, any tricky code that may need to be considered. The customer owns the requirements. The developers own the tech specs, and the functional spec is a middle ground. Testing is done against the tech specs (usually unit testing) then against the functional specs (usually system testing) and then against the requirements (UAT). The important part of this (and we are struggling with) is that the developers still need to deliver to the functional spec, and the original business requirements. In reality the functional and tech specs are just there for clarity. In short, my main tip is to first work out the process you wish to implement. Then seek agreement from all parties involved in your proposed process, then work on the templates to fit. The templates themselves are only are a small part of the change you want to make. A: Start off simple, and work your way from there. Since this is your first experience working with this, use a word document with bullet points. Write it, re-read it and provide enough detail that it makes sense. For technical specifications, you may want to lead the developer toward a solution, but for functional specifications the "how" should be completely missing. A: I would suggest to have a look at the Roberston's Volere template here. They are part of the Atlantic Systems Guild, together with people like Tom DeMarco and Timothy Lister of "Peopleware" fame. As the template is copyrighted, I will not reproduce it here, but give you some of the main headers: * *The Purpose of the Project *The Stakeholders *Mandated Constraints *Naming Conventions and Terminology *Relevant Facts and Assumptions *The Scope of the Work *Business Data Model and Data Dictionary *The Scope of the Product *Functional Requirements *Look and Feels Requirements ... There are many more, but this should give you an idea. The most interesting part of the template is the requirements shell that lists functional requirements on a kind of cue card. Again copyrighted, but truly valuable. Look here in chapter 9. A: Not a template, but Joel has written a couple of articles on writing a functional spec. He also has sample here.
{ "language": "en", "url": "https://stackoverflow.com/questions/52290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: Determine size of page via HttpModule Here's an easy one for you: I'm currently logging request duration via an HttpModule and I'd like to find out the number of bytes each page is as well. HttpContext.Current.Response.OutputStream.Length throws a NotSupportedException. What's an easy way to do this? A: I have an HttpModule that implements a stream rewriter. It derives from the Stream class. In my HttpModule I have the following code: void app_PreRequestHandlerExecute(object sender, EventArgs e) { HttpResponse response = HttpContext.Current.Response; response.Filter = new MyRewriterStream(response.Filter); } In the stream class I have the following code that overrides the default Write method: public override void Write(byte[] buffer, int offset, int count) { string outStr; outStr = UTF8Encoding.UTF8.GetString(buffer, offset, count); //Do useful stuff and write back to the stream } You can just take the length of the string at the second point
{ "language": "en", "url": "https://stackoverflow.com/questions/52311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the real overhead of try/catch in C#? So, I know that try/catch does add some overhead and therefore isn't a good way of controlling process flow, but where does this overhead come from and what is its actual impact? A: Contrary to theories commonly accepted, try/catch can have significant performance implications, and that's whether an exception is thrown or not! * *It disables some automatic optimisations (by design), and in some cases injects debugging code, as you can expect from a debugging aid. There will always be people who disagree with me on this point, but the language requires it and the disassembly shows it so those people are by dictionary definition delusional. *It can impact negatively upon maintenance. This is actually the most significant issue here, but since my last answer (which focused almost entirely on it) was deleted, I'll try to focus on the less significant issue (the micro-optimisation) as opposed to the more significant issue (the macro-optimisation). The former has been covered in a couple of blog posts by Microsoft MVPs over the years, and I trust you could find them easily yet StackOverflow cares so much about content so I'll provide links to some of them as filler evidence: * *Performance implications of try/catch/finally (and part two), by Peter Ritchie explores the optimisations which try/catch/finally disables (and I'll go further into this with quotes from the standard) *Performance Profiling Parse vs. TryParse vs. ConvertTo by Ian Huff states blatantly that "exception handling is very slow" and demonstrates this point by pitting Int.Parse and Int.TryParse against each other... To anyone who insists that TryParse uses try/catch behind the scenes, this ought to shed some light! There's also this answer which shows the difference between disassembled code with- and without using try/catch. It seems so obvious that there is an overhead which is blatantly observable in code generation, and that overhead even seems to be acknowledged by people who Microsoft value! Yet I am, repeating the internet... Yes, there are dozens of extra MSIL instructions for one trivial line of code, and that doesn't even cover the disabled optimisations so technically it's a micro-optimisation. I posted an answer years ago which got deleted as it focused on the productivity of programmers (the macro-optimisation). This is unfortunate as no saving of a few nanoseconds here and there of CPU time is likely to make up for many accumulated hours of manual optimisation by humans. Which does your boss pay more for: an hour of your time, or an hour with the computer running? At what point do we pull the plug and admit that it's time to just buy a faster computer? Clearly, we should be optimising our priorities, not just our code! In my last answer I drew upon the differences between two snippets of code. Using try/catch: int x; try { x = int.Parse("1234"); } catch { return; } // some more code here... Not using try/catch: int x; if (int.TryParse("1234", out x) == false) { return; } // some more code here Consider from the perspective of a maintenance developer, which is more likely to waste your time, if not in profiling/optimisation (covered above) which likely wouldn't even be necessary if it weren't for the try/catch problem, then in scrolling through source code... One of those has four extra lines of boilerplate garbage! As more and more fields are introduced into a class, all of this boilerplate garbage accumulates (both in source and disassembled code) well beyond reasonable levels. Four extra lines per field, and they're always the same lines... Were we not taught to avoid repeating ourselves? I suppose we could hide the try/catch behind some home-brewed abstraction, but... then we might as well just avoid exceptions (i.e. use Int.TryParse). This isn't even a complex example; I've seen attempts at instantiating new classes in try/catch. Consider that all of the code inside of the constructor might then be disqualified from certain optimisations that would otherwise be automatically applied by the compiler. What better way to give rise to the theory that the compiler is slow, as opposed to the compiler is doing exactly what it's told to do? Assuming an exception is thrown by said constructor, and some bug is triggered as a result, the poor maintenance developer then has to track it down. That might not be such an easy task, as unlike the spaghetti code of the goto nightmare, try/catch can cause messes in three dimensions, as it could move up the stack into not just other parts of the same method, but also other classes and methods, all of which will be observed by the maintenance developer, the hard way! Yet we are told that "goto is dangerous", heh! At the end I mention, try/catch has its benefit which is, it's designed to disable optimisations! It is, if you will, a debugging aid! That's what it was designed for and it's what it should be used as... I guess that's a positive point too. It can be used to disable optimizations that might otherwise cripple safe, sane message passing algorithms for multithreaded applications, and to catch possible race conditions ;) That's about the only scenario I can think of to use try/catch. Even that has alternatives. What optimisations do try, catch and finally disable? A.K.A How are try, catch and finally useful as debugging aids? they're write-barriers. This comes from the standard: 12.3.3.13 Try-catch statements For a statement stmt of the form: try try-block catch ( ... ) catch-block-1 ... catch ( ... ) catch-block-n * *The definite assignment state of v at the beginning of try-block is the same as the definite assignment state of v at the beginning of stmt. *The definite assignment state of v at the beginning of catch-block-i (for any i) is the same as the definite assignment state of v at the beginning of stmt. *The definite assignment state of v at the end-point of stmt is definitely assigned if (and only if) v is definitely assigned at the end-point of try-block and every catch-block-i (for every i from 1 to n). In other words, at the beginning of each try statement: * *all assignments made to visible objects prior to entering the try statement must be complete, which requires a thread lock for a start, making it useful for debugging race conditions! *the compiler isn't allowed to: * *eliminate unused variable assignments which have definitely been assigned to before the try statement *reorganise or coalesce any of it's inner-assignments (i.e. see my first link, if you haven't already done so). *hoist assignments over this barrier, to delay assignment to a variable which it knows won't be used until later (if at all) or to pre-emptively move later assignments forward to make other optimisations possible... A similar story holds for each catch statement; suppose within your try statement (or a constructor or function it invokes, etc) you assign to that otherwise pointless variable (let's say, garbage=42;), the compiler can't eliminate that statement, no matter how irrelevant it is to the observable behaviour of the program. The assignment needs to have completed before the catch block is entered. For what it's worth, finally tells a similarly degrading story: 12.3.3.14 Try-finally statements For a try statement stmt of the form: try try-block finally finally-block • The definite assignment state of v at the beginning of try-block is the same as the definite assignment state of v at the beginning of stmt. • The definite assignment state of v at the beginning of finally-block is the same as the definite assignment state of v at the beginning of stmt. • The definite assignment state of v at the end-point of stmt is definitely assigned if (and only if) either: o v is definitely assigned at the end-point of try-block o v is definitely assigned at the end-point of finally-block If a control flow transfer (such as a goto statement) is made that begins within try-block, and ends outside of try-block, then v is also considered definitely assigned on that control flow transfer if v is definitely assigned at the end-point of finally-block. (This is not an only if—if v is definitely assigned for another reason on this control flow transfer, then it is still considered definitely assigned.) 12.3.3.15 Try-catch-finally statements Definite assignment analysis for a try-catch-finally statement of the form: try try-block catch ( ... ) catch-block-1 ... catch ( ... ) catch-block-n finally finally-block is done as if the statement were a try-finally statement enclosing a try-catch statement: try { try try-block catch ( ... ) catch-block-1 ... catch ( ... ) catch-block-n } finally finally-block A: In my experience the biggest overhead is in actually throwing an exception and handling it. I once worked on a project where code similar to the following was used to check if someone had a right to edit some object. This HasRight() method was used everywhere in the presentation layer, and was often called for 100s of objects. bool HasRight(string rightName, DomainObject obj) { try { CheckRight(rightName, obj); return true; } catch (Exception ex) { return false; } } void CheckRight(string rightName, DomainObject obj) { if (!_user.Rights.Contains(rightName)) throw new Exception(); } When the test database got fuller with test data, this lead to a very visible slowdown while openening new forms etc. So I refactored it to the following, which - according to later quick 'n dirty measurements - is about 2 orders of magnitude faster: bool HasRight(string rightName, DomainObject obj) { return _user.Rights.Contains(rightName); } void CheckRight(string rightName, DomainObject obj) { if (!HasRight(rightName, obj)) throw new Exception(); } So in short, using exceptions in normal process flow is about two orders of magnitude slower then using similar process flow without exceptions. A: I'm not an expert in language implementations (so take this with a grain of salt), but I think one of the biggest costs is unwinding the stack and storing it for the stack trace. I suspect this happens only when the exception is thrown (but I don't know), and if so, this would be decently sized hidden cost every time an exception is thrown... so it's not like you are just jumping from one place in the code to another, there is a lot going on. I don't think it's a problem as long as you are using exceptions for EXCEPTIONAL behavior (so not your typical, expected path through the program). A: Not to mention if it's inside a frequently-called method it may affect the overall behavior of the application. For example, I consider the use of Int32.Parse as a bad practice in most cases since it throws exceptions for something that can be caught easily otherwise. So to conclude everything written here: 1) Use try..catch blocks to catch unexpected errors - almost no performance penalty. 2) Don't use exceptions for excepted errors if you can avoid it. A: I wrote an article about this a while back because there were a lot of people asking about this at the time. You can find it and the test code at http://www.blackwasp.co.uk/SpeedTestTryCatch.aspx. The upshot is that there is a tiny amount of overhead for a try/catch block but so small that it should be ignored. However, if you are running try/catch blocks in loops that are executed millions of times, you may want to consider moving the block to outside of the loop if possible. The key performance issue with try/catch blocks is when you actually catch an exception. This can add a noticeable delay to your application. Of course, when things are going wrong, most developers (and a lot of users) recognise the pause as an exception that is about to happen! The key here is not to use exception handling for normal operations. As the name suggests, they are exceptional and you should do everything you can to avoid them being thrown. You should not use them as part of the expected flow of a program that is functioning correctly. A: Are you asking about the overhead of using try/catch/finally when exceptions aren't thrown, or the overhead of using exceptions to control process flow? The latter is somewhat akin to using a stick of dynamite to light a toddler's birthday candle, and the associated overhead falls into the following areas: * *You can expect additional cache misses due to the thrown exception accessing resident data not normally in the cache. *You can expect additional page faults due to the thrown exception accessing non-resident code and data not normally in your application's working set. * *for example, throwing the exception will require the CLR to find the location of the finally and catch blocks based on the current IP and the return IP of every frame until the exception is handled plus the filter block. *additional construction cost and name resolution in order to create the frames for diagnostic purposes, including reading of metadata etc. *both of the above items typically access "cold" code and data, so hard page faults are probable if you have memory pressure at all: * *the CLR tries to put code and data that is used infrequently far from data that is used frequently to improve locality, so this works against you because you're forcing the cold to be hot. *the cost of the hard page faults, if any, will dwarf everything else. *Typical catch situations are often deep, therefore the above effects would tend to be magnified (increasing the likelihood of page faults). As for the actual impact of the cost, this can vary a lot depending on what else is going on in your code at the time. Jon Skeet has a good summary here, with some useful links. I tend to agree with his statement that if you get to the point where exceptions are significantly hurting your performance, you have problems in terms of your use of exceptions beyond just the performance. A: I made a blog entry about this subject last year. Check it out. Bottom line is that there is almost no cost for a try block if no exception occurs - and on my laptop, an exception was about 36μs. That might be less than you expected, but keep in mind that those results where on a shallow stack. Also, first exceptions are really slow. A: It is vastly easier to write, debug, and maintain code that is free of compiler error messages, code-analysis warning messages, and routine accepted exceptions (particularly exceptions that are thrown in one place and accepted in another). Because it is easier, the code will on average be better written and less buggy. To me, that programmer and quality overhead is the primary argument against using try-catch for process flow. The computer overhead of exceptions is insignificant in comparison, and usually tiny in terms of the application's ability to meet real-world performance requirements. A: Three points to make here: * *Firstly, there is little or NO performance penalty in actually having try-catch blocks in your code. This should not be a consideration when trying to avoid having them in your application. The performance hit only comes into play when an exception is thrown. *When an exception is thrown in addition to the stack unwinding operations etc that take place which others have mentioned you should be aware that a whole bunch of runtime/reflection related stuff happens in order to populate the members of the exception class such as the stack trace object and the various type members etc. *I believe that this is one of the reasons why the general advice if you are going to rethrow the exception is to just throw; rather than throw the exception again or construct a new one as in those cases all of that stack information is regathered whereas in the simple throw it is all preserved. A: I really like Hafthor's blog post, and to add my two cents to this discussion, I'd like to say that, it's always been easy for me to have the DATA LAYER throw only one type of exception (DataAccessException). This way my BUSINESS LAYER knows what exception to expect and catches it. Then depending on further business rules (i.e. if my business object participates in the workflow etc), I may throw a new exception (BusinessObjectException) or proceed without re/throwing. I'd say don't hesitate to use try..catch whenever it is necessary and use it wisely! For example, this method participates in a workflow... Comments? public bool DeleteGallery(int id) { try { using (var transaction = new DbTransactionManager()) { try { transaction.BeginTransaction(); _galleryRepository.DeleteGallery(id, transaction); _galleryRepository.DeletePictures(id, transaction); FileManager.DeleteAll(id); transaction.Commit(); } catch (DataAccessException ex) { Logger.Log(ex); transaction.Rollback(); throw new BusinessObjectException("Cannot delete gallery. Ensure business rules and try again.", ex); } } } catch (DbTransactionException ex) { Logger.Log(ex); throw new BusinessObjectException("Cannot delete gallery.", ex); } return true; } A: We can read in Programming Languages Pragmatics by Michael L. Scott that the nowadays compilers do not add any overhead in common case, this means, when no exceptions occurs. So every work is made in compile time. But when an exception is thrown in run-time, compiler needs to perform a binary search to find the correct exception and this will happen for every new throw that you made. But exceptions are exceptions and this cost is perfectly acceptable. If you try to do Exception Handling without exceptions and use return error codes instead, probably you will need a if statement for every subroutine and this will incur in a really real time overhead. You know a if statement is converted to a few assembly instructions, that will performed every time you enter in your sub-routines. Sorry about my English, hope that it helps you. This information is based on cited book, for more information refer to Chapter 8.5 Exception Handling. A: Let us analyse one of the biggest possible costs of a try/catch block when used where it shouldn't need to be used: int x; try { x = int.Parse("1234"); } catch { return; } // some more code here... And here's the one without try/catch: int x; if (int.TryParse("1234", out x) == false) { return; } // some more code here Not counting the insignificant white-space, one might notice that these two equivelant pieces of code are almost exactly the same length in bytes. The latter contains 4 bytes less indentation. Is that a bad thing? To add insult to injury, a student decides to loop while the input can be parsed as an int. The solution without try/catch might be something like: while (int.TryParse(...)) { ... } But how does this look when using try/catch? try { for (;;) { x = int.Parse(...); ... } } catch { ... } Try/catch blocks are magical ways of wasting indentation, and we still don't even know the reason it failed! Imagine how the person doing debugging feels, when code continues to execute past a serious logical flaw, rather than halting with a nice obvious exception error. Try/catch blocks are a lazy man's data validation/sanitation. One of the smaller costs is that try/catch blocks do indeed disable certain optimizations: http://msmvps.com/blogs/peterritchie/archive/2007/06/22/performance-implications-of-try-catch-finally.aspx. I guess that's a positive point too. It can be used to disable optimizations that might otherwise cripple safe, sane message passing algorithms for multithreaded applications, and to catch possible race conditions ;) That's about the only scenario I can think of to use try/catch. Even that has alternatives.
{ "language": "en", "url": "https://stackoverflow.com/questions/52312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "102" }
Q: C# switch: case not falling through to other cases limitation This question is kind of an add-on to this question In C#, a switch case cannot fall through to other cases, this causes a compilation error. In this case I am just adding some number to the month total for the selected month and each subsequent month thereafter. (simple example, not meant to be real) switch (month) { case 0: add something to month totals case 1: add something to month totals case 2: add something to month totals default: break; } Is there a logical alternative to this in C# without having to write out a ton of if statements? if (month <= 0) add something to month if (month <= 1) add something to month if (month <= 2) add something to month .... etc A: In C# switch statements you can fall through cases only if there is no statement for the case you want to fall through switch(myVar) { case 1: case 2: // Case 1 or 2 get here break; } However if you want to fall through with a statement you must use the dreaded GOTO switch(myVar) { case 1: // Case 1 statement goto case 2; case 2: // Case 1 or 2 get here break; } A: Often times when you see the noise from a huge switch statement or many if statements that might fall into more than one block, you're trying to suppress a bad design. Instead, what if you implemented the Specification pattern to see if something matched, and then act on it? foreach(MonthSpecification spec in this.MonthSpecifications) { if(spec.IsSatisfiedBy(month)) spec.Perform(month); } then you can just add up different specs that match what you're trying to do. It's hard to tell what your domain is, so my example might be a little contrived. A: There is already a question addressing this topic: C# switch statement limitations - why? EDIT: My main purpose in pointing that out, gentlebeasts, is that two questions of near-identical name add confusion to the pool of questions. A: Are you adding constants? If so, maybe something like this would work(C syntax): const int addToTotals[] = {123, 456, ..., 789}; for(i=month;i<12;i++) totals += addToTotals[i]; You can do a similar thing with variable or function pointers if you need more complex statements than add constant to totals for each month following. -Adam A: Write the switch cases in reverse order case 2: case 1: case 0: break; default: Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/52313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: T-SQL trim &nbsp (and other non-alphanumeric characters) We have some input data that sometimes appears with &nbsp characters on the end. The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters. Ltrim and Rtrim don't remove the characters, so we're forced to do something like: UPDATE myTable SET myColumn = replace(myColumn,char(160),'') WHERE charindex(char(160),myColumn) > 0 This works for the &nbsp, but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters? A: This page has a sample of how you can remove non-alphanumeric chars: -- Put something like this into a user function: DECLARE @cString VARCHAR(32) DECLARE @nPos INTEGER SELECT @cString = '90$%45623 *6%}~:@' SELECT @nPos = PATINDEX('%[^0-9]%', @cString) WHILE @nPos > 0 BEGIN SELECT @cString = STUFF(@cString, @nPos, 1, '') SELECT @nPos = PATINDEX('%[^0-9]%', @cString) END SELECT @cString A: This will remove all non alphanumeric chracters CREATE FUNCTION [dbo].[fnRemoveBadCharacter] ( @BadString nvarchar(20) ) RETURNS nvarchar(20) AS BEGIN DECLARE @nPos INTEGER SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString) WHILE @nPos > 0 BEGIN SELECT @BadString = STUFF(@BadString, @nPos, 1, '') SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString) END RETURN @BadString END Use the function like: UPDATE TableToUpdate SET ColumnToUpdate = dbo.fnRemoveBadCharacter(ColumnToUpdate) WHERE whatever A: How is the table being populated? While it is possible to scrub this in sql a better approach would be to change the column type to int and scrub the data before it's loaded into the database (SSIS). Is this an option? A: For large datasets I have had better luck with this function that checks the ASCII value. I have added options to keep only alpha, numeric or alphanumeric based on the parameters. --CleanType 1 - Remove all non alpanumeric -- 2 - Remove only alpha -- 3 - Remove only numeric CREATE FUNCTION [dbo].[fnCleanString] ( @InputString varchar(8000) , @CleanType int , @LeaveSpaces bit ) RETURNS varchar(8000) AS BEGIN -- // Declare variables -- =========================================================== DECLARE @Length int , @CurLength int = 1 , @ReturnString varchar(8000)='' SELECT @Length = len(@InputString) -- // Begin looping through each char checking ASCII value -- =========================================================== WHILE (@CurLength <= (@Length+1)) BEGIN IF (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 48 and 57 AND @CleanType in (1,3) ) or (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 65 and 90 AND @CleanType in (1,2) ) or (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 97 and 122 AND @CleanType in (1,2) ) or (ASCII(SUBSTRING(@InputString,@CurLength,1)) = 32 AND @LeaveSpaces = 1 ) BEGIN SET @ReturnString = @ReturnString + SUBSTRING(@InputString,@CurLength,1) END SET @CurLength = @CurLength + 1 END RETURN @ReturnString END A: If the mobile could start with a Plus(+) I will use the function like this CREATE FUNCTION [dbo].[Mobile_NoAlpha](@Mobile VARCHAR(1000)) RETURNS VARCHAR(1000) AS BEGIN DECLARE @StartsWithPlus BIT = 0 --check if the mobile starts with a plus(+) IF LEFT(@Mobile, 1) = '+' BEGIN SET @StartsWithPlus = 1 --Take out the plus before using the regex to eliminate invalid characters SET @Mobile = RIGHT(@Mobile, LEN(@Mobile)-1) END WHILE PatIndex('%[^0-9]%', @Mobile) > 0 SET @Mobile = Stuff(@Mobile, PatIndex('%[^0-9]%', @Mobile), 1, '') IF @StartsWithPlus = 1 SET @Mobile = '+' + @Mobile RETURN @Mobile END
{ "language": "en", "url": "https://stackoverflow.com/questions/52315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Tablet PC SDK (1.7) Merge Module + VS2008 + Windows Vista? I have a VS2005 deployment & setup project, that makes use of the Tablet PC SDK 1.7 Merge Module, so users of Windows XP can make use of the managed Microsoft.Ink.DLL library. Now that we've moved over to Vista/VS2008, do I still need to install the TPC SDK (to get the merge module) or can I make use of something that Vista has? Google seems plagued with vague references. If I add the merge module for SDK 1.7, how will this affect current Vista users (which will have the Tablet PC capabilities built-in)? A: As usual, one of the trickiest aspects of Tablet development is deployment: * *Tablet functionality isn't built into the Home Basic or Starter editions of Vista so if you want your program to work on those, you still need the MSM. *You should be ok using merge modules on Tablet-enabled versions of Vista. I mean, it's equivalent installing the MSM onto an existing XP Tablet that already had the components. It won't add it if it's already there. *XP 2005 Tablet included TPC 1.7. These are also installed on Tablet-enabled versions of Vista too. If you stick with those core features, just installing the main 1.7 MSM everywhere's probably cool. However, Vista also added new ink analysis capabilities, some stylus input APIs, and a new InkCanvas control so if you need any of these, are there additional merge modules you need to install if you want everything to still work on XP 2005. So bottom line, if you care about XP and/or Home Basic Vista, you still need to deal with merge modules... stuff should still work on Vista. If you're just targeting premium versions of Vista, you don't need 'em anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/52319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Updating Legacy Code from System.Web.Mail to System.Net.Mail in Visual Studio 2005: Problems sending E-Mail Using the obsolete System.Web.Mail sending email works fine, here's the code snippet: Public Shared Sub send(ByVal recipent As String, ByVal from As String, ByVal subject As String, ByVal body As String) Try Dim Message As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage Message.To = recipent Message.From = from Message.Subject = subject Message.Body = body Message.BodyFormat = MailFormat.Html Try SmtpMail.SmtpServer = MAIL_SERVER SmtpMail.Send(Message) Catch ehttp As System.Web.HttpException critical_error("Email sending failed, reason: " + ehttp.ToString) End Try Catch e As System.Exception critical_error(e, "send() in Util_Email") End Try End Sub and here's the updated version: Dim mailMessage As New System.Net.Mail.MailMessage() mailMessage.From = New System.Net.Mail.MailAddress(from) mailMessage.To.Add(New System.Net.Mail.MailAddress(recipent)) mailMessage.Subject = subject mailMessage.Body = body mailMessage.IsBodyHtml = True mailMessage.Priority = System.Net.Mail.MailPriority.Normal Try Dim smtp As New Net.Mail.SmtpClient(MAIL_SERVER) smtp.Send(mailMessage) Catch ex As Exception MsgBox(ex.ToString) End Try I have tried many different variations and nothing seems to work, I have a feeling it may have to do with the SmtpClient, is there something that changed in the underlying code between these versions? There are no exceptions that are thrown back. A: The System.Net.Mail library uses the config files to store the settings so you may just need to add a section like this <system.net> <mailSettings> <smtp from="[email protected]"> <network host="smtpserver1" port="25" userName="username" password="secret" defaultCredentials="true" /> </smtp> </mailSettings> </system.net> A: Have you tried adding smtp.UseDefaultCredentials = True before the send? Also, what happens if you try changing: mailMessage.From = New System.Net.Mail.MailAddress(from) mailMessage.To.Add(New System.Net.Mail.MailAddress(recipent)) to this: mailMessage.From = New System.Net.Mail.MailAddress(from,recipent) -- Kevin Fairchild A: I've tested your code and my mail is sent successfully. Assuming that you're using the same parameters for the old code, I would suggest that your mail server (MAIL_SERVER) is accepting the message and there's a delay in processing or it considers it spam and discards it. I would suggest sending a message using a third way (telnet if you're feeling brave) and see if that is successful. EDIT: I note (from your subsequent answer) that specifying the port has helped somewhat. You've not said if you're using port 25 (SMTP) or port 587 (Submission) or something else. If you're not doing it already, using the sumission port may also help solve your problem. Wikipedia and rfc4409 have more details. A: Are you setting the credentials for the E-Mail? smtp.Credentials = New Net.NetworkCredential("[email protected]", "password") I had this error, however I believe it threw an exception. A: Everything you are doing is correct. Here's the things i would check. * *Double check that the SMTP service in IIS is running right. *Make sure it's not getting flagged as spam. those are usually the biggest culprits whenever we have had issues w/ sending email. Also, just noticed you are doing MsgBox(ex.Message). I believe they blocked MessageBox from working asp.net in a service pack, so it might be erroring out, you just might not know it. check your event log. A: I added the port number for the mail server and it started working sporadically, it seems that it was a problem with the server and a delay in sending the messages. Thanks for your answers, they were all helpful!
{ "language": "en", "url": "https://stackoverflow.com/questions/52321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to validate an XML file against a schema using Visual Studio 2005 Is it possible to validate an xml file against its associated schema using Visual Studio 2005 IDE? I could only see options to create a schema based on the current file, or show the XSLT output A: It's done automatically, errors appear as warnings in the "Error List" and are additionally underlined with the blue squiggle in the source file. Not sure if there is another way to validate the file, but this will do for now. A: XmlSchemaValidator Warning: It's not pretty to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/52326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is causing a JVMTI_ERROR_NULL_POINTER? I'm getting an error when my application starts. It appears to be after it's initialized its connection to the database. It also may be when it starts to spawn threads, but I haven't been able to cause it to happen on purpose. The entire error message is: FATAL ERROR in native method: JDWP NewGlobalRef, jvmtiError=JVMTI_ERROR_NULL_POINTER(100) JDWP exit error JVMTI_ERROR_NULL_POINTER(100): NewGlobalRef erickson: I'm not very familiar with the DB code, but hopefully this string is helpful: jdbc:sqlserver://localhost;databasename=FOO Tom Hawtin: It's likely I was only getting this error when debugging, but it wasn't consistent enough for me to notice. Also, I fixed a bug that was causing multiple threads to attempt to update the same row in DB and I haven't gotten the JVMTI... error since. A: JVMTI is the debugging and profiling protocol. So, I'm guessint it's something peculiar to the environment you are attempting to run your application in. A: I'm guessing you are using a native-code–based database driver (JDBC driver type 1 or 2). And I'm guessing that driver is buggy. If you could provide more information about the driver and your datasource configuration or connection string, it might help determine some answers.
{ "language": "en", "url": "https://stackoverflow.com/questions/52343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to detect (using .ASPX) if Javascript is enabled on browser I'm thinking this might be a quick and easy way to lower the form spam on our site just a little bit. The idea being that (I have read) spammers aren't running with javascript enabled. (Or at least they are accessing your website without running javascript. I.e., they aren't browsing up to it in IE or FF. I can use .asp or .aspx. A: The simplest way is to set a cookie via javascript and check for it on postback.However, if you're looking to minimize spam you should actually have the browser perform a simple task which requires javascript execution. See Phil Haack's "Invisibile Captcha Validator" control, which has since been included in his Subkismet library: http://haacked.com/archive/2006/09/26/Lightweight_Invisible_CAPTCHA_Validator_Control.aspx A: In .net, you can use Request.Browser.JavaScript to detect if the browser supports JavaScript. However, the user may still have Javascript disabled. An ugly way to check to see if Javascript is enabled, is to use window.location to redirect to page.aspx?jscript=true, and then check Request.Querystring for that value. A: So, you want to force users to use JavaScript in order to use your site? I'd rather just use a simple Captcha. If you aren't a big-name site, you can get away with some relatively simple Captchas. That's how we reduced spam at our site. A: To be honest, you shouldn't need to use a server-side language to detect javascript, and furthermore spammers are not necessarily not running javascript. (sorry about the double-negative) Your objective is good, but your approach is wrong - implementing a CAPTCHA, as suggested by a few of our peers, would be a great way to handle this. A: I see you've accepted the noscript answer, but how will you use this to fight spam? noscript will allow you to add special content for users without JS, but unless you're generating the rest of your site in JS, it will still be available to user agents without JS. A captcha of some sort is still likely the best bet. Ultimately, you're trying to get the user agent to prove that it's being controlled by a human, so do your best to make it prove that actual fact, instead of something else. Screen readers for the visually impaired typically go without Javascript, too, and many people browsing from mobile devices have Javascript disabled to speed things up.
{ "language": "en", "url": "https://stackoverflow.com/questions/52344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to determine the size of an object in Java I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause OutOfMemoryErrors. Each row translates into an object. Is there a way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a VM? Right now, I have code that says read up to 32,000 rows, but I'd also like to have code that says read as many rows as possible until I've used 32MB of memory. A: Some years back Javaworld had an article on determining the size of composite and potentially nested Java objects, they basically walk through creating a sizeof() implementation in Java. The approach basically builds on other work where people experimentally identified the size of primitives and typical Java objects and then apply that knowledge to a method that recursively walks an object graph to tally the total size. It is always going to be somewhat less accurate than a native C implementation simply because of the things going on behind the scenes of a class but it should be a good indicator. Alternatively a SourceForge project appropriately called sizeof that offers a Java5 library with a sizeof() implementation. P.S. Do not use the serialization approach, there is no correlation between the size of a serialized object and the amount of memory it consumes when live. A: Firstly "the size of an object" isn't a well-defined concept in Java. You could mean the object itself, with just its members, the Object and all objects it refers to (the reference graph). You could mean the size in memory or the size on disk. And the JVM is allowed to optimise things like Strings. So the only correct way is to ask the JVM, with a good profiler (I use YourKit), which probably isn't what you want. However, from the description above it sounds like each row will be self-contained, and not have a big dependency tree, so the serialization method will probably be a good approximation on most JVMs. The easiest way to do this is as follows: Serializable ser; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(ser); oos.close(); return baos.size(); Remember that if you have objects with common references this will not give the correct result, and size of serialization will not always match size in memory, but it is a good approximation. The code will be a bit more efficient if you initialise the ByteArrayOutputStream size to a sensible value. A: There is also the Memory Measurer tool (formerly at Google Code, now on GitHub), which is simple and published under the commercial-friendly Apache 2.0 license, as discussed in a similar question. It, too, requires a command-line argument to the java interpreter if you want to measure memory byte consumption, but otherwise seems to work just fine, at least in the scenarios I have used it. A: The java.lang.instrument.Instrumentation class provides a nice way to get the size of a Java Object, but it requires you to define a premain and run your program with a java agent. This is very boring when you do not need any agent and then you have to provide a dummy Jar agent to your application. So I got an alternative solution using the Unsafe class from the sun.misc. So, considering the objects heap alignment according to the processor architecture and calculating the maximum field offset, you can measure the size of a Java Object. In the example below I use an auxiliary class UtilUnsafe to get a reference to the sun.misc.Unsafe object. private static final int NR_BITS = Integer.valueOf(System.getProperty("sun.arch.data.model")); private static final int BYTE = 8; private static final int WORD = NR_BITS/BYTE; private static final int MIN_SIZE = 16; public static int sizeOf(Class src){ // // Get the instance fields of src class // List<Field> instanceFields = new LinkedList<Field>(); do{ if(src == Object.class) return MIN_SIZE; for (Field f : src.getDeclaredFields()) { if((f.getModifiers() & Modifier.STATIC) == 0){ instanceFields.add(f); } } src = src.getSuperclass(); }while(instanceFields.isEmpty()); // // Get the field with the maximum offset // long maxOffset = 0; for (Field f : instanceFields) { long offset = UtilUnsafe.UNSAFE.objectFieldOffset(f); if(offset > maxOffset) maxOffset = offset; } return (((int)maxOffset/WORD) + 1)*WORD; } class UtilUnsafe { public static final sun.misc.Unsafe UNSAFE; static { Object theUnsafe = null; Exception exception = null; try { Class<?> uc = Class.forName("sun.misc.Unsafe"); Field f = uc.getDeclaredField("theUnsafe"); f.setAccessible(true); theUnsafe = f.get(uc); } catch (Exception e) { exception = e; } UNSAFE = (sun.misc.Unsafe) theUnsafe; if (UNSAFE == null) throw new Error("Could not obtain access to sun.misc.Unsafe", exception); } private UtilUnsafe() { } } A: You can use the java.lang.instrument package. Compile and put this class in a JAR: import java.lang.instrument.Instrumentation; public class ObjectSizeFetcher { private static Instrumentation instrumentation; public static void premain(String args, Instrumentation inst) { instrumentation = inst; } public static long getObjectSize(Object o) { return instrumentation.getObjectSize(o); } } Add the following to your MANIFEST.MF: Premain-Class: ObjectSizeFetcher Use the getObjectSize() method: public class C { private int x; private int y; public static void main(String [] args) { System.out.println(ObjectSizeFetcher.getObjectSize(new C())); } } Invoke with: java -javaagent:ObjectSizeFetcherAgent.jar C A: Without having to mess with instrumentation and so on, and if you don't need to know the byte-exact size of an object, you could go with the following approach: System.gc(); Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); do your job here System.gc(); Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); This way you read the used memory before and after, and calling the GC just before getting the used memory you lower the "noise" almost to 0. For a more reliable result you can run your job n times, and then divide the used memory by n, obtaining how much memory one run takes. Even more, you can run the whole thing more times and make an average. A: I was looking for a runtime calculation of an object size that met the following requirements: * *Available at runtime with no need to include instrumentation. *Works with Java 9+ without access to Unsafe. *Is based on the Class only. Not a deep sizeOf that takes into consideration string lengths, array lengths, etc. The following is based on the core code of the original java specialists article (https://www.javaspecialists.eu/archive/Issue078.html) and a few bits from the Unsafe version in another answer to this question. I hope someone finds it useful. public class JavaSize { private static final int NR_BITS = Integer.valueOf(System.getProperty("sun.arch.data.model")); private static final int BYTE = 8; private static final int WORD = NR_BITS / BYTE; private static final int HEADER_SIZE = 8; public static int sizeOf(Class<?> clazz) { int result = 0; while (clazz != null) { Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (!Modifier.isStatic(fields[i].getModifiers())) { if (fields[i].getType().isPrimitive()) { Class<?> primitiveClass = fields[i].getType(); if (primitiveClass == boolean.class || primitiveClass == byte.class) { result += 1; } else if (primitiveClass == short.class) { result += 2; } else if (primitiveClass == int.class || primitiveClass == float.class) { result += 4; } else if (primitiveClass == double.class || primitiveClass == long.class) { result += 8; } } else { // assume compressed references. result += 4; } } } clazz = clazz.getSuperclass(); // round up to the nearest WORD length. if ((result % WORD) != 0) { result += WORD - (result % WORD); } } result += HEADER_SIZE; return result; } } A: A possible year 2022 answer. https://github.com/ehcache/sizeof https://mvnrepository.com/artifact/org.ehcache/sizeof https://mvnrepository.com/artifact/org.ehcache/sizeof/0.4.0 Version 0.4.0 has only a (compile) dependency on https://mvnrepository.com/artifact/org.slf4j/slf4j-api which is a good thing. Sample code: //import org.ehcache.sizeof.SizeOf; SizeOf sizeOf = SizeOf.newInstance(); // (1) long shallowSize = sizeOf.sizeOf(someObject); // (2) long deepSize = sizeOf.deepSizeOf(someObject); // (3) A: If you would just like to know how much memory is being used in your JVM, and how much is free, you could try something like this: // Get current size of heap in bytes long heapSize = Runtime.getRuntime().totalMemory(); // Get maximum size of heap in bytes. The heap cannot grow beyond this size. // Any attempt will result in an OutOfMemoryException. long heapMaxSize = Runtime.getRuntime().maxMemory(); // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created. long heapFreeSize = Runtime.getRuntime().freeMemory(); edit: I thought this might be helpful as the question author also stated he would like to have logic that handles "read as many rows as possible until I've used 32MB of memory." A: Here is a utility I made using some of the linked examples to handle 32-bit, 64-bit and 64-bit with compressed OOP. It uses sun.misc.Unsafe. It uses Unsafe.addressSize() to get the size of a native pointer and Unsafe.arrayIndexScale( Object[].class ) for the size of a Java reference. It uses the field offset of a known class to work out the base size of an object. import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.IdentityHashMap; import java.util.Stack; import sun.misc.Unsafe; /** Usage: * MemoryUtil.sizeOf( object ) * MemoryUtil.deepSizeOf( object ) * MemoryUtil.ADDRESS_MODE */ public class MemoryUtil { private MemoryUtil() { } public static enum AddressMode { /** Unknown address mode. Size calculations may be unreliable. */ UNKNOWN, /** 32-bit address mode using 32-bit references. */ MEM_32BIT, /** 64-bit address mode using 64-bit references. */ MEM_64BIT, /** 64-bit address mode using 32-bit compressed references. */ MEM_64BIT_COMPRESSED_OOPS } /** The detected runtime address mode. */ public static final AddressMode ADDRESS_MODE; private static final Unsafe UNSAFE; private static final long ADDRESS_SIZE; // The size in bytes of a native pointer: 4 for 32 bit, 8 for 64 bit private static final long REFERENCE_SIZE; // The size of a Java reference: 4 for 32 bit, 4 for 64 bit compressed oops, 8 for 64 bit private static final long OBJECT_BASE_SIZE; // The minimum size of an Object: 8 for 32 bit, 12 for 64 bit compressed oops, 16 for 64 bit private static final long OBJECT_ALIGNMENT = 8; /** Use the offset of a known field to determine the minimum size of an object. */ private static final Object HELPER_OBJECT = new Object() { byte b; }; static { try { // Use reflection to get a reference to the 'Unsafe' object. Field f = Unsafe.class.getDeclaredField( "theUnsafe" ); f.setAccessible( true ); UNSAFE = (Unsafe) f.get( null ); OBJECT_BASE_SIZE = UNSAFE.objectFieldOffset( HELPER_OBJECT.getClass().getDeclaredField( "b" ) ); ADDRESS_SIZE = UNSAFE.addressSize(); REFERENCE_SIZE = UNSAFE.arrayIndexScale( Object[].class ); if( ADDRESS_SIZE == 4 ) { ADDRESS_MODE = AddressMode.MEM_32BIT; } else if( ADDRESS_SIZE == 8 && REFERENCE_SIZE == 8 ) { ADDRESS_MODE = AddressMode.MEM_64BIT; } else if( ADDRESS_SIZE == 8 && REFERENCE_SIZE == 4 ) { ADDRESS_MODE = AddressMode.MEM_64BIT_COMPRESSED_OOPS; } else { ADDRESS_MODE = AddressMode.UNKNOWN; } } catch( Exception e ) { throw new Error( e ); } } /** Return the size of the object excluding any referenced objects. */ public static long shallowSizeOf( final Object object ) { Class<?> objectClass = object.getClass(); if( objectClass.isArray() ) { // Array size is base offset + length * element size long size = UNSAFE.arrayBaseOffset( objectClass ) + UNSAFE.arrayIndexScale( objectClass ) * Array.getLength( object ); return padSize( size ); } else { // Object size is the largest field offset padded out to 8 bytes long size = OBJECT_BASE_SIZE; do { for( Field field : objectClass.getDeclaredFields() ) { if( (field.getModifiers() & Modifier.STATIC) == 0 ) { long offset = UNSAFE.objectFieldOffset( field ); if( offset >= size ) { size = offset + 1; // Field size is between 1 and PAD_SIZE bytes. Padding will round up to padding size. } } } objectClass = objectClass.getSuperclass(); } while( objectClass != null ); return padSize( size ); } } private static final long padSize( final long size ) { return (size + (OBJECT_ALIGNMENT - 1)) & ~(OBJECT_ALIGNMENT - 1); } /** Return the size of the object including any referenced objects. */ public static long deepSizeOf( final Object object ) { IdentityHashMap<Object,Object> visited = new IdentityHashMap<Object,Object>(); Stack<Object> stack = new Stack<Object>(); if( object != null ) stack.push( object ); long size = 0; while( !stack.isEmpty() ) { size += internalSizeOf( stack.pop(), stack, visited ); } return size; } private static long internalSizeOf( final Object object, final Stack<Object> stack, final IdentityHashMap<Object,Object> visited ) { // Scan for object references and add to stack Class<?> c = object.getClass(); if( c.isArray() && !c.getComponentType().isPrimitive() ) { // Add unseen array elements to stack for( int i = Array.getLength( object ) - 1; i >= 0; i-- ) { Object val = Array.get( object, i ); if( val != null && visited.put( val, val ) == null ) { stack.add( val ); } } } else { // Add unseen object references to the stack for( ; c != null; c = c.getSuperclass() ) { for( Field field : c.getDeclaredFields() ) { if( (field.getModifiers() & Modifier.STATIC) == 0 && !field.getType().isPrimitive() ) { field.setAccessible( true ); try { Object val = field.get( object ); if( val != null && visited.put( val, val ) == null ) { stack.add( val ); } } catch( IllegalArgumentException e ) { throw new RuntimeException( e ); } catch( IllegalAccessException e ) { throw new RuntimeException( e ); } } } } } return shallowSizeOf( object ); } } A: Back when I worked at Twitter, I wrote a utility for calculating deep object size. It takes into account different memory models (32-bit, compressed oops, 64-bit), padding, subclass padding, works correctly on circular data structures and arrays. You can just compile this one .java file; it has no external dependencies: https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/objectsize/ObjectSizeCalculator.java A: Much of the other answers provide shallow sizes - e.g. the size of a HashMap without any of the keys or values, which isn't likely what you want. The jamm project uses the java.lang.instrumentation package above but walks the tree and so can give you the deep memory use. new MemoryMeter().measureDeep(myHashMap); https://github.com/jbellis/jamm To use MemoryMeter, start the JVM with "-javaagent:/jamm.jar" A: There isn't a method call, if that's what you're asking for. With a little research, I suppose you could write your own. A particular instance has a fixed sized derived from the number of references and primitive values plus instance bookkeeping data. You would simply walk the object graph. The less varied the row types, the easier. If that's too slow or just more trouble than it's worth, there's always good old-fashioned row counting rule-of-thumbs. A: I wrote a quick test once to estimate on the fly: public class Test1 { // non-static nested class Nested { } // static nested static class StaticNested { } static long getFreeMemory () { // waits for free memory measurement to stabilize long init = Runtime.getRuntime().freeMemory(), init2; int count = 0; do { System.out.println("waiting..." + init); System.gc(); try { Thread.sleep(250); } catch (Exception x) { } init2 = init; init = Runtime.getRuntime().freeMemory(); if (init == init2) ++ count; else count = 0; } while (count < 5); System.out.println("ok..." + init); return init; } Test1 () throws InterruptedException { Object[] s = new Object[10000]; Object[] n = new Object[10000]; Object[] t = new Object[10000]; long init = getFreeMemory(); //for (int j = 0; j < 10000; ++ j) // s[j] = new Separate(); long afters = getFreeMemory(); for (int j = 0; j < 10000; ++ j) n[j] = new Nested(); long aftersn = getFreeMemory(); for (int j = 0; j < 10000; ++ j) t[j] = new StaticNested(); long aftersnt = getFreeMemory(); System.out.println("separate: " + -(afters - init) + " each=" + -(afters - init) / 10000); System.out.println("nested: " + -(aftersn - afters) + " each=" + -(aftersn - afters) / 10000); System.out.println("static nested: " + -(aftersnt - aftersn) + " each=" + -(aftersnt - aftersn) / 10000); } public static void main (String[] args) throws InterruptedException { new Test1(); } } General concept is allocate objects and measure change in free heap space. The key being getFreeMemory(), which requests GC runs and waits for the reported free heap size to stabilize. The output of the above is: nested: 160000 each=16 static nested: 160000 each=16 Which is what we expect, given alignment behavior and possible heap block header overhead. The instrumentation method detailed in the accepted answer here the most accurate. The method I described is accurate but only under controlled conditions where no other threads are creating/discarding objects. A: Just use java visual VM. It has everything you need to profile and debug memory problems. It also has a OQL (Object Query Language) console which allows you to do many useful things, one of which being sizeof(o) A: When using JetBrains IntelliJ, first enable "Attach memory agent" in File | Settings | Build, Execution, Deployment | Debugger. When debugging, right-click a variable of interest and choose "Calculate Retained Size": A: You should use jol, a tool developed as part of the OpenJDK project. JOL (Java Object Layout) is the tiny toolbox to analyze object layout schemes in JVMs. These tools are using Unsafe, JVMTI, and Serviceability Agent (SA) heavily to decoder the actual object layout, footprint, and references. This makes JOL much more accurate than other tools relying on heap dumps, specification assumptions, etc. To get the sizes of primitives, references and array elements, use VMSupport.vmDetails(). On Oracle JDK 1.8.0_40 running on 64-bit Windows (used for all following examples), this method returns Running 64-bit HotSpot VM. Using compressed oop with 0-bit shift. Using compressed klass with 3-bit shift. Objects are 8 bytes aligned. Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] You can get the shallow size of an object instance using ClassLayout.parseClass(Foo.class).toPrintable() (optionally passing an instance to toPrintable). This is only the space consumed by a single instance of that class; it does not include any other objects referenced by that class. It does include VM overhead for the object header, field alignment and padding. For java.util.regex.Pattern: java.util.regex.Pattern object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) 01 00 00 00 (0000 0001 0000 0000 0000 0000 0000 0000) 4 4 (object header) 00 00 00 00 (0000 0000 0000 0000 0000 0000 0000 0000) 8 4 (object header) cb cf 00 20 (1100 1011 1100 1111 0000 0000 0010 0000) 12 4 int Pattern.flags 0 16 4 int Pattern.capturingGroupCount 1 20 4 int Pattern.localCount 0 24 4 int Pattern.cursor 48 28 4 int Pattern.patternLength 0 32 1 boolean Pattern.compiled true 33 1 boolean Pattern.hasSupplementary false 34 2 (alignment/padding gap) N/A 36 4 String Pattern.pattern (object) 40 4 String Pattern.normalizedPattern (object) 44 4 Node Pattern.root (object) 48 4 Node Pattern.matchRoot (object) 52 4 int[] Pattern.buffer null 56 4 Map Pattern.namedGroups null 60 4 GroupHead[] Pattern.groupNodes null 64 4 int[] Pattern.temp null 68 4 (loss due to the next object alignment) Instance size: 72 bytes (reported by Instrumentation API) Space losses: 2 bytes internal + 4 bytes external = 6 bytes total You can get a summary view of the deep size of an object instance using GraphLayout.parseInstance(obj).toFootprint(). Of course, some objects in the footprint might be shared (also referenced from other objects), so it is an overapproximation of the space that could be reclaimed when that object is garbage collected. For the result of Pattern.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$") (taken from this answer), jol reports a total footprint of 1840 bytes, of which only 72 are the Pattern instance itself. java.util.regex.Pattern instance footprint: COUNT AVG SUM DESCRIPTION 1 112 112 [C 3 272 816 [Z 1 24 24 java.lang.String 1 72 72 java.util.regex.Pattern 9 24 216 java.util.regex.Pattern$1 13 24 312 java.util.regex.Pattern$5 1 16 16 java.util.regex.Pattern$Begin 3 24 72 java.util.regex.Pattern$BitClass 3 32 96 java.util.regex.Pattern$Curly 1 24 24 java.util.regex.Pattern$Dollar 1 16 16 java.util.regex.Pattern$LastNode 1 16 16 java.util.regex.Pattern$Node 2 24 48 java.util.regex.Pattern$Single 40 1840 (total) If you instead use GraphLayout.parseInstance(obj).toPrintable(), jol will tell you the address, size, type, value and path of field dereferences to each referenced object, though that's usually too much detail to be useful. For the ongoing pattern example, you might get the following. (Addresses will likely change between runs.) java.util.regex.Pattern object externals: ADDRESS SIZE TYPE PATH VALUE d5e5f290 16 java.util.regex.Pattern$Node .root.next.atom.next (object) d5e5f2a0 120 (something else) (somewhere else) (something else) d5e5f318 16 java.util.regex.Pattern$LastNode .root.next.next.next.next.next.next.next (object) d5e5f328 21664 (something else) (somewhere else) (something else) d5e647c8 24 java.lang.String .pattern (object) d5e647e0 112 [C .pattern.value [^, [, a, -, z, A, -, Z, 0, -, 9, _, ., +, -, ], +, @, [, a, -, z, A, -, Z, 0, -, 9, -, ], +, \, ., [, a, -, z, A, -, Z, 0, -, 9, -, ., ], +, $] d5e64850 448 (something else) (somewhere else) (something else) d5e64a10 72 java.util.regex.Pattern (object) d5e64a58 416 (something else) (somewhere else) (something else) d5e64bf8 16 java.util.regex.Pattern$Begin .root (object) d5e64c08 24 java.util.regex.Pattern$BitClass .root.next.atom.val$rhs (object) d5e64c20 272 [Z .root.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false] d5e64d30 24 java.util.regex.Pattern$1 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object) d5e64d48 24 java.util.regex.Pattern$1 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object) d5e64d60 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object) d5e64d78 24 java.util.regex.Pattern$1 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object) d5e64d90 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object) d5e64da8 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs.val$lhs (object) d5e64dc0 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs (object) d5e64dd8 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs (object) d5e64df0 24 java.util.regex.Pattern$5 .root.next.atom (object) d5e64e08 32 java.util.regex.Pattern$Curly .root.next (object) d5e64e28 24 java.util.regex.Pattern$Single .root.next.next (object) d5e64e40 24 java.util.regex.Pattern$BitClass .root.next.next.next.atom.val$rhs (object) d5e64e58 272 [Z .root.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false] d5e64f68 24 java.util.regex.Pattern$1 .root.next.next.next.atom.val$lhs.val$lhs.val$lhs (object) d5e64f80 24 java.util.regex.Pattern$1 .root.next.next.next.atom.val$lhs.val$lhs.val$rhs (object) d5e64f98 24 java.util.regex.Pattern$5 .root.next.next.next.atom.val$lhs.val$lhs (object) d5e64fb0 24 java.util.regex.Pattern$1 .root.next.next.next.atom.val$lhs.val$rhs (object) d5e64fc8 24 java.util.regex.Pattern$5 .root.next.next.next.atom.val$lhs (object) d5e64fe0 24 java.util.regex.Pattern$5 .root.next.next.next.atom (object) d5e64ff8 32 java.util.regex.Pattern$Curly .root.next.next.next (object) d5e65018 24 java.util.regex.Pattern$Single .root.next.next.next.next (object) d5e65030 24 java.util.regex.Pattern$BitClass .root.next.next.next.next.next.atom.val$rhs (object) d5e65048 272 [Z .root.next.next.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false] d5e65158 24 java.util.regex.Pattern$1 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object) d5e65170 24 java.util.regex.Pattern$1 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$rhs (object) d5e65188 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs (object) d5e651a0 24 java.util.regex.Pattern$1 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$rhs (object) d5e651b8 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom.val$lhs.val$lhs (object) d5e651d0 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom.val$lhs (object) d5e651e8 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom (object) d5e65200 32 java.util.regex.Pattern$Curly .root.next.next.next.next.next (object) d5e65220 120 (something else) (somewhere else) (something else) d5e65298 24 java.util.regex.Pattern$Dollar .root.next.next.next.next.next.next (object) The "(something else)" entries describe other objects in the heap that are not part of this object graph. The best jol documentation is the jol samples in the jol repository. The samples demonstrate common jol operations and show how you can use jol to analyze VM and garbage collector internals. A: You have to walk the objects using reflection. Be careful as you do: * *Just allocating an object has some overhead in the JVM. The amount varies by JVM so you might make this value a parameter. At least make it a constant (8 bytes?) and apply to anything allocated. *Just because byte is theoretically 1 byte doesn't mean it takes just one in memory. *There will be loops in object references, so you'll need to keep a HashMap or somesuch using object-equals as the comparator to eliminate infinite loops. @jodonnell: I like the simplicity of your solution, but many objects aren't Serializable (so this would throw an exception), fields can be transient, and objects can override the standard methods. A: You have to measure it with a tool, or estimate it by hand, and it depends on the JVM you are using. There is some fixed overhead per object. It's JVM-specific, but I usually estimate 40 bytes. Then you have to look at the members of the class. Object references are 4 (8) bytes in a 32-bit (64-bit) JVM. Primitive types are: * *boolean and byte: 1 byte *char and short: 2 bytes *int and float: 4 bytes *long and double: 8 bytes Arrays follow the same rules; that is, it's an object reference so that takes 4 (or 8) bytes in your object, and then its length multiplied by the size of its element. Trying to do it programmatically with calls to Runtime.freeMemory() just doesn't give you much accuracy, because of asynchronous calls to the garbage collector, etc. Profiling the heap with -Xrunhprof or other tools will give you the most accurate results. A: I accidentally found a java class "jdk.nashorn.internal.ir.debug.ObjectSizeCalculator", already in jdk, which is easy to use and seems quite useful for determining the size of an object. System.out.println(ObjectSizeCalculator.getObjectSize(new gnu.trove.map.hash.TObjectIntHashMap<String>(12000, 0.6f, -1))); System.out.println(ObjectSizeCalculator.getObjectSize(new HashMap<String, Integer>(100000))); System.out.println(ObjectSizeCalculator.getObjectSize(3)); System.out.println(ObjectSizeCalculator.getObjectSize(new int[]{1, 2, 3, 4, 5, 6, 7 })); System.out.println(ObjectSizeCalculator.getObjectSize(new int[100])); results: 164192 48 16 48 416 A: long heapSizeBefore = Runtime.getRuntime().totalMemory(); // Code for object construction ... long heapSizeAfter = Runtime.getRuntime().totalMemory(); long size = heapSizeAfter - heapSizeBefore; size gives you the increase in memory usage of the jvm due to object creation and that typically is the size of the object. A: My answer is based on the code supplied by Nick. That code measures total amount of bytes which are occupied by the serialized object. So this actually measures serialization stuff + plain object memory footprint (just serialize for example int and you will see that total amount of serialized bytes is not 4). So if you want to get raw byte number used exactly for your object - you need to modify that code a bit. Like so: import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class ObjectSizeCalculator { private Object getFirstObjectReference(Object o) { String objectType = o.getClass().getTypeName(); if (objectType.substring(objectType.length()-2).equals("[]")) { try { if (objectType.equals("java.lang.Object[]")) return ((Object[])o)[0]; else if (objectType.equals("int[]")) return ((int[])o)[0]; else throw new RuntimeException("Not Implemented !"); } catch (IndexOutOfBoundsException e) { return null; } } return o; } public int getObjectSizeInBytes(Object o) { final String STRING_JAVA_TYPE_NAME = "java.lang.String"; if (o == null) return 0; String objectType = o.getClass().getTypeName(); boolean isArray = objectType.substring(objectType.length()-2).equals("[]"); Object objRef = getFirstObjectReference(o); if (objRef != null && !(objRef instanceof Serializable)) throw new RuntimeException("Object must be serializable for measuring it's memory footprint using this method !"); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(o); oos.close(); byte[] bytes = baos.toByteArray(); for (int i = bytes.length - 1, j = 0; i != 0; i--, j++) { if (objectType != STRING_JAVA_TYPE_NAME) { if (bytes[i] == 112) if (isArray) return j - 4; else return j; } else { if (bytes[i] == 0) return j - 1; } } } catch (Exception e) { return -1; } return -1; } } I've tested this solution with primitive types, String, and on some trivial classes. There may be not covered cases also. UPDATE: Example modified to support memory footprint calculation of array objects. A: This answer is not related to Object size, but when you are using array to accommodate the objects; how much memory size it will allocate for the object. So arrays, list, or map all those collection won't be going to store objects really (only at the time of primitives, real object memory size is needed), it will store only references for those objects. Now the Used heap memory = sizeOfObj + sizeOfRef (* 4 bytes) in collection * *(4/8 bytes) depends on (32/64 bit) OS PRIMITIVES int [] intArray = new int [1]; will require 4 bytes. long [] longArray = new long [1]; will require 8 bytes. OBJECTS Object[] objectArray = new Object[1]; will require 4 bytes. The object can be any user defined Object. Long [] longArray = new Long [1]; will require 4 bytes. I mean to say all the object REFERENCE needs only 4 bytes of memory. It may be String reference OR Double object reference, But depends on object creation the memory needed will vary. e.g) If i create object for the below class ReferenceMemoryTest then 4 + 4 + 4 = 12 bytes of memory will be created. The memory may differ when you are trying to initialize the references. class ReferenceMemoryTest { public String refStr; public Object refObj; public Double refDoub; } So when are creating object/reference array, all its contents will be occupied with NULL references. And we know each reference requires 4 bytes. And finally, memory allocation for the below code is 20 bytes. ReferenceMemoryTest ref1 = new ReferenceMemoryTest(); ( 4(ref1) + 12 = 16 bytes) ReferenceMemoryTest ref2 = ref1; ( 4(ref2) + 16 = 20 bytes) A: You could generate a heap dump (with jmap, for example) and then analyze the output to find object sizes. This is an offline solution, but you can examine shallow and deep sizes, etc. A: Suppose I declare a class named Complex like: public class Complex { private final long real; private final long imaginary; // omitted } In order to see how much memory is allocated to live instances of this class: $ jmap -histo:live <pid> | grep Complex num #instances #bytes class name (module) ------------------------------------------------------- 327: 1 32 Complex A: If your application has the Apache commons lang library as a dependency or is using the Spring framework then you can also use the SerializationUtils class to quickly find out the approximate byte size of any given object. byte[] data = SerializationUtils.serialize(user); System.out.println("Approximate object size in bytes " + data.length); A: I doubt you want to do it programmatically unless you just want to do it once and store it for future use. It's a costly thing to do. There's no sizeof() operator in Java, and even if there was, it would only count the cost of the references to other objects and the size of the primitives. One way you could do it is to serialize the thing to a File and look at the size of the file, like this: Serializable myObject; ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("obj.ser")); oos.write (myObject); oos.close (); Of course, this assumes that each object is distinct and doesn't contain non-transient references to anything else. Another strategy would be to take each object and examine its members by reflection and add up the sizes (boolean & byte = 1 byte, short & char = 2 bytes, etc.), working your way down the membership hierarchy. But that's tedious and expensive and ends up doing the same thing the serialization strategy would do. A: For JSONObject the below code can help you. `JSONObject.toString().getBytes("UTF-8").length` returns size in bytes I checked it with my JSONArray object by writing it to a file. It is giving object size.
{ "language": "en", "url": "https://stackoverflow.com/questions/52353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "670" }
Q: SQL 2005 copy single column between databases I'm still fairly new to T-SQL and SQL 2005. I need to import a column of integers from a table in database1 to a identical table (only missing the column I need) in database2. Both are sql 2005 databases. I've tried the built in import command in Server Management Studio but it's forcing me to copy the entire table. This causes errors due to constraints and 'read-only' columns (whatever 'read-only' means in sql2005). I just want to grab a single column and copy it to a table. There must be a simple way of doing this. Something like: INSERT INTO database1.myTable columnINeed SELECT columnINeed from database2.myTable A: Inserting won't do it since it'll attempt to insert new rows at the end of the table. What it sounds like your trying to do is add a column to the end of existing rows. I'm not sure if the syntax is exactly right but, if I understood you then this will do what you're after. * *Create the column allowing nulls in database2. *Perform an update: UPDATE database2.dbo.tablename SET database2.dbo.tablename.colname = database1.dbo.tablename.colname FROM database2.dbo.tablename INNER JOIN database1.dbo.tablename ON database2.dbo.tablename.keycol = database1.dbo.tablename.keycol A: There is a simple way very much like this as long as both databases are on the same server. The fully qualified name is dbname.owner.table - normally the owner is dbo and there is a shortcut for ".dbo." which is "..", so... INSERT INTO Datbase1..MyTable (ColumnList) SELECT FieldsIWant FROM Database2..MyTable A: first create the column if it doesn't exist: ALTER TABLE database2..targetTable ADD targetColumn int null -- or whatever column definition is needed and since you're using Sql Server 2005 you can use the new MERGE statement. The MERGE statement has the advantage of being able to treat all situations in one statement like missing rows from source (can do inserts), missing rows from destination (can do deletes), matching rows (can do updates), and everything is done atomically in a single transaction. Example: MERGE database2..targetTable AS t USING (SELECT sourceColumn FROM sourceDatabase1..sourceTable) as s ON t.PrimaryKeyCol = s.PrimaryKeyCol -- or whatever the match should be bassed on WHEN MATCHED THEN UPDATE SET t.targetColumn = s.sourceColumn WHEN NOT MATCHED THEN INSERT (targetColumn, [other columns ...]) VALUES (s.sourceColumn, [other values ..]) The MERGE statement was introduced to solve cases like yours and I recommend using it, it's much more powerful than solutions using multiple sql batch statements that basically accomplish the same thing MERGE does in one statement without the added complexity. A: You could also use a cursor. Assuming you want to iterate all the records in the first table and populate the second table with new rows then something like this would be the way to go: DECLARE @FirstField nvarchar(100) DECLARE ACursor CURSOR FOR SELECT FirstField FROM FirstTable OPEN ACursor FETCH NEXT FROM ACursor INTO @FirstField WHILE @@FETCH_STATUS = 0 BEGIN INSERT INTO SecondTable ( SecondField ) VALUES ( @FirstField ) FETCH NEXT FROM ACursor INTO @FirstField END CLOSE ACursor DEALLOCATE ACursor A: MERGE is only available in SQL 2008 NOT SQL 2005 A: insert into Test2.dbo.MyTable (MyValue) select MyValue from Test1.dbo.MyTable This is assuming a great deal. First that the destination database is empty. Second that the other columns are nullable. You may need an update instead. To do that you will need to have a common key.
{ "language": "en", "url": "https://stackoverflow.com/questions/52356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the point of clog? I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the same place I have error messages going out to (perhaps something in /var/log/messages), then I probably am not writing too much out (so there isn't much lost by using non-buffered cerr). In my experience, I want my log messages up to date (not buffered) so I can help find a crash (so I don't want to be using the buffered clog). Apparently I should always be using cerr. I'd like to be able to redirect clog inside my program. It would be useful to redirect cerr so that when I call a library routine I can control where cerr and clog go to. Can some compilers support this? I just checked DJGPP and stdout is defined as the address of a FILE struct, so it is illegal to do something like "stdout = freopen(...)". * *Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr? *Is the only difference between clog and cerr the buffering? *How should I implement (or find) a more robust logging facility (links please)? A: Since there are several answers here about redirection, I will add this nice gem I stumbled across recently about redirection: #include <fstream> #include <iostream> class redirecter { public: redirecter(std::ostream & dst, std::ostream & src) : src(src), sbuf(src.rdbuf(dst.rdbuf())) {} ~redirecter() { src.rdbuf(sbuf); } private: std::ostream & src; std::streambuf * const sbuf; }; void hello_world() { std::cout << "Hello, world!\n"; } int main() { std::ofstream log("hello-world.log"); redirecter redirect(log, std::cout); hello_world(); return 0; } It's basically a redirection class that allows you to redirect any two streams, and restore it when you're finished. A: Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr? Yes. You want the rdbuf function. ofstream ofs("logfile"); cout.rdbuf(ofs.rdbuf()); cout << "Goes to file." << endl; Is the only difference between clog and cerr the buffering? As far as I know, yes. A: Redirections Konrad Rudolph answer is good in regard to how to redirect the std::clog (std::wclog). Other answers tell you about various possibilities such as using a command line redirect such as 2>output.log. With Unix you can also create a file and add another output to your commands with something like 3>output.log. In your program you then have to use fd number 3 to print the logs. You can continue to print to stdout and stderr normally. The Visual Studio IDE has a similar feature with their CDebug command, which sends its output to the IDE output window. stderr is the same as stdout? This is generally true, but under Unix you can setup the stderr to /dev/console which means that it goes to another tty (a.k.a. terminal). It's rarely used these days. I had it that way on IRIX. I would open a separate X-Window and see errors in it. Also many people send error messages to /dev/null. On the command line you write: command ...args... 2>/dev/null syslog One thing not mentioned, under Unix, you also have syslog(). The newest versions under Linux (and probably Mac OS/X) does a lot more than it used to. Especially, it can use the identity and some other parameters to redirect the logs to a specific file (i.e. mail.log). The syslog mechanism can be used between computers, so logs from computer A can be sent to computer B. And of course you can filter logs in various ways, especially by severity. The syslog() is also very simple to use: syslog(LOG_ERR, "message #%d", count++); It offers 8 levels (or severity), a format a la printf(), and a list of arguments for the format. Programmatically, you may tweak a few things if you first call the openlog() function. You must call it before your first call to syslog(). As mentioned by unixman83, you may want to use a macro instead. That way you can include some parameters to your messages without having to repeat them over and over again. Maybe something like this (see Variadic Macro): // (not tested... requires msg to be a string literal) #define LOG(lvl, msg, ...) \ syslog(lvl, msg " (in " __FILE__ ":%d)", __VA_ARGS__, __LINE__) You may also find __func__ useful. The redirection, filtering, etc. is done by creating configuration files. Here is an example from my snapwebsites project: mail.err /var/log/mail/mail.err mail.* /var/log/mail/mail.log & stop I install the file under /etc/rsyslog.d/ and run: invoke-rc.d rsyslog restart so the syslog server handles that change and saves any mail related logs to those folders. Note: I also have to create the /var/log/mail folder and the files inside the folder to make sure it all works right (because otherwise the mail daemon may not have enough permissions.) snaplogger (a little plug) I've used log4cplus, which, since version 1.2.x, is quite good. I have three cons about it, though: * *it requires me to completely clear everything if I want to call fork(); somehow it does not survive a fork(); call properly... (at least in the version I had it used a thread) *the configuration files (.properties) are not easy to manage in my environment where I like the administrators to make changes without modifying the original *it uses C++03 and we are now in 2019... I'd like to have at least C++11 Because of that, and especially because of point (1), I wrote my own version called snaplogger. This is not exactly a standalone project, though. I use many other projects from the snapcpp environment (it's much easier to just get snapcpp and run the bin/build-snap script or just get the binaries from launchpad.) The advantage of using a logger such as snaplogger or log4cplus is that you generally can define any number of destinations and many other parameters (such as the severity level as offered by syslog()). The log4cplus is capable of sending its output to many different places: files, syslog, MS-Windows log system, console, a server, etc. Check out the appenders in those two projects to have an idea of the list of possibilities. The interesting factor here is that any log can be sent to all the destinations. This is useful to have a file named all.log where all your services send their logs. This allows to understand certain bugs which would not be as easy with separate log files when running many services in parallel. Here is a simple example in a snaplogger configuration file: [all] type=file lock=true filename=/var/log/snapwebsites/all.log [file] lock=false filename=/var/log/snapwebsites/firewall.log Notice that for the all.log file I require a lock so multiple writers do not mangle the logs between each others. It's not necessary for the [file] section because I only have one process (no threads) for that one. Both offer you a way to add your own appenders. So for example if you have a Qt application with an output window, you could write an appender to send the output of the SNAP_LOG_ERROR() calls to that window. snaplogger also offers you a way to extend the variable support in messages (also called the format.) For example, I can insert the date using the ${date} variable. Then I can tweak it with a parameter. To only output the year, I use ${date:year}. This variable parameter support is also extensible. snaplogger can filter the output by severity (like syslog), by a regex, and by component. We have a normal and a secure component, the default is normal. I want logs sent to the secure component to be written to secure files. This means in a sub-directory which is way more protected than the normal logs that most admins can review. When I run my HTTP services, some times I send information such as the last 3 digits of a credit card. I prefer to have those in a secure log. It could also be password related errors. Anything I deem to be a security risk in a log, really. Again, components are extensible so you can have your own. A: One little point about the redirecter class. It needs to be destroyed properly, and only once. The destructor will ensure this will happen if the function it is declared in actually returns, and the object itself is never copied. To ensure it can't be copied, provide private copy and assignment operators: class redirecter { public: redirecter(std::ostream & src, std::ostream & dst) : src_(src), sbuf(src.rdbuf(dst.rdbuf())) {} ~redirecter() { src.rdbuf(sbuf); } private: std::ostream & src_; std::streambuf * const sbuf_; // Prevent copying. redirecter( const redirecter& ); redirecter& operator=( const redirecter& ); }; I'm using this technique by redirecting std::clog to a log file in my main(). To ensure that main() actually returns, I place the guts of main() in a try/catch block. Then elsewhere in my program, where I might call exit(), I throw an exception instead. This returns control to main() which can then execute a return statement. A: If you're in a posix shell environment (I'm really thinking of bash), you can redirect any file descriptor to any other file descriptor, so to redirect, you can just: $ myprogram 2>&5 to redirect stderr to the file represented by fd=5. Edit: on second thought, I like @Konrad Rudolph's answer about redirection better. rdbuf() is a more coherent and portable way to do it. As for logging, well...I start with the Boost library for all things C++ that isn't in the std library. Behold: Boost Logging v2 Edit: Boost Logging is not part of the Boost Libraries; it has been reviewed, but not accepted. Edit: 2 years later, back in May 2010, Boost did accept a logging library, now called Boost.Log. Of course, there are alternatives: * *Log4Cpp (a log4j-style API for C++) *Log4Cxx (Apache-sponsored log4j-style API) *Pantheios (defunct? last time I tried I couldn't get it to build on a recent compiler) *Google's GLog (hat-tip @SuperElectric) There's also the Windows Event logger. And a couple of articles that may be of use: * *Logging in C++ (Dr. Dobbs) *Logging and Tracing Simplified (Sun) A: Basic Logger #define myerr(e) {CriticalSectionLocker crit; std::cerr << e << std::endl;} Used as myerr("ERR: " << message); or myerr("WARN: " << message << code << etc); Is very effective. Then do: ./programname.exe 2> ./stderr.log perl parsestderr.pl stderr.log or just parse stderr.log by hand I admit this is not for extremely performance critical code. But who writes that anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/52357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "68" }
Q: Simple & basic form spam reduction: checking for Javascript? I'm trying to reduce the form spam on our website. (It's actually pretty recent). I seem to remember reading somewhere that the spammers aren't executing the Javascript on the site. Is that true? And if so, then could you simply check for javascript being disabled and then figure it's likely that it's spam? A: There are still a large number of people that run with Javascript turned off. Alternatively, I have had decent success with stopping form spam using CSS. Basically, include an input field and label that is hidden using CSS (display: none;) and once submitted, check if anything has been entered in the field. I generally label the field as a spam filter with an instruction to not put anything in the field, but all newer browsers will properly hide the block. * *More: Fighting Spam with CSS reCAPTCHA is also surprisingly easy to implement. A: check http://kahi.cz/wordpress/ravens-antispam-plugin/ for a nice answer if puts in <noscript><p><label for="websiteurl99f">Please type "e73053": </label><input type="text" name="websiteurl99f" id="websiteurl99f" /></p></noscript> <script type="text/javascript">/* <![CDATA[ */ document.write('<div><input type="hidden" name="websiteurl99f" value="e' + '73053" \/><\/div>'); /* ]]> */</script> so javascript users see nothing, non js users just type in a word if a spammer targets you specifically it won't take them long to code round it but for drive by spammers it should be good A: You could check - have JavaScript that populates a hidden form field with a specific value after the page loads. Then, when the page posts back to the server, check that hidden form field the expected value. If it is not there, that means the JavaScript didn't execute. As to whether you should assume it is spam is another story altogether, and one that has no certain answer, really. You could simply have a <noscript> tag and have it indicate to the user that their submission will not take unless they enable JavaScript. Once you have JavaScript running, however, the spammers will just use another workaround for that. :) A: In the same vein, adding a dummy field and then using CSS to hide it is a good way to trick the bots. If the field is submitted, you know a non-human probably completed the form. Especially effective if you label/name the field something along the lines of URL or website. A: I can't remember where I've seen this method but spam bots like to fill out forms. Have you considered putting a form field that is hidden with javascript (and says don't fill this field if the user doesn't have JavaScript). This way if something fills in this field you can ignore it as spam. A: Did you have any luck with this? I think some text based browsers have implemented basic JavaScript support, so maybe spam bots have as well? Otherwise I'm considering using a captcha for users without JavaScript and some automatic JavaScript check for other users.
{ "language": "en", "url": "https://stackoverflow.com/questions/52359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How can you determine what version(s) of .NET are running on a system? What are the different ways (programmatically and otherwise) to determine what versions of .NET are running on a system? A: Directly from the source: How to determine which versions and service pack levels of the Microsoft .NET Framework are installed A: If you're wanting the current framework version in use then you can see that via: System.Environment.Version A: I found How to check .NET Framework version installed much more usable. Essentially, open Internet Explorer, and paste this into the address bar: javascript:alert(navigator.userAgent) I don't know if it always works, or if it is complete, but it works for my uses, doesn't require a lot of extra reading, and works without installing anything additional. A: Get the smallest .NET Framework download possible that will tell you based on the headers you are sending. It only works on Internet Explorer or if you have the Firefox extension installed. More info in Hanselman's blog post. A: If you're using IIS6 and above, open up IIS and click on Web Service Extensions. It will list each framework installed. Granted, .NET 3.0 and 3.5 are both based on the 2.0 framework. A: It's not necessarily running I would say. Since you can have .NET 1.1, 2.0, 3.0 and 3.5 installed on the same machine and they can run perfectly side-by-side. Meaning one of your app can be running on top of 1.1 and another web application is running on 2.0. In IIS (for web app), this is quite easy, just go to the property of the virtual directory / application and go to the ASP.NET tab, you should see what version of .NET you are actually using (or rather, what version of ASP.NET which is pretty much tied into the .NET Framework version). ps. just remember, you can only run 1 version of .NET Framework per application pool in IIS. So if you try to use the same application pool to run different versions of the framework, you're in for a surprise. Solution is to just create a framework version specific application pool (i.e. one pool for all 1.1 framework and another for 2.0 framework)
{ "language": "en", "url": "https://stackoverflow.com/questions/52360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Ignore SVN ignore... possible? So I have some files I want to ignore in a subversion repository, but I don't want my ignore patterns for this to be propagated to the repository. In other words, I added some private files in my checkout that I want to keep, but they only exist for me and wouldn't make sense to be ignored for everyone, so if I use the svn:ignore, this will apply on the directory, and I either have to check that in (which I don't want to do), or see that this directory was modified every time I do an svn status. So, ideally I would like something like a .svnignore file which I could then mark to ignore itself as well as some other files (I think this is a possibility in git for example, using a .gitignore file, or whatever the name is). I'm guessing it might work to ignore the whole directory (maybe), but then I suspect I won't see any new files in that directory, which would also not be desirable. So does anybody know a way to do this in subversion? A: Subversion does have a per-user, global ignore setting, which sounds like what you want. Look in your .subversion directory (found in your home directory) and locate the Miscellany section of the config file. There should be an entry called global-ignores. For Windows users, this setting is found in the registry under HKEY_LOCAL_MACHINE\Software\Tigris.org\Subversion. More information is available in the Version Control with Subversion (the SVNBook). A: I'm confused about 2 things: * *why do you have files that you don't want to check in that other people might want to check in? seems like you'd get a conflict if that happened anyway *does just "ignoring" in the human sense not work for you? I'm just having trouble seeing a scenario where you wouldn't want to use svn:ignore...
{ "language": "en", "url": "https://stackoverflow.com/questions/52398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Patterns for the overlap of two objects I'm sure this has already been asked and answered so I apologize in advance for that but I'm not figuring out the correct keywords to search for. Searching for "Pattern" hits way too many Q & A's to be useful. I'm working on a regression testing app. I'm displaying a form on the screen and according to which user is logged in to the app some of the fields should be read-only. So I can abstract a field object and I can abstract a user object but what pattern should I be looking at to describe the intersection of these two concepts? In other words how should I describe that for Field 1 and User A, the field should be read-only? It seems like read-only (or not) should be a property of the Field class but as I said, it depends on which user is looking at the form. I've considered a simple two-dimensional array (e. g. ReadOnly[Field,User] = True) but I want to make sure I've picked the most effective structure to represent this. Are there any software design patterns regarding this kind of data structure? Am I overcomplicating things--would a two-dimensional array be the best way to go here? As I said if this has been asked and answered, I do apologize. I did search here and didn't find anything and a Google search failed to turn up anything either. A: Table driven designs can be effective. Steve Maguire had few nice examples in Writing Solid Code . They are also a great way to capture tests, see fit . In your case something like: Field1ReadonlyRules = { 'user class 1' : True, 'user class 2' : False } field1.readOnly = Field1ReadonlyRules[ someUser.userClass ] As an aside you probably want to model both users and user classes/roles/groups instead of combining them. A user typically captures who (authentication) while groups/roles capture what (permissions, capabilities) A: At first blush it sounds more like you have two different types of users and they have different access levels. This could be solved by inheritance (PowerUser, User) or by containing a security object or token that sets the level for the user. If you don't like inheritance as a rule, you could use a State pattern on the application, Decorate the user objects (Shudder) or possibly add strategy patterns for differing security levels. But I think it's a little early yet, I don't normally apply patterns until I have a firm idea of how the item will grown and be maintained.
{ "language": "en", "url": "https://stackoverflow.com/questions/52400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SQL Server best way to calculate datediff between current row and next row? I've got the following rough structure: Object -> Object Revisions -> Data The Data can be shared between several Objects. What I'm trying to do is clean out old Object Revisions. I want to keep the first, active, and a spread of revisions so that the last change for a time period is kept. The Data might be changed a lot over the course of 2 days then left alone for months, so I want to keep the last revision before the changes started and the end change of the new set. I'm currently using a cursor and temp table to hold the IDs and date between changes so I can select out the low hanging fruit to get rid of. This means using @LastID, @LastDate, updates and inserts to the temp table, etc... Is there an easier/better way to calculate the date difference between the current row and the next row in my initial result set without using a cursor and temp table? I'm on sql server 2000, but would be interested in any new features of 2005, 2008 that could help with this as well. A: Here is example SQL. If you have an Identity column, you can use this instead of "ActivityDate". SELECT DATEDIFF(HOUR, prev.ActivityDate, curr.ActivityDate) FROM MyTable curr JOIN MyTable prev ON prev.ObjectID = curr.ObjectID WHERE prev.ActivityDate = (SELECT MAX(maxtbl.ActivityDate) FROM MyTable maxtbl WHERE maxtbl.ObjectID = curr.ObjectID AND maxtbl.ActivityDate < curr.ActivityDate) I could remove "prev", but have it there assuming you need IDs from it for deleting. A: If the identity column is sequential you can use this approach: SELECT curr.*, DATEDIFF(MINUTE, prev.EventDateTime,curr.EventDateTime) Duration FROM DWLog curr join DWLog prev on prev.EventID = curr.EventID - 1 A: Hrmm, interesting challenge. I think you can do it without a self-join if you use the new-to-2005 pivot functionality. A: Here's what I've got so far, I wanted to give this a little more time before accepting an answer. DECLARE @IDs TABLE ( ID int , DateBetween int ) DECLARE @OID int SET @OID = 6150 -- Grab the revisions, calc the datediff, and insert into temp table var. INSERT @IDs SELECT ID, DATEDIFF(dd, (SELECT MAX(ActiveDate) FROM ObjectRevisionHistory WHERE ObjectID=@OID AND ActiveDate < ORH.ActiveDate), ActiveDate) FROM ObjectRevisionHistory ORH WHERE ObjectID=@OID -- Hard set DateBetween for special case revisions to always keep UPDATE @IDs SET DateBetween = 1000 WHERE ID=(SELECT MIN(ID) FROM @IDs) UPDATE @IDs SET DateBetween = 1000 WHERE ID=(SELECT MAX(ID) FROM @IDs) UPDATE @IDs SET DateBetween = 1000 WHERE ID=(SELECT ID FROM ObjectRevisionHistory WHERE ObjectID=@OID AND Active=1) -- Select out IDs for however I need them SELECT * FROM @IDs SELECT * FROM @IDs WHERE DateBetween < 2 SELECT * FROM @IDs WHERE DateBetween > 2 I'm looking to extend this so that I can keep at maximum so many revisions, and prune off the older ones while still keeping the first, last, and active. Should be easy enough through select top and order by clauses, um... and tossing in ActiveDate into the temp table. I got Peter's example to work, but took that and modified it into a subselect. I messed around with both and the sql trace shows the subselect doing less reads. But it does work and I'll vote him up when I get my rep high enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/52430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I draw text using OpenGL, SDL and C++? I heard about SDL_TFF which I read about here but I don't understand how am I supposed to connect the TrueType2 library. Maybe there is something better out there?
{ "language": "en", "url": "https://stackoverflow.com/questions/52431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Literal hashes in c#? I've been doing c# for a long time, and have never come across an easy way to just new up a hash. I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls. { "whatever" => {i => 1}; "and then something else" => {j => 2}}; A: When I'm not able to use C# 3.0, I use a helper function that translates a set of parameters into a dictionary. public IDictionary<KeyType, ValueType> Dict<KeyType, ValueType>(params object[] data) { Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>((data == null ? 0 :data.Length / 2)); if (data == null || data.Length == 0) return dict; KeyType key = default(KeyType); ValueType value = default(ValueType); for (int i = 0; i < data.Length; i++) { if (i % 2 == 0) key = (KeyType) data[i]; else { value = (ValueType) data[i]; dict.Add(key, value); } } return dict; } Use like this: IDictionary<string,object> myDictionary = Dict<string,object>( "foo", 50, "bar", 100 ); A: If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement. This example is based on the MSDN Example var students = new Dictionary<int, StudentName>() { { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}}, { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }}, { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }} }; A: Since C# 3.0 (.NET 3.5) hashtable literals can be specified like so: var ht = new Hashtable { { "whatever", new Hashtable { {"i", 1} } }, { "and then something else", new Hashtable { {"j", 2} } } }; A: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Dictionary { class Program { static void Main(string[] args) { Program p = new Program(); Dictionary<object, object > d = p.Dic<object, object>("Age",32,"Height",177,"wrest",36);//(un)comment //Dictionary<object, object> d = p.Dic<object, object>();//(un)comment foreach(object o in d) { Console.WriteLine(" {0}",o.ToString()); } Console.ReadLine(); } public Dictionary<K, V> Dic<K, V>(params object[] data) { //if (data.Length == 0 || data == null || data.Length % 2 != 0) return null; if (data.Length == 0 || data == null || data.Length % 2 != 0) return new Dictionary<K,V>(1){{ (K)new Object(), (V)new object()}}; Dictionary<K, V> dc = new Dictionary<K, V>(data.Length / 2); int i = 0; while (i < data.Length) { dc.Add((K)data[i], (V)data[++i]); i++; } return dc; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/52438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Are there C library resources similar to C++'s Boost library? I don't ever recall coming across anything for C that's as extensive as C++'s Boost library. A: I've never seen anything. Really, C++ templates are the enabling technology for STL and much of boost, and C doesn't have them. I've seen many C-interface libraries for things like image processing, 3D graphics, networking, etc., but never a real general-purpose library like boost. You can find pieces though - threading libraries, string libraries, etc. - that are similar to sections of boost. A: Depending on what exactly you're trying to do there is APR (The Apache Portable Runtime library) which is what the Apache http daemon is built on http://apr.apache.org/ For GUI, there is wxWidgets (formerly wxWindows) http://www.wxwidgets.org/ A: You can have a look at glib. It provides quite a few interesting things like containers, unicode support, threading... Have a look at its documentation A: Glib does compensate it partially in form of various unicode, string types. If you add Gobject you could get some object programming even some garbage collection. A: ACE (Adaptive Communication Environment) is sometimes mentioned. It's not quite an apples-to-apples comparison. Boost provides more "basic building blocks" whereas ACE provides more of an tightly integrated framework geared towards telco products. I have used both extensively and I find Boost vastly superior. One big advantage of Boost is that many of its features will show up in the STL extensions for the upcoming C++0x standard (see, for example, http://en.wikipedia.org/wiki/Technical_Report_1). A: or you can look at ccan http://ccan.ozlabs.org/ but no, there really isn't any complete package, glib comes closest
{ "language": "en", "url": "https://stackoverflow.com/questions/52445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Switching form Visual SourceSafe to CVS: what features are lost in Visual Studio? My company is using Visual SourceSafe (VSS) and Visual Studio 2005 (soon 2008). They want to switch to CVS, but the developers don't want to lose the integration we get with VSS and Visual Studio. I know there are CVS plugins, but what functionality, if any, is lost with CVS? A: If you're going to switch, why not switch to something better? CVS is a long way from state of the art in version control. A more modern system like Subversion or Vault not only offers better features, but it will get you better Visual Studio integration as well. A: Screaming at VSS for lost source code, etc. Seriously though, it is a very different model (optimistic locking), so you will probably lose some productivity for the first little while. I would probably look at using TortoiseCVS and "Open Folder In Windows Explorer" right-click or the Visual Studio Explorer plug-in rather than a CVS plug-in if you are using Visual Studio 2008 (all of the CVS plug-ins I have tried have had either serious functionality issues, or serious stability issues). VSS is really a terrible source control system, and moving to a modern style (optimistic locking) source control system will be a huge boon in the long run. You might want to skip the 1990s all together though and move to Subversion/Git/Mercurial and get into the 2000s. A: If you must switch to CVS (Subversion or a distributed VCS would be better) then the script we used to migrate and keep the change history can be found here. We are very happy with CVS, although we don't use Visual Studio integration as we find TortoiseCVS and SmartCVS much better. However if I was switching now I would look at Git or Mercurial. A: My hack is as follows: I am mainly a Java developer and I use Eclipse/RAD. The support for CVS is great and is very easy to work with. For the C# work I do I tried to find a CVS plugin for Visual Studio but was unhappy with the one I found. In the end, I decided to use Eclipse to handle the versioning of my C# projects. The procedure: * *Create a simple project in Eclipse *Open VS and save the project into the directory created by Eclipse *Return to Eclipse, press F5 to refresh the project *Share the project (i.e. add to CVS) *Add .sln to the list of externally handled files in the Eclipse settings *VS can now be opened directly from Eclipse by clicking the .sln file, the project can be worked on within VS. Upon exit from VS the project must be refreshed in Eclipse and can be synchronised with CVS Although I have not yet used the Subversion plugin, I guess that would work in a similar way. This solution works well for me especially as I spend most my time in Eclipse anyway. I did try using TortoiseCVS but found it tricky to use. Eclipse is free and the CVS interface is very usable. A: Visual Studio has a bad integration inside the IDE for CVS and SVN. Those free ones don't work well. I use Tortoise (outside Visual Studio), and it works fine. If you want something inside Visual Studio, you might check for not free plugin or to use TFS.
{ "language": "en", "url": "https://stackoverflow.com/questions/52447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IQuery NHibernate - does it HAVE to be a list? Can I return it as an object if I am doing a Select OneItem from Table Where OtherItem = "blah"? Is there a better way to do this? I am building a constructor to return an object based on its name rather than its ID. A: query.UniqueResult<T>() returns just one T A: If there's more than one potential result, then query.FirstResult() might be better. A: Or using LINQ you can have query.First(), query.SingleOrDefault(), query.Min(predicate) etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/52449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I find and decouple entities from a certificate when upgrading MS-SQLServer editions? While in the final throws of upgrading MS-SQL Server 2005 Express Edition to MS-SQL Server 2005 Enterprise Edition, I came across this error: The certificate cannot be dropped because one or more entities are either signed or encrypted using it. To continue, correct the problem... So, how do I find and decouple the entities signed/encrypted using this certificate so I can delete the certificate and proceed with the upgrade? I'm also kind of expecting/assuming that the upgrade setup will provide a new certificate and re-couple those former entities with it or I'll have to forcibly do so after the setup. A: The Microsoft forum has the following code snipit to delete the certificates: use msdb BEGIN TRANSACTION declare @sp sysname declare @exec_str nvarchar(1024) declare ms_crs_sps cursor global for select object_name(crypts.major_id) from sys.crypt_properties crypts, sys.certificates certs where crypts.thumbprint = certs.thumbprint and crypts.class = 1 and certs.name = '##MS_AgentSigningCertificate##' open ms_crs_sps fetch next from ms_crs_sps into @sp while @@fetch_status = 0 begin if exists(select * from sys.objects where name = @sp) begin print 'Dropping signature from: ' + @sp set @exec_str = N'drop signature from ' + quotename(@sp) + N' by certificate [##MS_AgentSigningCertificate##]' Execute(@exec_str) if (@@error <> 0) begin declare @err_str nvarchar(1024) set @err_str = 'Cannot drop signature from ' + quotename(@sp) + '. Terminating.' close ms_crs_sps deallocate ms_crs_sps ROLLBACK TRANSACTION RAISERROR(@err_str, 20, 127) WITH LOG return end end fetch next from ms_crs_sps into @sp end close ms_crs_sps deallocate ms_crs_sps COMMIT TRANSACTION go http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3876484&SiteID=17 I have not tried the script, so please backup your data and system before attempting and update here with results.
{ "language": "en", "url": "https://stackoverflow.com/questions/52460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Visual Web Developer Express and .NET, et al I'm coming from the open source world, and interested in giving ASP.NET a spin. But I'm having a little trouble separating the tools from the platform itself in regards to the licensing. I've downloaded Visual Web Developer 2008 Express, but not sure how different this is from one of the full-featured Visual Studio licenses -- and whether or not my Express license will prevent me from using all the features of ASP.NET. Is a Visual Studio license just an IDE, or does it include pieces of .NET not available to the Express license? What about the other tools like IIS and SQL Server? Thanks. A: All of .net is available in the .net SDK, so in theory you will not need Visual Studio at all. Now, there are some things that Express will not do. For example, the Database Designer is not very comprehensive and adding different remote databases is not or only very hardly possible. Still, in code you can connect to everything. There is also no Remote Debugger, no support for creating Setup Files (well, that does not apply to ASP.net anyway), no real Publish Web Site Feature (although that can be added manually as it's just a Frontend for a SDK tool), no integrated Unit testing (and Microsoft loves to threaten people who add it), etc. For a full comparison, see here: Visual Studio 2008 Editions But as said: Functionality of .net is all in the SDK, Visual Studio is just making it a bit easier to work with. A: Visual Studio is just an IDE, you can do all your .NET development with the SDK and notepad if you choose. In fact there is something to be said for learning it that way so you understand better how the pieces fit together! Microsoft have a version comparison matrix available so you can see exactly what is included each version. IIS is a Windows component and considered part of the OS, there is nothing else to buy. SQL Server comes in many flavours, SQL EXpress is free to use and whilst limited compared to the versions you pay for, it is more than enough to get started with ASP.Net A: Visual Studio is the IDE and does not include the platform. IIS and SQL Server are separate products. IIS is available as part of the windows install and the version is different depending on what version of Windows you are using. SQL Server also has an express product which is not as full featured as the Full versions of SQL Server, yet it is still rather valuable and useful especially for learning purposes. You can learn a lot from the free tutorials found on asp.net. A: Visual Studio is just the IDE. You could theoretically create every file in Notepad and compile manually with just the .net framework. IIS is an operating system feature, and SQL Server has different flavors with different capabilites. A: SharpDevelop is a Open Source IDE for C# and VB.net
{ "language": "en", "url": "https://stackoverflow.com/questions/52469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }