text
stringlengths
8
267k
meta
dict
Q: How to handle functions deprecation in library? I'm working on a Java library and would like to remove some functions from it. My reasons for this is public API and design cleanup. Some objects have setters, but should be immutable, some functionality has been implemented better/cleaner in different methods, etc. I have marked these methods 'deprecated', and would like to remove them eventually. At the moment I'm thinking about removing these after few sprints (two week development cycles). Are there any 'best practices' about removing redundant public code? /JaanusSiim A: Consider it this way, customer A downloads the latest version of you library file or frame work. He hits compile on this machine and suddenly he see thousands of errors because the member file or function does no longer exist. From this point on, you've given the customer a reason why not to upgrade to your new version and to stay with the old version. Raymond Chen answers this the best with his blog about win32 API, Though, our experience in our software house has been, once the API has been written we have to carry the API to the end of the product life cycle. To help users to new versions, we provide backwards compatibility with the old commands in the new framework. A: Set a date and publicize it in the @deprecated tag. The amount of time given to the removal depends on the amount of users your code has, how well connected you are with them and the the reason for the change. If you have thousands of users and you barely talk to them, the time frame should probably be in the decades range :-) If your users are your 10 coworkers and you see them daily, the time frame can easily be in the weeks range. /** * @deprecated * This method will be removed after Halloween! * @see #newLocationForFunctionality */ A: It depends on how often the code is rebuild. For example, if there are 4 applications using the library, and they are rebuild daily, a month is a long enough time to fix the deprecated calls. Also, if you use the deprecated tag, provide some comment on which code replaces the deprecated call. A: Use @deprecated tag. Read the Deprecation of APIs document for more info. After everyone using the code tells you they have cleaned up on their side, start removing the deprecated code and wait and see if someone complains - then tell them to fix their own code... A: Given that this is a library, consider archiving a version with the deprecated functions. Make this version available in both source code and compiled form, as a backup solution for those who haven't modernized their code to your new API. (The binary form is needed, because even you may have trouble compiling the old version in a few years.) Make it clear that this version will not be supported and enhanced. Tag this version with a symbolic symbol in your version control system. Then move forward. A: It certainly depends at which scale your API is used and what you promised upfront to your customers. As described by Vinko Vrsalovic, you should enter a date when they have to expect the abandon of the function. In production, if it's "just" a matter of getting cleaner code, I tend to leave things in place even past the deprecating date as long as it doesn't break anything. On the other hand in development I do it immediately, in order to get things sorted out quickly. A: You may be interested in examples of how deprecation works in some other projects. For example, here follows what the policy in the Django project for function deprecation is: A minor release may deprecate certain features from previous releases. If a feature in version A.B is deprecated, it will continue to work in version A.B+1. In version A.B+2, use of the feature will raise a PendingDeprecationWarning but will continue to work. Version A.B+3 will remove the feature entirely. A: too bad you are not using .Net :( The built in Obsolete attribute generates compiler warnings.
{ "language": "en", "url": "https://stackoverflow.com/questions/152205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: D (and Tango) on PowerPC Linux It's hard to search for D using Google, so I wasn't able to find a good answer: I have an old iBook G3 and I'd like to install Linux on it and use it to compile (and test) D programs written using Tango on it. Is this possible? Or hasn't anybody tried it, yet? After all the Mac port of GDC + Tango is broken in parts, too. A: This used to work, but it has been a combination with few users, and so I'm not sure if it has been tested recently. There shouldn't be major problems with Tango though - compiler is probably likely to a more likely issue. For that, you probably should try to compile your own from a recent SVN checkout (of GDC).
{ "language": "en", "url": "https://stackoverflow.com/questions/152209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using database resources in Axiom Safe Request I would like to know how to make use of an Axiom database resource inside a Safe function. Right now I'm just handling the connection manually but I know it would be better to use the already defined resources. A: I found how. if ever need to do it, you can do it like this: define db resource in safe.t_resources and then in the safe function java code: String DB_RESOURCE="DATABASE"; this.dbResource = getResource(this.DB_RESOURCE); Oracle oracle = new Oracle(this.dbResource); Connection conn = oracle.getConnection(); yep, that simple
{ "language": "en", "url": "https://stackoverflow.com/questions/152215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Boost Range Library: Traversing Two Ranges Sequentially Boost range library (http://www.boost.org/doc/libs/1_35_0/libs/range/index.html) allows us to abstract a pair of iterators into a range. Now I want to combine two ranges into one, viz: given two ranges r1 and r2, define r which traverses [r1.begin(), r1.end()[ and then [r2.begin(), r2.end()[. Is there some way to define r as a range using r1 and r2? A: I needed this again so I had a second look. There is a way to concat two ranges using boost/range/join.hpp. Unluckily the output range type is not included in the interface: #include "boost/range/join.hpp" #include "boost/foreach.hpp" #include <iostream> int main() { int a[] = {1, 2, 3, 4}; int b[] = {7, 2, 3, 4}; boost::iterator_range<int*> ai(&a[0], &a[4]); boost::iterator_range<int*> bi(&b[0], &b[4]); boost::iterator_range< boost::range_detail:: join_iterator<int*, int*, int, int&, boost::random_access_traversal_tag> > ci = boost::join(ai, bi); BOOST_FOREACH(int& i, ci) { std::cout << i; //prints 12347234 } } I found the output type using the compiler messages. C++0x auto will be relevant there as well. A: * *Can't you call the function twice, once for both ranges? Or are there problems with this approach? *Copy the two ranges into one container and pass that. *Write your own range class, so it iterates through r1 first and and through r2 second. A: I think you'd have to make a custom iterator that will 'roll over' r1.end() to r2.begin() when r1.end() is reached. Begin() and end() of that iterator would then be combined into your range r. AFAIK there is no standard boost function that will give you this behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/152216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Looking for a regular expression including alphanumeric + "&" and ";" Here's the problem: split=re.compile('\\W*') This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like k&amp;auml;ytt&amp;auml;j&aml;auml;. What should I add to the regex to include the & and ; characters? A: I would treat the entities as a unit (since they also can contain numerical character codes), resulting in the following regular expression: (\w|&(#(x[0-9a-fA-F]+|[0-9]+)|[a-z]+);)+ This matches * *either a word character (including “_”), or *an HTML entity consisting of * *the character “&”, * *the character “#”, * *the character “x” followed by at least one hexadecimal digit, or *at least one decimal digit, or *at least one letter (= named entity), *a semicolon *at least once. /EDIT: Thanks to ΤΖΩΤΖΙΟΥ for pointing out an error. A: You probably want to take the problem reverse, i.e. finding all the character without the spaces: [^ \t\n]* Or you want to add the extra characters: [a-zA-Z0-9&;]* In case you want to match HTML entities, you should try something like: (\w+|&\w+;)* A: you should make a character class that would include the extra characters. For example: split=re.compile('[\w&;]+') This should do the trick. For your information * *\w (lower case 'w') matches word characters (alphanumeric) *\W (capital W) is a negated character class (meaning it matches any non-alphanumeric character) ** matches 0 or more times and + matches one or more times, so * will match anything (even if there are no characters there). A: Looks like this RegEx did the trick: split=re.compile('(\\\W+&\\\W+;)*') Thanks for the suggestions. Most of them worked fine on Reggy, but I don't quite understand why they failed with re.compile.
{ "language": "en", "url": "https://stackoverflow.com/questions/152218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I distribute a WCF Peer to Peer application over the Internet? Can someone point me in the right direction? I wish to distribute a WCF peer to peer cloud over the internet. So far I've seen examples of how it works on the same subnet. I wish to push it a little further. A: I believe you'll need to look into using IPV6 Teredo Tunneling for crossing NAT and firewalls, so maybe check out this on WCF transports from MSDN. Also, take a look at the PRNP series Kevn Hoffman did this year. A: Depending on your application you may want to check out Groove Virtual Office, which was recently acquired by Microsoft and shipped with Office 2007. I don't believe it uses WCF, but it certainly uses .NET and has an SDK available that should allow you to create a P2P application with ease. If you are developing for the enterprise, be prepared to deal with scalability problems. A: I will look into Live Mesh, it may be the solution to my problem. A: So even though this is a year later... Haven't you tried out the One click deployment method? Or what about just having the MSI install package for download? Is the deployment or the communication that you are trying to solve. Sounds like a distribution problem. The method for getting pat NAT problems is called "Nat Traversal".
{ "language": "en", "url": "https://stackoverflow.com/questions/152238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ruby on rails (based on Mephisto) - Unable to contact server I am completely new to ruby and I inherited a ruby system for a product catalogue. Most of my users are able to view everything as they should but overseas users (specifically Mexico) cannot contact the server once logged in. They are an active user. I'm sorry I cannot be more specific, and the system is private so I cannot grant access. Has anyone had any issues similar to this before? Is it a user-end issue or a system error? A: Speaking as somebody who regularly ends up on your user's side of the fence, the number one culprit for this symptom is "Clueless administrator". There are many, many sites which generically block either large blocks of IP space or which geolocate and carve out big portions of the world. For example, a surprising number of American blogs block Asian countries (including Japan) out of a misplaced effort to avoid DDOS attacks (which actually probably originated in Russia or China but, hey, this species of administrator isn't very good on fine tuning solutions). I have to hop over to my American proxy server to access those sites. So the first thing I'd do to diagnose your problems is to see whether your Mexican users are making it to the server at all, or whether they're being blocked somewhere earlier (router? firewall? etc). Then, to determine whether the problem is on your end or their end, I'd try to replicate the issue with you proxying your connection through a Mexican proxy and repeating the actions they took to cause the issue. The fact that they get blocked after logging in could indicate that you have https issues , for example with an HTTPS accelerator installed [1], or it could be that your frontend server is properly serving up the static content but doing the checking on dynamic requests only. [1] We've seen some really weird bugs at work caused by a malfunctioning HTTPS accelerator. A: If it's working for everyone else then it would appear that the problem is not with Ruby or Rails working, since they are... My first thought would be to check for a network issue: are the Mexican users all behind the same proxy server and/or firewall? Is login handled within the Rails application or via some other resource? Can you see any evidence that requests from Mexican users are reaching your web server at all? A: Login is handled by the rails app. Am currently trying to hunt down the logs, taking some time as again I am new to this system. Cheers guys A: Maybe INS is cracking down on cyber-immigration.
{ "language": "en", "url": "https://stackoverflow.com/questions/152240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a good tool for writing a user manual (help file), which integrates with version control The people writing the user manual are not necessarily programmers, and they need a visual editor. A major issue is the internal format of the authoring tool; it should be readable text/html, so it's easy to compare versions of individual pages checked into version control. A: Microsoft HTML Help Workshop can be used to create good quality professional CHM help files. All you need is a bunch of HTML files. The tool "compiles" all these and bundles into a single Help file. The HTML files can be generated using Microsoft Word/Frontpage or even Dreamweaver. You might want to consider source controlling these HTML files. A: Latex. Lyx provides WYSIWYM for writing latex files. A: At my old job they used a tool by madcap software called flare. It seemed to work really well. A: There are other professional products which allow help file writing and they have support of "context ID" which makes context sensitive help possible. Doc To Help and RoboHelp are these type of products. A: A good combination to consider is Subversion, DocBook and Publican. * *Version control = Subversion *Content Authoring = DocBook *Publishing = Publican *Optional WYSIWYG = Serna At the moment, this is one of the toolchains in use by the world's largest provider of open source solutions, and the name behind much of the world's use of Linux-based operation systems in the enterprise market. Most (and close to all) of Red Hat's official documentation is created in such a manner. Same goes for Fedora. The major "pro" here is that these are freely available tools, with a strong overlap in the market of technical writers. All of which will be able to (but might not want to) write in XML, and picking up DocBook is like picking up HTML in the 90's. Subversion is a very common version control tool, that like DocBook is relatively easy to implement and use. Publican is a great publishing tool that can take DocBook XML, and publish it to PDF, HTML, HTML-single, etc. Obviously your writers can use a WYSIWYG like Serna, but I use snippets in Geany (on Fedora) or TextMate (on OS X) personally. The major "con" is the perception of technicality. Your writers might want WYSIWYG (and can have it), and depending on your documentation needs, this might be what you end up using. As you would know, there's a market out there for "Technical Writers" who specialize in fixing Microsoft Word styles (and markup), so the arguments for separating "authoring" from "publishing" are based on proven but distinct use cases for organizations that require documentation to be held up to the same standards of the engineering/programming/source production. Some of the extreme advice you will get comes from people and companies that have been exposed to the value of XML documentation, and especially those in the realms of DITA, where certain multi-nationals have a reputation for acquisitions that are influenced by the format and availability of the product knowledge. there are also the arguments that locking your documentation into a "sticky" or closed format doesn't help the future maintenance requirements. This is where the open source options gain support on a corporate level. Plus, obviously, it's free. A: You can use Subversion and MGTEK Help Producer. Help Producer makes help files from Word documents. TortoiseSVN comes with scripts to compare different revisions of Word documents, in Word itself (Word has a version compare tool). Your users are going to want a visual diff tool that resembles the one they are editing in. If they are just slightly not-technical, DocBook or Latex aren't going to work (I've tried giving my users both, and I even tried Epic Editor as a DocBook editor which is very expensive but didn't work out very well after all). Sticking to something they know (Word) will prevent you many headaches. I was very reluctant to go this route at first too, because I wanted a solution that was more 'technically perfect', but I realized over time that having happy and productive users was more important. Just saying that I know where you're coming from, but try the Word route - it works much better in practice than all the 'pure' text-based solutions that are out there. Regular users don't like markup based editing. A: DocBook (source: docbook.org) A: I created a documentation system called Mandown (Markdown/Html/Javascript/file-based relatively linked documents for portability) which would easily go under version control. The visual editor part you would have to figure out separately - I sometimes use HTML-Kit which at least has a preview feature. See What is the best way to store software documentation? Here's another tool to check out: Xilize A: If you're using Visual Studio, take a look at SandCastle - http://www.codeplex.com/Sandcastle. There's also a couple of tools that help you build sandcastle files, try searching "sandcastle" on codeplex. One of them is SandCastle Help File Builder (http://www.codeplex.com/SHFB), but I've never used it so I don't know if non-technical users will be happy with that. A: Mapcap Flare is the best commercial tool around. Written by the ex-developers of Robodoc A: We are using APT. It integrates well with the CI (standard build artifact) and is more alive than for instance word document. It is also possible to generate PDFs and other formats when needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/152241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Transaction encapsulation of multi-process writes I have a database scenario (I'm using Oracle) in which several processes make inserts into a table and a single process selects from it. The table is basically used as intermediate storage, to which multiple processes (in the following called the Writers) write log events, and from which a single process (in the following referred to as the Reader) reads the events for further processing. The Reader must read all events inserted into the table. Currently, this is done by each inserted record being assigned an id from an ascending sequence. The reader periodically selects a block of entries from the table where the id is larger than the largest id of the previously read block. E.g. something like: SELECT * FROM TRANSACTION_LOG WHERE id > ( SELECT last_id FROM READER_STATUS ); The problem with this approach is that since writers operate concurrently, rows are not always inserted in order according to their assigned id, even though these are assigned in sequentially ascending order. That is, a row with id=100 is sometimes written after a record with id=110, because the process of writing the row with id=110 started after the processes writing the record id=100, but committed first. This can result in the Reader missing the row with id=100 if it has already read row with id=110. Forcing the Writers to an exclusive lock on the table would solve the problem as this would force them to insert sequentially and also for the Reader to wait for any outstanding commits. This, however, would probably not be very fast. It is my thinking, that it would suffice for the Reader to wait for any outstanding Writer commits before reading. That is, Writers may continue to operate concurrently as longs as the Reader does read until all writers have finished. My question is this: How can I instruct my reader process to wait for any outstanding commits of my writer processes? Any alternative suggestions to the above problem are also welcome. A: Interesting problem. It sounds like you're building a nice solution. I hope I can help. A couple of suggestions... Writer Status You could create a table, WRITER_STATUS, which has a last_id field: Each writer updates this table before writing with the ID it is going to write to the log, but only if its ID is greater than the current value of last_id. The reader also checks this table and now knows if any writers have not yet written. Reader Log This may be more efficient. After the reader does a read, it checks for any holes in the records it's retrieved. It then logs any missing IDs to a MISSING_IDS table and for its next read it does something like SELECT * FROM TRANSACTION_LOG WHERE id > (SELECT last_id FROM READER_STATUS) OR id IN ( SELECT id from MISSING_IDS ) A: You might want to put an exclusive lock on the table in the reader process. This will wait until all writers finish and release their row locks, so you can be sure there are no outstanding writer transactions. A: I wouldn't do any locking, that can interfere with concurrency and throughput. You don't need the Reader_Status table either, if you keep track of which log rows you've processed on a row by row basis. Here's what I'd do: add a new column to your log table. Call it "processed" for example. Make it a boolean, defaults to false (or small integer, defaults to 0, or whatever). The Writers use the default value when they insert. When the Reader queries for the next block of records to process, he queries for rows where processed is false and the id value is low. SELECT * FROM Transaction_Log WHERE processed = 0 ORDER BY id LIMIT 10; As he processes them, the Reader uses UPDATE to change processed from false to true. So the next time the Reader queries for a block of records, he is sure he won't get rows he has already processed. UPDATE Transaction_Log SET processed = 1 WHERE id = ?; -- do this for each row processed This UPDATE shouldn't conflict with the INSERT operations done by the Writers. If any rows are committed out of sequence by other Writers, the Reader will see them next time he queries, if he always processes them in order of the id column from lowest value to highest value. A: Since you know last_id processed by Reader, you can request next work item in this manner: select * from Transaction_log where id = ( select last_id + 1 /* or whatever increment your sequencer has */ from Reader_status) A: I agree with AJ's solution ( link ). Additionally following suggestions may help to reduce the number of holes. 1) Use Oracle Sequence to create the id and use auto-increment like as follows INSERT INTO transaction_table VALUES(id__seq.nextval, <other columns>); 2) Use autoCommit(true) so that insert will commit immediately. These two steps will reduce the number of holes substantially. Still there is a possibility that some inserts started first but got committed later and a read operation happened in between.
{ "language": "en", "url": "https://stackoverflow.com/questions/152243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I use HTTP Basic Authentication with Django? We have a website running on Apache, access to which has a number of static pages protected via HTTP Basic authentication. I've written a new part of the site with Django using Django's built in support for user management. The problem I have is that users have to log in once via the HTTP Basic authentication and then again using a Django login form. This both clumsy and very confusing for users. I was wondering if anyone had found a way to make Django log a user in using the HTTP Basic authentication information. I not expecting to pass a password to Django, but rather if a user dave has been authenticated by Apache then they should be automatically logged into Django as dave too. (One option would be to make Apache and Django share a user store to ensure common usernames and passwords but this would still involve two login prompts which is what I'm trying to avoid.) A: Yes you can use basic autorization with django as something similar: def post(self, request): auth_header = request.META.get('HTTP_AUTHORIZATION', '') token_type, _, credentials = auth_header.partition(' ') import base64 expected = base64.b64encode(b'<username>:<password>').decode() if token_type != 'Basic' or credentials != expected: return HttpResponse(status=401) authorization success flow code ... request.META contains key HTTP_AUTHORIZATION in which your Autorization is present. In case if you are using apache with modWSGI, the key HTTP_AUTHORIZATION might not be present. You need to add below line in your WSGI config WSGIPassAuthorization On Refer this detailed answer: Passing apache2 digest authentication information to a wsgi script run by mod_wsgi Hope it is useful for someone who is wondering why HTTP_AUTHORIZATION key is not present A: For just supporting basic auth on some requests (and not mucking with the web server -- which is how someone might interpret your question title), you will want to look here: http://www.djangosnippets.org/snippets/243/ A: There is httpauth.py. I'm still a complete newb with Django so I've no idea how it fits in exactly, but it should do what you're looking for. Edit: here's a longer bug thread on the subject. A: This has been added to the Django 1.3 release. See more current documentation for this here: http://docs.djangoproject.com/en/dev/howto/auth-remote-user/ A: Do check out Oli's links. You basically see the authenticated username as verified by Basic HTTP Authentication in Django by looking at request.META['REMOTE_USER']. Update: Tested the proposed patch for ticket #689, which is available up-to-date in telenieko's git repository here. It applies cleanly at least on revision 9084 of Django. Activate the remote user authentication backend by * *adding the RemoteUserAuthMiddleware after AuthenticationMiddleware *adding the setting AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.RemoteUserAuthBackend',) If you use lighttpd and FastCGI like I do, activate mod_auth, create credentials for a test user (I called it testuser and set 123 as the password) and configure the Django site to require basic authentication. The following urls.py can be used to test the setup: from django.conf.urls.defaults import * from django.http import HttpResponse from django.contrib.auth.models import User urlpatterns = patterns('', url(regex='^$', view=lambda request: HttpResponse(repr(request), 'text/plain')), url(regex='^user/$', view=lambda request: HttpResponse(repr(request.user), 'text/plain')), url(regex='^users/$', view=lambda request: HttpResponse( ','.join(u.username for u in User.objects.all()), 'text/plain')), ) After reloading lighty and the Django FCGI server, loading the root of the site now asks for authentication and accepts the testuser credentials, and then outputs a dump of the request object. In request.META these new properties should be present: 'AUTH_TYPE': 'Basic' 'HTTP_AUTHORIZATION': 'Basic dGVzdHVzZXI6MTIz' 'REMOTE_USER': 'testuser' The /user/ URL can be used to check that you're indeed logged in as testuser: <User: testuser> And the /users/ URL now lists the automatically added testuser (here the admin user I had created when doing syncdb is also shown): admin,testuser If you don't want to patch Django, it's trivial to detach the RemoteUserAuthBackend and RemoteUserAuthMiddleware classes into a separate module and refer to that in the Django settings. A: Because django can be run in several ways, and only modpython gives you close integration with Apache, I don't believe there is a way for django to log you in basic on Apache's basic auth. Authentication should really be done at the application level as it'll give you much more control and will be simpler. You really don't want the hassle of sharing a userdata between Python and Apache. If you don't mind using a patched version of Django then there is a patch at http://www.djangosnippets.org/snippets/56/ which will give you some middleware to support basic auth. Basic auth is really quite simple - if the user isn't logged in you return a 401 authentication required status code. This prompts the browser to display a login box. The browser will then supply the username and password as bas64 encoded strings. The wikipedia entry http://en.wikipedia.org/wiki/Basic_access_authentication is pretty good. If the patch doesn't do what you want then you could implement basic auth yourself quite quickly. A: This seems to be a task for custom AuthenticationBackend - see Django documentation on this subject, djangosnippets.org has some real-life examples of such code (see 1 or 2) (and this is not really a hard thing). AuthenticationBackend subclasses have to have only 2 methods defined and their code is pretty straightforward: one has to return User object for user ID, the second has to perform credentials check and return User object if the credentials are valid.
{ "language": "en", "url": "https://stackoverflow.com/questions/152248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: Get class property name I have my winform application gathering data using databinding. Everything looks fine except that I have to link the property with the textedit using a string: Me.TextEdit4.DataBindings.Add(New System.Windows.Forms.Binding("EditValue", Me.MyClassBindingSource, "MyClassProperty", True)) This works fine but if I change the class' property name, the compiler obviously will not warn me . I would like to be able to get the property name by reflection but I don't know how to specify the name of the property I want (I only know how to iterate among all the properties of the class) Any idea? A: If you are using C# 3.0, there is a way to get the name of the property dynamically, without hard coded it. private string GetPropertyName<TValue>(Expression<Func<BindingSourceType, TValue>> propertySelector) { var memberExpression = propertySelector.Body as MemberExpression; return memberExpression != null ? memberExpression.Member.Name : string.empty; } Where BindingSourceType is the class name of your datasource object instance. Then, you could use a lambda expression to select the property you want to bind, in a strongly typed manner : this.textBox.DataBindings.Add(GetPropertyName(o => o.MyClassProperty), this.myDataSourceObject, "Text"); It will allow you to refactor your code safely, without braking all your databinding stuff. But using expression trees is the same as using reflection, in terms of performance. The previous code is quite ugly and unchecked, but you get the idea. A: Here is an example of what I'm talking about: [AttributeUsage(AttributeTargets.Property)] class TextProperyAttribute: Attribute {} class MyTextBox { [TextPropery] public string Text { get; set;} public int Foo { get; set;} public double Bar { get; set;} } static string GetTextProperty(Type type) { foreach (PropertyInfo info in type.GetProperties()) { if (info.GetCustomAttributes(typeof(TextProperyAttribute), true).Length > 0) { return info.Name; } } return null; } ... Type type = typeof (MyTextBox); string name = GetTextProperty(type); Console.WriteLine(name); // Prints "Text" A: Ironically reflection expects that you provide property name to get it's info :) You can create custom attribute, apply it to desired property. Then you will be able to simply get name of the property having this attribute. A: You'll have the same problem using reflection because in order to find the right property in all the type's properties, you'll have to know its name, right? A: You can reflect a Type, but you can't reflect its members except by name. If that were the only property, or you knew for certain the ordering you could find it by index, but generally speaking a string is the safest way to go. I believe changing the name will cause a run-time exception, but am not 100% certain, in either case that is probably the best possibility. Assuming no exception occurs automatically, you could add a Debug.Assert that checks to see if the property by that name exists, but again that is run time only. A: 1) Specify the exact property name that you want and keep it that way 2) Write a test involving that property name.
{ "language": "en", "url": "https://stackoverflow.com/questions/152250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: What's the best way to search a MySQL database with PHP? Say if I had a table of books in a MySQL database and I wanted to search the 'title' field for keywords (input by the user in a search field); what's the best way of doing this in PHP? Is the MySQL LIKE command the most efficient way to search? A: Yes, the most efficient way usually is searching in the database. To do that you have three alternatives: * *LIKE, ILIKE to match exact substrings *RLIKE to match POSIX regexes *FULLTEXT indexes to match another three different kinds of search aimed at natural language processing So it depends on what will you be actually searching for to decide what would the best be. For book titles I'd offer a LIKE search for exact substring match, useful when people know the book they're looking for and also a FULLTEXT search to help find titles similar to a word or phrase. I'd give them different names on the interface of course, probably something like exact for the substring search and similar for the fulltext search. An example about fulltext: http://www.onlamp.com/pub/a/onlamp/2003/06/26/fulltext.html A: Consider using sphinx. It's an open source full text engine that can consume your mysql database directly. It's far more scalable and flexible than hand coding LIKE statements (and far less susceptible to SQL injection) A: Here's a simple way you can break apart some keywords to build some clauses for filtering a column on those keywords, either ANDed or ORed together. $terms=explode(',', $_GET['keywords']); $clauses=array(); foreach($terms as $term) { //remove any chars you don't want to be searching - adjust to suit //your requirements $clean=trim(preg_replace('/[^a-z0-9]/i', '', $term)); if (!empty($clean)) { //note use of mysql_escape_string - while not strictly required //in this example due to the preg_replace earlier, it's good //practice to sanitize your DB inputs in case you modify that //filter... $clauses[]="title like '%".mysql_escape_string($clean)."%'"; } } if (!empty($clauses)) { //concatenate the clauses together with AND or OR, depending on //your requirements $filter='('.implode(' AND ', $clauses).')'; //build and execute the required SQL $sql="select * from foo where $filter"; } else { //no search term, do something else, find everything? } A: You may also check soundex functions (soundex, sounds like) in mysql manual http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_soundex Its functional to return these matches if for example strict checking (by LIKE or =) did not return any results. A: Paul Dixon's code example gets the main idea across well for the LIKE-based approach. I'll just add this usability idea: Provide an (AND | OR) radio button set in the interface, default to AND, then if a user's query results in zero (0) matches and contain at least two words, respond with an option to the effect: "Sorry, No matches were found for your search phrase. Expand search to match on ANY word in your phrase? Maybe there's a better way to word this, but the basic idea is to guide the person toward another query (that may be successful) without the user having to think in terms of the Boolean logic of AND and ORs. A: I think Like is the most efficient way if it's a word. Multi words may be split with explode function as said already. It may then be looped and used to search individually through the database. If same result is returned twice, it may be checked by reading the values into an array. If it already exists in the array, ignore it. Then with count function, you'll know where to stop while printing with a loop. Sorting may be done with similar_text function. The percentage is used to sort the array. That's the best.
{ "language": "en", "url": "https://stackoverflow.com/questions/152259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: tStringList passing in C# to Delphi DLL I have a Delphi DLL with a function defined as: function SubmitJobStringList(joblist: tStringList; var jobno: Integer): Integer; I am calling this from C#. How do I declare the first parameter as a tStringList does not exist in C#. I currently have the declaration as: [DllImport("opt7bja.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern int SubmitJobStringList(string[] tStringList, ref int jobno); But when I call it I get a memory access violation exception. Anyone know how to pass to a tStringList correctly from C#? A: If this is your DLL, I'd rewrite the function to accept an array of strings instead. Avoid passing classes as DLL parameters. Or, if you really want to use a TStringList for some reason, Delphi's VCL.Net can be used from any .Net language. An old example using TIniFile: http://cc.codegear.com/Item/22691 The example uses .Net 1.1 in Delphi 2005. Delphi 2006 and 2007 support .Net 2.0. A: You'll most likely not have any luck with this. The TStringList is more than just an array, it's a full-blown class, and the exact implementation details may differ from what is possible with .NET. Take a look at the Delphi VCL source code (that is, if you have it) and try to find out if you can rebuild the class in C#, and pass it with the help of your best friend, the Interop Marshaller. Note that even the Delphi string type is different from the .NET string type, and passing it without telling the marshaller what he should do, he will pass it as a char-array, most likely. Other than that, I would suggest changing the Delphi DLL. It's never a good thing to expose anything Delphi-specific in a DLL that is to be used by non-Delphi clients. Make the parameter an array of PChar and you should be fine. A: If you don't control the DLL and they can't or won't change it, you could always write your own Delphi wrapper in a separate DLL with parameters that are more cross-language friendly. Having a class as a parameter of a DLL function really is bad form. A: I am not exactly clear your way of using delphi and C#. It seems you have created a Win32 DLL which you want to call from C#. Offcourse you must be using PInvoke for this. I would suggest that you create a .NET DLL using your source code since complete porting of VCL is available. I can further elaborate if you wish.... A: In theory, you could do something like this by using pointers (casting them as the C# IntPtr type) instead of strongly typed object references (or perhaps wrapping them in some other type to avoid having to declare unsafe blocks), but the essential catch is this: The Delphi runtime must be the mechanism for allocating and deallocating memory for the objects. To that end, you must declare functions in your Delphi-compiled DLL which invoke the constructors and destructors for the TStringList class, you must make sure that your Delphi DLL uses the ShareMem unit, and you must take responsibility for incrementing and decrementing the reference count for your Delphi AnsiStrings before they leave the DLL and after they enter it, preferably also as functions exported from your Delphi DLL. In short, it's a lot of work since you must juggle two memory managers in the same process (the .NET CLR and Delphi's allocators) and you must both manage the memory manually and "fool" the Delphi memory manager and runtime. Is there a particular reason you are bound to this setup? Could you describe the problem you are trying to solve at a higher level? A: As Hemant Jangid said, you should easily be able to do this by compiling your code as a .NET dll and then referring to that assembly in your c# project. Of course, you'll only be able to do this if the version of Delphi you have has Delphi.NET. A: I don't know a lot about c#, but a technique that I use for transporting stringlists across contexts is using the .text property to get a string representing the list, then assigning that property on "the other side". It's usually easier to get a string over the wall that it is a full blown object.
{ "language": "en", "url": "https://stackoverflow.com/questions/152261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: middle click (new tabs) and javascript links I am in charge of a website at work and recently I have added ajaxy requests to make it faster and more responsive. But it has raised an issue. On my pages, there is an index table on the left, like a menu. Once you have clicked on it, it makes a request that fills the rest of the page. At anytime you can click on another item of the index to load a different page. Before adding javascript, it was possible to middle click (open new tabs) for each item of the index, which allowed to have other pages loading while I was dealing with one of them. But since I have changed all the links to be ajax requests, they now execute some javascript instead of being real links. So they are only opening empty tabs when I middle click on them. Is there a way to combine both functionalities: links firing javascript when left clicked or new tabs when middle clicked? Does it have to be some ugly javascript that catches every clicks and deal with them accordingly? Thanks. A: Yes, You need to lookup progressive enhancement and unobtrusive Javascript, and code your site to work with out Javascript enabled first and then add the Javascripts functions after you have the basic site working. A: I liked Oli's approach, but it didn't discern from left and middle clicks. checking the "which" field on the eventArgs will let you know. $(".detailLink").click(function (ev, ob) { //ev.which == 1 == left //ev.which == 2 == middle if (ev.which == 1) { //do ajaxy stuff return false; //tells browser to stop processing the event } //else just let it go on its merry way and open the new tab. }); A: Yes. Instead of: <a href="javascript:code">...</a> Do this: <a href="/non/ajax/display/page" id="thisLink">...</a> And then in your JS, hook the link via it's ID to do the AJAX call. Remember that you need to stop the click event from bubbling up. Most frameworks have an event killer built in that you can call (just look at its Event class). Here's the event handling and event-killer in jquery: $("#thisLink").click(function(ev, ob) { alert("thisLink was clicked"); ev.stopPropagation(); }); Of course you can be a lot more clever, while juggling things like this but I think it's important to stress that this method is so much cleaner than using onclick attributes. Keep your JS in the JS! A: It would require some testing, but I believe that most browsers do not execute the click handler when you click them, meaning that only the link is utilized. Not however that your handler function needs to return false to ensure these links aren't used when normally clicking. EDIT: Felt this could use an example: <a href="/Whatever/Wherever.htm" onclick="handler(); return false;" /> A: <a href="/original/url" onclick="return !doSomething();">link text</a> For more info and detailed explanation view my answer in another post. A: Possibly, I could provide two links each time, one firing the javascript and another being a real link that would allow for middle click. I presume, one of them would have to be an image to avoid overloading the index. A: The onclick event won't be fired for that type of click, so you need to add an href attribute which would actually work. One possible way to do this by adding a #bookmark to the URL to indicate to the target page what the required state is.
{ "language": "en", "url": "https://stackoverflow.com/questions/152262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Microsoft JScript runtime error: 'this._postBackSettings.async' is null or not an object I have report on my asp page and every time I change a filter and click view report, I get this error: Microsoft JScript runtime error: 'this._postBackSettings.async' is null or not an object I tried change the EnablePartialRendering="true" to EnablePartialRendering="false" but then people can't login on the site A: I discovered another solution to this problem. I use the Telerik RadScriptManager and RadAjaxManager (which are built upon the respective ASP.NET framework objects). I discovered some issues when I implemented JQuery UI animations to hide the buttons--animations which I executed "OnClientClick" of the button. To solve the problem, I handled the OnRequestStart and OnResponseEnd client events and executed the applicable hide and show animations from OnRequestStart and OnResponseEnd, respectively. I know not everyone uses Telerik, but this concept might be key, and probably applies to other AJAX frameworks: When performing client-side changes on ajaxified elements (especially changes like animations which occur during AJAX request processing), make those changes in your framework's RequestStart/ResponseEnd client side event handlers rather than in the client side event handlers of the ajaxified elements. A: I've had the same problem and haven't really found any satisfying solution until I ended up on https://siderite.dev/blog/thispostbacksettingsasync-is-null-or.html which does exactly what I want. Just to avoid problems with possible dead links in the future, here is the code: var script = @" if (Sys && Sys.WebForms && Sys.WebForms.PageRequestManager && Sys.WebForms.PageRequestManager.getInstance) { var prm = Sys.WebForms.PageRequestManager.getInstance(); if (prm && !prm._postBackSettings) { prm._postBackSettings = prm._createPostBackSettings(false, null, null); }"; ScriptManager.RegisterOnSubmitStatement( Page, Page.GetType(), "FixPopupFormSubmit", script); In case of a submit without the _postBackSettings being set it creates them, causing the null reference exception to disappear as _postBackSettings.async is then available. A: This problem is solved by setting EnablePartialRendering to false of ScriptManager. ScriptManager1.EnablePartialRendering = false; In OnInit event of the page where rsweb:ReportViewer is used. If you want to enable for other page then set it true on master page's OnInit. A: Put the button inside a panel (not update panel), then add this line to the panel DefaultButton="Button1" This will avoid the error. A: I also had this problem, although in my case there were no reports involved: it was a just a normal asp.net page with an image button. The thing was that on client click I was cancelling the next javascript events with this code: event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); I removed the code and the problem also disapeared. My guess is that asp.net ajax needs to do some processing on client click and maybe your report control is doing something like I was doing. Hope it helps you find your problem and sorry for my english :) Regards, MMM A: I got this problem just now and found a solution by accident. Problem started showing up after I moved the ScriptManager to a master page - and only when I was using pages with no update panels. Solved it by moving the ScriptManager tag to just in front of the content area of the master page. JavaScript ordering problems?
{ "language": "en", "url": "https://stackoverflow.com/questions/152276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Loading UTF-8 encoded dump into MySQL I've been pulling my hear out over this problem for a few hours yesterday: I've a database on MySQL 4.1.22 server with encoding set to "UTF-8 Unicode (utf8)" (as reported by phpMyAdmin). Tables in this database have default charset set to latin2. But, the web application (CMS Made Simple written in PHP) using it displays pages in utf8... However screwed up this may be, it actually works. The web app displays characters correctly (mostly Czech and Polish are used). I run: "mysqldump -u xxx -p -h yyy dbname > dump.sql". This gives me an SQL script which: * *looks perfect in any editor (like Notepad+) when displaying in UTF-8 - all characters display properly *all tables in the script have default charset set to latin2 *it has "/*!40101 SET NAMES latin2 */;" line at the beginning (among other settings) Now, I want to export this database to another server running on MySQL 5.0.67, also with server encoding set to "UTF-8 Unicode (utf8)". I copied the whole CMS Made Simple installation over, copied the dump.sql script and ran "mysql -h ddd -u zzz -p dbname < dump.sql". After that, all the characters are scrambled when displaying CMSMS web pages. I tried setting: SET character_set_client = utf8; SET character_set_connection = latin2; And all combinations (just to be safe, even if it doesn't make any sense to me): latin2/utf8, latin2/latin2, utf8/utf8, etc. - doesn't help. All characters still scrambled, however sometimes in a different way :). I also tried replacing all latin2 settings with utf8 in the script (set names and default charsets for tables). Nothing. Are there any MySQL experts here who could explain in just a few words (I'm sure it's simple after all) how this whole encoding stuff really works? I read 9.1.4. Connection Character Sets and Collations but found nothing helpful there. Thanks, Matt A: Did you try adding the --default-character-set=name option, like this: mysql --default-character-set=utf8 -h ddd -u zzz -p dbname < dump.sql I had that problem before and it worked after using that option. Hope it helps! A: Ugh... ok, seems I found a solution. MySQL isn't the culprit here. I did a simple dump and load now, with no changes to the dump.sql script - meaning I left "set names latin2" and tables charsets as they were. Then I switched my original CMSMS installation over to the new database and... it worked correctly. So actually encoding in the database is ok, or at least it works fine with CMSMS installation I had at my old hosting provider (CMSMS apparently does funny things with characters encoding). To make it work on my new hosting provider, I actually had to add this line to lib/adodb/drivers/adodb-mysql.inc.php in CMSMS installation: mysql_query('set names latin2',$this->_connectionID); This is a slightly modified solution from this post. You can find the exact line there as well. So it looks like mysql client configuration issue. A: SOLUTION for me: set this option in your php file, after mysql_connect (or after mysql_select_db).. mysql_query("SET NAMES 'utf8'");
{ "language": "en", "url": "https://stackoverflow.com/questions/152288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: svn + repository location I am about to set up a subversion server to be accessed via svn+ssh. I was wondering, where the default repository location is (on a unix box). Do you put it in /opt/svn or /home/svn or /usr/subversion or even /svn or somewhere else? I am looking for the place, most people put it. Is there a convention? EDIT: It is absolutely possible to "hide" the actual repository location from the user. For example (in my case) by wrapping the svnserve executable in a way that it is called like: svnserve -r /var/svn/repos A: I typically place the repositories somewhere under /var, usually in /var/lib/svn - I'm trying to follow the Filesystem Hierarchy Standard which has this to say about the purpose of /var: /var is specified here in order to make it possible to mount /usr read-only. Everything that once went into /usr that is written to during system operation (as opposed to installation and software maintenance) must be in /var. A: /home/svn here, mostly because I thought that at some point I might need a svn user... A: Based on the new FHS, you're supposed to put "Data for services provided by this system" into the /srv directory. There isn't any other guidance in the FHS except to put everything that is data for services in that directory, such as http, etc. I would suggest /srv/svn/. A: As far as the path for the repository goes, I like to partition and mount a directory called repository on it ;) /repository This way I can check the size easily using "df" Is it possible to hide the absolute path from the users? To answer this question, yes, but only if they don't have full access to the box. You set them up with an account, and have them generate a public/private key to login but you never give them the password. Then you cat their key into /home/<_user>/.ssh/authorized_keys and you edit the settings so that logging in with said key launches svn-serve. command="/usr/local/bin/svnserve -t -r /repository/" Now create a project in the repository: svnadmin create /repository/proj1 With SVN you have to give the user read/write access to the project directory. Then they are able to check out code like: svn co svn+ssh://host/proj1 The user never sees or knows the absolute path of the repository. A: It should definitely be in /var. I keep mine in /var/lib/svn. /opt is useful for keeping applications that you might not necessarily want as part of the system, for example: Firefox or MySql. A repository is not an application so it doesn't make sense to keep it in /opt. And like the comment above you can refer to the FHS
{ "language": "en", "url": "https://stackoverflow.com/questions/152299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What happened to NUnit? Why isn't this project maintained anymore? I love this app, however not updating it seems like a crime against all .Net developers. There are several items that I would love to add to it given the chance of a future release. Can anyone share something I don't know? A: The NUnit 2.5 Alpha 4 Release was released on September 14, 2008. Do you consider 16 days as not being maintained? A: http://nunit.org shows that the latest release is 2.4.8, released on July 21, 2008. It looks like it's still an active project to me. A: You are right. NUnit is a great app (or rather a system). But since it is a open project, everyone is responsible for maintaining it. The people who originally started the great work might have some personal constraints stopping them actively taking part in development...
{ "language": "en", "url": "https://stackoverflow.com/questions/152302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google 404 and .NET Custom Error Pages I've got an ASP.NET 2.0 website with a custom 404 page. When content is not found the site serves the custom 404 page with a query string addition of aspxerrorpath=/mauro.aspx. The 404 page itself is served with an HTTP status of 200. To try to resolve this I've added protected void Page_Load(object sender, EventArgs e) { Response.StatusCode = 404; } I added the Google widget and have two issues with it. In Internet Explorer 7 it does not display where it should. If I add it to the content, I get an "unknown error" on char 79 line 226 or thereabouts; if I add it to the head section the search boxes appear above the content. In Firefox it works fine. So my issues are: * *How do I make the widget appear inline? *How do I make the error page render as a 404 with the original name and path of the file being requested so that when I request mauro.aspx I get the content for the 404 page, but with the URL of mauro.aspx? (I assume that I will have to do some URL rewriting in the begin_request global.asax file, but would like this confirmed before I do anything silly.) A: There is a new redirect mode in ASP.NET 3.5 SP1 that you can now use so it doesn't redirect. It shows the error page, but keeps the URL the same: "Also nice for URL redirects. If you set the redirectMode on in web.config to "responseRewrite" you can avoid a redirect to a custom error page and leave the URL in the browser untouched." * *CustomErrorsSection.RedirectMode Property (MSDN) A: I've handled the 404 by doing this in the global.asax file protected void Application_BeginRequest(object sender, EventArgs e) { string url = Request.RawUrl; if ((url.Contains(".aspx")) && (!System.IO.File.Exists(Server.MapPath(url)))) { Server.Transfer("/Error/FileNotFound.aspx"); } } Now, if anyone can help me with the google widget that would be great!
{ "language": "en", "url": "https://stackoverflow.com/questions/152307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: XML Attributes vs Elements When should you use XML attributes and when should you use XML elements? e.g. <customData> <records> <record name="foo" description="bar" /> </records> </customData> or <customData> <records> <record> <name>foo</name> <description>bar</description> </record> </records> </customData> A: It's largely a matter of preference. I use Elements for grouping and attributes for data where possible as I see this as more compact than the alternative. For example I prefer..... <?xml version="1.0" encoding="utf-8"?> <data> <people> <person name="Rory" surname="Becker" age="30" /> <person name="Travis" surname="Illig" age="32" /> <person name="Scott" surname="Hanselman" age="34" /> </people> </data> ...Instead of.... <?xml version="1.0" encoding="utf-8"?> <data> <people> <person> <name>Rory</name> <surname>Becker</surname> <age>30</age> </person> <person> <name>Travis</name> <surname>Illig</surname> <age>32</age> </person> <person> <name>Scott</name> <surname>Hanselman</surname> <age>34</age> </person> </people> </data> However if I have data which does not represent easily inside of say 20-30 characters or contains many quotes or other characters that need escaping then I'd say it's time to break out the elements... possibly with CData blocks. <?xml version="1.0" encoding="utf-8"?> <data> <people> <person name="Rory" surname="Becker" age="30" > <comment>A programmer whose interested in all sorts of misc stuff. His Blog can be found at http://rorybecker.blogspot.com and he's on twitter as @RoryBecker</comment> </person> <person name="Travis" surname="Illig" age="32" > <comment>A cool guy for who has helped me out with all sorts of SVn information</comment> </person> <person name="Scott" surname="Hanselman" age="34" > <comment>Scott works for MS and has a great podcast available at http://www.hanselminutes.com </comment> </person> </people> </data> A: As a general rule, I avoid attributes altogether. Yes, attributes are more compact, but elements are more flexible, and flexibility is one of the most important advantages of using a data format like XML. What is a single value today can become a list of values tomorrow. Also, if everything's an element, you never have to remember how you modeled any particular bit of information. Not using attributes means you have one less thing to think about. A: Check out Elements vs. attributes by Ned Batchelder. Nice explanation and a good list of the benefits and disadvantages of Elements and Attributes. He boils it down to: Recommendation: Use elements for data that will be produced or consumed by a business application, and attributes for metadata. Important: Please see @maryisdead's comment below for further clarification. A: There is an article titled "Principles of XML design: When to use elements versus attributes" on IBM's website. Though there doesn't appear to be many hard and fast rules, there are some good guidelines mentioned in the posting. For instance, one of the recommendations is to use elements when your data must not be normalized for white space as XML processors can normalize data within an attribute thereby modifying the raw text. I find myself referring to this article from time to time as I develop various XML structures. Hopefully this will be helpful to others as well. edit - From the site: Principle of core content If you consider the information in question to be part of the essential material that is being expressed or communicated in the XML, put it in an element. For human-readable documents this generally means the core content that is being communicated to the reader. For machine-oriented records formats this generally means the data that comes directly from the problem domain. If you consider the information to be peripheral or incidental to the main communication, or purely intended to help applications process the main communication, use attributes. This avoids cluttering up the core content with auxiliary material. For machine-oriented records formats, this generally means application-specific notations on the main data from the problem-domain. As an example, I have seen many XML formats, usually home-grown in businesses, where document titles were placed in an attribute. I think a title is such a fundamental part of the communication of a document that it should always be in element content. On the other hand, I have often seen cases where internal product identifiers were thrown as elements into descriptive records of the product. In some of these cases, attributes were more appropriate because the specific internal product code would not be of primary interest to most readers or processors of the document, especially when the ID was of a very long or inscrutable format. You might have heard the principle data goes in elements, metadata in attributes. The above two paragraphs really express the same principle, but in more deliberate and less fuzzy language. Principle of structured information If the information is expressed in a structured form, especially if the structure may be extensible, use elements. On the other hand: If the information is expressed as an atomic token, use attributes. Elements are the extensible engine for expressing structure in XML. Almost all XML processing tools are designed around this fact, and if you break down structured information properly into elements, you'll find that your processing tools complement your design, and that you thereby gain productivity and maintainability. Attributes are designed for expressing simple properties of the information represented in an element. If you work against the basic architecture of XML by shoehorning structured information into attributes you may gain some specious terseness and convenience, but you will probably pay in maintenance costs. Dates are a good example: A date has fixed structure and generally acts as a single token, so it makes sense as an attribute (preferably expressed in ISO-8601). Representing personal names, on the other hand, is a case where I've seen this principle surprise designers. I see names in attributes a lot, but I have always argued that personal names should be in element content. A personal name has surprisingly variable structure (in some cultures you can cause confusion or offense by omitting honorifics or assuming an order of parts of names). A personal name is also rarely an atomic token. As an example, sometimes you may want to search or sort by a forename and sometimes by a surname. I should point out that it is just as problematic to shoehorn a full name into the content of a single element as it is to put it in an attribute. A: The limitations on attributes tell you where you can and can't use them: the attribute names must be unique, their order cannot be significant, and both the name and the value can contain only text. Elements, by contrast, can have non-unique names, have significant ordering, and can have mixed content. Attributes are usable in domains where they map onto data structures that follow those rules: the names and values of properties on an object, of columns in a row of a table, of entries in a dictionary. (But not if the properties aren't all value types, or the entries in the dictionary aren't strings.) A: My personal rule of thumb: if an element can contain only one of that thing, and its an atomic data (id, name, age, type, etc...) it should be an attribute otherwise an element. A: Personally I like using attributes for simple single-valued properties. Elements are (obviously) more suitable for complex types or repeated values. For single-valued properties, attributes lead to more compact XML and simpler addressing in most APIs. A: One of the better thought-out element vs attribute arguments comes from the UK GovTalk guidelines. This defines the modelling techniques used for government-related XML exchanges, but it stands on its own merits and is worth considering. Schemas MUST be designed so that elements are the main holders of information content in the XML instances. Attributes are more suited to holding ancillary metadata – simple items providing more information about the element content. Attributes MUST NOT be used to qualify other attributes where this could cause ambiguity. Unlike elements, attributes cannot hold structured data. For this reason, elements are preferred as the principal holders of information content. However, allowing the use of attributes to hold metadata about an element's content (for example, the format of a date, a unit of measure or the identification of a value set) can make an instance document simpler and easier to understand. A date of birth might be represented in a message as: <DateOfBirth>1975-06-03</DateOfBirth> However, more information might be required, such as how that date of birth has been verified. This could be defined as an attribute, making the element in a message look like: <DateOfBirth VerifiedBy="View of Birth Certificate">1975-06-03</DateOfBirth> The following would be inappropriate: <DateOfBirth VerifiedBy="View of Birth Certificate" ValueSet="ISO 8601" Code="2">1975-06-03</DateOfBirth> It is not clear here whether the Code is qualifying the VerifiedBy or the ValueSet attribute. A more appropriate rendition would be: <DateOfBirth> <VerifiedBy Code="2">View of Birth Certificate</VerifiedBy> <Value ValueSet="ISO 8601">1975-06-03</Value> </DateOfBirth> A: I tend to use elements when it's data that a human reader would need to know and attributes when it's only for processing (e.g. IDs). This means that I rarely use attributes, as the majority of the data is relevant to the domain being modeled. A: Here is another strategy that can help distinguishing elements from attributes: think of objects and keep in mind MVC. Objects can have members (object variables) and properties (members with setters and getters). Properties are highly useful with MVC design, allowing change notification mechanism. If this is the direction taken, attributes will be used for internal application data that cannot be changed by the user; classic examples will be ID or DATE_MODIFIED. Elements will therefore be used to data that can be modified by users. So the following would make sense considering the librarian first add a book item (or a magazine), and then can edit its name author ISBN etc: <?xml version="1.0" encoding="utf-8"?> <item id="69" type="book"> <authors count="1"> <author> <name>John Smith</name> <author> </authors> <ISBN>123456790</ISBN> </item>
{ "language": "en", "url": "https://stackoverflow.com/questions/152313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "70" }
Q: How to capture the "Print" button from the menu bar in a macro I have a sheet with a custom button on it from where I control the printing process. Now the user clicks on the menu bar's print icon and this produces an "undefined" output. How can I intercept this menu bar button? * *Thanks A: Handle the Workbook_BeforePrint event. private sub Workbook_BeforePrint (cancel as boolean) '//g_MyFlag is set when the user clicks you toolbar button. '//It must get cleared in the end of your procedure. if not g_MyFlag then cancel = true: exit sub end sub In MS Word, it's also possible to redefine the system macro itself. You'd have to create a macro named FilePrint(), and Word would call it instead its own. A pity you can't do that in Excel.
{ "language": "en", "url": "https://stackoverflow.com/questions/152314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Learning C++ Templates Can anyone recommend any good resources for learning C++ Templates? Many thanks. A: This is a more advanced, but very useful, book on templates and template use. Modern C++ Design A: Bruce Eckel's Thinking in C++ is how I learned about templates. The first volume has an introductory chapter and the second volume has an in-depth chapter on templates. There's Bjarne Stroustrop's The C++ Programming Language which has a good chapter on them. And The C++ Standard Library: A Tutorial and Reference which is about the standard library, but would definitely help you get a better understanding of how templates could be used in the real world. . A: Be sure to differentiate between generic programming and template metaprogramming (which is more like another paradigm) Generic programming can be learnt from the C++ bible, but you can just as well take a look at the java generics etc... one about metaprogramming: Josuttis' book C++ Templates: The Complete Guide A: The 2 volumes of 'Thinking in C++' go over the basics of templates. They can either be bought in print, or downloaded for free (and legal) use here. A: I recomned that you get C++ Templates - The Complete Guide it's an excellent resource and reference. A: I've found cplusplus.com to be helpful on numerous occasions. Looks like they've got a pretty good intro to templates. If its an actual book you're looking for, Effective C++ is a classic with a great section on templates. A: "The C++ Programming language" by Bjarne Stroustrop
{ "language": "en", "url": "https://stackoverflow.com/questions/152318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: VBA array sort function? I'm looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other sort algorithm other than bubble or merge would suffice. Please note that this is to work with MS Project 2003, so should avoid any of the Excel native functions and anything .net related. A: I posted some code in answer to a related question on StackOverflow: Sorting a multidimensionnal array in VBA The code samples in that thread include: * *A vector array Quicksort; *A multi-column array QuickSort; *A BubbleSort. Alain's optimised Quicksort is very shiny: I just did a basic split-and-recurse, but the code sample above has a 'gating' function that cuts down on redundant comparisons of duplicated values. On the other hand, I code for Excel, and there's a bit more in the way of defensive coding - be warned, you'll need it if your array contains the pernicious 'Empty()' variant, which will break your While... Wend comparison operators and trap your code in an infinite loop. Note that quicksort algorthms - and any recursive algorithm - can fill the stack and crash Excel. If your array has fewer than 1024 members, I'd use a rudimentary BubbleSort. Public Sub QuickSortArray(ByRef SortArray As Variant, _ Optional lngMin As Long = -1, _ Optional lngMax As Long = -1, _ Optional lngColumn As Long = 0) On Error Resume Next 'Sort a 2-Dimensional array ' Sample Usage: sort arrData by the contents of column 3 ' ' QuickSortArray arrData, , , 3 ' 'Posted by Jim Rech 10/20/98 Excel.Programming 'Modifications, Nigel Heffernan: ' ' Escape failed comparison with empty variant ' ' Defensive coding: check inputs Dim i As Long Dim j As Long Dim varMid As Variant Dim arrRowTemp As Variant Dim lngColTemp As Long If IsEmpty(SortArray) Then Exit Sub End If If InStr(TypeName(SortArray), "()") < 1 Then 'IsArray() is somewhat broken: Look for brackets in the type name Exit Sub End If If lngMin = -1 Then lngMin = LBound(SortArray, 1) End If If lngMax = -1 Then lngMax = UBound(SortArray, 1) End If If lngMin >= lngMax Then ' no sorting required Exit Sub End If i = lngMin j = lngMax varMid = Empty varMid = SortArray((lngMin + lngMax) \ 2, lngColumn) ' We send 'Empty' and invalid data items to the end of the list: If IsObject(varMid) Then ' note that we don't check isObject(SortArray(n)) - varMid might pick up a valid default member or property i = lngMax j = lngMin ElseIf IsEmpty(varMid) Then i = lngMax j = lngMin ElseIf IsNull(varMid) Then i = lngMax j = lngMin ElseIf varMid = "" Then i = lngMax j = lngMin ElseIf varType(varMid) = vbError Then i = lngMax j = lngMin ElseIf varType(varMid) > 17 Then i = lngMax j = lngMin End If While i <= j While SortArray(i, lngColumn) < varMid And i < lngMax i = i + 1 Wend While varMid < SortArray(j, lngColumn) And j > lngMin j = j - 1 Wend If i <= j Then ' Swap the rows ReDim arrRowTemp(LBound(SortArray, 2) To UBound(SortArray, 2)) For lngColTemp = LBound(SortArray, 2) To UBound(SortArray, 2) arrRowTemp(lngColTemp) = SortArray(i, lngColTemp) SortArray(i, lngColTemp) = SortArray(j, lngColTemp) SortArray(j, lngColTemp) = arrRowTemp(lngColTemp) Next lngColTemp Erase arrRowTemp i = i + 1 j = j - 1 End If Wend If (lngMin < j) Then Call QuickSortArray(SortArray, lngMin, j, lngColumn) If (i < lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn) End Sub A: I converted the 'fast quick sort' algorithm to VBA, if anyone else wants it. I have it optimized to run on an array of Int/Longs but it should be simple to convert it to one that works on arbitrary comparable elements. Private Sub QuickSort(ByRef a() As Long, ByVal l As Long, ByVal r As Long) Dim M As Long, i As Long, j As Long, v As Long M = 4 If ((r - l) > M) Then i = (r + l) / 2 If (a(l) > a(i)) Then swap a, l, i '// Tri-Median Methode!' If (a(l) > a(r)) Then swap a, l, r If (a(i) > a(r)) Then swap a, i, r j = r - 1 swap a, i, j i = l v = a(j) Do Do: i = i + 1: Loop While (a(i) < v) Do: j = j - 1: Loop While (a(j) > v) If (j < i) Then Exit Do swap a, i, j Loop swap a, i, r - 1 QuickSort a, l, j QuickSort a, i + 1, r End If End Sub Private Sub swap(ByRef a() As Long, ByVal i As Long, ByVal j As Long) Dim T As Long T = a(i) a(i) = a(j) a(j) = T End Sub Private Sub InsertionSort(ByRef a(), ByVal lo0 As Long, ByVal hi0 As Long) Dim i As Long, j As Long, v As Long For i = lo0 + 1 To hi0 v = a(i) j = i Do While j > lo0 If Not a(j - 1) > v Then Exit Do a(j) = a(j - 1) j = j - 1 Loop a(j) = v Next i End Sub Public Sub sort(ByRef a() As Long) QuickSort a, LBound(a), UBound(a) InsertionSort a, LBound(a), UBound(a) End Sub A: You didn't want an Excel-based solution but since I had the same problem today and wanted to test using other Office Applications functions I wrote the function below. Limitations: * *2-dimensional arrays; *maximum of 3 columns as sort keys; *depends on Excel; Tested calling Excel 2010 from Visio 2010 Option Base 1 Private Function sort_array_2D_excel(array_2D, array_sortkeys, Optional array_sortorders, Optional tag_header As String = "Guess", Optional tag_matchcase As String = "False") ' Dependencies: Excel; Tools > References > Microsoft Excel [Version] Object Library Dim excel_application As Excel.Application Dim excel_workbook As Excel.Workbook Dim excel_worksheet As Excel.Worksheet Set excel_application = CreateObject("Excel.Application") excel_application.Visible = True excel_application.ScreenUpdating = False excel_application.WindowState = xlNormal Set excel_workbook = excel_application.Workbooks.Add excel_workbook.Activate Set excel_worksheet = excel_workbook.Worksheets.Add excel_worksheet.Activate excel_worksheet.Visible = xlSheetVisible Dim excel_range As Excel.Range Set excel_range = excel_worksheet.Range("A1").Resize(UBound(array_2D, 1) - LBound(array_2D, 1) + 1, UBound(array_2D, 2) - LBound(array_2D, 2) + 1) excel_range = array_2D For i_sortkey = LBound(array_sortkeys) To UBound(array_sortkeys) If IsNumeric(array_sortkeys(i_sortkey)) Then sortkey_range = Chr(array_sortkeys(i_sortkey) + 65 - 1) & "1" Set array_sortkeys(i_sortkey) = excel_worksheet.Range(sortkey_range) Else MsgBox "Error in sortkey parameter:" & vbLf & "array_sortkeys(" & i_sortkey & ") = " & array_sortkeys(i_sortkey) & vbLf & "Terminating..." End End If Next i_sortkey For i_sortorder = LBound(array_sortorders) To UBound(array_sortorders) Select Case LCase(array_sortorders(i_sortorder)) Case "asc" array_sortorders(i_sortorder) = XlSortOrder.xlAscending Case "desc" array_sortorders(i_sortorder) = XlSortOrder.xlDescending Case Else array_sortorders(i_sortorder) = XlSortOrder.xlAscending End Select Next i_sortorder Select Case LCase(tag_header) Case "yes" tag_header = Excel.xlYes Case "no" tag_header = Excel.xlNo Case "guess" tag_header = Excel.xlGuess Case Else tag_header = Excel.xlGuess End Select Select Case LCase(tag_matchcase) Case "true" tag_matchcase = True Case "false" tag_matchcase = False Case Else tag_matchcase = False End Select Select Case (UBound(array_sortkeys) - LBound(array_sortkeys) + 1) Case 1 Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Header:=tag_header, MatchCase:=tag_matchcase) Case 2 Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Header:=tag_header, MatchCase:=tag_matchcase) Case 3 Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Key3:=array_sortkeys(3), Order3:=array_sortorders(3), Header:=tag_header, MatchCase:=tag_matchcase) Case Else MsgBox "Error in sortkey parameter:" & vbLf & "Maximum number of sort columns is 3!" & vbLf & "Currently passed: " & (UBound(array_sortkeys) - LBound(array_sortkeys) + 1) End End Select For i_row = 1 To excel_range.Rows.Count For i_column = 1 To excel_range.Columns.Count array_2D(i_row, i_column) = excel_range(i_row, i_column) Next i_column Next i_row excel_workbook.Close False excel_application.Quit Set excel_worksheet = Nothing Set excel_workbook = Nothing Set excel_application = Nothing sort_array_2D_excel = array_2D End Function This is an example on how to test the function: Private Sub test_sort() array_unsorted = dim_sort_array() Call msgbox_array(array_unsorted) array_sorted = sort_array_2D_excel(array_unsorted, Array(2, 1, 3), Array("desc", "", "asdas"), "yes", "False") Call msgbox_array(array_sorted) End Sub Private Function dim_sort_array() Dim array_unsorted(1 To 5, 1 To 3) As String i_row = 0 i_row = i_row + 1 array_unsorted(i_row, 1) = "Column1": array_unsorted(i_row, 2) = "Column2": array_unsorted(i_row, 3) = "Column3" i_row = i_row + 1 array_unsorted(i_row, 1) = "OR": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2) i_row = i_row + 1 array_unsorted(i_row, 1) = "XOR": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2) i_row = i_row + 1 array_unsorted(i_row, 1) = "NOT": array_unsorted(i_row, 2) = "B": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2) i_row = i_row + 1 array_unsorted(i_row, 1) = "AND": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2) dim_sort_array = array_unsorted End Function Sub msgbox_array(array_2D, Optional string_info As String = "2D array content:") msgbox_string = string_info & vbLf For i_row = LBound(array_2D, 1) To UBound(array_2D, 1) msgbox_string = msgbox_string & vbLf & i_row & vbTab For i_column = LBound(array_2D, 2) To UBound(array_2D, 2) msgbox_string = msgbox_string & array_2D(i_row, i_column) & vbTab Next i_column Next i_row MsgBox msgbox_string End Sub If anybody tests this using other versions of office please post here if there are any problems. A: I wonder what would you say about this array sorting code. It's quick for implementation and does the job ... haven't tested for large arrays yet. It works for one-dimensional arrays, for multidimensional additional values re-location matrix would need to be build (with one less dimension that the initial array). For AR1 = LBound(eArray, 1) To UBound(eArray, 1) eValue = eArray(AR1) For AR2 = LBound(eArray, 1) To UBound(eArray, 1) If eArray(AR2) < eValue Then eArray(AR1) = eArray(AR2) eArray(AR2) = eValue eValue = eArray(AR1) End If Next AR2 Next AR1 A: Dim arr As Object Dim InputArray 'Creating a array list Set arr = CreateObject("System.Collections.ArrayList") 'String InputArray = Array("d", "c", "b", "a", "f", "e", "g") 'number 'InputArray = Array(6, 5, 3, 4, 2, 1) ' adding the elements in the array to array_list For Each element In InputArray arr.Add element Next 'sorting happens arr.Sort 'Converting ArrayList to an array 'so now a sorted array of elements is stored in the array sorted_array. sorted_array = arr.toarray A: Take a look here: Edit: The referenced source (allexperts.com) has since closed, but here are the relevant author comments: There are many algorithms available on the web for sorting. The most versatile and usually the quickest is the Quicksort algorithm. Below is a function for it. Call it simply by passing an array of values (string or numeric; it doesn't matter) with the Lower Array Boundary (usually 0) and the Upper Array Boundary (i.e. UBound(myArray).) Example: Call QuickSort(myArray, 0, UBound(myArray)) When it's done, myArray will be sorted and you can do what you want with it. (Source: archive.org) Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long) Dim pivot As Variant Dim tmpSwap As Variant Dim tmpLow As Long Dim tmpHi As Long tmpLow = inLow tmpHi = inHi pivot = vArray((inLow + inHi) \ 2) While (tmpLow <= tmpHi) While (vArray(tmpLow) < pivot And tmpLow < inHi) tmpLow = tmpLow + 1 Wend While (pivot < vArray(tmpHi) And tmpHi > inLow) tmpHi = tmpHi - 1 Wend If (tmpLow <= tmpHi) Then tmpSwap = vArray(tmpLow) vArray(tmpLow) = vArray(tmpHi) vArray(tmpHi) = tmpSwap tmpLow = tmpLow + 1 tmpHi = tmpHi - 1 End If Wend If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi End Sub Note that this only works with single-dimensional (aka "normal"?) arrays. (There's a working multi-dimensional array QuickSort here.) A: Explanation in German but the code is a well-tested in-place implementation: Private Sub QuickSort(ByRef Field() As String, ByVal LB As Long, ByVal UB As Long) Dim P1 As Long, P2 As Long, Ref As String, TEMP As String P1 = LB P2 = UB Ref = Field((P1 + P2) / 2) Do Do While (Field(P1) < Ref) P1 = P1 + 1 Loop Do While (Field(P2) > Ref) P2 = P2 - 1 Loop If P1 <= P2 Then TEMP = Field(P1) Field(P1) = Field(P2) Field(P2) = TEMP P1 = P1 + 1 P2 = P2 - 1 End If Loop Until (P1 > P2) If LB < P2 Then Call QuickSort(Field, LB, P2) If P1 < UB Then Call QuickSort(Field, P1, UB) End Sub Invoked like this: Call QuickSort(MyArray, LBound(MyArray), UBound(MyArray)) A: Natural Number (Strings) Quick Sort Just to pile onto the topic. Normally, if you sort strings with numbers you'll get something like this: Text1 Text10 Text100 Text11 Text2 Text20 But you really want it to recognize the numerical values and be sorted like Text1 Text2 Text10 Text11 Text20 Text100 Here's how to do it... Note: * *I stole the Quick Sort from the internet a long time ago, not sure where now... *I translated the CompareNaturalNum function which was originally written in C from the internet as well. *Difference from other Q-Sorts: I don't swap the values if the BottomTemp = TopTemp Natural Number Quick Sort Public Sub QuickSortNaturalNum(strArray() As String, intBottom As Integer, intTop As Integer) Dim strPivot As String, strTemp As String Dim intBottomTemp As Integer, intTopTemp As Integer intBottomTemp = intBottom intTopTemp = intTop strPivot = strArray((intBottom + intTop) \ 2) Do While (intBottomTemp <= intTopTemp) ' < comparison of the values is a descending sort Do While (CompareNaturalNum(strArray(intBottomTemp), strPivot) < 0 And intBottomTemp < intTop) intBottomTemp = intBottomTemp + 1 Loop Do While (CompareNaturalNum(strPivot, strArray(intTopTemp)) < 0 And intTopTemp > intBottom) ' intTopTemp = intTopTemp - 1 Loop If intBottomTemp < intTopTemp Then strTemp = strArray(intBottomTemp) strArray(intBottomTemp) = strArray(intTopTemp) strArray(intTopTemp) = strTemp End If If intBottomTemp <= intTopTemp Then intBottomTemp = intBottomTemp + 1 intTopTemp = intTopTemp - 1 End If Loop 'the function calls itself until everything is in good order If (intBottom < intTopTemp) Then QuickSortNaturalNum strArray, intBottom, intTopTemp If (intBottomTemp < intTop) Then QuickSortNaturalNum strArray, intBottomTemp, intTop End Sub Natural Number Compare(Used in Quick Sort) Function CompareNaturalNum(string1 As Variant, string2 As Variant) As Integer 'string1 is less than string2 -1 'string1 is equal to string2 0 'string1 is greater than string2 1 Dim n1 As Long, n2 As Long Dim iPosOrig1 As Integer, iPosOrig2 As Integer Dim iPos1 As Integer, iPos2 As Integer Dim nOffset1 As Integer, nOffset2 As Integer If Not (IsNull(string1) Or IsNull(string2)) Then iPos1 = 1 iPos2 = 1 Do While iPos1 <= Len(string1) If iPos2 > Len(string2) Then CompareNaturalNum = 1 Exit Function End If If isDigit(string1, iPos1) Then If Not isDigit(string2, iPos2) Then CompareNaturalNum = -1 Exit Function End If iPosOrig1 = iPos1 iPosOrig2 = iPos2 Do While isDigit(string1, iPos1) iPos1 = iPos1 + 1 Loop Do While isDigit(string2, iPos2) iPos2 = iPos2 + 1 Loop nOffset1 = (iPos1 - iPosOrig1) nOffset2 = (iPos2 - iPosOrig2) n1 = Val(Mid(string1, iPosOrig1, nOffset1)) n2 = Val(Mid(string2, iPosOrig2, nOffset2)) If (n1 < n2) Then CompareNaturalNum = -1 Exit Function ElseIf (n1 > n2) Then CompareNaturalNum = 1 Exit Function End If ' front padded zeros (put 01 before 1) If (n1 = n2) Then If (nOffset1 > nOffset2) Then CompareNaturalNum = -1 Exit Function ElseIf (nOffset1 < nOffset2) Then CompareNaturalNum = 1 Exit Function End If End If ElseIf isDigit(string2, iPos2) Then CompareNaturalNum = 1 Exit Function Else If (Mid(string1, iPos1, 1) < Mid(string2, iPos2, 1)) Then CompareNaturalNum = -1 Exit Function ElseIf (Mid(string1, iPos1, 1) > Mid(string2, iPos2, 1)) Then CompareNaturalNum = 1 Exit Function End If iPos1 = iPos1 + 1 iPos2 = iPos2 + 1 End If Loop ' Everything was the same so far, check if Len(string2) > Len(String1) ' If so, then string1 < string2 If Len(string2) > Len(string1) Then CompareNaturalNum = -1 Exit Function End If Else If IsNull(string1) And Not IsNull(string2) Then CompareNaturalNum = -1 Exit Function ElseIf IsNull(string1) And IsNull(string2) Then CompareNaturalNum = 0 Exit Function ElseIf Not IsNull(string1) And IsNull(string2) Then CompareNaturalNum = 1 Exit Function End If End If End Function isDigit(Used in CompareNaturalNum) Function isDigit(ByVal str As String, pos As Integer) As Boolean Dim iCode As Integer If pos <= Len(str) Then iCode = Asc(Mid(str, pos, 1)) If iCode >= 48 And iCode <= 57 Then isDigit = True End If End Function A: Heapsort implementation. An O(n log(n)) (both average and worst case), in place, unstable sorting algorithm. Use with: Call HeapSort(A), where A is a one dimensional array of variants, with Option Base 1. Sub SiftUp(A() As Variant, I As Long) Dim K As Long, P As Long, S As Variant K = I While K > 1 P = K \ 2 If A(K) > A(P) Then S = A(P): A(P) = A(K): A(K) = S K = P Else Exit Sub End If Wend End Sub Sub SiftDown(A() As Variant, I As Long) Dim K As Long, L As Long, S As Variant K = 1 Do L = K + K If L > I Then Exit Sub If L + 1 <= I Then If A(L + 1) > A(L) Then L = L + 1 End If If A(K) < A(L) Then S = A(K): A(K) = A(L): A(L) = S K = L Else Exit Sub End If Loop End Sub Sub HeapSort(A() As Variant) Dim N As Long, I As Long, S As Variant N = UBound(A) For I = 2 To N Call SiftUp(A, I) Next I For I = N To 2 Step -1 S = A(I): A(I) = A(1): A(1) = S Call SiftDown(A, I - 1) Next End Sub A: @Prasand Kumar, here's a complete sort routine based on Prasand's concepts: Public Sub ArrayListSort(ByRef SortArray As Variant) ' 'Uses the sort capabilities of a System.Collections.ArrayList object to sort an array of values of any simple 'data-type. ' 'AUTHOR: Peter Straton ' 'CREDIT: Derived from Prasand Kumar's post at: https://stackoverflow.com/questions/152319/vba-array-sort-function ' '************************************************************************************************************* Static ArrayListObj As Object Dim i As Long Dim LBnd As Long Dim UBnd As Long LBnd = LBound(SortArray) UBnd = UBound(SortArray) 'If necessary, create the ArrayList object, to be used to sort the specified array's values If ArrayListObj Is Nothing Then Set ArrayListObj = CreateObject("System.Collections.ArrayList") Else ArrayListObj.Clear 'Already allocated so just clear any old contents End If 'Add the ArrayList elements from the array of values to be sorted. (There appears to be no way to do this 'using a single assignment statement.) For i = LBnd To UBnd ArrayListObj.Add SortArray(i) Next i ArrayListObj.Sort 'Do the sort 'Transfer the sorted ArrayList values back to the original array, which can be done with a single assignment 'statement. But the result is always zero-based so then, if necessary, adjust the resulting array to match 'its original index base. SortArray = ArrayListObj.ToArray If LBnd <> 0 Then ReDim Preserve SortArray(LBnd To UBnd) End Sub A: Somewhat related, but I was also looking for a native excel VBA solution since advanced data structures (Dictionaries, etc.) aren't working in my environment. The following implements sorting via a binary tree in VBA: * *Assumes array is populated one by one *Removes duplicates *Returns a separated string ("0|2|3|4|9") which can then be split. I used it for returning a raw sorted enumeration of rows selected for an arbitrarily selected range Private Enum LeafType: tEMPTY: tTree: tValue: End Enum Private Left As Variant, Right As Variant, Center As Variant Private LeftType As LeafType, RightType As LeafType, CenterType As LeafType Public Sub Add(x As Variant) If CenterType = tEMPTY Then Center = x CenterType = tValue ElseIf x > Center Then If RightType = tEMPTY Then Right = x RightType = tValue ElseIf RightType = tTree Then Right.Add x ElseIf x <> Right Then curLeaf = Right Set Right = New TreeList Right.Add curLeaf Right.Add x RightType = tTree End If ElseIf x < Center Then If LeftType = tEMPTY Then Left = x LeftType = tValue ElseIf LeftType = tTree Then Left.Add x ElseIf x <> Left Then curLeaf = Left Set Left = New TreeList Left.Add curLeaf Left.Add x LeftType = tTree End If End If End Sub Public Function GetList$() Const sep$ = "|" If LeftType = tValue Then LeftList$ = Left & sep ElseIf LeftType = tTree Then LeftList = Left.GetList & sep End If If RightType = tValue Then RightList$ = sep & Right ElseIf RightType = tTree Then RightList = sep & Right.GetList End If GetList = LeftList & Center & RightList End Function 'Sample code Dim Tree As new TreeList Tree.Add("0") Tree.Add("2") Tree.Add("2") Tree.Add("-1") Debug.Print Tree.GetList() 'prints "-1|0|2" sortedList = Split(Tree.GetList(),"|") A: This is what I use to sort in memory - it can easily be expanded to sort an array. Sub sortlist() Dim xarr As Variant Dim yarr As Variant Dim zarr As Variant xarr = Sheets("sheet").Range("sing col range") ReDim yarr(1 To UBound(xarr), 1 To 1) ReDim zarr(1 To UBound(xarr), 1 To 1) For n = 1 To UBound(xarr) zarr(n, 1) = 1 Next n For n = 1 To UBound(xarr) - 1 y = zarr(n, 1) For a = n + 1 To UBound(xarr) If xarr(n, 1) > xarr(a, 1) Then y = y + 1 Else zarr(a, 1) = zarr(a, 1) + 1 End If Next a yarr(y, 1) = xarr(n, 1) Next n y = zarr(UBound(xarr), 1) yarr(y, 1) = xarr(UBound(xarr), 1) yrng = "A1:A" & UBound(yarr) Sheets("sheet").Range(yrng) = yarr End Sub A: I think my code (tested) is more "educated", assuming the simpler the better. Option Base 1 'Function to sort an array decscending Function SORT(Rango As Range) As Variant Dim check As Boolean check = True If IsNull(Rango) Then check = False End If If check Then Application.Volatile Dim x() As Variant, n As Double, m As Double, i As Double, j As Double, k As Double n = Rango.Rows.Count: m = Rango.Columns.Count: k = n * m ReDim x(n, m) For i = 1 To n Step 1 For j = 1 To m Step 1 x(i, j) = Application.Large(Rango, k) k = k - 1 Next j Next i SORT = x Else Exit Function End If End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/152319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "97" }
Q: Send mail from a Windows script I would like to send mail from a script on a Windows Server 2003 Standard Edition. I think the server setup is pretty much out of the box. The mail server is an Exchange one, and when you're on the internal network you can use plain old SMTP. I have done it from my machine with Perl, but unfortunately Perl is not available on the server. Is there an easy way of doing this from a .bat-file or any other way that doesn't require installing some additional software? Edit: Thanks for the quick replies. The "blat" thingie would probably work fine but with wscript I don't have to use a separate binary. I didn't see PhiLho's post the first time I edited and selected an answer. No need for me to duplicate the code here. Just save the script to a file, say sendmail.vbs, and then call it from the command prompt like so: wscript sendmail.vbs A: If the server happened (I realize how old this question is) to have Powershell v2 installed, the CmdLet Send-MailMessage would do this in one line. Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> [[-Body] <string>] [[-SmtpServer] <string>] [-Attachments <string[]>] [-Bcc <string[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>] [-DeliveryNotficationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Encoding <Encoding>] [-Priority {Normal | Low | High}] [-UseSsl] [<CommonParameters>] A: I don't know if dropping a binary alongside the .bat file counts as installing software, but, if not, you can use blat to do this. A: It is possible with Wscript, using CDO: Dim objMail Set objMail = CreateObject("CDO.Message") objMail.From = "Me <Me@Server.com>" objMail.To = "You <You@AnotherServer.com>" objMail.Subject = "That's a mail" objMail.Textbody = "Hello World" objMail.AddAttachment "C:\someFile.ext" ---8<----- You don't need this part if you have an active Outlook [Express] account ----- ' Use an SMTP server objMail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 ' Name or IP of Remote SMTP Server objMail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _ "smtp.server.com" ' Server port (typically 25) objMail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 objMail.Configuration.Fields.Update ----- End of SMTP usage ----->8--- objMail.Send Set objMail=Nothing Wscript.Quit Update: found more info there: VBScript To Send Email Using CDO By default it seems it uses Outlook [Express], so it didn't worked on my computer but you can use a given SMTP server, which worked fine for me. A: If you have outlook/exchange installed you should be able to use CDONTs, just create a mail.vbs file and call it in a batch file like so (amusing they are in the same dir) wscript mail.vbs for the VBScript code check out http://support.microsoft.com/kb/197920 http://www.w3schools.com/asp/asp_send_email.asp forget the fact they the two links speak about ASP, it should work fine as a stand alone script with out iis. A: I think that you'll have to install some ActiveX or other component what could be invoked from WScript, such as: http://www.activexperts.com/ActivEmail/ and: http://www.emailarchitect.net/webapp/SMTPCOM/developers/scripting.asp Otherwise, you'll have to write the entire SMTP logic (if possible, not sure) in WScript all on your own. A: Use CDONTS with Windows Scripting Host (WScript) A: Is there a way you send without referencing the outside schema urls. http://schemas.microsoft.com/cdo/configuration/ That is highly useless as it can't be assumed all boxes will have outside internet access to send mail internally on the local exchange. Is there a way to save the info from those urls locally?
{ "language": "en", "url": "https://stackoverflow.com/questions/152323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How do you structure your SVN repository? What is better? A: server:1080/repo/projectA/trunk/... branches/branch1 branches/branch2 branches/branch3 tags/tag1/... tags/tag2/... server:1080/repo/projectB/trunk/... branches/branch1 branches/branch2 branches/branch3 tags/tag1/... tags/tag2/... B: server:1080/repo/trunk/projectA/... branches/projectA/branch1 branches/projectA/branch2 branches/projectA/branch3 tags/projectA/tag1/... tags/projectA/tag2/... server:1080/repo/trunk/projectB/trunk/... branches/projectB/branch1 branches/projectB/branch2 branches/projectB/branch3 tags/projectB/tag1/... tags/projectB/tag2/... What repository structure do you use and WHY? A: I would suggest an option C: server:1080/projectA/trunk/... branches/branch1 branches/branch2 branches/branch3 tags/tag1/... tags/tag2/... server:1080/projectB/trunk/... branches/branch1 branches/branch2 branches/branch3 tags/tag1/... tags/tag2/... I prefer to keep separate projects in separate repositories. Using svn:externals makes it easy to manage code library projects that are shared among two or more application projects. A: We use A, because the other one didn't make sense to us. Note that a "project" with regard to SVN is not necessarily a single project, but may be several projects that belong together (i.e. what you would put into a Solution in Visual Studio). This way, you have anything related grouped together. All branches, tags and the trunk of a specific project. Makes perfect sense to me. Grouping by branch/tag instead does not make sense to me, because the branches of different projects have nothing in common, except that they're all branches. But in the end, people use both ways. Do what you like, but when you decided, try to stay with it :) As an addition: We have separate repositories per customer, i.e. all projects for a customer are in the same repository. This way you can e.g. make backups of a single customer at once, or give the source code of anything the customer owns to him without fighting with SVN. A: The Repository Administration chapter of the SVN book includes a section on Planning Your Repository Organization outlining different strategies and their implication, particularly the implications of the repository layout on branching and merging. A: We use setting B. Beause it is easier to check out/tag multiple projects at once. In svn 1.5 it is possible via sparse checkout, but not a one-click operation. You want to use setting B, if some projects have hidden dependencies inbeetween. A: We use /repos/projectA/component1/trunk - branches - tags /repos/projectA/component2/trunk - branches - tags /repos/projectB/component3/trunk - branches - tags /repos/projectB/component4/trunk - branches - tags Which I'm starting to regret. It should be flatter. This would be better. /repos/projectA/trunk - branches - tags /repos/projectB/trunk - branches - tags /repos/component1/trunk - branches - tags /repos/component2/trunk - branches - tags /repos/component3/trunk - branches - tags /repos/component4/trunk - branches - tags Why? Products (components, finished software) last forever. Projects come and go. Last year there's just one project team creating product QUUX. Next year, that team is dispersed and one or two people maintain QUUX. Next year, there will be two big QUUX expansion projects. Given that timeline, should QUUX appear in three project repositories? No, QUUX is independent of any particular project. It is true that the projects do have work products (documents, backlogs, etc.) that are part of getting the work done, but aren't the actual goal of the work. Hence the "projectX" repositories for that material -- stuff that no one will care about after the project is done. I worked on one product that had three teams. Big problem with coordination of work because each project managed it's repository independently. There were inter-team releases and inter-team coordination. At then end of the day, it was supposed to one piece of software. However, as you can guess, it was three pieces of software with weird overlaps and redundancy. A: Personally I use following repository structure: /project /trunk /tags /builds /PA /A /B /releases /AR /BR /RC /ST /branches /experimental /maintenance /versions /platforms /releases There is also a diagram illustrating how those directories are used. Also there is specific version numbering approach I use. It plays significant role in repository structuring. Recently I have developed training dedicated to Software Configuration Management where I describe version numbering approach and why exactly this repository structure is the best. Here are presentation slides. There is also my answer on the question about 'Multiple SVN Repositories vs single company repository'. It might be helpful as long as you address this aspect of repository structuring in your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/152328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: GetProcessesByName() and Windows Server 2003 scheduled task Does anybody know what user privileges are needed for the following code needs to successfully execute as a scheduled task on Windows Server 2003: System.Diagnostics.Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName) When NOT running as scheduled task i.e. under a logged in user, as long as the user is a member of "Performance Monitor Users", this code will not throw an exception. When running as a scheduled task under the same user account, it fails. The only way I can get it to work is to run it as a member of the Local Administrator group. Any ideas? A: My humblest apologies. The user I was using was NOT a member of "Performance Monitor Users" group. This is necessary for .NET Framework 1.1 implementation of System.Diagnostics. I have added the user to this group, and all is well. A: What user rights assignments have you given the account that is running as a scheduled task? You'll need to give the account in question 'Log on as a batch job' in your local security settings. Update: Does your app write to any files and if so does the scheduled task user have enough rights? I just knocked up a test app that writes the process names from the Process[] array returned by Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName) to a file and it works just fine as a scheduled task...even running under the identity of a user that is only a member of the Users group (not even a member of 'Performance Monitor Users'. The folder it writes to is assigned modify rights to SYSTEM, Administrators and the scheduled task user. Any chance of pasting your code or at least a small enough snippet that demonstrates the exe failing as a scheduled task so we can help diagnose the problem? Cheers Kev A: One issue that I have seen with reading the process name is that access to the performance counters can get disabled. Crack open your registry and see if this key is there: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance] "Disable Performance Counters"=dword:00000001 You can either set it to zero or deleted it. A: Taken from MSDN: Permissions LinkDemand - for full trust for the immediate caller. This member cannot be used by partially trusted code.
{ "language": "en", "url": "https://stackoverflow.com/questions/152337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF Unit Test How to unit test WCF services? Any 3rd Party tools available? A: If one really wants to test WCF services, it's best to go with integration tests that actually exercise the client-server connectivity part of it. A: If you want to test the actual running service then SoapUI is free and has some excellent features. The only caveat is that I have only tried it with the Basic HTTP binding. A: As aku says, if you're testing service methods (ie code behaviour) then you can unit test that directly and bypass the WCF infrastructure. Of course, if your code depends on WCF context classes (like OperationContext) then I suggest introducing wrappers much like ASP.NET MVC does for HttpContext. For testing connectivity, it will depend on the type of endpoints you have configured. In some cases you can just self-host your WCF service inside the unit test (like you would with a WCF Windows Service) and test that. However, you may need to spin up the ASP.NET Development Web Server or even IIS if you want to test WCF behaviour specific to those hosting environments (ie SSL, authentication methods). This gets tricky and can start making demands on the configuration of everyone's development machine and the build servers but is doable. A: I think the best approach is to separately test all concerns; test connectivity, client lib (proxies) and service method calls. Mocking and dependency injection is a good way to tests connectivity and service behaviour independently, but I doubt that it can get around middleware dependent endpoint tests. You can create a service host in your test (self-hosted) and load you service. Once you set up your end points you can connect to it using your client proxies. This should work with simple HTTP and WSHTTP. In your Unit test you need to create a service reference to your service. Then you can create a host and wire your client with the test host together. I would try to avoid any tests using the "WCF Service Host" aka WcfSvcHost. (I mention this only because some people referred to the Visual Studio utils; which will work only if you only run tests from your IDE.) If you need to check exotic authentication scenarios or endpoints which use special middleware you will need to create tests using the middleware. For simple sanity checks, etc using self-hosting is sufficient. Middleware dependent testing can cause test deployment issues if you are using a build server. By middleware dependent endpoints I mean endpoints which are using for example MOMs (MSMQ, RabbitMQ, etc) or really exotic protocols, etc. Perhaps testing the client proxies with a self-hosted mock and testing the exotic endpoints separately is the way to go. If you want to use dependency injection there are a few pretty sophisticated frameworks which provide “service abstraction” features which allow you to inject mock services, etc. I used Spring.NET with WCF a few times. Castle Windsor has WCF facilities as well. Self-hosted test example: ServiceHost serviceHost = null; try { var baseAddress = new Uri("http://localhost:8000/TestService"); serviceHost = new ServiceHost(typeof (ServiceClass), baseAddress); Binding binding = new WSHttpBinding(); var address = new EndpointAddress("http://localhost:8000/TestService/MyService"); var endpoint = serviceHost .AddServiceEndpoint(typeof (IServiceContract), binding, address.Uri); var smb = new ServiceMetadataBehavior {HttpGetEnabled = true}; serviceHost.Description.Behaviors.Add(smb); using (var client = new ProxyClient(endpoint.Name, endpoint.Address)) { endpoint.Name = client.Endpoint.Name; serviceHost.Open(); // ... magic happens } serviceHost.Close(); } catch (Exception ex) { // ... tests } finally { if (serviceHost != null) { ((IDisposable) serviceHost).Dispose(); } } I would like to point out that functional testing tools are not the same as unit testing tools. Unit testing should be about breaking down your test into a bunch of independent tests while functional testing is mostly about testing workflows end to end. A: You can use Typemock Isolator to do that. Here are a couple of posts on the issue of testing the client side, and the server side. You can do that without any dependency, including a config file. Gil Zilberfeld Typemock A: Typemock Isolator is a tool for unit testing wcf services, amoung other things... A: What exactly do you want to test? Connectivity or service methods? Cool thing about WCF is that you can just define interfaces (err, contracts) and test them as regular code. Then you can assume that they will work via any connection type supported by WCF. Connectivity can be tested by hosting your service directly in UT or on development web-server. As for tools, you there are tons of unit testing frameworks: NUnit, built-in tests in Visual Studio, xUnit, etc, etc. You can download "Visual Studio 2008 and .NET Framework 3.5 Training Kit" and ".NET Framework 3.5 Enhancements Training Kit" if I recall correctly there were samples for WCF unit tests A: I have seen SOA Test used to evaluate performance and scalability tests on WCF services, if this is what you seek. I have no information on cost or liscencing. In our case, we captured the messages from our UI in order to perform automated testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/152338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: In Java, do I need to declare my collection synchronized if it's read-only? I fill a collection one single time when my J2EE webapp starts. Then, several thread may access it at same time but only to read it. I know using a synchronized collection is mandatory for parallels write but do I still need it for parallels read ? A: You do not have to, as explained in other answers. If you want to ensure that your collection is read only, you can use: yourCollection = Collections.unmodifableCollection(yourCollection); (similar method exist for List, Set, Map and other collection types) A: Normally no because you are not changing the internal state of the collection in this case. When you iterate over the collection a new instance of the iterator is created and the state of the iteration is per iterator instance. Aside note: Remember that by keeping a read-only collection you are only preventing modifications to the collection itself. Each collection element is still changeable. class Test { public Test(final int a, final int b) { this.a = a; this.b = b; } public int a; public int b; } public class Main { public static void main(String[] args) throws Exception { List<Test> values = new ArrayList<Test>(2); values.add(new Test(1, 2)); values.add(new Test(3, 4)); List<Test> readOnly = Collections.unmodifiableList(values); for (Test t : readOnly) { t.a = 5; } for (Test t : values) { System.out.println(t.a); } } } This outputs: 5 5 Important considerations from @WMR answser. It depends on if the threads that are reading your collection are started before or after you're filling it. If they're started before you fill it, you have no guarantees (without synchronizing), that these threads will ever see the updated values. The reason for this is the Java Memory Model, if you wanna know more read the section "Visibility" at this link: http://gee.cs.oswego.edu/dl/cpj/jmm.html And even if the threads are started after you fill your collection, you might have to synchronize because your collection implementation could change its internal state even on read operations (thanks Michael Bar-Sinai, I didn't know such collections existed). Another very interesting read on the topic of concurrency which covers topics like publishing of objects, visibility, etc. in much more detail is Brian Goetz's book Java Concurrency in Practice. A: It depends on if the threads that are reading your collection are started before or after you're filling it. If they're started before you fill it, you have no guarantees (without synchronizing), that these threads will ever see the updated values. The reason for this is the Java Memory Model, if you wanna know more read the section "Visibility" at this link: http://gee.cs.oswego.edu/dl/cpj/jmm.html And even if the threads are started after you fill your collection, you might have to synchronize because your collection implementation could change its internal state even on read operations (thanks Michael Bar-Sinai, I didn't know such collections existed in the standard JDK). Another very interesting read on the topic of concurrency which covers topics like publishing of objects, visibility, etc. in much more detail is Brian Goetz's book Java Concurrency in Practice. A: In the general case, you should. This is because some collections change their internal structure during reads. A LinkedHashMap that uses access order is a good example. But don't just take my word for it: In access-ordered linked hash maps, merely querying the map with get is a structural modification The Linked hash map's javadoc If you are absolutely sure that there are no caches, no collection statistics, no optimizations, no funny stuff at all - you don't need to sync. In that case I would have put a type constraint on the collection: Don't declare the collection as a Map (which would allow LinkedHashMap) but as HashMap (for the purists, a final subclass of HashMap, but that might be taking it too far...). A: The collection itself does not, but keep in mind that if what it holds is not immutable also, those seperate classes need their own synchronization.
{ "language": "en", "url": "https://stackoverflow.com/questions/152342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: NSWindow launched from statusItem menuItem does not appear as active window I have a statusItem application written in PyObjC. The statusItem has a menuItem which is supposed to launch a new window when it is clicked: # Create statusItem statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) statusItem.setHighlightMode_(TRUE) statusItem.setEnabled_(TRUE) statusItem.retain() # Create menuItem menu = NSMenu.alloc().init() menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Preferences', 'launchPreferences:', '') menu.addItem_(menuitem) statusItem.setMenu_(menu) The launchPreferences: method is: def launchPreferences_(self, notification): preferences = Preferences.alloc().initWithWindowNibName_('Preferences') preferences.showWindow_(self) Preferences is an NSWindowController class: class Preferences(NSWindowController): When I run the application in XCode (Build & Go), this works fine. However, when I run the built .app file externally from XCode, the statusItem and menuItem appear as expected but when I click on the Preferences menuItem the window does not appear. I have verified that the launchPreferences code is running by checking console output. Further, if I then double click the .app file again, the window appears but if I change the active window away by clicking, for example, on a Finder window, the preferences window disappears. This seems to me to be something to do with the active window. Update 1 I have tried these two answers but neither work. If I add in to the launchPreferences method: preferences.makeKeyAndOrderFront_() or preferences.setLevel_(NSNormalWindowLevel) then I just get an error: 'Preferences' object has no attribute A: You need to send the application an activateIgnoringOtherApps: message and then send the window makeKeyAndOrderFront:. In Objective-C this would be: [NSApp activateIgnoringOtherApps:YES]; [[self window] makeKeyAndOrderFront:self]; A: I have no idea of PyObjC, never used that, but if this was Objective-C code, I'd say you should call makeKeyAndOrderFront: on the window object if you want it to become the very first front window. A newly created window needs to be neither key, nor front, unless you make it either or like in this case, both. The other issue that worries me is that you say the window goes away (gets invisible) when it's not active anymore. This sounds like your window is no real window. Have you accidentally set it to be a "Utility Window" in Interface Builder? Could you try to manually set the window level, using setLevel: to NSNormalWindowLevel before the window is displayed on screen for the first time whether it still goes away when becoming inactive?
{ "language": "en", "url": "https://stackoverflow.com/questions/152344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically setting background colour of a Silverlight control (Listbox) How do I set the background colour of items in a list box dynamically? i.e. there is some property on my business object that I'm binding too, so based on some business rules I want the background colour to be different? <ListBox Background="Red"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Background" Value="Red"/> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Margin="5"> <TextBlock VerticalAlignment="Bottom" FontFamily="Comic Sans MS" FontSize="12" Width="70" Text="{Binding Name}" /> <TextBlock VerticalAlignment="Bottom" FontFamily="Comic Sans MS" FontSize="12" Width="70" Text="{Binding Age}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> EDIT: It says here In Silverlight, you must add x:Key attributes to your custom styles and reference them as static resources. Silverlight does not support implicit styles applied using the TargetType attribute value. Does this impact my approach? A: Ok - if you need custom logic to determine the background then I would look into building a simple IValueConverter class. You just need to implement the IValueConverter interface and, in its Convert method, change the supplied value into a Brush. Here's a quick post from Sahil Malik that describes IValueConverters - it might help: http://blah.winsmarts.com/2007-3-WPF__DataBinding_to_Calculated_Values--The_IValueConverter_interface.aspx A: To bind your background to more than one property, you can use IMultiValueConverter. It's just like IValueConverter except that it works with MultiBinding to pass more than one value into a class and get back a single value. Here's a post I found with a run-through on IMultiValueConverter and MultiBinding: http://blog.paranoidferret.com/index.php/2008/07/21/wpf-tutorial-using-multibindings/ Edit: If IMultiValueConverter isn't available (it looks like Silverlight only has IValueConverter) then you can always pass your entire bound object (eg your Person object) to an IValueConverter and use various properties from that to return your Brush. A: @Matt Thanks for the reply. I'll look into triggers. My only problem is that, the logic for determining whether a row should be coloured is slightly more involved so I cant just checking a property, so I actually need to run some logic to determine the colour. Any ideas? I guess I could make a UI object with all the relevant fields I need, but I kinda didnt want to take the approach. A: You could try binding something in your controltemplate (ie a border or something) to the TemplateBackground. Then set the background on your listbox to determine the colour it will be. <Border Margin="-2,-2,-2,0" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1,1,1,0" CornerRadius="11,11,0,0">
{ "language": "en", "url": "https://stackoverflow.com/questions/152376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Credential Caching Fail on SVN 1.5.2 via HTTP We recently installed SVN 1.5.2 (with VisualSVN/Apache) on some of our servers / virtual machines, and now when I send a commandline command with username/password they don't get cached anymore. Before, we were running SVN 1.5.0 installed with CollabNet, on svn://, and the credentials were cached after the first command. So far, I'm finding difficulties in troubleshooting this. My situation is: * *SERVER_SVN (SVN 1.5.2 via svn://) *SERVER_HTTP (SVN 1.5.2 via http://) Command from commandline to SERVER_SVN: credentials cached fine Same command to SERVER_HTTP: credentials are not cached So, it seems like an http/apache server problem... BUT, from Tortoise the credentials are cached to both servers, so it also seems a client call problem. I'm running out of ideas... A sample command sequence I use: svn ls c:\mylocalfolderSVN --username foo --password bar svn ls c:\mylocalfolderSVN // this works svn ls c:\mylocalfolderHTTP --username foo --password bar svn ls c:\mylocalfolderHTTP // this fails The last command stops and asks for authentication. Is credentials caching different between svn:// and http://, or did we miss something in the server configuration? Thanks in advance for any suggestion. A: AFAIK the credential caching is a client responsibility. All the server does is ask for those credentials when necessary. I'd check the local client configuration files and maybe see what happens with different version clients. A: Are you fully qualifying the domain name of the SVN server? If the caching for HTTP is cookie based and the server is writing a cookie with the FQDN, but your request doesn't use the FQDN (you are using svnserver and the FQDN is svnserver.company) then the cookie may not be valid and each request will need authentication. A: As wds points out, SVN credentials caching is done on the client side by svn.exe, after receiving a response from the server like "ok, I actually used the credentials you send, and they're fine". And this is why I can't figure out what's happening: I have 2 servers installed from scratch, I send the same commandlines to both, one set of credentials is cached, the other is not... but TortoiseSVN, which uses the same svn.exe underneath, caches both (maybe it cheats, caching the credentials then svn.exe fails to do so). My best guess right now is that the http:// server does not send an "appropriate" response to svn.exe, but I really don't feel like sniffing all the http requests to see what's happening, call me lazy, but I've got funnier stuff to do :-) So I changed my design, now I'll be keeping the SVN password in memory (WinForm client application, all used in our internal network), and pass it with each command. A: In order to cache credentials, apart from appropriate configuration, you need to execute SVN like this: svn ls REPOSITORY_URL instead of svn ls WORKING_COPY_PATH This is what worked for me, not really sure if this is the solution in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/152382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Define a one-to-one relationship with LinqToSQL I'm playing around with LinqToSQL using an existing multi-lingual database, but I'm running into issues mapping a fairly important one-to-one relationship, so I suspect I am using the feature incorrectly for my database design. Assume two tables, Category and CategoryDetail. Category contains the CategoryId (PK), ParentId and TemplateId. CategoryDetail contains the CategoryId (FK), LanguageId, Title and Description (in the appropriate language), with a combined PK of CategoryId and LanguageId. If I drag-and-drop these tables into the LinqToSQL designer, the resultant object model has Category with a collection of CategoryDetail objects, which should never be the case. I'd like to be able to filter on LanguageId at the DataContext level, meaning that the whole Category is encapsulated within Category.CategoryDetail, not all language version encapsulated within Category.CategoryDetails. This database worked fine on my old object library (an old-school custom BOL and DAL), but I fear that LinqToSQL would require this to change in order to give me the required result. What is the best way to make this relationship (and language filtering) as seamless as possible? A: I would have to assume cant be a true 1 to 1. Sounds like you have a PK of CatID and Lang ID on the Cat Details table. That would explain why its putting a collection. I could be wrong as you didnt mention the PK's of the CatDetails table EDIT: A combined Pk of CatID and Lang ID makes that a 1:m relationship, and Linq to SQL is actually doing the correct thing. The only way it could possibly be a true 1:1 is if you had a lang ID on the cat table as well and that was part of the FK. I htink you may have to rethink what you want to do, or how you want to implement it. A: You can view properties of the association. (Right click on the line representing the association and show properties.) The properties will tell you if it is a one-to-one or one-to-many relationship. This is reflected in code by having either a single entity association (one-to-one) or an entity set association (one-to-many). A: I think LINQ to SQL models the database structure directly. You have two tables so it creates 2 objects. Have you had a look at LINQ to Entities this allows you to create another layer above the database strucure to make for more readable classes. A: Since you don't have a 1:1 relationship the mapping alone will not provide the desired functionality. However it is easy to provide a method in the parent auto-generated class that does the job: public partial class Category { public IEnumerable<CategoryDetail> GetDetailsByLanguage(string langID) { return this.CategoryDetails.Where(c => c.LangID == langID); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/152384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What technologies do C++ programmers need to know? C++ was the first programming language I really got into, but the majority of my work on it was academic or for game programming. Most of the programming jobs where I live require Java or .NET programmers and I have a fairly good idea of what technologies they require aside from the basic language. For example, a Java programmer might be required to know EJB, Servlets, Hibernate, Spring, and other technologies, libraries, and frameworks. I'm not sure about C++, however. In real life situations, for general business programming, what are C++ programmers required to know beyond the language features? Stuff like Win32 API, certain libraries, frameworks, technologies, tools, etc. Edit: I was thinking of the standard library as well when I said basic language, sorry if it was wrong or not clear. I was wondering if there are any more specific domain requirements similar to all the technologies Java or .NET programmers might be required to learn as apposed to what C++ programmers need to know in general. I do agree that the standard library and Boost are essential, but is there anything beyond that or is it different for every company/project/domain? A: technologies you should know as a C++ programmer (and therefore more technically knowledgeable than lesser programmers ;) ): performance issues - what makes things go slow, how to find and fix such issues. I also mean stuff like context switching, cache lines, optimised searches, memory usage and constraints, and similar stuff that your average VB/C# developer doesn't care about. threading issues - how to get the most from a multi-threaded app, how to detect and fix abuses of the same. low-level communications - especially being able to connect to obscure systems that no-one else has written a toolkit for (especially radio comms), latency and bandwidth management. Otherwise, for specific tools - it depends on what you're targeting, Windows dev will be different to Linux, different to embedded. A: This will largely depend on the used platform and other constraints. As a general rule, a good (C++) programmer is (or should be) able to learn a platform-specific API in a very short time. For C++, it's much more important to understand the different tool chains (e.g. a Windows programmer should also know the GCC tool chain) and differences in compilers. Programmer should also understand limitations and platform-dependend behaviour of the language. As for libraries, C++ programmers absolutely need to know STL and Boost. No discussion. A: Standard Template Library http://en.wikipedia.org/wiki/Standard_Template_Library A: As for every language, I believe there are three interconnected levels of knowledge : * *Master your language. Every programmer should (do what it takes to) master the syntax. Good references to achieve this are : * *The C++ Programming Language by Bjarne Stroustrup. *Effective C++ series by Scott Meyers. *Know your libraries extensively. * *STL is definitely a must as it has been included in the C++ Standard Library, so knowing it is very close to point 1 : you have to master it. *Knowing boost can be very interesting, as a multi-platform and generic library. *Know the libraries you are supposed to work with, whether it is Win32 API, OCCI, XPCOM or UNO (just a few examples here). No need to know a database library if you develop purely graphic components... *Develop your knowledge of patterns. Cannot avoid Design Patterns: Elements of Reusable Object-Oriented Software here... So, my answer to your updated question would be : know your language, know your platform, know your domain. I think there is enough work by itself here, especially in C++. It's an evergoing work that should never be overlooked. A: Besides the stuff everyone listed, keep in mind that C++ programmer have space on the embedded systems market (much more than most other high level languages).So familiarity with embedded systems and development may open a lot of doors and job opportunities where you will not be competing so heavily with Java development for example. So learning to code compact code (compact after compiled) and low memory usage techniques is a good bet. A: C++ developer have to grok std and boost libraries. List of other technologies largely depends on project type. For sure you will have some interaction with SO, so you will need to know API of your environment. As for data-access and other stuffs there are tons for different solutions. C++ is much richer than some managed langs in that sense. 99% of old popular systems have C/C++ interface. After you clarified your question a bit in the comment to my answer I can recommend: * *Good code browser (SourceInsight or Understand For C++ for example) *Static analysis tools (Link, KlockWork Inforce, etc.) *MySQL\SQLite (I encountered these DB in a huge number of C++ projects) *UI technologies (OpenGL\GLUT, DirectX, GDI, Qt, etc) A: if you're using gcc you should definitely know gdb. Actually, you should be proficient with the local debugger for whichever compiler you're using. Other than that there is such a wide range of libraries used that being able to quickly pick up an API is more useful than any specific one. I would suggest learning doxygen though. A: If you are using linux then Valgrind is a very usefull tool for checking how your program deals with memory access. A: In no specific order * *COM/ATL *DirectX *MFC & Win32 *STL *GDI *BOOST A: The popular way to use C++ in the mobile space would involve learning Symbian OS development. http://developer.symbian.com
{ "language": "en", "url": "https://stackoverflow.com/questions/152387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: How do I merge TMainMenu's that use separate imagelists and retain the correct images by each menu item? I have a program with two TForm classes and have added a TMainMenu to them each. I am then trying to merge them dynamically at run-time. My problem is that when they merge the menu items in the merged in TMainMenu now display images stored in the imagelist in the form they were merged into rather than the images stored in their original form's imagelist. Am I doing something wrong? is there a work around so that the menu item's continue to use the imagelist in the form they originated from? I use the merged-in form in a number of projects, otherwise a single shared imagelist would make sense. If I need to clarify anything, please say. Thanks Peter A: The way I handle this is to have a single image list on a datamodule, and then include that in each form so that they can share that single set of icons. A: I had exactly the same problem a while ago, but I also ran into other menu merge problems because my app was MDI, so I decided to do things in a completely different way. What you could try, though, is dynamically adding one form's images to the other form's ImageList, and 'redirecting' the ImageIndexes. Might be a bit tricky, but should work. What I eventually ended up with, is using the Toolbar2000 package for all my menus and toolbars. You can then download a very nice piece of code, called TB2Merge, which does exactly what you want. It also makes use of some of Toolbar2000's infrastructure to link a menu item's image to a different TImageList --- infrastructure that is not present in the VCL's TMainMenu. Be sure to read TB2Merge's documentation thoroughly!
{ "language": "en", "url": "https://stackoverflow.com/questions/152405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you write a (simple) variable "toggle"? Given the following idioms: 1) variable = value1 if condition variable = value2 2) variable = value2 if not condition variable = value1 3) if condition variable = value2 else variable = value1 4) if not condition variable = value1 else variable = value2 Which do you prefer, and why? We assume the most common execution path to be that of condition being false. I tend to learn towards using 1), although I'm not exactly sure why I like it more. Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax, and they are not suitable for extending the variable assignment to include more than one statement in the future. variable = condition ? value2 : value1 ... variable = value2 if condition else value1 A: I prefer method 3 because it is more concise and a logical unit. It sets the value only once, it can be moved around as a block, and it's not that error-prone (which happens, esp. in method 1 if setting-to-value1 and checking-and-optionally-setting-to-value2 are separated by other statements) A: 3) is the clearest expression of what you want to happen. I think all the others require some extra thinking to determine which value is going to end up in the variable. In practice, I would use the ternary operator (?:) if I was using a language that supported it. I prefer to write in functional or declarative style over imperative whenever I can. A: In theory, I prefer #3 as it avoids having to assign a value to the variable twice. In the real world though I use any of the four above that would be more readable or would express more clearly my intention. A: I tend to use #1 alot myself. if condition reads easier than if !condition, especially if you acidentally miss the '!', atleast to my mind atleast. Most coding I do is in C#, but I still tend to steer clear of the terniary operator, unless I'm working with (mostly) local variables. Lines tend to get long VERY quickly in a ternary operator if you're calling three layers deep into some structure, which quickly decreases the readability again. A: Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax This is no argument for not using them in languages that do provide such a syntax. Incidentally, that includes all current mainstream languages after my last count. and they are not suitable for extending the variable assignment to include more than one statement in the future. This is true. However, it's often certain that such an extension will absolutely never take place because the condition will always yield one of two possible cases. In such situations I will always prefer the expression variant over the statement variant because it reduces syntactic clutter and improves expressiveness. In other situations I tend to go with the switch statement mentioned before – if the language allows this usage. If not, fall-back to generic if. A: switch statement also works. If it's simple and more than 2 or 3 options, that's what I use. A: In a situation where the condition might not happen. I would go with 1 or 2. Otherwise its just based on what i want the code to do. (ie. i agree with cruizer) A: I tend to use if not...return. But that's if you are looking to return a variable. Getting disqualifiers out of the way first tends to make it more readable. It really depends on the context of the statement and also the language. A case statement might work better and be readable most of the time, but performance suffers under VB so a series of if/else statements makes more sense in that specific case. A: Method 1 or method 3 for me. Method 1 can avoid an extra scope entrance/exit, but method 3 avoids an extra assignment. I'd tend to avoid Method 2 as I try to keep condition logic as simple as possible (in this case, the ! is extraneous as it could be rewritten as method 1 without it) and the same reason applies for method 4. A: It depends on what the condition is I'm testing. If it's an error flag condition then I'll use 1) setting the Error flag to catch the error and then if the condition is successfull clear the error flag. That way there's no chance of missing an error condition. For everything else I'd use 3) The NOT logic just adds to confusion when reading the code - well in my head, can't speak for eveyone else :-) A: If the variable has a natural default value I would go with #1. If either value is equally (in)appropriate for a default then I would go with #2. A: It depends. I like the ternary operators, but sometimes it's clearer if you use an 'if' statement. Which of the four alternatives you choose depends on the context, but I tend to go for whichever makes the code's function clearer, and that varies from situation to situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/152416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to sign custom Soap Header? I've added a custom soap header <MyApp:FOO> element to the <soap:Header> element and the requirments states that i must sign this element , how would one do that? <MyApp:FOO> contains a number of things (username, preferences, etc) that identifies a user on higher level. I've succesfully used a policy file and now a policyClass with CertificateAssertions and SoapFilters to sign wsu:Timestamp, wsu:action, wsu:MessageId etc. But now the <MyApp:FOO> element needs to signed aswell. What i've understood this far is that the element that needs to be signed must be indentified with a wsu:Id attribute and then transformed using xml-exc-c14n. So, how do I specify that the soap header should be signed aswell? This is the current class that i use for signing my message. internal class FOOClientOutFilter: SendSecurityFilter { X509SecurityToken clientToken; public FOOClientOutFilter(SSEKCertificateAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { // Get the client security token. clientToken = X509TokenProvider.CreateToken(StoreLocation.CurrentUser, StoreName.My, "CN=TestClientCert"); // Get the server security token. serverToken = X509TokenProvider.CreateToken(StoreLocation.LocalMachine, StoreName.My, "CN=TestServerCert"); } public override void SecureMessage(SoapEnvelope envelope, Security security) { // Sign the SOAP message with the client's security token. security.Tokens.Add(clientToken); security.Elements.Add(new MessageSignature(clientToken)); } } A: My current version of SecureMessage seems to do the trick.. public override void SecureMessage(SoapEnvelope envelope, Security security) { //EncryptedData data = new EncryptedData(userToken); SignatureReference ssekSignature = new SignatureReference(); MessageSignature signature = new MessageSignature(clientToken); // encrypt custom headers for (int index = 0; index < envelope.Header.ChildNodes.Count; index++) { XmlElement child = envelope.Header.ChildNodes[index] as XmlElement; // find all FOO headers if (child != null && child.Name == "FOO") { string id = Guid.NewGuid().ToString(); child.SetAttribute("Id", "http://docs.oasis-" + "open.org/wss/2004/01/oasis-200401-" + "wss-wssecurity-utility-1.0.xsd", id); signature.AddReference(new SignatureReference("#" + id)); } } // Sign the SOAP message with the client's security token. security.Tokens.Add(clientToken); security.Elements.Add(signature); } A: Including supplementary articles from MSDN How to: Add an Id Attribute to a SOAP Header How to: Digitally Sign a Custom SOAP Header
{ "language": "en", "url": "https://stackoverflow.com/questions/152419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Caching the sessionfactory As far as I've gathered (read: measured), building the configuration and the sessionfactory by far takes the most time in executing a query using nhibernate. Is there anything against making the sessionfactory static, so it will only be configured once per appDomain? I know there are locking and racing issues when using this approach, but personally I don't see where this would break my application when using this approach on the sessionfactory. The reason I am asking this is because it's really hard to test for possible threading issues, as it doesn't occur all the time. A: Session factory should be started at the application start indeed. You could check the best practices here.
{ "language": "en", "url": "https://stackoverflow.com/questions/152432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Code coverage for PL/SQL Does anyone have tools or experience with code coverage for PL/SQL. I believe this is possible using DBMS_PROFILER? A: http://www.toadworld.com/BLOGS/tabid/67/EntryID/267/Default.aspx has info about checking code coverage using the PL/SQL profiler. Some helpful info about profiling on 9i or 10g is included in Metalink Article 243755.1 "Implementing and Using the PL/SQL Profiler" for information on profiling code. Grab the prof.zip from the bottom of the article, it has a profiler.sql which will nicely format your results after a profiling run. More 10g documentation is available here without a MetaLinka account: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_profil.htm If you are running 11g there is a new Hierarchical Profiler documented here: http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28424/adfns_profiler.htm A: See SD Test Coverage Tools. We're about to release a PLSQL test coverage tool with the same capabilities as our other tools, including a GUI to display the results on top of your source code, and a generated coverage report that collects details on individual functions as well as rollups for packages. EDIT 2/15/2011: PLSQL test coverage production tool is available. A: Not sure if this is quite what you're after, but in 10g onwards there's a tool to do static PL/SQL code analysis. Info here... http://www.psoug.org/reference/plsql_warnings.html Note that it can be enabled at either session or database level. In my experience it's thrown up quite a few false negatives so far. A: I found something useful on http://www.databasejournal.com/features/oracle/article.php/10893_2197231_3 page. select exec.cnt/total.cnt * 100 "Code% coverage" from (select count(1) cnt from plsql_profiler_data d, plsql_profiler_units u where d.runid = &&runid and u.runid = d.runid and u.unit_number = d.unit_number and u.unit_name = upper('&&name') and u.unit_owner = upper('&&owner') ) total, (select count(1) cnt from plsql_profiler_data d, plsql_profiler_units u where d.runid = &&runid and u.runid = d.runid and u.unit_number = d.unit_number and u.unit_name = upper('&&name') and u.unit_owner = upper('&&owner') and d.total_occur > 0) exec; A: There is a package you can install called DBMS_profiler. With this, you can start a profile and Oracle will store data in special tables. Then stop the profile and report from those tables. A: With Oracle 12.2c now you can use DBMS_PLSQL_CODE_COVERAGE package. In fact, this provides basic-block level coverage. Basic-block is the smallest executable code. These are few references to find more information. Oracle documentation Tutorial Youtube Video
{ "language": "en", "url": "https://stackoverflow.com/questions/152435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Do you recommend Native C++ to C++\CLI shift? I have been working as a native C++ programmer for last few years. Now we are starting a new project from the scratch. So what is your thoughts on shifting to C++\CLI at the cost of losing platform independent code. Are there are any special advantages that one can gain by shifting to C++\CLI? A: Some questions to consider before switching: [1] Are you fine with sticking to Windows? There are .NET clones for other OS's, but your app is not going to just run transparently. A complexity you might not need. [2] Are you considering switching just for the garbage collection support? If so, you can just use some C++ garbage collector libraries. And if you figure out how to leverage std::shared_ptr, you might not feel the need for garbage collectors. An overhead you might not need. [3] Are you considering C++/CLI because of the garbage collection & all the useful .NET classes that you can leverage? If so, why not just switch to c#. C++/CLI is a transitional technology, and it is best not to invest resources in such things. c# is getting pretty mature and usable. Personally, I would just stick with C++ ;). A: I would recommend the following, based on my experience with C++, C# and .NET: * *If you want to go the .NET way, use C#. *If you do not want .NET, use traditional C++. *If you have to bridge traditional C++ with .NET code, use C++/CLI. Works both with .NET calling C++ classes and C++ calling .NET classes. I see no sense in just going to C++/CLI if you don't need it. A: Is there any benefit to you? You will likely lose the ablity to switch to another OS. A: don't bother unless you're integrating with .NET apps. Certainly do not use STL/CLR as its performance is truly awful. Its tempting to flip that switch to use the .NET class libraries, but there are alternatives. If you do this, you will not be able to port your code so easily. It also seems that the rise of OSS is increasing, so now might be the time to investigate using cross-platform libraries and tools. You can deploy a linux app much more easily than a windows one (by shipping a fully-configured OS!), and you get much better ROI if you deploy linux clients (as they're free). If I were a businessman, I would be looking to at least have the capability to deploy on linux or mac than just windows-only. Strategically, I would not want to bet that the world stayed with Microsoft in 5 years time. A: The main advantage you would get moving to C++/CLI is to get access to the .NET libraries and the framework itself (garbage collection etc.). However, as far as I can tell the main reason C++/CLI exists is to ease the porting of existing C++ code to run in the .NET framework. New projects are encouraged to use C#. If you need to use existing C++ code mixed in with the .NET framework, then it would make sense to use C++/CLI, but in general you should just begin with C#. If there is something in .NET that the new project needs to use extensively (maybe simpler GUI design or something), then use C#. if not, then stick with native C++. I don't think you will lose anything by doing that. A: I dislike C++/CLI so much that I'd recommend steering clear, as I describe here. Some suggest using C++/CLI as a bridge between standard C++ and C#, but thanks to the way C++/CLI is designed, it is very tedious to use that way (you have to manually create wrappers of normal C++ code that can be called from C#). Therefore, I would recommend SWIG instead for interfacing standard C++ with C# (although admittedly, SWIG has a substantial learning curve). A: Take a look at those two articles: A Critical Overview of C++/CLI, Part I A Critical Overview of C++/CLI, Part II I believe that by now you are convinced as I am that C++/CLI is neither a "set of extensions to C++" (in many aspects it’s actually a subset of C++), nor is it related to C++ more than any other language with semicolons and curly braces. Furthermore, C++/CLI is definitely a Windows-oriented programming language; it’s definitely not a language that a Solaris 10 server or a Nokia mobile phone will be happy to run. What does it have anything to do with C++? A: One main disadvantage of using C++/CLR is the possibility of losing your IP (intellectual Property) if the code is not obscured suficently. In general I agree with the statements made by other members here. If you want portable code independant of the MS .net vm then native C/C++ is the way to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/152436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: LDAP entire subtree copy I am actually new to this forum and I kept trying for a few days to find an easy way to copy an entire LDAP subtree to another tree. Since I couldn't find anything useful, i thought of dropping a question here as well. Does anybody know how to do this programatically ? For normal operations like add, remove, search, I've been using Spring LDAP. Thanks a lot ! A: I actually don't know Spring LDAP but if your LDAP interface does not provide any high level abstraction for moving/renaming or copying an entire subtree you have to move/rename or copy all subtree nodes recursively. The LDAP API does not provide such an option directly. The following is pseudo-code: function copySubtree(oldDn, newDn) { copyNode(oldDn, newDn); // the new node will be created here if (nodeHasChildren(oldDn) { foreach (nodeGetChildren(oldDn) as childDn) { childRdn=getRdn(childDn); // we have to get the 'local' part, the so called RDN newChildDn=childRdn + ',' + newDn; // the new DN will be the old RDN concatenated with the new parent's DN copySubtree(childDn, newChildDn); // call this function recursively } } } A: Dump it as LDIF, edit the DNs via search & replace (or via script), and import the new LDIF. Spring may not be the tool to do this. Is it necessary that you manipulate the directory with Spring? I presume OpenLDAP's ldapsearch and ldapadd should work against any server, and they will dump/load LDIF. A: Do note that passwords are tricky to copy. You may or may not be able to read them via the LDAP API. It would depend on the LDAP implementation you are using this against. Thus a copy to a new location may not get everything you want or need.
{ "language": "en", "url": "https://stackoverflow.com/questions/152439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unit testing for PL/SQL Anyone have any experience or tools for unit testing PL/SQL. The best looking tool I've seen for this seems to be Quests Code Tester, but i'm not sure how well that would integration with continuous integration tools or command line testing? A: I use utPLSQL as the framework and OUnit as the client. utPLSQL isn't really meant to be used by itself, a good graphical client is required. OUnit is the predecessor to Qute. Qute is also a good tool but more complex than my requirements - it allows you to construct tests using a GUI and does good stuff like test code generation. Edit: My understanding is that utPLSQL stores all results in database tables, including all historical results which would make a good data source for gathering statistics for continuous integration. You can also define test groups so a single call to utPLSQL can call multiple test packages. A: Check utPLSQL out. I found it somewhat difficult to start with, but i think it does the job reasonably well. As for continuous integration tools, I used to create usual tests (NUnit, C#) that just called the stored procedures created with utPLSQL and checked their result out. A: I have created and using PL/SQL unit testing framework using Ruby library ruby-plsql. It provides much shorter and more readable tests than utPLSQL and gives more flexibility compared to GUI tools (like Quest Code Tester or SQLDeveloper 2.1). A: There are a few listed on the wikipedia : http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#PL.2FSQL A: The last version of SQL Developer includes an Unit Test suite very interesting. A: I found this interesting post about the continuous integration for PL/SQL projects. It meanly deals with the unit testing of PL/SQL code, using the previously listed utPLSQL framework... A: I'm using python py.test with cx_oracle to build test scripts for pl/sql packages. Works nice so far. A: I've recently used successfully unit testing framework of PL/SQL Commons toolkit (see also author's slides). The toolkit is not yet publicly available (at the time of the writing) but if you drop an email to the authors you'll get a working package (or at least I got).
{ "language": "en", "url": "https://stackoverflow.com/questions/152441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process? When I backup or restore a database using MS SQL Server Management Studio, I get a visual indication of how far the process has progressed, and thus how much longer I still need to wait for it to finish. If I kick off the backup or restore with a script, is there a way to monitor the progress, or do I just sit back and wait for it to finish (hoping that nothing has gone wrong?) Edited: My need is specifically to be able to monitor the backup or restore progress completely separate from the session where the backup or restore was initiated. A: Script to check the Backup and Restore progress in SQL Server: Many times it happens that your backup (or restore) activity has been started by another Database Administrator or by a job, and you cannot use the GUI anything else to check the progress of that Backup / Restore. By combining multiple commands, I have generated below script which can give us a summary of current backups and restores which are happening on the server. select r.session_id, r.blocking_session_id, db_name(database_id) as [DatabaseName], r.command, [SQL_QUERY_TEXT] = Substring(Query.TEXT, (r.statement_start_offset / 2) + 1, ( ( CASE r.statement_end_offset WHEN - 1 THEN Datalength(Query.TEXT) ELSE r.statement_end_offset END - r.statement_start_offset ) / 2 ) + 1), [SP_Name] =Coalesce(Quotename(Db_name(Query.dbid)) + N'.' + Quotename(Object_schema_name(Query.objectid, Query.dbid)) + N'.' + Quotename(Object_name(Query.objectid, Query.dbid)), ''), r.percent_complete, start_time, CONVERT(VARCHAR(20), DATEADD(ms, [estimated_completion_time], GETDATE()), 20) AS [ETA_COMPLETION_TIME], CONVERT(NUMERIC(6, 2), r.[total_elapsed_time] / 1000.0 / 60.0) AS [Elapsed_MIN], CONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0) AS [Remaning_ETA_MIN], CONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0/ 60.0) AS [ETA_Hours], wait_type, wait_time/1000 as Wait_Time_Sec, wait_resource from sys.dm_exec_requests r cross apply sys.fn_get_sql(r.sql_handle) as Query where r.session_id>50 and command IN ('RESTORE DATABASE','BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG') A: SELECT session_id as SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a WHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE') A: Try wih : SELECT * FROM sys.dm_exec_requests where command like '%BACKUP%' SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command like '%BACKUP%' SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time FROM sys.dm_exec_requests WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE') A: Use STATS in the BACKUP command if it is just a script. Inside code it is a bit more complicated. In ODBC for example, you set SQL_ATTR_ASYNC_ENABLE and then look for SQL_STILL_EXECUTING return code, and do some repeated calls of SQLExecDirect until you get a SQL_SUCCESS (or eqiv). A: Use STATS option: http://msdn.microsoft.com/en-us/library/ms186865.aspx A: I think the best way to find out how your restore or backup progress is by the following query: USE[master] GO SELECT session_id AS SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a WHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE') GO The query above, identify the session by itself and perform a percentage progress every time you press F5 or Execute button on SSMS! The query was performed by the guy who write this post A: I found this sample script here that seems to be working pretty well: SELECT r.session_id , r.command , CONVERT(NUMERIC(6,2), r.percent_complete) AS [Percent Complete] , CONVERT(VARCHAR(20), DATEADD(ms,r.estimated_completion_time,GetDate()),20) AS [ETA Completion Time] , CONVERT(NUMERIC(10,2), r.total_elapsed_time/1000.0/60.0) AS [Elapsed Min] , CONVERT(NUMERIC(10,2), r.estimated_completion_time/1000.0/60.0) AS [ETA Min] , CONVERT(NUMERIC(10,2), r.estimated_completion_time/1000.0/60.0/60.0) AS [ETA Hours] , CONVERT(VARCHAR(1000), (SELECT SUBSTRING(text,r.statement_start_offset/2, CASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END) FROM sys.dm_exec_sql_text(sql_handle) ) ) AS [SQL] FROM sys.dm_exec_requests r WHERE command IN ('RESTORE DATABASE', 'BACKUP DATABASE') A: Add STATS=10 or STATS=1 in backup command. BACKUP DATABASE [xxxxxx] TO DISK = N'E:\\Bachup_DB.bak' WITH NOFORMAT, NOINIT, NAME = N'xxxx-Complète Base de données Sauvegarde', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10 GO. A: SELECT session_id as SPID, command, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time, a.text AS Query FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a WHERE r.command in ('BACKUP DATABASE', 'BACKUP LOG', 'RESTORE DATABASE', 'RESTORE LOG') A: If you know the sessionID then you can use the following: SELECT * FROM sys.dm_exec_requests WHERE session_id = 62 Or if you want to narrow it down: SELECT command, percent_complete, start_time FROM sys.dm_exec_requests WHERE session_id = 62 A: Here's a simple script that generally does the trick for me: SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time FROM sys.dm_exec_requests WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE') A: Yes. If you have installed sp_who2k5 into your master database, you can simply run: sp_who2k5 1,1 The resultset will include all the active transactions. The currently running backup(s) will contain the string "BACKUP" in the requestCommand field. The aptly named percentComplete field will give you the progress of the backup. Note: sp_who2k5 should be a part of everyone's toolkit, it does a lot more than just this. A: For anyone running SQL Server on RDS (AWS), there's a built-in procedure callable in the msdb database which provides comprehensive information for all backup and restore tasks: exec msdb.dbo.rds_task_status; This will give a full rundown of each task, its configuration, details about execution (such as completed percentage and total duration), and a task_info column which is immensely helpful when trying to figure out what's wrong with a backup or restore. A: I had a similar issue when working on Database restore operation on MS SQL Server 2012. However, for my own scenario, I just needed to see the progress of the DATABASE RESTORE operation in the script window All I had to do was add the STATS option to the script: USE master; GO ALTER DATABASE mydb SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO RESTORE DATABASE mydb FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_21-08-2020.bak' WITH REPLACE, STATS = 10, RESTART, MOVE 'my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\my_db.mdf', MOVE 'my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\mydb_log.ldf' GO ALTER DATABASE mydb SET MULTI_USER; GO And then I switched to the Messages tab of the Script window to see the progress of the DATABASE RESTORE operation: If you want to get more information after the DATABASE RESTORE operation you can use this command suggested by eythort: SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command = 'RESTORE DATABASE' That's all. I hope this helps A: To monitor the backup or restore progress completely separate from the session where the backup or restore was initiated. No third party tools required. Tested on Microsoft SQL Server 2012. SELECT percent_complete, * FROM sys.dm_exec_requests WHERE command In ( 'RESTORE DATABASE', 'BACKUP DATABASE' ) A: I am using sp_whoisactive, very informative an basically industry standard. it returns percent complete as well. A: simply run bkp_status on master db you will get backup status
{ "language": "en", "url": "https://stackoverflow.com/questions/152447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "113" }
Q: What is the difference between a port and a socket? This was a question raised by one of the software engineers in my organisation. I'm interested in the broadest definition. A: The port was the easiest part, it is just a unique identifier for a socket. A socket is something processes can use to establish connections and to communicate with each other. Tall Jeff had a great telephone analogy which was not perfect, so I decided to fix it: * *ip and port ~ phone number *socket ~ phone device *connection ~ phone call *establishing connection ~ calling a number *processes, remote applications ~ people *messages ~ speech A: A socket is a structure in your software. It's more-or-less a file; it has operations like read and write. It isn't a physical thing; it's a way for your software to refer to physical things. A port is a device-like thing. Each host has one or more networks (those are physical); a host has an address on each network. Each address can have thousands of ports. One socket only may be using a port at an address. The socket allocates the port approximately like allocating a device for file system I/O. Once the port is allocated, no other socket can connect to that port. The port will be freed when the socket is closed. Take a look at TCP/IP Terminology. A: from Oracle Java Tutorial: A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. A: Port and socket can be compared to the Bank Branch. The building number of the "Bank" is analogous to IP address. A bank has got different sections like: * *Savings account department *Personal loan department *Home loan department *Grievance department So 1 (savings account department), 2 (personal loan department), 3 (home loan department) and 4 (grievance department) are ports. Now let us say you go to open a savings account, you go to the bank (IP address), then you go to "savings account department" (port number 1), then you meet one of the employees working under "savings account department". Let us call him SAVINGACCOUNT_EMPLOYEE1 for opening account. SAVINGACCOUNT_EMPLOYEE1 is your socket descriptor, so there may be SAVINGACCOUNT_EMPLOYEE1 to SAVINGACCOUNT_EMPLOYEEN. These are all socket descriptors. Likewise, other departments will be having employess working under them and they are analogous to socket. A: Firsty, I think we should start with a little understanding of what constitutes getting a packet from A to B. A common definition for a network is the use of the OSI Model which separates a network out into a number of layers according to purpose. There are a few important ones, which we'll cover here: * *The data link layer. This layer is responsible for getting packets of data from one network device to another and is just above the layer that actually does the transmitting. It talks about MAC addresses and knows how to find hosts based on their MAC (hardware) address, but nothing more. *The network layer is the layer that allows you to transport data across machines and over physical boundaries, such as physical devices. The network layer must essentially support an additional address based mechanism which relates somehow to the physical address; enter the Internet Protocol (IPv4). An IP address can get your packet from A to B over the internet, but knows nothing about how to traverse individual hops. This is handled by the layer above in accordance with routing information. *The transport layer. This layer is responsible for defining the way information gets from A to B and any restrictions, checks or errors on that behaviour. For example, TCP adds additional information to a packet such that it is possible to deduce if packets have been lost. TCP contains, amongst other things, the concept of ports. These are effectively different data endpoints on the same IP address to which an Internet Socket (AF_INET) can bind. As it happens, so too does UDP, and other transport layer protocols. They don't technically need to feature ports, but these ports do provide a way for multiple applications in the layers above to use the same computer to receive (and indeed make) outgoing connections. Which brings us to the anatomy of a TCP or UDP connection. Each features a source port and address, and a target port and address. This is so that in any given session, the target application can respond, as well as receive, from the source. So ports are essentially a specification-mandated way of allowing multiple concurrent connections sharing the same address. Now, we need to take a look at how you communicate from an application point of view to the outside world. To do this, you need to kindly ask your operating system and since most OSes support the Berkeley Sockets way of doing things, we see we can create sockets involving ports from an application like this: int fd = socket(AF_INET, SOCK_STREAM, 0); // tcp socket int fd = socket(AF_INET, SOCK_DGRAM, 0); // udp socket // later we bind... Great! So in the sockaddr structures, we'll specify our port and bam! Job done! Well, almost, except: int fd = socket(AF_UNIX, SOCK_STREAM, 0); is also possible. Urgh, that's thrown a spanner in the works! Ok, well actually it hasn't. All we need to do is come up with some appropriate definitions: * *An internet socket is the combination of an IP address, a protocol and its associated port number on which a service may provide data. So tcp port 80, stackoverflow.com is an internet socket. *An unix socket is an IPC endpoint represented in the file system, e.g. /var/run/database.sock. *A socket API is a method of requesting an application be able to read and write data to a socket. Voila! That tidies things up. So in our scheme then, * *A port is a numeric identifier which, as part of a transport layer protocol, identifies the service number which should respond to the given request. So really a port is a subset of the requirements for forming an internet socket. Unfortunately, it just so happens that the meaning of the word socket has been applied to several different ideas. So I heartily advise you name your next project socket, just to add to the confusion ;) A: A socket is a data I/O mechanism. A port is a contractual concept of a communication protocol. A socket can exist without a port. A port can exist witout a specific socket (e.g. if several sockets are active on the same port, which may be allowed for some protocols). A port is used to determine which socket the receiver should route the packet to, with many protocols, but it is not always required and the receiving socket selection can be done by other means - a port is entirely a tool used by the protocol handler in the network subsystem. e.g. if a protocol does not use a port, packets can go to all listening sockets or any socket. A: Port: A port can refer to a physical connection point for peripheral devices such as serial, parallel, and USB ports. The term port also refers to certain Ethernet connection points, s uch as those on a hub, switch, or router. Socket: A socket represents a single connection between two network applications. These two applications nominally run on different computers, but sockets can also be used for interprocess communication on a single computer. Applications can create multiple sockets for communicating with each other. Sockets are bidirectional, meaning that either side of the connection is capable of both sending and receiving data. A: Relative TCP/IP terminology which is what I assume is implied by the question. In layman's terms: A PORT is like the telephone number of a particular house in a particular zip code. The ZIP code of the town could be thought of as the IP address of the town and all the houses in that town. A SOCKET on the other hand is more like an established phone call between telephones of a pair of houses talking to each other. Those calls can be established between houses in the same town or two houses in different towns. It's that temporary established pathway between the pair of phones talking to each other that is the SOCKET. A: Generally, you will get a lot of theoretical but one of the easiest ways to differentiate these two concepts is as follows: In order to get a service, you need a service number. This service number is called a port. Simple as that. For example, the HTTP as a service is running on port 80. Now, many people can request the service, and a connection from client-server gets established. There will be a lot of connections. Each connection represents a client. In order to maintain each connection, the server creates a socket per connection to maintain its client. A: A socket = IP Address + a port (numeric address) Together they identify an end-point for a network connection on a machine. (Did I just flunk network 101?) A: In a broad sense, Socket - is just that, a socket, just like your electrical, cable or telephone socket. A point where "requisite stuff" (power, signal, information) can go out and come in from. It hides a lot of detailed stuff, which is not required for the use of the "requisite stuff". In software parlance, it provides a generic way of defining a mechanism of communication between two entities (those entities could be anything - two applications, two physically separate devices, User & Kernel space within an OS, etc) A Port is an endpoint discriminator. It differentiates one endpoint from another. At networking level, it differentiates one application from another, so that the networking stack can pass on information to the appropriate application. A: Socket is an abstraction provided by kernel to user applications for data I/O. A socket type is defined by the protocol it's handling, an IPC communication etc. So if somebody creates a TCP socket he can do manipulations like reading data to socket and writing data to it by simple methods and the lower level protocol handling like TCP conversions and forwarding packets to lower level network protocols is done by the particular socket implementation in the kernel. The advantage is that user need not worry about handling protocol specific nitigrities and should just read and write data to socket like a normal buffer. Same is true in case of IPC, user just reads and writes data to socket and kernel handles all lower level details based on the type of socket created. Port together with IP is like providing an address to the socket, though its not necessary, but it helps in network communications. A: These are basic networking concepts so I will explain them in an easy yet a comprehensive way to understand in details. * *A socket is like a telephone (i.e. end to end device for communication) *IP is like your telephone number (i.e. address for your socket) *Port is like the person you want to talk to (i.e. the service you want to order from that address) *A socket can be a client or a server socket (i.e. in a company the telephone of the customer support is a server but a telephone in your home is mostly a client) So a socket in networking is a virtual communication device bound to a pair (ip , port) = (address , service). Note: * *A machine, a computer, a host, a mobile, or a PC can have multiple addresses , multiple open ports, and thus multiple sockets. Like in an office you can have multiple telephones with multiple telephone numbers and multiple people to talk to. *Existence of an open/active port necessitate that you must have a socket bound to it, because it is the socket that makes the port accessible. However, you may have unused ports for the time being. *Also note, in a server socket you can bind it to (a port, a specific address of a machine) or to (a port, all addresses of a machine) as in the telephone you may connect many telephone lines (telephone numbers) to a telephone or one specific telephone line to a telephone and still you can reach a person through all these telephone lines or through a specific telephone line. *You can not associate (bind) a socket with two ports as in the telephone usually you can not always have two people using the same telephone at the same time . *Advanced: on the same machine you cannot have two sockets with same type (client, or server) and same port and ip. However, if you are a client you can open two connections, with two sockets, to a server because the local port in each of these client's sockets is different) Hope it clears you doubts A: There seems to be a lot of answers equating socket with the connection between 2 PC's..which I think is absolutely incorrect. A socket has always been the endpoint on 1 PC, that may or may not be connected - surely we've all used listener or UDP sockets* at some point. The important part is that it's addressable and active. Sending a message to 1.1.1.1:1234 is not likely to work, as there is no socket defined for that endpoint. Sockets are protocol specific - so the implementation of uniqueness that both TCP/IP and UDP/IP uses* (ipaddress:port), is different than eg., IPX (Network, Node, and...ahem, socket - but a different socket than is meant by the general "socket" term. IPX socket numbers are equivalent to IP ports). But, they all offer a unique addressable endpoint. Since IP has become the dominant protocol, a port (in networking terms) has become synonomous with either a UDP or TCP port number - which is a portion of the socket address. * *UDP is connection-less - meaning no virtual circuit between the 2 endpoints is ever created. However, we still refer to UDP sockets as the endpoint. The API functions make it clear that both are just different type of sockets - SOCK_DGRAM is UDP (just sending a message) and SOCK_STREAM is TCP (creating a virtual circuit). *Technically, the IP header holds the IP Address, and the protocol on top of IP (UDP or TCP) holds the port number. This makes it possible to have other protocols (eg. ICMP that have no port numbers, but do have IP addressing information). A: Short brief answer. A port can be described as an internal address within a host that identifies a program or process. A socket can be described as a programming interface allowing a program to communicate with other programs or processes, on the internet, or locally. A: A port denotes a communication endpoint in the TCP and UDP transports for the IP network protocol. A socket is a software abstraction for a communication endpoint commonly used in implementations of these protocols (socket API). An alternative implementation is the XTI/TLI API. See also: Stevens, W. R. 1998, UNIX Network Programming: Networking APIs: Sockets and XTI; Volume 1, Prentice Hall. Stevens, W. R., 1994, TCP/IP Illustrated, Volume 1: The Protocols, Addison-Wesley. A: Socket is SW abstraction of networking endpoint, used as the interface to the application. In Java, C# it is represented by object, in Linux, Unix it is a file. Port is just a property of a socket you have specify if you want to establish a communication. To receieve packet from a socket you have to bind it to specific local port and NIC (with local IP address) or all NICs (INADDR_ANY is specified in the bind call). To send packet, you have to specify port and IP of the remote socket. A: They are terms from two different domains: 'port' is a concept from TCP/IP networking, 'socket' is an API (programming) thing. A 'socket' is made (in code) by taking a port and a hostname or network adapter and combining them into a data structure that you can use to send or receive data. A: A socket consists of three things: * *An IP address *A transport protocol *A port number A port is a number between 1 and 65535 inclusive that signifies a logical gate in a device. Every connection between a client and server requires a unique socket. For example: * *1030 is a port. *(10.1.1.2 , TCP , port 1030) is a socket. A: A socket is basically an endpoint for network communication, consisting of at least an IP-address and a port. In Java/C# a socket is a higher level implementation of one side of a two-way connection. Also, a (non-normative) definition in the Java Tutorial. A: Already theoretical answers have been given to this question. I would like to give a practical example to this question, which will clear your understanding about Socket and Port. I found it here This example will walk you thru the process of connecting to a website, such as Wiley. You would open your web browser (like Mozilla Firefox) and type www.wiley.com into the address bar. Your web browser uses a Domain Name System (DNS) server to look up the name www.wiley.com to identify its IP address is. For this example, the address is 192.0.2.100. Firefox makes a connection to the 192.0.2.100 address and to the port where the application layer web server is operating. Firefox knows what port to expect because it is a well-known port . The well-known port for a web server is TCP port 80. The destination socket that Firefox attempts to connect is written as socket:port, or in this example, 192.0.2.100:80. This is the server side of the connect, but the server needs to know where to send the web page you want to view in Mozilla Firefox, so you have a socket for the client side of the connection also. The client side connection is made up of your IP address, such as 192.168.1.25, and a randomly chosen dynamic port number. The socket associated with Firefox looks like 192.168.1.25:49175. Because web servers operate on TCP port 80, both of these sockets are TCP sockets, whereas if you were connecting to a server operating on a UDP port, both the server and client sockets would be UDP sockets. A: A single port can have one or more sockets connected with different external IP's like a multiple electrical outlet. TCP 192.168.100.2:9001 155.94.246.179:39255 ESTABLISHED 1312 TCP 192.168.100.2:9001 171.25.193.9:61832 ESTABLISHED 1312 TCP 192.168.100.2:9001 178.62.199.226:37912 ESTABLISHED 1312 TCP 192.168.100.2:9001 188.193.64.150:40900 ESTABLISHED 1312 TCP 192.168.100.2:9001 198.23.194.149:43970 ESTABLISHED 1312 TCP 192.168.100.2:9001 198.49.73.11:38842 ESTABLISHED 1312 A: After reading the excellent up-voted answers, I found that the following point needed emphasis for me, a newcomer to network programming: TCP-IP connections are bi-directional pathways connecting one address:port combination with another address:port combination. Therefore, whenever you open a connection from your local machine to a port on a remote server (say www.google.com:80), you are also associating a new port number on your machine with the connection, to allow the server to send things back to you, (e.g. 127.0.0.1:65234). It can be helpful to use netstat to look at your machine's connections: > netstat -nWp tcp (on OS X) Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 192.168.0.6.49871 17.172.232.57.5223 ESTABLISHED ... A: A socket is a communication endpoint. A socket is not directly related to the TCP/IP protocol family, it can be used with any protocol your system supports. The C socket API expects you to first get a blank socket object from the system that you can then either bind to a local socket address (to directly retrieve incoming traffic for connection-less protocols or to accept incoming connection requests for connection-oriented protocols) or that you can connect to a remote socket address (for either kind of protocol). You can even do both if you want to control both, the local socket address a socket is bound to and the remote socket address a socket is connected to. For connection-less protocols connecting a socket is even optional but if you don't do that, you'll have to also pass the destination address with every packet you want to send over the socket as how else would the socket know where to send this data to? Advantage is that you can use a single socket to send packets to different socket addresses. Once you have your socket configured and maybe even connected, consider it to be a bi-directional communication pipe. You can use it to pass data to some destination and some destination can use it to pass data back to you. What you write to a socket is send out and what has been received is available for reading. Ports on the other hand are something that only certain protocols of the TCP/IP protocol stack have. TCP and UDP packets have ports. A port is just a simple number. The combination of source port and destination port identify a communication channel between two hosts. E.g. you may have a server that shall be both, a simple HTTP server and a simple FTP server. If now a packet arrives for the address of that server, how would it know if that is a packet for the HTTP or the FTP server? Well, it will know so as the HTTP server will run on port 80 and the FTP server on port 21, so if the packet arrives with a destination port 80, it is for the HTTP server and not for the FTP server. Also the packet has a source port since without such a source port, a server could only have one connection to one IP address at a time. The source port makes it possible for a server to distinguish otherwise identical connections: they all have the same destination port, e.g. port 80, the same destination IP (the IP of the server), and the same source IP, as they all come from the same client, but as they have different source ports, the server can distinguish them from each other. And when the server sends back replies, it will do so to the port the request came from, that way the client can also distinguish different replies it receives from the same server. A: A socket is a special type of file handle which is used by a process to request network services from the operating system. A socket address is the triple: {protocol, local-address, local-process} where the local process is identified by a port number. In the TCP/IP suite, for example: {tcp, 193.44.234.3, 12345} A conversation is the communication link between two processes thus depicting an association between two. An association is the 5-tuple that completely specifies the two processes that comprise a connection: {protocol, local-address, local-process, foreign-address, foreign-process} In the TCP/IP suite, for example: {tcp, 193.44.234.3, 1500, 193.44.234.5, 21} could be a valid association. A half-association is either: {protocol, local-address, local-process} or {protocol, foreign-address, foreign-process} which specify each half of a connection. The half-association is also called a socket or a transport address. That is, a socket is an end point for communication that can be named and addressed in a network. The socket interface is one of several application programming interfaces (APIs) to the communication protocols. Designed to be a generic communication programming interface, it was first introduced by the 4.2BSD UNIX system. Although it has not been standardized, it has become a de facto industry standard. A: A socket address is an IP address & port number 123.132.213.231 # IP address :1234 # port number 123.132.213.231:1234 # socket address A connection occurs when 2 sockets are bound together. A: A socket represents a single connection between two network applications. These two applications nominally run on different computers, but sockets can also be used for interprocess communication on a single computer. Applications can create multiple sockets for communicating with each other. Sockets are bidirectional, meaning that either side of the connection is capable of both sending and receiving data. Therefore a socket can be created theoretically at any level of the OSI model from 2 upwards. Programmers often use sockets in network programming, albeit indirectly. Programming libraries like Winsock hide many of the low-level details of socket programming. Sockets have been in widespread use since the early 1980s. A port represents an endpoint or "channel" for network communications. Port numbers allow different applications on the same computer to utilize network resources without interfering with each other. Port numbers most commonly appear in network programming, particularly socket programming. Sometimes, though, port numbers are made visible to the casual user. For example, some Web sites a person visits on the Internet use a URL like the following: http://www.mairie-metz.fr:8080/ In this example, the number 8080 refers to the port number used by the Web browser to connect to the Web server. Normally, a Web site uses port number 80 and this number need not be included with the URL (although it can be). In IP networking, port numbers can theoretically range from 0 to 65535. Most popular network applications, though, use port numbers at the low end of the range (such as 80 for HTTP). Note: The term port also refers to several other aspects of network technology. A port can refer to a physical connection point for peripheral devices such as serial, parallel, and USB ports. The term port also refers to certain Ethernet connection points, such as those on a hub, switch, or router. ref http://compnetworking.about.com/od/basicnetworkingconcepts/l/bldef_port.htm ref http://compnetworking.about.com/od/itinformationtechnology/l/bldef_socket.htm A: With some analogy Although a lot technical stuff is already given above for sockets... I would like to add my answer, just in case , if somebody still could not feel the difference between ip, port and sockets Consider a server S, and say person X,Y,Z need a service (say chat service) from that server S then IP address tells --> who? is that chat server 'S' that X,Y,Z want to contact okay, you got "who is the server" but suppose that server 'S' is providing some other services to other people as well,say 'S' provides storage services to person A,B,C then port tells ---> which? service you (X,Y,Z) need i.e. chat service and not that storage service okay.., you make server to come to know that 'chat service' is what you want and not the storage but you are three and the server might want to identify all the three differently there comes the socket now socket tells--> which one? particular connection that is , say , socket 1 for person X socket 2 for person Y and socket 3 for person Z A: Summary A TCP socket is an endpoint instance defined by an IP address and a port in the context of either a particular TCP connection or the listening state. A port is a virtualisation identifier defining a service endpoint (as distinct from a service instance endpoint aka session identifier). A TCP socket is not a connection, it is the endpoint of a specific connection. There can be concurrent connections to a service endpoint, because a connection is identified by both its local and remote endpoints, allowing traffic to be routed to a specific service instance. There can only be one listener socket for a given address/port combination. Exposition This was an interesting question that forced me to re-examine a number of things I thought I knew inside out. You'd think a name like "socket" would be self-explanatory: it was obviously chosen to evoke imagery of the endpoint into which you plug a network cable, there being strong functional parallels. Nevertheless, in network parlance the word "socket" carries so much baggage that a careful re-examination is necessary. In the broadest possible sense, a port is a point of ingress or egress. Although not used in a networking context, the French word porte literally means door or gateway, further emphasising the fact that ports are transportation endpoints whether you ship data or big steel containers. For the purpose of this discussion I will limit consideration to the context of TCP-IP networks. The OSI model is all very well but has never been completely implemented, much less widely deployed in high-traffic high-stress conditions. The combination of an IP address and a port is strictly known as an endpoint and is sometimes called a socket. This usage originates with RFC793, the original TCP specification. A TCP connection is defined by two endpoints aka sockets. An endpoint (socket) is defined by the combination of a network address and a port identifier. Note that address/port does not completely identify a socket (more on this later). The purpose of ports is to differentiate multiple endpoints on a given network address. You could say that a port is a virtualised endpoint. This virtualisation makes multiple concurrent connections on a single network interface possible. It is the socket pair (the 4-tuple consisting of the client IP address, client port number, server IP address, and server port number) that specifies the two endpoints that uniquely identifies each TCP connection in an internet. (TCP-IP Illustrated Volume 1, W. Richard Stevens) In most C-derived languages, TCP connections are established and manipulated using methods on an instance of a Socket class. Although it is common to operate on a higher level of abstraction, typically an instance of a NetworkStream class, this generally exposes a reference to a socket object. To the coder this socket object appears to represent the connection because the connection is created and manipulated using methods of the socket object. In C#, to establish a TCP connection (to an existing listener) first you create a TcpClient. If you don't specify an endpoint to the TcpClient constructor it uses defaults - one way or another the local endpoint is defined. Then you invoke the Connect method on the instance you've created. This method requires a parameter describing the other endpoint. All this is a bit confusing and leads you to believe that a socket is a connection, which is bollocks. I was labouring under this misapprehension until Richard Dorman asked the question. Having done a lot of reading and thinking, I'm now convinced that it would make a lot more sense to have a class TcpConnection with a constructor that takes two arguments, LocalEndpoint and RemoteEndpoint. You could probably support a single argument RemoteEndpoint when defaults are acceptable for the local endpoint. This is ambiguous on multihomed computers, but the ambiguity can be resolved using the routing table by selecting the interface with the shortest route to the remote endpoint. Clarity would be enhanced in other respects, too. A socket is not identified by the combination of IP address and port: [...]TCP demultiplexes incoming segments using all four values that comprise the local and foreign addresses: destination IP address, destination port number, source IP address, and source port number. TCP cannot determine which process gets an incoming segment by looking at the destination port only. Also, the only one of the [various] endpoints at [a given port number] that will receive incoming connection requests is the one in the listen state. (p255, TCP-IP Illustrated Volume 1, W. Richard Stevens) As you can see, it is not just possible but quite likely for a network service to have numerous sockets with the same address/port, but only one listener socket on a particular address/port combination. Typical library implementations present a socket class, an instance of which is used to create and manage a connection. This is extremely unfortunate, since it causes confusion and has lead to widespread conflation of the two concepts. Hagrawal doesn't believe me (see comments) so here's a real sample. I connected a web browser to http://dilbert.com and then ran netstat -an -p tcp. The last six lines of the output contain two examples of the fact that address and port are not enough to uniquely identify a socket. There are two distinct connections between 192.168.1.3 (my workstation) and 54.252.94.236:80 (the remote HTTP server) TCP 192.168.1.3:63240 54.252.94.236:80 SYN_SENT TCP 192.168.1.3:63241 54.252.94.236:80 SYN_SENT TCP 192.168.1.3:63242 207.38.110.62:80 SYN_SENT TCP 192.168.1.3:63243 207.38.110.62:80 SYN_SENT TCP 192.168.1.3:64161 65.54.225.168:443 ESTABLISHED Since a socket is the endpoint of a connection, there are two sockets with the address/port combination 207.38.110.62:80 and two more with the address/port combination 54.252.94.236:80. I think Hagrawal's misunderstanding arises from my very careful use of the word "identifies". I mean "completely, unambiguously and uniquely identifies". In the above sample there are two endpoints with the address/port combination 54.252.94.236:80. If all you have is address and port, you don't have enough information to tell these sockets apart. It's not enough information to identify a socket. Addendum Paragraph two of section 2.7 of RFC793 says A connection is fully specified by the pair of sockets at the ends. A local socket may participate in many connections to different foreign sockets. This definition of socket is not helpful from a programming perspective because it is not the same as a socket object, which is the endpoint of a particular connection. To a programmer, and most of this question's audience are programmers, this is a vital functional difference. @plugwash makes a salient observation. The fundamental problem is that the TCP RFC definition of socket is in conflict with the defintion of socket used by all major operating systems and libraries. By definition the RFC is correct. When a library misuses terminology, this does not supersede the RFC. Instead, it imposes a burden of responsibility on users of that library to understand both interpretations and to be careful with words and context. Where RFCs do not agree, the most recent and most directly applicable RFC takes precedence. References * *TCP-IP Illustrated Volume 1 The Protocols, W. Richard Stevens, 1994 Addison Wesley *RFC793, Information Sciences Institute, University of Southern California for DARPA *RFC147, The Definition of a Socket, Joel M. Winett, Lincoln Laboratory A: An application consists of pair of processes which communicate over the network (client-server pair). These processes send and receive messages, into and from the network through a software interface called socket. Considering the analogy presented in the book "Computer Networking: Top Down Approach". There is a house that wants to communicate with other house. Here, house is analogous to a process, and door to a socket. Sending process assumes that there is a infrastructure on the other side of the door that will transport the data to the destination. Once the message is arrived on the other side, it passes through receiver's door (socket) into the house (process). This illustration from the same book can help you: Sockets are part of transport layer, which provides logical communication to applications. This means that from application's point of view both hosts are directly connected to each other, even though there are numerous routers and/or switches between them. Thus a socket is not a connection itself, it's the end point of the connection. Transport layer protocols are implemented only on hosts, and not on intermediate routers. Ports provide means of internal addressing to a machine. The primary purpose it to allow multiple processes to send and receive data over the network without interfering with other processes (their data). All sockets are provided with a port number. When a segment arrives to a host, the transport layer examines the destination port number of the segment. It then forwards the segment to the corresponding socket. This job of delivering the data in a transport layer segment to the correct socket is called de-multiplexing. The segment's data is then forwarded to the process attached to the socket. A: I know that there are lot of explanations. But, there is one more easy way to understand with practical example. We all can connect to HTTP port 80, but does it mean only one user can connect to that port at a time?. The answer is obviously 'no'. Multiple users for multiple purposes can access HTTP port 80 but they still get proper response they are waiting for, from the server, can't they?. Now think about it for a minute, how?. Yes you are correct, its IP address that uniquely identifies different users who contacts for different purposes. If you would have read the previous answers before reaching here, you would know that IP address is a part of information that socket consists. Think about it, is it possible to have a communication without sockets?. The answer is 'Yes' but you cannot run more than one application in a port but we know that we are not a 'Dump' switch that runs on just hardware. A: Uff.. too many people linking socket concept to a two-endpoints communication, mostly on TCP/IP protocol. But: * *NO - Socket is not related to a two-endpoint communication. It's the local endpoint, which can or cannot be connected on the other side (Think about a server socket listening for incoming connection) *NO - Socket it's not strictly related to TCP/IP. It is defined with a protcol, which can be TCP/IP, but can be anything else. For example you can have socket that communicates over files. You can also implement a new protocol yourself to have a communication over USB lamp which sends data by flashing: that would still be a socket from the application point of view. Regarding the port concept it's correct what you read on other answers. Port is mostly intended to be the number value (2 bytes, 0-65535) in TCP or UDP packet. Just let me stress that TCP or UPD not necessarily are used on top of IP. So: * *NO - it's not correct saying that port is part of TCP/IP or UDP/IP. It's part of TCP or UDP, or any other protocol which define and use it. IP has no knowledge of what a port is. A: A port number is a way to identify a specific process to which an internet or other network message is to be forwarded when it arrives at a server. Any program when in the state of execution is called a process and the port number is used to identify a specific process within a certain system. Imagine you send a letter one of the house members, address of this house is IP address and the person that you want the letter to be delivered is a port number. * *Socket is one endpoint of a two way communication link between two processes on the network. A socket consists of a port number and an IP. TCP uses this information to identify the process on a specific IP address to which that data needs to be delivered. If you set up a socket connection between 2 in local host, their ip address will be same because they are on the same machine, or as I mentioned above example they are in the same house. But their port number will be different. Because they are two different people in the same house, server and client. A: A socket allows to the communication between two applications in a single machine or two machine. actually it is like door. if the door opens there can be a connection between the process or application that are inside the door and outside the door. There are 4 types of sockets: * *stream sockets *datagram sockets *raw sockets *sequential packet sockets. Sockets are mostly used in client-server applications. The port identifies different end points on a network address. It contains a numerical value. As overall a socket is a combination of a port and a network address. A: A connection socket (fd) is presented for local address + local port + peer address + peer port. Process recv/send data via socket abstract. A listening socket (fd) is presented for local address + local listening port. Process can accept new connection via socket. A: A port is an entity that is used by networking protocols to attain access to connected hosts. Ports could be application-specific or related to a certain communication medium. Different protocols use different ports to access the hosts, like HTTP uses port 80 or FTP uses port 23. You can assign user-defined port numbers in your application, but they should be above 1023. Ports open up the connection to the required host while sockets are an endpoint in an inter-network or an inter-process communication. Sockets are assigned by APIs(Application Programming Interface) by the system. A more subtle difference can be made saying that, when a system is rebooted ports will be present while the sockets will be destroyed. A: As simply as possible, there's no physical difference between a socket and a port, the way there is between, e.g., PATA and SATA. They're just bits of software reading and writing a NIC. A port is essentially a public socket, some of which are well-known/well-accepted, the usual example being 80, dedicated to HTTP. Anyone who wants to exchange traffic using a certain protocol, HTTP in this instance, canonically goes to port 80. Of course, 80 is not physically dedicated to HTTP (it's not physically anything, it's just a number, a logical value), and could be used on some particular machine for some other protocol ad libitum, as long as those attempting to connect know which protocol (which could be quite private) to use. A socket is essentially a private port, established for particular purposes known to the connecting parties but not necessarily known to anyone else. The underlying transport layer is usually TCP or UDP, but it doesn't have to be. The essential characteristic is that both ends know what's going on, whatever that might be. The key here is that when a connection request is received on some port, the reply handshake includes information about the socket created to service the particular requester. Subsequent communication takes place through that (private) socket connection, not the public port connection on which the service continues to listen for connection requests. A: Definitions of Port Vinton G. Cerf and Robert E. Kahn (May 1974). A Protocol for Packet Network Intercommunication. IEEE Transactions on Communications, Volume 22, Number 5. IEEE. A port is a unit of a "pair of [entities that] will exchange one or more messages over a period of time.” “… We could view the sequence of messages produced by one port as if it were embedded in an infinitely long stream of bytes... We emphasise that the sequence number associated with a given packet is unique only to the pair of ports that are communicating... Arriving packets are examined to determine for which port they are intended... Provision should be made for a destination process to specify that it is willing to LISTEN to a specific port or 'any' port." A "port is simply a designator of one... duplex... message stream... [among one or more] message streams... associated with a process." Information Sciences Institute: University of Southern California (September 1981). RFC 793: Transmission Control Protocol: DARPA Internet Program Protocol Specification. A port is one entity of one or more entities through which a process communicates via one or more communication streams with one or more other processes. "Since a process may need to distinguish among several communication streams between itself and another process (or processes), we imagine that each process may have a number of ports through which it communicates with the ports of other processes.” “The intent is that connection be allowed only between ports operating with exactly the same security and compartment values and at the higher of the precedence level requested by the two ports.” “Note this check is placed following the sequence check to prevent a segment from an old connection between these ports with a different security or precedence from causing an abort of the current connection.” “A port is an address that specifies which logical input or output channel of a process is associated with [a stream of] data.” "To allow for many processes within a single Host to use TCP communication facilities simultaneously, the TCP provides a set of addresses or ports within each host.” “The portion of a socket that specifies which logical input or output channel of a process is associated with the data.”   Definitions of Socket Oracle (2020). Class Socket. Java Platform, Standard Edition 7 API Specification. "A socket is an endpoint for communication between two machines." Information Sciences Institute: University of Southern California (September 1981). RFC 793: Transmission Control Protocol: DARPA Internet Program Protocol Specification. A socket is a string consisting of an Internet address [i.e., the first eight-bit number (e.g., 123) of a network address (e.g., 123.45.78.0), a period, the second eight-bit number (e.g., 45) of the network address, a period, the third eight-bit number (e.g., 78) of the network address, a period, and a host address (e.g., 90)], a colon, and a TCP port (e.g., 1234). A socket is a unit of “A pair of [entities that] uniquely identify [a] connection[, and that] may be simultaneously used in multiple connections.” "To allow for many processes within a single Host to use TCP communication facilities simultaneously, the TCP provides a set of addresses or ports within each host. Concatenated with the network and host addresses from the internet communication layer, this forms a socket. A pair of sockets uniquely identifies each connection. That is, a socket may be simultaneously used in multiple connections." “To provide for unique addresses within each TCP, we concatenate an internet address identifying the TCP with a port identifier to create a socket which will be unique throughout all networks connected together.” “The reliability and flow control mechanisms described above require that TCPs initialize and maintain certain status information for each data stream. The combination of this information, including sockets, sequence numbers, and window sizes, is called a connection. Each connection is uniquely specified by a pair of sockets identifying its two sides.”
{ "language": "en", "url": "https://stackoverflow.com/questions/152457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1105" }
Q: Running a J6SE app on an NT box I need to run a Java application, which we are trying to port to Java 6, on an NT box. I manage to run java 5 on it (although not officially supported), but when I try to run java 6 I get the following error: Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Program Files\Java\jre1.6.0_05\bin\awt.dll: The specified procedure could not be found at java.lang.ClassLoader$NativeLibrary.load(Native Method) at java.lang.ClassLoader.loadLibrary0(Unknown Source) at java.lang.ClassLoader.loadLibrary(Unknown Source) at java.lang.Runtime.loadLibrary0(Unknown Source) at java.lang.System.loadLibrary(Unknown Source) at sun.security.action.LoadLibraryAction.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at sun.awt.NativeLibLoader.loadLibraries(Unknown Source) at sun.awt.DebugHelper.<clinit>(Unknown Source) at java.awt.EventQueue.<clinit>(Unknown Source) at javax.swing.SwingUtilities.invokeLater(Unknown Source) at ui.sequencer.test.WindowTest.main(WindowTest.java:136) Anybody has any idea how to solve this? This persists even when I move the java executables to another directory with no spaces in its name. p.s. I know, I should upgrade, but it's not up to me or my company - this is a very very bug huge gigantic company we work with, and they intend to keep NT for another 5 years. A: OK, Thanks for all the viewers and to @Roel Spiker and @Partyzant for their answers. It can't be done. Not unless you install windows2000 on the NT box. This is because awt.dll fr J6SE uses new methods in User32.dll, which is part of the windows OS (linked to kernel.dll et al). Use the dll dependency walker and see for yourself. Another possible solution is to alter OpenJDK slightly to use other methods available in windows NT. A: Java SE 6 requires at least Windows 2000. A: I you are not using a GUI, for instance AWT, Swing or SWT, you could try starting you application in headless mode. See http://java.sun.com/developer/technicalArticles/J2SE/Desktop/headless/ for more information. To start java in headless mode, use java -Djava.awt.headless=true It would take care of the UnsatisfiedLinkError. I don't know if that's the only obstacle though.
{ "language": "en", "url": "https://stackoverflow.com/questions/152462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the best way to change a user-password remotely in Unix? What is the best way to change a user-password remotely in Unix? This must be performed by the user, in a Web-app or Windows-App, without using SSH or any direct connection between the user and the server (direct command line not allowed). Thanks Webmin seemed to be a good application to do that, but I found it extremely hard to configure it right. My Unix users are unable to login to Webmin or Usermin. Do you know any other alternatives to Webmin and Usermin? Thanks A: Use Webmin (more specifically the UserMin module). Webmin provides a mini webserver, so you just need to install and configure it slightly. You'll get a lot more than just password-changing, and you can remove functionality you don't want the user to have. A: @Rich Bradshaw Just make sure you don't introduce security issues. The solution should use https encryption (the password should be never sent in clear text). It should be protected against shell injection attacks (strip any newlines from input, escape it properly etc). More details depend on choosen implementation. A: I've done this in the past to change passwords on several servers at once by using a script written in Expect. It's perfect for the job but you will need the servers to be listening via SSH. Once written, the script will execute on your local workstation and will connect to the remote host, do the interaction you've scripted, and then you should be gold. All the while, using the encryption you're already trusting if you're running SSH. Just don't save the passwords in your script: you should be able to prompt yourself for them (even taking them by command line argument is generally considered poor practice.) Expect is a great language too: lots of fun! A: You could write a server side script that ran passwd, you could do that in any language that allows shell commands to be run.
{ "language": "en", "url": "https://stackoverflow.com/questions/152468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.NET user login best practices I want to make a login system using ASP.NET (MVC). On the internet, I found some bad examples that involved SQL in Click events. Other information pointed to the ASP.NET built-in membership provider. However, I want to roll my own. I don't want to use the built-in membership provider, as it only seems to work on MS SQL, and I don't like the idea of having a few foreign tables in my database. I could probably think of something, but I need a few pointers in the right direction. It does not have to be high-security, but just regular common-sense security. And I have a few direct questions: * *A lot of systems seem to have the Session ID stored in a user table. I guess this is to tie a session to a user to prevent hijacking. Do check this every time a user enters a page? And what do I do if the session expires? *Hashing, salting, what does it do? I know of MD5 hashing and I have used it before. But not salting. *Best practices for cookies? A: I dont know about best practices but I can tell you what I do. Its not hitech security but it does the job. I use forms authentication. I receive the password secured with ssl via a textbox on the login page. I take that password and hash it. (Hashing is like one way encryption, you can get hash code that cant be reversed back to the password). I take that hash and compare it to the users hash in the database. If the hash's match i use asp.nets built in authentication handling, which handles cookies for me. The FormsAuthentication class has methods available to do this fo you, such as SetAuthCookie and RedirectFromLogin. they will set the cookie and mark them as authenticated. The cookie asp.net uses is encrypted. I cant speak for its security level though, but its in fairly common use. In my class i do the password check and use formsauth to handle the rest: if(SecurityHelper.LoginUser(txtUsername.Text, txtPassword.Text)) { FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true); } A: You can implement your own membership provider using the ASP.NET infrastructure, see MSDN docs for MemberShipProvider class. A: The built in provider works well. It does actually work with MySQL, although I found it not to be as straight forward as the MS SQL version. If you can use then do, it'll save you hours of work. If you need to use another data store then I concur with axel_c, if I was going to roll my own then I'd write a membership provider as per MS specification. It will make the code more maintainable for any developers following you. A: Salting is the practice of adding a unqiue string of characters to whatever is being hashed. Suppose mySalt = abc123 and my password is passwd. In PHP, I would use hashResult = md5(mySalt + password). Suppose the string is intercepted. You try to match the string, but you end up matching gibberish because the password was salted before encrypted. Just remember that whatever you use for salt must be continuous throughout the application. If you salt the password before storage, you must compare the hashed, salted password to the DB. A: You can use the built in SQL membership provider - and you could set up a dedicated "user access" database if you don't want the .Net membership tables within your database - just specify that in the connection string. THe advantage with the provider model is at the application level, the code is independent of what particular authentication store you have used. There are a good series of tutirials on the asp.net site: link text A: I would avoid the whole issue and use openid. There is a library available that you can use directly. Here is a link to a blog post about putting this in place A: A disadvantage of the Membership Provider by microsoft is that you can't use it in a domain driven approach. If you want to, you can create your own user object with your own password hash and still use the authentication cookies provided by Microsoft. Using these authentication cookies means that you don't have to manage the session IDs yourself. public void SignIn(User user) { FormsAuthentication.SignOut(); var ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now.AddMinutes(30), expires, alse, null); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = ticket.Expiration }; httpContextProvider.GetCurrentHttpContext().Response.Cookies.Add(authCookie); } public void SignOut() { FormsAuthentication.SignOut(); } I use my own user object and tables. I store my passwords hashed in the usertable with a unique salt per user. This is secure, easy to implement and it will fit in your design. Your database table won't be polluted by Microsofts membership provider crap.
{ "language": "en", "url": "https://stackoverflow.com/questions/152469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Is there a way to print all methods of an object? Is there a way to print all methods of an object in JavaScript? A: Here is an ES6 sample. // Get the Object's methods names: function getMethodsNames(obj = this) { return Object.keys(obj) .filter((key) => typeof obj[key] === 'function'); } // Get the Object's methods (functions): function getMethods(obj = this) { return Object.keys(obj) .filter((key) => typeof obj[key] === 'function') .map((key) => obj[key]); } obj = this is an ES6 default parameter, you can pass in an Object or it will default to this. Object.keys returns an Array of the Object's own enumerable properties. Over the window Object it will return [..., 'localStorage', ...'location']. (param) => ... is an ES6 arrow function, it's a shorthand for function(param) { return ... } with an implicit return. Array.filter creates a new array with all elements that pass the test (typeof obj[key] === 'function'). Array.map creates a new array with the results of calling a provided function on every element in this array (return obj[key]). A: Take a gander at this code:- function writeLn(s) { //your code to write a line to stdout WScript.Echo(s) } function Base() {} Base.prototype.methodA = function() {} Base.prototype.attribA = "hello" var derived = new Base() derived.methodB = function() {} derived.attribB = "world"; function getMethods(obj) { var retVal = {} for (var candidate in obj) { if (typeof(obj[candidate]) == "function") retVal[candidate] = {func: obj[candidate], inherited: !obj.hasOwnProperty(candidate)} } return retVal } var result = getMethods(derived) for (var name in result) { writeLn(name + " is " + (result[name].inherited ? "" : "not") + " inherited") } The getMethod function returns the set of methods along with whether the method is one that has been inherited from a prototype. Note that if you intend to use this on objects that are supplied from the context such as browser/DOM object then it won't work IE. A: If you just want to look what is inside an object, you can print all object's keys. Some of them can be variables, some - methods. The method is not very accurate, however it's really quick: console.log(Object.keys(obj)); A: Sure: function getMethods(obj) { var result = []; for (var id in obj) { try { if (typeof(obj[id]) == "function") { result.push(id + ": " + obj[id].toString()); } } catch (err) { result.push(id + ": inaccessible"); } } return result; } Using it: alert(getMethods(document).join("\n")); A: From here: Example 1: This example writes out all the properties of the "navigator" object, plus their values: for (var myprop in navigator){ document.write(myprop+": "+navigator[myprop]+"<br>") } Just replace 'navigator' with whatever object you are interested in and you should be good to go. As mentioned by Anthony in the comments section - This returns all attributes not just methods as the question asked for. Oops! That'll teach me to try and answer a question in a language I don't know. Still, I think the code is useful - just not what was required. A: Since methods in JavaScript are just properties that are functions, the for..in loop will enumerate them with an exception - it won't enumerate built-in methods. As far as I know, there is no way to enumerate built-in methods. And you can't declare your own methods or properties on an object that aren't enumerable this way.
{ "language": "en", "url": "https://stackoverflow.com/questions/152483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "79" }
Q: MSBuild: How to obtain number of warnings raised? There is a MSBuild script, that includes number if Delphi and C# projects, unit tests etc. The problem is: how to mark build failed if warnings were raised (for testing purposes, not for release builds)? Using LogError instead of LogWarning in custom tasks seems to be not a good option, because the build should test as much as it's able (until real error) to report as much warnings as possible in a time (build project is using in CruiseControl.NET). May be, the solution is to create my own logger that would store warnings flag inside, but I cannot find if there is a way to read this flag in the end of build? P.S. There is no problem to fail the build immediately after receiving a warning (Delphi compiler output is processed by custom task, and /warnaserror could be used for C#), but the desired behavior is "build everything; collect all warnings; fail the build" to report about all warnings, not only about the first one. P.P.S. As far as I really need not number of warnings, but just flag of their presence, I decided to simplify signaling mechanism, and use trivial Mutex instead of shared memory. Code is below: using System; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System.Threading; namespace Intrahealth.Build.WarningLogger { public sealed class WarningLoggerCheck : Task { public override bool Execute() { Log.LogMessage("WarningLoggerCheck:" + mutexName + "..."); result = false; Mutex m = null; try { m = Mutex.OpenExisting(mutexName); } catch (WaitHandleCannotBeOpenedException) { result = true; } catch (Exception) { } if (result) Log.LogMessage("WarningLoggerCheck PASSED"); else Log.LogError("Build log contains warnings. Build is FAILED"); return result; } private bool result = true; [Output] public bool Result { get { return result; } } private string mutexName = "WarningLoggerMutex"; public string MutexName { get { return mutexName; } set { mutexName = value ?? "WarningLoggerMutex"; } } } public class WarningLogger : Logger { internal static int warningsCount = 0; private string mutexName = String.Empty; private Mutex mutex = null; public override void Initialize(IEventSource eventSource) { eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised); } private void SetMutex() { if (mutexName == String.Empty) { mutexName = "WarningLoggerMutex"; if (this.Parameters != null && this.Parameters != String.Empty) { mutexName = this.Parameters; } } mutex = new Mutex(false, mutexName); } void eventSource_WarningRaised(object sender, BuildWarningEventArgs e) { if (e.Message != null && e.Message.Contains("MSB3146")) return; if (e.Code != null && e.Code.Equals("MSB3146")) return; if (warningsCount == 0) SetMutex(); warningsCount++; } } } A: AFAIK MSBuild has no built-in support to retrieve the warning count at a given point of the build script. You can however follow these steps to achieve this goal: * *Create a custom logger that listens for the warning event and counts the number of warnings *Create a custom task that exposes an [Output] WarningCount property *The custom task gets somehow the value of the warning count from the custom logger The most difficult step is step 3. For this there are several options and you can freely search them under IPC - Inter Process Comunication. Follows a working example of how you can achieve this. Each item is a different Class Library. SharedMemory http://weblogs.asp.net/rosherove/archive/2003/05/01/6295.aspx I've created a wrapper for named shared memory that was part of a larger project. It basically allows serialized types and object graphs to be stored in and retrieved from shared memory (including as you'd expect cross process). Whether the larger project ever gets completed is another matter ;-). SampleLogger Implements the custom logger that keeps track of the warning count. namespace SampleLogger { using System; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; using DM.SharedMemory; public class MySimpleLogger : Logger { private Segment s; private int warningCount; public override void Initialize(IEventSource eventSource) { eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised); this.s = new Segment("MSBuildMetadata", SharedMemoryCreationFlag.Create, 65535); this.s.SetData(this.warningCount.ToString()); } void eventSource_WarningRaised(object sender, BuildWarningEventArgs e) { this.warningCount++; this.s.SetData(this.warningCount.ToString()); } public override void Shutdown() { this.s.Dispose(); base.Shutdown(); } } } SampleTasks Implements the custom task that reads the number of warnings raised in the MSbuild project. The custom task reads from the shared memory written by the custom logger implemented in class library SampleLogger. namespace SampleTasks { using System; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; using DM.SharedMemory; public class BuildMetadata : Task { public int warningCount; [Output] public int WarningCount { get { Segment s = new Segment("MSBuildMetadata", SharedMemoryCreationFlag.Attach, 0); int warningCount = Int32.Parse(s.GetData() as string); return warningCount; } } public override bool Execute() { return true; } } } Going for a spin. <?xml version="1.0" encoding="UTF-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Main"> <UsingTask TaskName="BuildMetadata" AssemblyFile="F:\temp\SampleLogger\bin\debug\SampleTasks.dll" /> <Target Name="Main"> <Warning Text="Sample warning #1" /> <Warning Text="Sample warning #2" /> <BuildMetadata> <Output TaskParameter="WarningCount" PropertyName="WarningCount" /> </BuildMetadata> <Error Text="A total of $(WarningCount) warning(s) were raised." Condition="$(WarningCount) > 0" /> </Target> </Project> If you run the following command: c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MSBuild test.xml /logger:SampleLogger.dll This will be the output: Microsoft (R) Build Engine Version 2.0.50727.3053 [Microsoft .NET Framework, Version 2.0.50727.3053] Copyright (C) Microsoft Corporation 2005. All rights reserved. Build started 30-09-2008 13:04:39. __________________________________________________ Project "F:\temp\SampleLogger\bin\debug\test.xml" (default targets): Target Main: F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #1 F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #2 F:\temp\SampleLogger\bin\debug\test.xml(15,3): error : A total of 2 warning(s) were raised. Done building target "Main" in project "test.xml" -- FAILED. Done building project "test.xml" -- FAILED. Build FAILED. F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #1 F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #2 F:\temp\SampleLogger\bin\debug\test.xml(15,3): error : A total of 2 warning(s) were raised. 2 Warning(s) 1 Error(s) Time Elapsed 00:00:00.01 A: The C# compiler (csc.exe) has a /warnaserror switch will will treat warnings as errors and fail the build. This is also available as a setting in the .csproj file. I assume Delphi has a similar ability. A: msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release >> %MrB-BUILDLOG% findstr /r /c:"[1-9][0-9]* Error(s)" >> %MrB-BUILDLOG% if not errorlevel 1 ( echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-BUILDLOG% ) else ( findstr /r /c:"[1-9][0-9]* Warning(s)" >> %MrB-BUILDLOG% if not errorlevel 1 ( echo ERROR: sending notification email for build warnings in '%~nx1'. >> %MrB-BUILDLOG% ) else ( echo Successful build of '%~nx1'. >> %MrB-BUILDLOG% ) )
{ "language": "en", "url": "https://stackoverflow.com/questions/152487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What does this do? tasklist /m "mscor*" Saw this question here : What Great .NET Developers Ought To Know (More .NET Interview Questions) A: This is a very useful command line tool in windows that shows you a list of all running processes. Passing in a command line parameter of /m "mscor*" lists out all of the processes running on your machine running that are using assemblies that begin with the name "mscor". The "*" is a wildcard character. A: It would seem to list all processes using modules like mscoree.dll, mscorwks.dll, etc. This would be .NET processes and possibly processes hosting .NET plug-ins. A: It will show processes that have loaded modules (usaully .DLL files) hosting the .NET runtime. The same technique can be used to search for other DLLs that have been loaded. On a related note, Process Explorer is a Microsoft task manager replacement that will show .NET processes highlighted. I cannot recommend it enough. It is well worth investigating along with the rest of the Sysinternals Suite.
{ "language": "en", "url": "https://stackoverflow.com/questions/152506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How do I rename all folders and files to lowercase on Linux? I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter). Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would be a shell script, since a shell should be available on any Linux box. There were some valid arguments about details of the file renaming. * *I think files with the same lowercase names should be overwritten; it's the user's problem. When checked out on a case-ignoring file system, it would overwrite the first one with the latter, too. *I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code). *The script would be needed to run a build on a Linux system, so I think changes to CVS or Subversion version control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate. A: Here's my suboptimal solution, using a Bash shell script: #!/bin/bash # First, rename all folders for f in `find . -depth ! -name CVS -type d`; do g=`dirname "$f"`/`basename "$f" | tr '[A-Z]' '[a-z]'` if [ "xxx$f" != "xxx$g" ]; then echo "Renaming folder $f" mv -f "$f" "$g" fi done # Now, rename all files for f in `find . ! -type d`; do g=`dirname "$f"`/`basename "$f" | tr '[A-Z]' '[a-z]'` if [ "xxx$f" != "xxx$g" ]; then echo "Renaming file $f" mv -f "$f" "$g" fi done Folders are all renamed correctly, and mv isn't asking questions when permissions don't match, and CVS folders are not renamed (CVS control files inside that folder are still renamed, unfortunately). Since "find -depth" and "find | sort -r" both return the folder list in a usable order for renaming, I preferred using "-depth" for searching folders. A: One-liner: for F in K*; do NEWNAME=$(echo "$F" | tr '[:upper:]' '[:lower:]'); mv "$F" "$NEWNAME"; done Or even: for F in K*; do mv "$F" "${F,,}"; done Note that this will convert only files/directories starting with letter K, so adjust accordingly. A: Using Larry Wall's filename fixer: $op = shift or die $help; chomp(@ARGV = <STDIN>) unless @ARGV; for (@ARGV) { $was = $_; eval $op; die $@ if $@; rename($was,$_) unless $was eq $_; } It's as simple as find | fix 'tr/A-Z/a-z/' (where fix is of course the script above) A: The original question asked for ignoring SVN and CVS directories, which can be done by adding -prune to the find command. E.g to ignore CVS: find . -name CVS -prune -o -exec mv '{}' `echo {} | tr '[A-Z]' '[a-z]'` \; -print [edit] I tried this out, and embedding the lower-case translation inside the find didn't work for reasons I don't actually understand. So, amend this to: $> cat > tolower #!/bin/bash mv $1 `echo $1 | tr '[:upper:]' '[:lower:]'` ^D $> chmod u+x tolower $> find . -name CVS -prune -o -exec tolower '{}' \; Ian A: Not portable, Zsh only, but pretty concise. First, make sure zmv is loaded. autoload -U zmv Also, make sure extendedglob is on: setopt extendedglob Then use: zmv '(**/)(*)~CVS~**/CVS' '${1}${(L)2}' To recursively lowercase files and directories where the name is not CVS. A: for f in `find -depth`; do mv ${f} ${f,,} ; done find -depth prints each file and directory, with a directory's contents printed before the directory itself. ${f,,} lowercases the file name. A: This works nicely on macOS too: ruby -e "Dir['*'].each { |p| File.rename(p, p.downcase) }" A: Smaller still I quite like: rename 'y/A-Z/a-z/' * On case insensitive filesystems such as OS X's HFS+, you will want to add the -f flag: rename -f 'y/A-Z/a-z/' * A: This is a small shell script that does what you requested: root_directory="${1?-please specify parent directory}" do_it () { awk '{ lc= tolower($0); if (lc != $0) print "mv \"" $0 "\" \"" lc "\"" }' | sh } # first the folders find "$root_directory" -depth -type d | do_it find "$root_directory" ! -type d | do_it Note the -depth action in the first find. A: Use typeset: typeset -l new # Always lowercase find $topPoint | # Not using xargs to make this more readable while read old do new="$old" # $new is a lowercase version of $old mv "$old" "$new" # Quotes for those annoying embedded spaces done On Windows, emulations, like Git Bash, may fail because Windows isn't case-sensitive under the hood. For those, add a step that mv's the file to another name first, like "$old.tmp", and then to $new. A: One can simply use the following which is less complicated: rename 'y/A-Z/a-z/' * A: This works on CentOS/Red Hat Linux or other distributions without the rename Perl script: for i in $( ls | grep [A-Z] ); do mv -i "$i" "`echo $i | tr 'A-Z' 'a-z'`"; done Source: Rename all file names from uppercase to lowercase characters (In some distributions the default rename command comes from util-linux, and that is a different, incompatible tool.) A: In OS X, mv -f shows "same file" error, so I rename twice: for i in `find . -name "*" -type f |grep -e "[A-Z]"`; do j=`echo $i | tr '[A-Z]' '[a-z]' | sed s/\-1$//`; mv $i $i-1; mv $i-1 $j; done A: With MacOS, Install the rename package, brew install rename Use, find . -iname "*.py" -type f | xargs -I% rename -c -f "%" This command find all the files with a *.py extension and converts the filenames to lower case. `f` - forces a rename For example, $ find . -iname "*.py" -type f ./sample/Sample_File.py ./sample_file.py $ find . -iname "*.py" -type f | xargs -I% rename -c -f "%" $ find . -iname "*.py" -type f ./sample/sample_file.py ./sample_file.py A: Lengthy But "Works With No Surprises & No Installations" This script handles filenames with spaces, quotes, other unusual characters and Unicode, works on case insensitive filesystems and most Unix-y environments that have bash and awk installed (i.e. almost all). It also reports collisions if any (leaving the filename in uppercase) and of course renames both files & directories and works recursively. Finally it's highly adaptable: you can tweak the find command to target the files/dirs you wish and you can tweak awk to do other name manipulations. Note that by "handles Unicode" I mean that it will indeed convert their case (not ignore them like answers that use tr). # adapt the following command _IF_ you want to deal with specific files/dirs find . -depth -mindepth 1 -exec bash -c ' for file do # adapt the awk command if you wish to rename to something other than lowercase newname=$(dirname "$file")/$(basename "$file" | awk "{print tolower(\$0)}") if [ "$file" != "$newname" ] ; then # the extra step with the temp filename is for case-insensitive filesystems if [ ! -e "$newname" ] && [ ! -e "$newname.lcrnm.tmp" ] ; then mv -T "$file" "$newname.lcrnm.tmp" && mv -T "$newname.lcrnm.tmp" "$newname" else echo "ERROR: Name already exists: $newname" fi fi done ' sh {} + References My script is based on these excellent answers: https://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names How to convert a string to lower case in Bash? A: A concise version using the "rename" command: find my_root_dir -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \; This avoids problems with directories being renamed before files and trying to move files into non-existing directories (e.g. "A/A" into "a/a"). Or, a more verbose version without using "rename". for SRC in `find my_root_dir -depth` do DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'` if [ "${SRC}" != "${DST}" ] then [ ! -e "${DST}" ] && mv -T "${SRC}" "${DST}" || echo "${SRC} was not renamed" fi done P.S. The latter allows more flexibility with the move command (for example, "svn mv"). A: The simplest approach I found on Mac OS X was to use the rename package from http://plasmasturm.org/code/rename/: brew install rename rename --force --lower-case --nows * --force Rename even when a file with the destination name already exists. --lower-case Convert file names to all lower case. --nows Replace all sequences of whitespace in the filename with single underscore characters. A: This works if you already have or set up the rename command (e.g. through brew install in Mac): rename --lower-case --force somedir/* A: Most of the answers above are dangerous, because they do not deal with names containing odd characters. Your safest bet for this kind of thing is to use find's -print0 option, which will terminate filenames with ASCII NUL instead of \n. Here is a script, which only alter files and not directory names so as not to confuse find: find . -type f -print0 | xargs -0n 1 bash -c \ 's=$(dirname "$0")/$(basename "$0"); d=$(dirname "$0")/$(basename "$0"|tr "[A-Z]" "[a-z]"); mv -f "$s" "$d"' I tested it, and it works with filenames containing spaces, all kinds of quotes, etc. This is important because if you run, as root, one of those other scripts on a tree that includes the file created by touch \;\ echo\ hacker::0:0:hacker:\$\'\057\'root:\$\'\057\'bin\$\'\057\'bash ... well guess what ... A: for f in `find`; do mv -v "$f" "`echo $f | tr '[A-Z]' '[a-z]'`"; done A: Just simply try the following if you don't need to care about efficiency. zip -r foo.zip foo/* unzip -LL foo.zip A: I needed to do this on a Cygwin setup on Windows 7 and found that I got syntax errors with the suggestions from above that I tried (though I may have missed a working option). However, this solution straight from Ubuntu forums worked out of the can :-) ls | while read upName; do loName=`echo "${upName}" | tr '[:upper:]' '[:lower:]'`; mv "$upName" "$loName"; done (NB: I had previously replaced whitespace with underscores using: for f in *\ *; do mv "$f" "${f// /_}"; done ) A: Slugify Rename (regex) It is not exactly what the OP asked for, but what I was hoping to find on this page: A "slugify" version for renaming files so they are similar to URLs (i.e. only include alphanumeric, dots, and dashes): rename "s/[^a-zA-Z0-9\.]+/-/g" filename A: I would reach for Python in this situation, to avoid optimistically assuming paths without spaces or slashes. I've also found that python2 tends to be installed in more places than rename. #!/usr/bin/env python2 import sys, os def rename_dir(directory): print('DEBUG: rename('+directory+')') # Rename current directory if needed os.rename(directory, directory.lower()) directory = directory.lower() # Rename children for fn in os.listdir(directory): path = os.path.join(directory, fn) os.rename(path, path.lower()) path = path.lower() # Rename children within, if this child is a directory if os.path.isdir(path): rename_dir(path) # Run program, using the first argument passed to this Python script as the name of the folder rename_dir(sys.argv[1]) A: If you use Arch Linux, you can install rename) package from AUR that provides the renamexm command as /usr/bin/renamexm executable and a manual page along with it. It is a really powerful tool to quickly rename files and directories. Convert to lowercase rename -l Developers.mp3 # or --lowcase Convert to UPPER case rename -u developers.mp3 # or --upcase, long option Other options -R --recursive # directory and its children -t --test # Dry run, output but don't rename -o --owner # Change file owner as well to user specified -v --verbose # Output what file is renamed and its new name -s/str/str2 # Substitute string on pattern --yes # Confirm all actions You can fetch the sample Developers.mp3 file from here, if needed ;) A: None of the solutions here worked for me because I was on a system that didn't have access to the perl rename script, plus some of the files included spaces. However, I found a variant that works: find . -depth -exec sh -c ' t=${0%/*}/$(printf %s "${0##*/}" | tr "[:upper:]" "[:lower:]"); [ "$t" = "$0" ] || mv -i "$0" "$t" ' {} \; Credit goes to "Gilles 'SO- stop being evil'", see this answer on the similar question "change entire directory tree to lower-case names" on the Unix & Linux StackExchange. A: I believe the one-liners can be simplified: for f in **/*; do mv "$f" "${f:l}"; done A: ( find YOURDIR -type d | sort -r; find yourdir -type f ) | grep -v /CVS | grep -v /SVN | while read f; do mv -v $f `echo $f | tr '[A-Z]' '[a-z]'`; done First rename the directories bottom up sort -r (where -depth is not available), then the files. Then grep -v /CVS instead of find ...-prune because it's simpler. For large directories, for f in ... can overflow some shell buffers. Use find ... | while read to avoid that. And yes, this will clobber files which differ only in case... A: find . -depth -name '*[A-Z]*'|sed -n 's/\(.*\/\)\(.*\)/mv -n -v -T \1\2 \1\L\2/p'|sh I haven't tried the more elaborate scripts mentioned here, but none of the single commandline versions worked for me on my Synology NAS. rename is not available, and many of the variations of find fail because it seems to stick to the older name of the already renamed path (eg, if it finds ./FOO followed by ./FOO/BAR, renaming ./FOO to ./foo will still continue to list ./FOO/BAR even though that path is no longer valid). Above command worked for me without any issues. What follows is an explanation of each part of the command: find . -depth -name '*[A-Z]*' This will find any file from the current directory (change . to whatever directory you want to process), using a depth-first search (eg., it will list ./foo/bar before ./foo), but only for files that contain an uppercase character. The -name filter only applies to the base file name, not the full path. So this will list ./FOO/BAR but not ./FOO/bar. This is ok, as we don't want to rename ./FOO/bar. We want to rename ./FOO though, but that one is listed later on (this is why -depth is important). This comand in itself is particularly useful to finding the files that you want to rename in the first place. Use this after the complete rename command to search for files that still haven't been replaced because of file name collisions or errors. sed -n 's/\(.*\/\)\(.*\)/mv -n -v -T \1\2 \1\L\2/p' This part reads the files outputted by find and formats them in a mv command using a regular expression. The -n option stops sed from printing the input, and the p command in the search-and-replace regex outputs the replaced text. The regex itself consists of two captures: the part up until the last / (which is the directory of the file), and the filename itself. The directory is left intact, but the filename is transformed to lowercase. So, if find outputs ./FOO/BAR, it will become mv -n -v -T ./FOO/BAR ./FOO/bar. The -n option of mv makes sure existing lowercase files are not overwritten. The -v option makes mv output every change that it makes (or doesn't make - if ./FOO/bar already exists, it outputs something like ./FOO/BAR -> ./FOO/BAR, noting that no change has been made). The -T is very important here - it treats the target file as a directory. This will make sure that ./FOO/BAR isn't moved into ./FOO/bar if that directory happens to exist. Use this together with find to generate a list of commands that will be executed (handy to verify what will be done without actually doing it) sh This pretty self-explanatory. It routes all the generated mv commands to the shell interpreter. You can replace it with bash or any shell of your liking. A: Using bash, without rename: find . -exec bash -c 'mv $0 ${0,,}' {} \;
{ "language": "en", "url": "https://stackoverflow.com/questions/152514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "234" }
Q: Are there guidelines for updating C++Builder applications for C++Builder 2009? I have a range of Win32 VCL applications developed with C++Builder from BCB5 onwards, and want to port them to ECB2009 or whatever it's now called. Some of my applications use the old TNT/TMS unicode components, so I have a good mix of AnsiStrings and WideStrings throughout the code. The new version introduces UnicodeString, and a bunch of #defines that change the way functions like c_str behave. I want to modify my code in a way that is as backwards-compatible as possible, so that the same code base can still be compiled and run (in a non-unicode fashion) on BCB2007 if necessary. Particular areas of concern are: * *Passing strings to/from Win32 API functions *Interop with TXMLDocument *'Raw' strings used for RS232 comms, etc. Rather than knife-and-fork the changes, I'm looking for guidelines that I can apply to ease the migration, while keeping backwards compatibility wherever possible. If no such guidelines already exist, maybe we can formulate some here? A: The biggest issue is compatibility for C++Builder 2009 and previous versions, the Unicode differences are some, but the project configuration files have changed as well. From the discussions I've been following on the CodeGear forums, there are not a whole lot of choices in the matter. I think the first place to start, if you have not done so, is the C++Builder 2009 release notes. The biggest thing seen has been the TCHAR mapping (to wchar or char); using the STL string varieties may be a help, since they shouldn't be very different between the two versions. The mapping existed in C++Builder 2007 as well (with the tchar header). A: For any code that does not need to be explicitally Ansi or explitically Unicode, you should consider using the System::String, System::Char, and System::PChar typedefs as much as possible. That will help ease a lot of migration, and they work in previous versions. When passing a System::String to an API function, you have to take into account the new "TCHAR maps to" setting in the Project options. If you try to pass AnsiString::c_str() when "TCHAR maps to" is set to "wchar_t", or UnicodeString::c_str() when "TCHAR maps to" is set to "char", you will have to perform appropriate typecasts. If you have "TCHAR maps to" set to "wchar_t". Technically, UnicodeString::t_str() does the same thing as TCHAR does in the API, however t_str() can be very dangerous if you misuse it (when "TCHAR maps to" is set to "char", t_str() transforms the UnicodeString's internal data to Ansi). For "raw" strings, you can use the new RawByteString type (though I do not recommend it), or TBytes instead (which is an array of bytes - recommended). You should not be using Ansi/Wide/UnicodeString for non-character data to begin with. Most people used AnsiString as makeshift data buffers in past versions. Do not do that anymore. This is particularly important because AnsiString is now codepage-aware, and thus your data might get converted to other codepages when you least expect it.
{ "language": "en", "url": "https://stackoverflow.com/questions/152528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What is the best way to select string fields based on character ranges? I need to add the ability for users of my software to select records by character ranges. How can I write a query that returns all widgets from a table whose name falls in the range Ba-Bi for example? Currently I'm using greater than and less than operators, so the above example would become: select * from widget where name >= 'ba' and name < 'bj' Notice how I have "incremented" the last character of the upper bound from i to j so that "bike" would not be left out. Is there a generic way to find the next character after a given character based on the field's collation or would it be safer to create a second condition? select * from widget where name >= 'ba' and (name < 'bi' or name like 'bi%') My application needs to support localization. How sensitive is this kind of query to different character sets? I also need to support both MSSQL and Oracle. What are my options for ensuring that character casing is ignored no matter what language appears in the data? A: Let's skip directly to localization. Would you say "aa" >= "ba" ? Probably not, but that is where it sorts in Sweden. Also, you simply can't assume that you can ignore casing in any language. Casing is explicitly language-dependent, with the most common example being Turkish: uppercase i is İ. Lowercase I is ı. Now, your SQL DB defines the result of <, == etc by a "collation order". This is definitely language specific. So, you should explicitly control this, for every query. A Turkish collation order will put those i's where they belong (in Turkish). You can't rely on the default collation. As for the "increment part", don't bother. Stick to >= and <=. A: For MSSQL see this thread: http://bytes.com/forum/thread483570.html . For Oracle, it depends on your Oracle version, as Oracle 10 now supports regex(p) like queries: http://www.psoug.org/reference/regexp.html (search for regexp_like ) and see this article: http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/rischert_regexp_pt1.html HTH A: Frustratingly, the Oracle substring function is SUBSTR(), whilst it SQL-Server it's SUBSTRING(). You could write a simple wrapper around one or both of them so that they share the same function name + prototype. Then you can just use MY_SUBSTRING(name, 2) >= 'ba' AND MY_SUBSTRING(name, 2) <= 'bi' or similar. A: You could use this... select * from widget where name Like 'b[a-i]%' This will match any row where the name starts with b, the second character is in the range a to i, and any other characters follow. A: I think that I'd go with something simple like appending a high-sorting string to the end of the upper bound. Something like: select * from widgetwhere name >= 'ba' and name <= 'bi'||'~' I'm not sure that would survive EBCDIC conversion though A: You could also do it like this: select * from widget where left(name, 2) between 'ba' and 'bi' If your criteria length changes (as you seemed to indicate in a comment you left), the query would need to have the length as an input also: declare @CriteriaLength int set @CriteriaLength = 4 select * from widget where left(name, @CriteriaLength) between 'baaa' and 'bike'
{ "language": "en", "url": "https://stackoverflow.com/questions/152537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Stored procedure bit parameter activating additional where clause to check for null I have a stored procedure that looks like: CREATE PROCEDURE dbo.usp_TestFilter @AdditionalFilter BIT = 1 AS SELECT * FROM dbo.SomeTable T WHERE T.Column1 IS NOT NULL AND CASE WHEN @AdditionalFilter = 1 THEN T.Column2 IS NOT NULL Needless to say, this doesn't work. How can I activate the additional where clause that checks for the @AdditionalFilter parameter? Thanks for any help. A: CREATE PROCEDURE dbo.usp_TestFilter @AdditionalFilter BIT = 1 AS SELECT * FROM dbo.SomeTable T WHERE T.Column1 IS NOT NULL AND (@AdditionalFilter = 0 OR T.Column2 IS NOT NULL) If @AdditionalFilter is 0, the column won't be evaluated since it can't affect the outcome of the part between brackets. If it's anything other than 0, the column condition will be evaluated. A: This practice tends to confuse the query optimizer. I've seen SQL Server 2000 build the execution plan exactly the opposite way round and use an index on Column1 when the flag was set and vice-versa. SQL Server 2005 seemed to at least get the execution plan right on first compilation, but you then have a new problem. The system caches compiled execution plans and tries to reuse them. If you first use the query one way, it will still execute the query that way even if the extra parameter changes, and different indexes would be more appropriate. You can force a stored procedure to be recompiled on this execution by using WITH RECOMPILE in the EXEC statement, or every time by specifying WITH RECOMPILE on the CREATE PROCEDURE statement. There will be a penalty as SQL Server re-parses and optimizes the query each time. In general, if the form of your query is going to change, use dynamic SQL generation with parameters. SQL Server will also cache execution plans for parameterized queries and auto-parameterized queries (where it tries to deduce which arguments are parameters), and even regular queries, but it gives most weight to stored procedure execution plans, then parameterized, auto-parameterized and regular queries in that order. The higher the weight, the longer it can stay in RAM before the plan is discarded, if the server needs the memory for something else. A: CREATE PROCEDURE dbo.usp_TestFilter @AdditionalFilter BIT = 1 AS SELECT * FROM dbo.SomeTable T WHERE T.Column1 IS NOT NULL AND (NOT @AdditionalFilter OR T.Column2 IS NOT NULL) A: select * from SomeTable t where t.Column1 is null and (@AdditionalFilter = 0 or t.Column2 is not null)
{ "language": "en", "url": "https://stackoverflow.com/questions/152541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: *.h or *.hpp for your class definitions I've always used a *.h file for my class definitions, but after reading some boost library code, I realised they all use *.hpp. I've always had an aversion to that file extension, I think mainly because I'm not used to it. What are the advantages and disadvantages of using *.hpp over *.h? A: I prefer .hpp for C++ to make it clear to both editors and to other programmers that it is a C++ header rather than a C header file. A: Here are a couple of reasons for having different naming of C vs C++ headers: * *Automatic code formatting, you might have different guidelines for formatting C and C++ code. If the headers are separated by extension you can set your editor to apply the appropriate formatting automatically *Naming, I've been on projects where there were libraries written in C and then wrappers had been implemented in C++. Since the headers usually had similar names, i.e. Feature.h vs Feature.hpp, they were easy to tell apart. *Inclusion, maybe your project has more appropriate versions available written in C++ but you are using the C version (see above point). If headers are named after the language they are implemented in you can easily spot all the C-headers and check for C++ versions. Remember, C is not C++ and it can be very dangerous to mix and match unless you know what you are doing. Naming your sources appropriately helps you tell the languages apart. A: Fortunately, it is simple. You should use the .hpp extension if you're working with C++ and you should use .h for C or mixing C and C++. A: I always considered the .hpp header to be a sort of portmanteau of .h and .cpp files...a header which contains implementation details as well. Typically when I've seen (and use) .hpp as an extension, there is no corresponding .cpp file. As others have said, this isn't a hard and fast rule, just how I tend to use .hpp files. A: Codegear C++Builder uses .hpp for header files automagically generated from Delphi source files, and .h files for your "own" header files. So, when I'm writing a C++ header file I always use .h. A: C++ ("C Plus Plus") makes sense as .cpp Having header files with a .hpp extension doesn't have the same logical flow. A: Bjarne Stroustrup and Herb Sutter have a statement to this question in their C++ Core guidelines found on: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-source which is also refering to the latest changes in the standard extension (C++11, C++14, etc.) SF.1: Use a .cpp suffix for code files and .h for interface files if your Y project doesn't already follow another convention Reason It's a longstanding convention. But consistency is more important, so if your project uses something else, follow that. Note This convention reflects a common use pattern: Headers are more often shared with C to compile as both C++ and C, which typically uses .h, and it's easier to name all headers .h instead of having different extensions for just those headers that are intended to be shared with C. On the other hand, implementation files are rarely shared with C and so should typically be distinguished from .c files, so it's normally best to name all C++ implementation files something else (such as .cpp). The specific names .h and .cpp are not required (just recommended as a default) and other names are in widespread use. Examples are .hh, .C, and .cxx. Use such names equivalently. In this document, we refer to .h and .cpp > as a shorthand for header and implementation files, even though the actual extension may be different. Your IDE (if you use one) may have strong opinions about suffices. I'm not a big fan of this convention because if you are using a popular library like boost, your consistency is already broken and you should better use .hpp. A: It does not matter which extension you use. Either one is OK. I use *.h for C and *.hpp for C++. A: In one of my jobs in the early 90's, we used .cc and .hh for source and header files respectively. I still prefer it over all the alternatives, probably because it's easiest to type. A: EDIT [Added suggestion from Dan Nissenbaum]: By one convention, .hpp files are used when the prototypes are defined in the header itself. Such definitions in headers are useful in case of templates, since the compiler generates the code for each type only on template instantiation. Hence, if they are not defined in header files, their definitions will not be resolved at link time from other compilation units. If your project is a C++ only project that makes heavy use of templates, this convention will be useful. Certain template libraries that adhere to this convention provide headers with .hpp extensions to indicate that they do not have corresponding .cpp files. another convention is to use .h for C headers and .hpp for C++; a good example would be the boost library. Quote from Boost FAQ, File extensions communicate the "type" of the file, both to humans and to computer programs. The '.h' extension is used for C header files, and therefore communicates the wrong thing about C++ header files. Using no extension communicates nothing and forces inspection of file contents to determine type. Using '.hpp' unambiguously identifies it as C++ header file, and works well in actual practice. (Rainer Deyke) A: It is easy for tools and humans to differentiate something. That's it. In conventional use (by boost, etc), .hpp is specifically C++ headers. On the other hand, .h is for non-C++-only headers (mainly C). To precisely detect the language of the content is generally hard since there are many non-trivial cases, so this difference often makes a ready-to-use tool easy to write. For humans, once get the convention, it is also easy to remember and easy to use. However, I'd point out the convention itself does not always work, as expected. * *It is not forced by the specification of languages, neither C nor C++. There exist many projects which do not follow the convention. Once you need to merge (to mix) them, it can be troublesome. *.hpp itself is not the only choice. Why not .hh or .hxx? (Though anyway, you usually need at least one conventional rule about filenames and paths.) I personally use both .h and .hpp in my C++ projects. I don't follow the convention above because: * *The languages used by each part of the projects are explicitly documented. No chance to mix C and C++ in same module (directory). Every 3rdparty library is required to conforming to this rule. *The conformed language specifications and allowed language dialects used by the projects are also documented. (In fact, I even document the source of the standard features and bug fix (on the language standard) being used.) This is somewhat more important than distinguishing the used languages since it is too error-prone and the cost of test (e.g. compiler compatibility) may be significant (complicated and time-consuming), especially in a project which is already in almost pure C++. Filenames are too weak to handle this. *Even for the same C++ dialect, there may be more important properties suitable to the difference. For example, see the convention below. *Filenames are essentially pieces of fragile metadata. The violation of convention is not so easy to detect. To be stable dealing the content, a tool should eventually not only depend on names. The difference between extensions is only a hint. Tools using it should also not be expected behave same all the time, e.g. language-detecting of .h files on github.com. (There may be something in comments like shebang for these source files to be better metadata, but it is even not conventional like filenames, so also not reliable in general.) I usually use .hpp on C++ headers and the headers should be used (maintained) in a header-only manner, e.g. as template libraries. For other headers in .h, either there is a corresponding .cpp file as implementation, or it is a non-C++ header. The latter is trivial to differentiate through the contents of the header by humans (or by tools with explicit embedded metadata, if needed). A: As many here have already mentioned, I also prefer using .hpp for header-only libraries that use template classes/functions. I prefer to use .h for header files accompanied by .cpp source files or shared or static libraries. Most of the libraries I develop are template based and thus need to be header only, but when writing applications I tend to separate declaration from implementation and end up with .h and .cpp files A: I use .hpp because I want the user to differentiate what headers are C++ headers, and what headers are C headers. This can be important when your project is using both C and C++ modules: Like someone else explained before me, you should do it very carefully, and its starts by the "contract" you offer through the extension .hpp : C++ Headers (Or .hxx, or .hh, or whatever) This header is for C++ only. If you're in a C module, don't even try to include it. You won't like it, because no effort is done to make it C-friendly (too much would be lost, like function overloading, namespaces, etc. etc.). .h : C/C++ compatible or pure C Headers This header can be included by both a C source, and a C++ source, directly or indirectly. It can included directly, being protected by the __cplusplus macro: * *Which mean that, from a C++ viewpoint, the C-compatible code will be defined as extern "C". *From a C viewpoint, all the C code will be plainly visible, but the C++ code will be hidden (because it won't compile in a C compiler). For example: #ifndef MY_HEADER_H #define MY_HEADER_H #ifdef __cplusplus extern "C" { #endif void myCFunction() ; #ifdef __cplusplus } // extern "C" #endif #endif // MY_HEADER_H Or it could be included indirectly by the corresponding .hpp header enclosing it with the extern "C" declaration. For example: #ifndef MY_HEADER_HPP #define MY_HEADER_HPP extern "C" { #include "my_header.h" } #endif // MY_HEADER_HPP and: #ifndef MY_HEADER_H #define MY_HEADER_H void myCFunction() ; #endif // MY_HEADER_H A: I use .h because that's what Microsoft uses, and what their code generator creates. No need to go against the grain. A: I'm answering this as an reminder, to give point to my comment(s) on "user1949346" answer to this same OP. So as many already answered: either way is fine. Followed by emphasizes of their own impressions. Introductory, as also in the previous named comments stated, my opinion is C++ header extensions are proposed to be .h if there is actually no reason against it. Since the ISO/IEC documents use this notation of header files and no string matching to .hpp even occurs in their language documentations about C++. But I'm now aiming for an approvable reason WHY either way is ok, and especially why it's not subject of the language it self. So here we go. The C++ documentation (I'm actually taking reference from the version N3690) defines that a header has to conform to the following syntax: 2.9 Header names header-name: < h-char-sequence > " q-char-sequence " h-char-sequence: h-char h-char-sequence h-char h-char: any member of the source character set except new-line and > q-char-sequence: q-char q-char-sequence q-char q-char: any member of the source character set except new-line and " So as we can extract from this part, the header file name may be anything that is valid in the source code, too. Except containing '\n' characters and depending on if it is to be included by <> it is not allowed to contain a >. Or the other way if it is included by ""-include it is not allowed to contain a ". In other words: if you had a environment supporting filenames like prettyStupidIdea.>, an include like: #include "prettyStupidIdea.>" would be valid, but: #include <prettyStupidIdea.>> would be invalid. The other way around the same. And even #include <<.<> would be a valid includable header file name. Even this would conform to C++, it would be a pretty pretty stupid idea, tho. And that's why .hpp is valid, too. But it's not an outcome of the committees designing decisions for the language! So discussing about to use .hpp is same as doing it about .cc, .mm or what ever else I read in other posts on this topic. I have to admit I have no clue where .hpp came from1, but I would bet an inventor of some parsing tool, IDE or something else concerned with C++ came to this idea to optimize some internal processes or just to invent some (probably even for them necessarily) new naming conventions. But it is not part of the language. And whenever one decides to use it this way. May it be because he likes it most or because some applications of the workflow require it, it never2 is a requirement of the language. So whoever says "the pp is because it is used with C++", simply is wrong in regards of the languages definition. C++ allows anything respecting the previous paragraph. And if there is anything the committee proposed to use, then it is using .h since this is the extension sued in all examples of the ISO document. Conclusion: As long you don't see/feel any need of using .h over .hpp or vise versa, you shouldn't bother. Because both would be form a valid header name of same quality in respect to the standard. And therefore anything that REQUIRES you to use .h or .hpp is an additional restriction of the standard which could even be contradicting with other additional restrictions not conform with each other. But as OP doesn't mention any additional language restriction, this is the only correct and approvable answer to the question "*.h or *.hpp for your class definitions" is: Both are equally correct and applicable as long as no external restrictions are present. 1From what I know, apparently, it is the boost framework that came up with that .hpp extension. 2Of course I can't say what some future versions will bring with it! A: In "The C++ Programming Language, Third Edition by Bjarne Stroustrup", the nº1 must-read C++ book, he uses *.h. So I assume the best practice is to use *.h. However, *.hpp is fine as well! A: There is no advantage to any particular extension, other than that one may have a different meaning to you, the compiler, and/or your tools. header.h is a valid header. header.hpp is a valid header. header.hh is a valid header. header.hx is a valid header. h.header is a valid header. this.is.not.a.valid.header is a valid header in denial. ihjkflajfajfklaf is a valid header. As long as the name can be parsed properly by the compiler, and the file system supports it, it's a valid header, and the only advantage to its extension is what one reads into it. That being said, being able to accurately make assumptions based on the extension is very useful, so it would be wise to use an easily-understandable set of rules for your header files. Personally, I prefer to do something like this: * *If there are already any established guidelines, follow them to prevent confusion. *If all source files in the project are for the same language, use .h. There's no ambiguity. *If some headers are compatible with multiple languages, while others are only compatible with a single language, extensions are based on the most restrictive language that a header is compatible with. A header compatible with C, or with both C & C++, gets .h, while a header compatible with C++ but not C gets .hpp or .hh or something of the sort. This, of course, is but one of many ways to handle extensions, and you can't necessarily trust your first impression even if things seem straightforward. For example, I've seen mention of using .h for normal headers, and .tpp for headers that only contain definitions for templated class member functions, with .h files that define templated classes including the .tpp files that define their member functions (instead of the .h header directly containing both the function declaration and the definition). For another example, a good many people always reflect the header's language in its extension, even when there's no chance of ambiguity; to them, .h is always a C header and .hpp (or .hh, or .hxx, etc.) is always a C++ header. And yet again, some people use .h for "header associated with a source file" and .hpp for "header with all functions defined inline". Considering this, the main advantage would come in consistently naming your headers in the same style, and making that style readily apparent to anyone examining your code. This way, anyone familiar with your usual coding style will be able to determine what you mean with any given extension with just a cursory glance. A: I've recently started using *.hpp for c++ headers. The reason is that I use emacs as my primary editor and it enters automatically into c-mode when you load a *.h file and into c++-mode when you load a *.hpp file. Apart that fact I see no good reasons for choosing *.h over *.hpp or vice-versa. A: You can call your includes whatever you like. Just need to specify that full name in the #include. I suggest that if you work with C to use .h and when with C++ to use .hpp. It is in the end just a convention. A: The extension of the source file may have meaning to your build system, for example, you might have a rule in your makefile for .cpp or .c files, or your compiler (e.g. Microsoft cl.exe) might compile the file as C or C++ depending on the extension. Because you have to provide the whole filename to the #include directive, the header file extension is irrelevant. You can include a .c file in another source file if you like, because it's just a textual include. Your compiler might have an option to dump the preprocessed output which will make this clear (Microsoft: /P to preprocess to file, /E to preprocess to stdout, /EP to omit #line directives, /C to retain comments) You might choose to use .hpp for files that are only relevant to the C++ environment, i.e. they use features that won't compile in C.
{ "language": "en", "url": "https://stackoverflow.com/questions/152555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "737" }
Q: How do you handle TDD in the continuous integration? Imagine you are implementing the user story containing various new features and adding complexity to the code base. The existing code is quite well covered and you have just decided upon interfaces. You are starting to implement the functionality starting with tests. Now you have fairly complex test cases based on the requirements but the implementation is nowhere near the point when you are able to commit to the SCM fully working code and many test are failing (as they should). There is an assumption that in continuous integration all builds should be green if possible and thus you shouldn't commit as you would break the build. But you also shouldn't "Go dark" and keep such amount of code for yourself... What is the suggested procedure in such situation? A: Do not decide on all interfaces beforehand. Develop incrementally in a typical TDD rhythm: write a test; make the test pass; refactor. That should keep everything in good shape, the bar will always be green and you can check code in without worrying that you will break the build. It requires a different style of writing code, but you will get used to the rhythm eventually. A: What about skipping those tests that you know won't pass because the functionality is currently missing? Make it obvious that you are skipping the tests too! Really make it scream "like a stuck pig", as they say in Oz! (-: As you add functionality, enable the associated tests and keep "your bar green!" Here's another great article over at The Pragmatic Programmers that covers making broken windows obvious to others. HTH cheers, Rob
{ "language": "en", "url": "https://stackoverflow.com/questions/152579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What's the canonical way to check for type in Python? How do I check if an object is of a given type, or if it inherits from a given type? How do I check if the object o is of type str? Beginners often wrongly expect the string to already be "a number" - either expecting Python 3.x input to convert type, or expecting that a string like '1' is also simultaneously an integer. This is the wrong canonical for those questions. Please carefully read the question and then use How do I check if a string represents a number (float or int)?, How can I read inputs as numbers? and/or Asking the user for input until they give a valid response as appropriate. A: For more complex type validations I like typeguard's approach of validating based on python type hint annotations: from typeguard import check_type from typing import List try: check_type('mylist', [1, 2], List[int]) except TypeError as e: print(e) You can perform very complex validations in very clean and readable fashion. check_type('foo', [1, 3.14], List[Union[int, float]]) # vs isinstance(foo, list) and all(isinstance(a, (int, float)) for a in foo) A: isinstance(o, str) will return True if o is an str or is of a type that inherits from str. type(o) is str will return True if and only if o is a str. It will return False if o is of a type that inherits from str. A: I think the cool thing about using a dynamic language like Python is you really shouldn't have to check something like that. I would just call the required methods on your object and catch an AttributeError. Later on this will allow you to call your methods with other (seemingly unrelated) objects to accomplish different tasks, such as mocking an object for testing. I've used this a lot when getting data off the web with urllib2.urlopen() which returns a file like object. This can in turn can be passed to almost any method that reads from a file, because it implements the same read() method as a real file. But I'm sure there is a time and place for using isinstance(), otherwise it probably wouldn't be there :) A: The accepted answer answers the question in that it provides the answers to the asked questions. Q: What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type? A: Use isinstance, issubclass, type to check based on types. As other answers and comments are quick to point out however, there's a lot more to the idea of "type-checking" than that in python. Since the addition of Python 3 and type hints, much has changed as well. Below, I go over some of the difficulties with type checking, duck typing, and exception handling. For those that think type checking isn't what is needed (it usually isn't, but we're here), I also point out how type hints can be used instead. Type Checking Type checking is not always an appropriate thing to do in python. Consider the following example: def sum(nums): """Expect an iterable of integers and return the sum.""" result = 0 for n in nums: result += n return result To check if the input is an iterable of integers, we run into a major issue. The only way to check if every element is an integer would be to loop through to check each element. But if we loop through the entire iterator, then there will be nothing left for intended code. We have two options in this kind of situation. * *Check as we loop. *Check beforehand but store everything as we check. Option 1 has the downside of complicating our code, especially if we need to perform similar checks in many places. It forces us to move type checking from the top of the function to everywhere we use the iterable in our code. Option 2 has the obvious downside that it destroys the entire purpose of iterators. The entire point is to not store the data because we shouldn't need to. One might also think that checking if checking all of the elements is too much then perhaps we can just check if the input itself is of the type iterable, but there isn't actually any iterable base class. Any type implementing __iter__ is iterable. Exception Handling and Duck Typing An alternative approach would be to forgo type checking altogether and focus on exception handling and duck typing instead. That is to say, wrap your code in a try-except block and catch any errors that occur. Alternatively, don't do anything and let exceptions rise naturally from your code. Here's one way to go about catching an exception. def sum(nums): """Try to catch exceptions?""" try: result = 0 for n in nums: result += n return result except TypeError as e: print(e) Compared to the options before, this is certainly better. We're checking as we run the code. If there's a TypeError anywhere, we'll know. We don't have to place a check everywhere that we loop through the input. And we don't have to store the input as we iterate over it. Furthermore, this approach enables duck typing. Rather than checking for specific types, we have moved to checking for specific behaviors and look for when the input fails to behave as expected (in this case, looping through nums and being able to add n). However, the exact reasons which make exception handling nice can also be their downfall. * *A float isn't an int, but it satisfies the behavioral requirements to work. *It is also bad practice to wrap the entire code with a try-except block. At first these may not seem like issues, but here's some reasons that may change your mind. * *A user can no longer expect our function to return an int as intended. This may break code elsewhere. *Since exceptions can come from a wide variety of sources, using the try-except on the whole code block may end up catching exceptions you didn't intend to. We only wanted to check if nums was iterable and had integer elements. *Ideally we'd like to catch exceptions our code generators and raise, in their place, more informative exceptions. It's not fun when an exception is raised from someone else's code with no explanation other than a line you didn't write and that some TypeError occured. In order to fix the exception handling in response to the above points, our code would then become this... abomination. def sum(nums): """ Try to catch all of our exceptions only. Re-raise them with more specific details. """ result = 0 try: iter(nums) except TypeError as e: raise TypeError("nums must be iterable") for n in nums: try: result += int(n) except TypeError as e: raise TypeError("stopped mid iteration since a non-integer was found") return result You can kinda see where this is going. The more we try to "properly" check things, the worse our code is looking. Compared to the original code, this isn't readable at all. We could argue perhaps this is a bit extreme. But on the other hand, this is only a very simple example. In practice, your code is probably much more complicated than this. Type Hints We've seen what happens when we try to modify our small example to "enable type checking". Rather than focusing on trying to force specific types, type hinting allows for a way to make types clear to users. from typing import Iterable def sum(nums: Iterable[int]) -> int: result = 0 for n in nums: result += n return result Here are some advantages to using type-hints. * *The code actually looks good now! *Static type analysis may be performed by your editor if you use type hints! *They are stored on the function/class, making them dynamically usable e.g. typeguard and dataclasses. *They show up for functions when using help(...). *No need to sanity check if your input type is right based on a description or worse lack thereof. *You can "type" hint based on structure e.g. "does it have this attribute?" without requiring subclassing by the user. The downside to type hinting? * *Type hints are nothing more than syntax and special text on their own. It isn't the same as type checking. In other words, it doesn't actually answer the question because it doesn't provide type checking. Regardless, however, if you are here for type checking, then you should be type hinting as well. Of course, if you've come to the conclusion that type checking isn't actually necessary but you want some semblance of typing, then type hints are for you. A: To Hugo: You probably mean list rather than array, but that points to the whole problem with type checking - you don't want to know if the object in question is a list, you want to know if it's some kind of sequence or if it's a single object. So try to use it like a sequence. Say you want to add the object to an existing sequence, or if it's a sequence of objects, add them all try: my_sequence.extend(o) except TypeError: my_sequence.append(o) One trick with this is if you are working with strings and/or sequences of strings - that's tricky, as a string is often thought of as a single object, but it's also a sequence of characters. Worse than that, as it's really a sequence of single-length strings. I usually choose to design my API so that it only accepts either a single value or a sequence - it makes things easier. It's not hard to put a [ ] around your single value when you pass it in if need be. (Though this can cause errors with strings, as they do look like (are) sequences.) A: After the question was asked and answered, type hints were added to Python. Type hints in Python allow types to be checked but in a very different way from statically typed languages. Type hints in Python associate the expected types of arguments with functions as runtime accessible data associated with functions and this allows for types to be checked. Example of type hint syntax: def foo(i: int): return i foo(5) foo('oops') In this case we want an error to be triggered for foo('oops') since the annotated type of the argument is int. The added type hint does not cause an error to occur when the script is run normally. However, it adds attributes to the function describing the expected types that other programs can query and use to check for type errors. One of these other programs that can be used to find the type error is mypy: mypy script.py script.py:12: error: Argument 1 to "foo" has incompatible type "str"; expected "int" (You might need to install mypy from your package manager. I don't think it comes with CPython but seems to have some level of "officialness".) Type checking this way is different from type checking in statically typed compiled languages. Because types are dynamic in Python, type checking must be done at runtime, which imposes a cost -- even on correct programs -- if we insist that it happen at every chance. Explicit type checks may also be more restrictive than needed and cause unnecessary errors (e.g. does the argument really need to be of exactly list type or is anything iterable sufficient?). The upside of explicit type checking is that it can catch errors earlier and give clearer error messages than duck typing. The exact requirements of a duck type can only be expressed with external documentation (hopefully it's thorough and accurate) and errors from incompatible types can occur far from where they originate. Python's type hints are meant to offer a compromise where types can be specified and checked but there is no additional cost during usual code execution. The typing package offers type variables that can be used in type hints to express needed behaviors without requiring particular types. For example, it includes variables such as Iterable and Callable for hints to specify the need for any type with those behaviors. While type hints are the most Pythonic way to check types, it's often even more Pythonic to not check types at all and rely on duck typing. Type hints are relatively new and the jury is still out on when they're the most Pythonic solution. A relatively uncontroversial but very general comparison: Type hints provide a form of documentation that can be enforced, allow code to generate earlier and easier to understand errors, can catch errors that duck typing can't, and can be checked statically (in an unusual sense but it's still outside of runtime). On the other hand, duck typing has been the Pythonic way for a long time, doesn't impose the cognitive overhead of static typing, is less verbose, and will accept all viable types and then some. A: In Python 3.10, you can use | in isinstance: >>> isinstance('1223', int | str) True >>> isinstance('abcd', int | str) True A: The most Pythonic way to check the type of an object is... not to check it. Since Python encourages Duck Typing, you should just try...except to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method! Of course, sometimes these nice abstractions break down and isinstance(obj, cls) is what you need. But use sparingly. A: Use isinstance to check if o is an instance of str or any subclass of str: if isinstance(o, str): To check if the type of o is exactly str, excluding subclasses of str: if type(o) is str: See Built-in Functions in the Python Library Reference for relevant information. Checking for strings in Python 2 For Python 2, this is a better way to check if o is a string: if isinstance(o, basestring): because this will also catch Unicode strings. unicode is not a subclass of str; both str and unicode are subclasses of basestring. In Python 3, basestring no longer exists since there's a strict separation of strings (str) and binary data (bytes). Alternatively, isinstance accepts a tuple of classes. This will return True if o is an instance of any subclass of any of (str, unicode): if isinstance(o, (str, unicode)): A: isinstance(o, str) Link to docs A: You can check for type of a variable using __name__ of a type. Ex: >>> a = [1,2,3,4] >>> b = 1 >>> type(a).__name__ 'list' >>> type(a).__name__ == 'list' True >>> type(b).__name__ == 'list' False >>> type(b).__name__ 'int' A: If you have to check for the type of str or int please use instanceof. As already mentioned by others the explanation is to also include sub classes. One important example for sub classes from my perspective are Enums with data type like IntEnum or StrEnum. Which are a pretty nice way to define related constants. However, it is kind of annoying if libraries do not accept those as such types. Example: import enum class MyEnum(str, enum.Enum): A = "a" B = "b" print(f"is string: {isinstance(MyEnum.A, str)}") # True print(f"is string: {type(MyEnum.A) == str}") # False!!! print(f"is string: {type(MyEnum.A.value) == str}") # True A: A simple way to check type is to compare it with something whose type you know. >>> a = 1 >>> type(a) == type(1) True >>> b = 'abc' >>> type(b) == type('') True A: I think the best way is to typing well your variables. You can do this by using the "typing" library. Example: from typing import NewType UserId = NewType ('UserId', int) some_id = UserId (524313`) See https://docs.python.org/3/library/typing.html. A: In Python, you can use the built-in isinstance() function to check if an object is of a given type, or if it inherits from a given type. To check if the object o is of type str, you would use the following code: if isinstance(o, str): # o is of type str You can also use type() function to check the object type. if type(o) == str: # o is of type str You can also check if the object is a sub class of a particular class using issubclass() function. if issubclass(type(o),str): # o is sub class of str
{ "language": "en", "url": "https://stackoverflow.com/questions/152580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1777" }
Q: Is this a reasonable "Application entry point"? I have recently come across a situation where code is dynamically loading some libraries, wiring them up, then calling what is termed the "application entry point" (one of the libraries must implement IApplication.Run()). Is this a valid "Appliation entry point"? I would always have considered the application entry point to be before the loading of the libraries and found the IApplication.Run() being called after a considerable amount of work slightly misleading. A: The terms application and system are terms that are so widely and diversely used that you need to agree what they mean upfront with your conversation partner. E.g. sometimes an application is something with a UI, and a system is 'UI-less'. In general it's just a case of you say potato, I say potato. As for the example you use: that's just what a runtime (e.g. .NET or java) does: loading a set of libraries and calling the application entry point, i.e. the "main" method. So in your case, the code loading the libraries is doing just the same, and probably calling a method on an interface, you could then consider the loading code to be the runtime for that application. It's just a matter of perspective. A: The term "application" can mean whatever you want it to mean. "Application" merely means a collection of resources (libraries, code, images, etc) that work together to help you solve a problem. So to answer your question, yes, it's a valid use of the term 'application'. A: Application on its own means actually nothing. It is often used by people to talk about computer programs that provide some value to the user. A more correct term is application software and this has the following definition: Application software is a subclass of computer software that employs the capabilities of a computer directly and thoroughly to a task that the user wishes to perform. This should be contrasted with system software which is involved in integrating a computer's various capabilities, but typically does not directly apply them in the performance of tasks that benefit the user. In this context the term application refers to both the application software and its implementation. And since application really means application software, and software is any piece of code that performs any kind of task on a computer, I'd say also a library can be an application. Most terms are of artificial nature anyway. Is a plugin no application? Is the flash plugin of your browser no application? People say no, it's just a plugin. Why? Because it can't run on it's own, it needs to be loaded into a real process. But there is no definition saying only things that "can run on their own" are applications. Same holds true for a library. The core application could just be an empty container and all logic and functionality, even the interaction with the user, could be performed by plugins or libraries, in which case that would be more an application than the empty container that just provides some context for the application to run. Compare this to Java. A Java application can't run on it's own, it must run within a Java Virtual Machine (JVM), does that mean the JVM is the application and the Java Code is just... well what? Isn't the Java code the real application and the JVM just an empty runtime environment that provides nothing to the end user without the loaded Java code? A: I think probably what you're referring to is the main() function in C/C++ code or WinMain in a Windows app. That is, it's the point where execution is normally started in an app. Your question is pretty broad and vague--for example, which OS are you running this on--but this may be what you're looking for. This might also address the question. Bear in mind when you're asking questions, details are your friend. People can give you a much better, more informed answer when you provide them with details. EDIT: In a broader context consider what has to happen from the standpoint of the OS. When the user specifies that they want to run an app, the OS has to load the app from the hard drive and then when the app is loaded into memory, it has to pass control to some point in the memory blocked occupied by the newly loaded app to continue execution. That would be the "Application Entry Point". When an app is constructed with dynamically linked code the OS has to load all that dynamically linked code in order to get the correct app image into memory. Loading up those shared bits of code does not change the fact that the OS must have a point to which to pass control when the app is loaded into memory. A: I think in this context "application entry point" means "the point at which the application (your code) enters the library".
{ "language": "en", "url": "https://stackoverflow.com/questions/152582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Identify GET and POST parameters in Ruby on Rails What is the simplest way to identify and separate GET and POST parameters from a controller in Ruby on Rails, which will be equivalent to $_GET and $_POST variables in PHP? A: There is a difference between GET and POST params. A POST HTTP request can still have GET params. GET parameters are URL query parameters. POST parameters are parameters in the body of the HTTP request. you can access these separately from the request.GET and request.POST hashes. A: You can use the request.get? and request.post? methods to distinguish between HTTP Gets and Posts. * *See http://api.rubyonrails.org/classes/ActionDispatch/Request.html A: request.get? will return boolean true if it is GET method, request.post? will return boolean true if it is POST method, A: If you want to check the type of request in order to prevent doing anything when the wrong method is used, be aware that you can also specify it in your routes.rb file: map.connect '/posts/:post_id', :controller => 'posts', :action => 'update', :conditions => {:method => :post} or map.resources :posts, :conditions => {:method => :post} Your PostsController's update method will now only be called when you effectively had a post. Check out the doc for resources. A: I don't know of any convenience methods in Rails for this, but you can access the querystring directly to parse out parameters that are set there. Something like the following: request.query_string.split(/&/).inject({}) do |hash, setting| key, val = setting.split(/=/) hash[key.to_sym] = val hash end A: You can do it using: request.POST and request.GET A: There are three very-lightly-documented hash accessors on the request object for this: * *request.query_parameters - sent as part of the query string, i.e. after a ? *request.path_parameters - decoded from the URL via routing, i.e. controller, action, id *request.request_parameters - All params, including above as well as any sent as part of the POST body You can use Hash#reject to get to the POST-only params as needed. Source: http://guides.rubyonrails.org/v2.3.8/action_controller_overview.html section 9.1.1 I looked in an old Rails 1.2.6 app and these accessors existed back then as well. A: I think what you want to do isn't very "Rails", if you know what I mean. Your GET requests should be idempotent - you should be able to issue the same GET request many times and get the same result each time. A: You don't need to know that level of detail in the controller. Your routes and forms will cause appropriate items to be added to the params hash. Then in the controller you just access say params[:foo] to get the foo parameter and do whatever you need to with it. The mapping between GET and POST (and PUT and DELETE) and controller actions is set up in config/routes.rb in most modern Rails code. A: I think what Jesse Reiss is talking about is a situation where in your routes.rb file you have post 'ctrllr/:a/:b' => 'ctrllr#an_action' and you POST to "/ctrllr/foo/bar?a=not_foo" POST values {'a' => 'still_not_foo'}, you will have three different values of 'a': 'foo', 'not_foo', and 'still_not_foo' 'params' in the controller will have 'a' set to 'foo'. To find 'a' set to 'not_foo' and 'still_not_foo', you need to examine request.GET and request.POST I wrote a gem which distinguishes between these different key=>value pairs at https://github.com/pdxrod/routesfordummies. A: if request.query_parameters().to_a.empty?
{ "language": "en", "url": "https://stackoverflow.com/questions/152585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How to initialize ConnectionStrings collection in NUnit I want to test ASP.NET application using NUnit, but it seems WebConfigurationManager.ConnectionStrings collection is empty when running from NUnit GUI. Could you tell me how to initialize this collection (probably in [SetUp] function of [TestFixture])? Should I copy Web.config somethere? Thank you! A: NUnit .config file location depends on how you created the NUnit project file Where .config files for NUnit tests are located is a little bit more complicated than other posts here suggest. There are settings for this in the NUnit GUI Project/Edit dialogue. The default values all depend upon how you created your NUnit project file. When you open the NUnit GUI and select File/Open and then select a .dll file a new project gets set up with settings to look for a config file with the same name as the dll in the same directory. So if you loaded \bin\debug\MyTests.dll NUnit looks for \bin\Debug\MyTests.dll.config by default. The only trouble with this is that when you create a release build you need to create a separate NUnit project. If you have created the NUnit project by selecting File/NewProject then the default setting is to look for a config file with the same name as the NUnit project. So if you created \MyNUnitProject.nunit NUnit looks for \MyNUnitProject.config by default. The chances are you have used Visual Studio to create an \App.config file and stuck it in the source folder for your test dll. When you buld your test project this gets copied to \bin\Debug\MyTests.dll.config or \bin\Release\MyTests.dll.config depending upon the configuration you have selected. If you have opened the MyTest.dll directly in NUnit this will work fine, however if you have created a new NUnit project you’re in trouble as it will not look for these files by default. To resolve the issue you need to open up the Project/Edit dialog in the NUnit GUI and check that you have two Configurations Debug & Release to match your .Net project. Once you have done this you can select the Debug Configuration and set the ApplicationBase to bin\Debug\ and set the Configuration File Name to MyTests.dll.config. Do the same for the Release configuration and away you go. A: If you have your unit-test assembly named Company.Component.Tests.dll, then just make sure that Company.Component.Tests.dll.config is there with the proper connection string. Additionally, it might be a good idea to decouple your connection provider class from the configuration, so that you will have flexibility in persistence (i.e.: switching from *.config to something else) and easier testing. Also check out "How NUnit Finds Config Files" A: You can use the app.config for libraries (where I assume your tests are) and put them in there.
{ "language": "en", "url": "https://stackoverflow.com/questions/152586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: F# style - prefer () or <| Which of theese two alternatives do you find yourself using most often, and which is more "idiomatic"? * *f arg (obj.DoStuff()) *f arg <| obj.DoStuff() A: Overall, I don't know that one or the other is more idiomatic. Personally, the only time I use <| is with "raise": raise <| new FooException("blah") Apart from that, I always use parens. Note that since most F# code uses curried functions, this does not typically imply any "extra" parens: f arg (g x y) It's when you get into non-curried functions and constructors and whatnot that it starts getting less pretty: f arg (g(x,y)) We will probably at least consider changing the F# languages rules so that high-precedence applications bind even more tightly; right now f g() parses like f g () but a lot of people would like it to parse as f (g()) (the motivating case in the original question). If you have a strong opinion about this, leave a comment on this response. A: Because type inference works from left to right, a bonus of using |> is that it allows F# to infer the type of the argument of the function. As a contrived example, [1; 2; 3] |> (fun x -> x.Length*2) works just fine, but (fun x -> x.Length*2) [1; 2; 3] complains of "lookup on object of indeterminate type". A: I use () much much more often, but thats just preference, I'm pretty sure that <| is more idomatic, but I use () by habit. A: Whenever possible, I much prefer |> because it reads from left to right.
{ "language": "en", "url": "https://stackoverflow.com/questions/152602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C#: Getting maximum and minimum values of arbitrary properties of all items in a list I have a specialized list that holds items of type IThing: public class ThingList : IList<IThing> {...} public interface IThing { Decimal Weight { get; set; } Decimal Velocity { get; set; } Decimal Distance { get; set; } Decimal Age { get; set; } Decimal AnotherValue { get; set; } [...even more properties and methods...] } Sometimes I need to know the maximum or minimum of a certain property of all the things in the list. Because of "Tell don't ask" we let the List figure it out: public class ThingList : IList<IThing> { public Decimal GetMaximumWeight() { Decimal result = 0; foreach (IThing thing in this) { result = Math.Max(result, thing.Weight); } return result; } } Thats very nice. But sometimes I need the minimum weight, sometimes the maximum velocity and so on. I don't want a GetMaximum*()/GetMinimum*() pair for every single property. One solution would be reflection. Something like (hold your nose, strong code smell!): Decimal GetMaximum(String propertyName); Decimal GetMinimum(String propertyName); Are there any better, less smelly ways to accomplish this? Thanks, Eric Edit: @Matt: .Net 2.0 Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005). Maybe we should move to .Net 3.5 and Visual Studio 2008 sometime soon. Thanks, guys. Conclusion: There are diffent ways that are far better than reflection. Depending on runtime and C# version. Have a look at Jon Skeets answer for the differences. All answers are are very helpful. I will go for Sklivvz suggestion (anonymous methods). There are several code snippets from other people (Konrad Rudolph, Matt Hamilton and Coincoin) which implement Sklivvz idea. I can only "accept" one answer, unfortunately. Thank you very much. You can all feel "accepted", altough only Sklivvz gets the credits ;-) A: If using .NET 3.5, why not use lambdas? public Decimal GetMaximum(Func<IThing, Decimal> prop) { Decimal result = Decimal.MinValue; foreach (IThing thing in this) result = Math.Max(result, prop(thing)); return result; } Usage: Decimal result = list.GetMaximum(x => x.Weight); This is strongly typed and efficient. There are also extension methods that already do exactly this. A: (Edited to reflect .NET 2.0 answer, and LINQBridge in VS2005...) There are three situations here - although the OP only has .NET 2.0, other people facing the same problem may not... 1) Using .NET 3.5 and C# 3.0: use LINQ to Objects like this: decimal maxWeight = list.Max(thing => thing.Weight); decimal minWeight = list.Min(thing => thing.Weight); 2) Using .NET 2.0 and C# 3.0: use LINQBridge and the same code 3) Using .NET 2.0 and C# 2.0: use LINQBridge and anonymous methods: decimal maxWeight = Enumerable.Max(list, delegate(IThing thing) { return thing.Weight; } ); decimal minWeight = Enumerable.Min(list, delegate(IThing thing) { return thing.Weight; } ); (I don't have a C# 2.0 compiler to hand to test the above - if it complains about an ambiguous conversion, cast the delegate to Func<IThing,decimal>.) LINQBridge will work with VS2005, but you don't get extension methods, lambda expressions, query expressions etc. Clearly migrating to C# 3 is a nicer option, but I'd prefer using LINQBridge to implementing the same functionality myself. All of these suggestions involve walking the list twice if you need to get both the max and min. If you've got a situation where you're loading from disk lazily or something like that, and you want to calculate several aggregates in one go, you might want to look at my "Push LINQ" code in MiscUtil. (That works with .NET 2.0 as well.) A: For C# 2.0 and .Net 2.0 you can do the following for Max: public delegate Decimal GetProperty<TElement>(TElement element); public static Decimal Max<TElement>(IEnumerable<TElement> enumeration, GetProperty<TElement> getProperty) { Decimal max = Decimal.MinValue; foreach (TElement element in enumeration) { Decimal propertyValue = getProperty(element); max = Math.Max(max, propertyValue); } return max; } And here is how you would use it: string[] array = new string[] {"s","sss","ddsddd","333","44432333"}; Max(array, delegate(string e) { return e.Length;}); Here is how you would do it with C# 3.0, .Net 3.5 and Linq, without the function above: string[] array = new string[] {"s","sss","ddsddd","333","44432333"}; array.Max( e => e.Length); A: Here's an attempt, using C# 2.0, at Skilwz's idea. public delegate T GetPropertyValueDelegate<T>(IThing t); public T GetMaximum<T>(GetPropertyValueDelegate<T> getter) where T : IComparable { if (this.Count == 0) return default(T); T max = getter(this[0]); for (int i = 1; i < this.Count; i++) { T ti = getter(this[i]); if (max.CompareTo(ti) < 0) max = ti; } return max; } You'd use it like this: ThingList list; Decimal maxWeight = list.GetMaximum(delegate(IThing t) { return t.Weight; }); A: Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005). You seem to have misunderstood the answers (especially Jon's). You can use option 3 from his answer. If you don't want to use LinqBridge you can still use a delegate and implement the Max method yourself, similar to the method I've posted: delegate Decimal PropertyValue(IThing thing); public class ThingList : IList<IThing> { public Decimal Max(PropertyValue prop) { Decimal result = Decimal.MinValue; foreach (IThing thing in this) { result = Math.Max(result, prop(thing)); } return result; } } Usage: ThingList lst; lst.Max(delegate(IThing thing) { return thing.Age; }); A: How about a generalised .Net 2 solution? public delegate A AggregateAction<A, B>( A prevResult, B currentElement ); public static Tagg Aggregate<Tcoll, Tagg>( IEnumerable<Tcoll> source, Tagg seed, AggregateAction<Tagg, Tcoll> func ) { Tagg result = seed; foreach ( Tcoll element in source ) result = func( result, element ); return result; } //this makes max easy public static int Max( IEnumerable<int> source ) { return Aggregate<int,int>( source, 0, delegate( int prev, int curr ) { return curr > prev ? curr : prev; } ); } //but you could also do sum public static int Sum( IEnumerable<int> source ) { return Aggregate<int,int>( source, 0, delegate( int prev, int curr ) { return curr + prev; } ); } A: If you were you using .NET 3.5 and LINQ: Decimal result = myThingList.Max(i => i.Weight); That would make the calculation of Min and Max fairly trivial. A: Yes, you should use a delegate and anonymous methods. For an example see here. Basically you need to implement something similar to the Find method of Lists. Here is a sample implementation public class Thing { public int theInt; public char theChar; public DateTime theDateTime; public Thing(int theInt, char theChar, DateTime theDateTime) { this.theInt = theInt; this.theChar = theChar; this.theDateTime = theDateTime; } public string Dump() { return string.Format("I: {0}, S: {1}, D: {2}", theInt, theChar, theDateTime); } } public class ThingCollection: List<Thing> { public delegate Thing AggregateFunction(Thing Best, Thing Candidate); public Thing Aggregate(Thing Seed, AggregateFunction Func) { Thing res = Seed; foreach (Thing t in this) { res = Func(res, t); } return res; } } class MainClass { public static void Main(string[] args) { Thing a = new Thing(1,'z',DateTime.Now); Thing b = new Thing(2,'y',DateTime.Now.AddDays(1)); Thing c = new Thing(3,'x',DateTime.Now.AddDays(-1)); Thing d = new Thing(4,'w',DateTime.Now.AddDays(2)); Thing e = new Thing(5,'v',DateTime.Now.AddDays(-2)); ThingCollection tc = new ThingCollection(); tc.AddRange(new Thing[]{a,b,c,d,e}); Thing result; //Max by date result = tc.Aggregate(tc[0], delegate (Thing Best, Thing Candidate) { return (Candidate.theDateTime.CompareTo( Best.theDateTime) > 0) ? Candidate : Best; } ); Console.WriteLine("Max by date: {0}", result.Dump()); //Min by char result = tc.Aggregate(tc[0], delegate (Thing Best, Thing Candidate) { return (Candidate.theChar < Best.theChar) ? Candidate : Best; } ); Console.WriteLine("Min by char: {0}", result.Dump()); } } The results: Max by date: I: 4, S: w, D: 10/3/2008 12:44:07 AM Min by char: I: 5, S: v, D: 9/29/2008 12:44:07 AM
{ "language": "en", "url": "https://stackoverflow.com/questions/152613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How can I know on the client side when the HTTP handler is done processing? Probably a long question for a simple solution, but here goes... I have a custom made silverlight control for selecting multiple files and sending them to the server. It sends files to a general handler (FileReciever.ashx) using the OpenWriteAsync method of a WebCLient control. Basically, the silverlight code does something like this for each file: WebClient client = new WebClient(); client.OpenWriteCompleted += (sender, e) => { PushData(data, e.Result); e.Result.Close(); data.Close(); }; client.OpenWriteAsync(handlerUri); The server side handler simply reads the incoming stream, and then does some more processing with the resulting byte array. THE PROBLEM is that client side OpenWriteCompleted is done as soon as all the data has been sent over the wire. My code will then contine with the next file. What I really want is to wait until the ASHX handler has finished with all it's processing of that request. How do I do that? Any wait mechanism on WebClient? Any callback I can do on the HttpContext in the handler? Should I use some other kind of transfer technique? Please advice! A: The same question has been asked in Silverlight forums. The Microsoft endorsed answer was that you can't do that with WebClient and OpenWriteAsync. You need to either user UploadStringAsync or an HttpWebRequest. A: Hrm, maybe a simple solutioin could be to tag the url with a GUID(the guid being unique per file, or transfer, whatever makes sense to your situatuation). Then you can have another simple web service that is capable of checking on the status of the other service, based on the guid, and have your silverlight client query that new service for its processing status(by passing the new web service the guid of the past transfer). A: I'm assuming that you're concerned that the data being returned from the handler is taking a long time to transfer and the server is not being utilized during that time. There isn't a way to tell when the server is done processing, so I don't think you can do this without changing your architecture. I would have your handler only an identifier of some sort (like a GUID or int) that can be used to retrieve the result of the handler in another request. So the page would call the handler, the handler would store the result and return the identifier, the page would call the handler the second time and call another handler to get the result of the first call. This would keep your server in use while your data was transferring. A: Or you can probably do it with JavaScript (jQuery)... if you don't mind using JavaScript that is. A: If files are not very big, and is feasible to keep each of them in memory, an ugly yet effective solution is converting them to strings and sending them using the UploadStringAsync method. Avoid this approach if file size is unbounded, but if you can now that they will be relatively small, it is possible to use this approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/152618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Wordpress Site Monitoring software / service What do you use to monitor the uptime / performance of your websites, specifically those based on a PHP/MySQL platform like Wordpress? I'm looking for something that alerts me if the site is down, or performing too slowly, and has some useful (not volumeous!) charts showing me any potential problems, and what to do about them. Thanks! A: We along with the usual Nagios, we use Pingdom. It comes with lots of default checks. For example it also reports how fast your website is or since they employ tests from different locations you get a nice graph how accessible your website was. To put some sense into it, add a reference check (e.g. google) and see how you perform. Aside from HTTP etc. you can also check other services (mail, database, etc.). If they are not reachable from the outside, you can always create a script that outputs a standard "OK" and have Pingdom check on that, and report back if the output changed. I should add that Pingdom is not a free service. But we've been using them for 10 months now and they haven't troubled us. :) A: Try looking at Zabbix http://www.zabbix.com/ * *WEB performance monitoring *WEB availability monitoring *Support of POST and GET methods A: Try out Insping also * *performance monitoring *availability monitoring *e-mail and SMS alerts
{ "language": "en", "url": "https://stackoverflow.com/questions/152623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Idiomatic C++ for reading from a const map For an std::map<std::string, std::string> variables, I'd like to do this: BOOST_CHECK_EQUAL(variables["a"], "b"); The only problem is, in this context variables is const, so operator[] won't work :( Now, there are several workarounds to this; casting away the const, using variables.count("a") ? variables.find("a")->second : std::string() or even making a function wrapping that. None of these seem to me to be as nice as operator[]. What should I do? Is there a standard way of doing this (beautifully)? Edit: Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function. A: find is the idiomatic form. Casting away const is almost always a bad idea. You'd have to guarantee that no write operation is performed. While this can be reasonably expected of a read access on a map, the specification doesn't say anything about this. If you know that the value exists you can of course forego the test using count (which is quite inefficient, anyway, since it means traversing the map twice. Even if you don't know whether the element exists I wouldn't use this. Use the following instead: T const& item(map<TKey, T> const& m, TKey const& key, T const& def = T()) { map<TKey, T>::const_iterator i = m.find(key); return i == m.end() ? def : i->second; } /EDIT: As Chris has correctly pointed out, default-construction of objects of type T might be expensive, especially since this is done even if this object isn't actually needed (because the entry exists). If this is the case, don't use the default value for the def argument in the above case. A: An interesting aside, there are two ways do the template type discovery in the get implementation that was accepted (the one that gets the value or returns a default constructed object). One, you can do what was accepted and have: template <typename K, typename V> V get1(const std::map<K, V>& theMap, const K const key) { std::map<K, V>::const_iterator iter(theMap.find(key)); return iter != theMap.end() ? iter->second : V(); } or you can use the map type and get the types off of that: template<typename T> typename T::mapped_type get2(const T& theMap, const typename T::key_type& key) { typename T::const_iterator itr = theMap.find(key); return itr != theMap.end() ? itr->second : typename T::mapped_type(); } The advantage of this is that the type of the key being passed in doesn't play in the type discovery and it can be something that can be implicitly converted to a key. For example: std::map<std::string, int> data; get1(data, "hey"); // doesn't compile because the key type is ambiguous get2(data, "hey"); // just fine, a const char* can be converted to a string A: template <typename K, typename V> V get(std::map<K, V> const& map, K const& key) { std::map<K, V>::const_iterator iter(map.find(key)); return iter != map.end() ? iter->second : V(); } Improved implementation based on comments: template <typename T> typename T::mapped_type get(T const& map, typename T::key_type const& key) { typename T::const_iterator iter(map.find(key)); return iter != map.end() ? iter->second : typename T::mapped_type(); } A: Casting away const is wrong, because operator[] on map<> will create the entry if it isn't present with a default constructed string. If the map is actually in immutable storage then it will fail. This must be so because operator[] returns a non-const reference to allow assignment. (eg. m[1] = 2) A quick free function to implement the comparison: template<typename CONT> bool check_equal(const CONT& m, const typename CONT::key_type& k, const typename CONT::mapped_type& v) { CONT::const_iterator i(m.find(k)); if (i == m.end()) return false; return i->second == v; } I'll think about syntactic sugar and update if I think of something. ... The immediate syntactic sugar involved a free function that does a map<>::find() and returns a special class that wraps map<>::const_iterator, and then has overloaded operator==() and operator!=() to allow comparison with the mapped type. So you can do something like: if (nonmutating_get(m, "key") == "value") { ... } I'm not convinced that is much better than: if (check_equal(m, "key", "value")) { ... } And it is certainly much more complex and what is going on is much less obvious. The purpose of the object wrapping the iterator is to stop having default constructed data objects. If you don't care, then just use the "get" answer. In response to the comment about the get being preferred over a comparison in the hope of finding some future use, I have these comments: * *Say what you mean: calling a function called "check_equal" makes it clear that you are doing an equality comparison without object creation. *I recommend only implementing functionality once you have a need. Doing something before then is often a mistake. *Depending on the situation, a default constructor might have side-effects. If you are comparing, why do anything extra? *The SQL argument: NULL is not equivalent to an empty string. Is the absence of a key from your container really the same as the key being present in your container with a default constructed value? Having said all that, a default constructed object is equivalent to using map<>::operator[] on a non-const container. And perhaps you have a current requirement for a get function that returns a default constructed object; I know I have had that requirement in the past. A: Indeed, operator[] is a non-const one on std::map, since it automatically inserts a key-value pair in the map if it weren't there. (Oooh side-effects!) The right way is using map::find and, if the returned iterator is valid (!= map.end()), returning the second, as you showed. map<int, int> m; m[1]=5; m[2]=6; // fill in some couples ... map<int,int>::const_iterator it = m.find( 3 ); if( it != m.end() ) { int value = it->second; // ... do stuff with value } You could add a map::operator[]( const key_type& key ) const in a subclass of the std::map you're using, and assert the key to be found, after which you return the it->second. A: std::map<std::string, std::string>::const_iterator it( m.find("a") ); BOOST_CHECK_EQUAL( ( it == m.end() ? std::string("") : it->second ), "b" ); That doesn't look too bad to me... I probably wouldn't write a function for this. A: Following up xtofl's idea of specializing the map container. Will the following work well? template <typename K,typename V> struct Dictionary:public std::map<K,V> { const V& operator[] (const K& key) const { std::map<K,V>::const_iterator iter(this->find(key)); BOOST_VERIFY(iter!=this->end()); return iter->second; } };
{ "language": "en", "url": "https://stackoverflow.com/questions/152643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Different item template for each item in a WPF List? I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this? A: Have a look at the ItemTemplateSelector property of your list control. You can point it to a custom TemplateSelector and decide which template to use in code. Here's a blog post describing TemplateSelectors: http://blogs.interknowlogy.com/johnbowen/archive/2007/06/21/20463.aspx Edit: Here's a better post: http://blog.paranoidferret.com/index.php/2008/07/16/wpf-tutorial-how-to-use-a-datatemplateselector/ A: the ItemTemplateSelector will work but I think it is easier to create multiple DataTemplates in your resource section and then just giving each one a DataType. This will automatically then use this DataTemplate if the items generator detects the matching data type? <DataTemplate DataType={x:Type local:ObjectA}> ... </DataTemplate> Also make sure that you have no x:Key set for the DataTemplate. Read more about this approach here
{ "language": "en", "url": "https://stackoverflow.com/questions/152664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to prevent Windows Installer from running each time Access 2003 and 2007 start when there are installed on the same machine? Is it possible to prevent the Windows Installer from running every time Access 2003 and Access 2007 are started, when they are both installed on the same machine at the same time..? Like many developers I need to run more than 1 version of MS Access. I have just installed Access 2007. If I open Access 2003 and then open Access 2007 I have to wait 3mins for the 'Configuring Microsoft Office Enterprise 2007..." dialog. Then if I open Access 2003 again it takes another 30secs or so to configure that. PLEASE NOTE: I am using shortcuts to open the files that include the full path to Access. Eg to open Access 2007: "C:\program files\microsoft office 12\office12\msaccess.exe" "C:\test.accdb" and for 2003: "C:\program files\microsoft office 11\office11\msaccess.exe" "C:\test.mdb" A: The fix to the problem is very simple as it turns out - simply run the following commands (by pressing the Windows Key+R or typing it into the Start/Run command box. Use the line with Office\11.0 if you have Office 2003 installed and Office\12.0 if you have Office 2007 installed. You can use both if you have both installed : reg add HKCU\Software\Microsoft\Office\11.0\Word\Options /v NoReReg /t REG_DWORD /d 1 reg add HKCU\Software\Microsoft\Office\12.0\Word\Options /v NoReReg /t REG_DWORD /d 1 That is it. Office 2007 might want to have one more spin round the block with it's configuration dialog box, but that should be it. C: \Program Files>Common Files>microsoft shared>OFFICE12>Office Setup Controller>SETUP.exe change to SETUPold.exe [HKEY_CURRENT_USER\Software\Classes\Access.Application] This key will cause the config screen to constantly cycle everytime you open Access 2007. By deleting the key and everything under it, it fixes the cycling problem and Access 2007 opens right away. A: This is caused by Windows Installer, which is used by both installers. Advertised shortcuts as used by both Office 2003 and Office 2007 invoke Windows Installer to check that the entire feature is installed properly; the installer detects that something else (in this case the other product) has registered the file extensions used by Access (possibly the ProgIds as well) and decides that a repair is necessary, so it invokes the 'Configuring Office' dialog and proceeds to reinstall various components. To avoid this, run Access from Program Files directly; create shortcuts if you'll be doing this frequently. A: Want to cut it down to about 20 seconds to reconfigure Access 2007 after opening Access 2003? Download and install Office 2007 sp1: http://www.microsoft.com/downloads/details.aspx?FamilyId=9EC51594-992C-4165-A997-25DA01F388F5&displaylang=en Btw, you can't avoid the reconfiguration between Access 2007 and earlier versions. Access 2007 uses some of the same registry keys as earlier versions and they have to be rewritten when opening Access 2007. A: The best workaround I've found for this is to use VMWare Thinapp to virtualize one (or more) of the offending versions of Access: http://www.vmware.com/products/thinapp/ It's a little more lightweight than a full Virtual PC / VMWare / etc installation, but unfortunately still a bit of a hassle to set up and not free. A: Just Install Office 2007 Sp2, that works.
{ "language": "en", "url": "https://stackoverflow.com/questions/152670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DataReader within try block causing potential null reference error There is probably is simple fix for this but I currently have code similar to dim dr as dbDataReader try dr = connection.getDataReader(sql_str) Catch ex as sqlClientException log.error(ex) finally if not IsNothing(dr) then dr.close end if end try However Visual Studio still warns me that the if not IsNothing(dr) then dr.close end if Can cause a NullReferenceException. What is the best way to mitigate this? I can't move the declaration into the try block. A: If GetDataReader throws, dr will not be assigned and will still have its initial value. VB.NET does initialise references to Nothing, but the compiler will not let you rely on that. If using .NET 2.0, I would recommend a Using statement: Using dr As DbDataReader = connection.GetDataReader(sql_str) Try ' Do something with dr ' Catch ex As SqlClientException log.error(ex) End Try End Using A: Explicitly initialize the dr declaration to Nothing as such: Dim dr As DbDataReader = Nothing And the warning will disappear. A: Your code is correct. In the finally statement, as long as you check to make sure your objects are not null, it won't throw a null reference exception based on what happens in your code. A: I don't remember exactly, how VB.NET initialize variable, but in C# you must set "dr" some value/reference before you use them somewhere. I think this should work: dim dr as dbDataReader try dr = connection.getDataReader(sql_str) Catch ex as sqlClientException log.error(ex) dr = Nothing ' there is the change ' ' finaly block is not necesary ' end try if not IsNothing(dr) then dr.close end if
{ "language": "en", "url": "https://stackoverflow.com/questions/152675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WinForms printing: how can I access the progress dialog? When printing in Windows forms, or doing a print preview, a dialog is displayed with text like Page [P] of [DOC] where [P] is page number and [DOC] is the name of the document. The dialog also contains a button to allow the user to cancel the print job. How can I change the text displayed? What I would prefer is text like Page [P] of [Pages] where [Pages] is the total number of pages, to give the user an indication how long it will take to print all pages. If possible I would also like to show a progress bar, because when a print job is started, I know exactly how many pages will be printed. A: I did this: * *Derive your own class from PrintDocument, handling all printing *Set the print controller to a new StandardPrintController (no dialog displayed then) *Display your own dialog, e.g. display and close in OnBeginPrint and OnEndPrint, update in OnPrintPage If I remember correctly, there was no way to change the text, and since the default dialog is not localizable, we could not use it. It works fine with what I wrote above though.
{ "language": "en", "url": "https://stackoverflow.com/questions/152676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is Eclipse the best IDE for Java? Is Eclipse the best IDE for Java? If not, is there something better? I want to know and possibly try it out. Thanks. A: I used IntelliJ for almost 5+ years (from v1.5 to v7) and around 8 months ago I migrated to IBM RAD (which is built on top of old eclipse platform) and around 3 months ago I settled down with Eclipse (Ganymede). I used IntelliJ on a mid size projects (with 10k classes) and I'm using Eclipse on one with just few hundreds of classes. I found both of these IDEs (IntelliJ and Eclipse) to be good. IBM RAD is just a waste of money (ofcourse one could be stuck in an IBM shop without choice). IntelliJ has far superior refactoring capabilities and keyboard shortcuts for most of the features compared to Eclipse. It supports importing projects from Eclipse. It has better built in xml handling capabilities (with refactorings applicable almost like for the java code). Built in Intelli Sense is also very good. Eclipse is a great tool and its free. It took me around 1-2 months to get used to Eclipse from IntelliJ (lot of unlearning of shortcuts), but I got hang of Eclipse, it has been pretty smooth. I havent used Eclipse on mid size project. Both IntelliJ and Eclipse have active plugin communities and both integrate well with version control systems, unit test frameworks, application servers and profilers. IntelliJ started becoming slow and bloated starting from v4.0. It was slow with mid size projects. I would not use IntelliJ unless its performance can be improved. I havent used these two IDEs for anything other than java development. If you are a java developer and your company pays for IntelliJ and if your project is not too big, go for it. Otherwise, dont despair: Eclipse is always there. A: I gave Eclipse a 3 months ride at my new work, but after that I found out that normal Maven project can be run in IntelliJ IDEA too (unless it's Eclipse plugin/EMF/something of course ;-)). 3 months are not enough to compare it with 8+ years with IDEA, but it's enough to claim I gave it a fair try. I decided to live with its perspectives (other IDEs don't need them), with its poor debugger (doesn't show date values unless you click on them! etc.), with its comparatively worse completion than IDEA has. Now after all those years IDEA is also free (community edition) and I use it without much trouble. Of course I miss some of those "Ultimate" features of paid version, but it's far better than Eclipse. Biggest difference is the whole mindset needed for both of these IDEs. But after you master the mindset of either I can't understand what can anyone hold to Eclipse - unless you need its plugin ecosystem or you have some serious investments there. Example of "mindset" differences: You have to save in Eclipse, not in IDEA, and I don't care what is better or worse - but you have to save in Eclipse to let him clean up underlined errors that are not errors anymore, etc. ;-) You have to save there in order to get rid of errors in other files too, because other file doesn't see the changes otherwise. I blogged much more about this topic - and yes, I'm biased, though I tried to be as little as possible. But after some time it wasn't simply possible: :-) * *http://virgo47.wordpress.com/2011/01/30/eclipse-vs-intellij-idea/ *http://virgo47.wordpress.com/2011/02/22/from-intellij-idea-to-eclipse-2/ *http://virgo47.wordpress.com/2011/03/24/from-intellij-idea-to-eclipse-3/ *http://virgo47.wordpress.com/2011/04/10/from-intellij-idea-to-eclipse-4/ And no, not even IDEA is perfect, I know it. Because I use it a lot. But it is the best Java IDE if you ask me. Even the Community edition. A: Let me just start out by saying that Eclipse is a fantastic IDE for Java and many other languages. Its plugin architecture and its extensibility are hard to rival and the fact that it's free is a huge plus for smaller teams or tight budgets. A few things that I hate about Eclipse. * *The documentation is really lacking. I don't know who writes the stuff, but if it's not just flatly missing, it's incomplete. If it's not incomplete, then it's just flat out wrong. I have wasted many precious hours trying to use a given feature in Eclipse by walking through its documentation only to discover that it was all trash to begin with. *Despite the size of the project, I have found the community to be very lacking and/or confusing enough to be hard to participate in. I have tried several times to get help on a particular subject or plugin only to be sent to 3 or 4 different newsgroups who all point to the other newsgroup or just plain don't respond. This can be very frustrating, as much smaller open source products that I use are really good about answering questions I have. Perhaps it's simply a function of the size of the community. *If you need functionality beyond the bundled functionality of one of their distros (for instance, the Eclipse for Java EE Developers distro which bundles things like the WTP), I have found the installation process for extra plugins excruciatingly painful. I don't know why they can't make that process simpler (or maybe I'm just spoiled on my Mac at home and don't know how bad it really is out in the 'real' world) but if I'm not just unsuccessful, oftentimes it's a process of multiple hours to get a new plugin installed. This was supposedly one of their goals in 3.4 (to make installation of new projects simpler); if they succeeded, I can't tell. *Documentation in the form of books and actual tutorials is sorely lacking. I want a master walkthrough for something as dense and feature-rich as Eclipse; something that says, 'hey, did you know about this feature and how it can really make you more productive?'. As far as I've found, nothing like that exists. If you want to figure out Eclipse, you've got one option, sit down and play with it (literally play with it, not just see a feature and go and read the documentation for it, because that probably doesn't exist or is wrong). Despite these things, Eclipse really is a great IDE. Its refactoring tooling works tremendously well. The handling of Javadoc works perfectly. All of features we've come to expect of an IDE are their (code completion, templates, integration with various SCMSs, integration with build systems). Its code formatting and cleanup tools are very powerful. I find its build system to work well and intuitively. I think these are the things upon which its reputation is really built. I don't have enough experience with other IDEs or with other distros of Eclipse (I've seen RAD at work quite a few times; I can't believe anyone would pay what they're charging for that) to comment on them, but I've been quite happy with Eclipse for the most part. One tip I have heard from multiple places is that if you want Eclipse without a lot of the hassle that can come with its straight install, go with a for-pay distro of it. My Eclipse is a highly recommended version that I've seen all over the net that is really very affordable (last I heard, $50 for the distro plus a year of free upgrades). If you have the budget and need the added functionality, I'd go with something like that. Anyway, I've tried to be as detailed as I can. I hope this helps and good luck on your search! :) A: [This is not really an answer, just an anecdote. I worked with guys who used emacs heavily loaded with macros and color coded. Crazy! Why do that when there are so many good IDEs out there?] if you know you way around emacs you can code 100x faster then an IDE. And it can handle bunch of diffrent languages so you do not need to change your coding enviroment if you need to code in another language. Works on all operating systems, you can custimize/add anything you want. Even edit files half way across the world over ssh.(no downloading or uploading). Before calling them crazy you gotto use it first. i am sure they are calling you crazy for using an IDE :). A: IntelliJ IDEA was awsome. Now it is just "better than Eclipse". You can code in IDEA several times faster than in Eclipse in my experience (I moved from being an Eclipse early-adopter to IDEA and haven't looked back) but IDEA has a number of flaws: * *Full version is not free. *It hogs memory *Project management is not great *Jetbrains keep bringing out minor enhancements and calling them major releases. IDEA is now slower and buggier than it was a few years ago. And you get charged for the pleasure! (IDEA now has a free Community Edition) I still wouldn't go back though; the code refactorings and intentions in IDEA are just too good. A major version of Eclipse came out a while back and it took me about an hour of searching on the website to figure out what was actually contained in the release which might persuade me back into the fold. Visit JetBrains to see how to sell an IDE! A: It is often said that there are better IDE's for various languages (eg Java) than Eclipse. The power of Eclipse is that it's basically the same IDE for many languages, meaning that if you know you'll have to code in several programming languages (Java, C++, Python) it's a huge advantage that you only have to learn one IDE: Eclipse. A: Eclipse! It can be slow at times and uses a lot of memory but it works well. A: I don't know if Eclipse is THE BEST Java IDE, but it is definitely very decent and my favorite IDE. I tried IntelliJ briefly before, and found that it's pretty similar to Eclipse (IntelliJ might offer some nicer features, but Eclipse is free and open source). I never really tried NetBean because I know Eclipse before I know NetBean. Eclipse is my favorite because: * *Free *Extensible (to a point that you can turn it in to C++ IDE or DB Development IDE) *Open source *I know how to write Eclipse plugin *You can develop a product easily with Eclipse (exp. Lime Wire is Eclipse under the hood) If you are used to using conventional Java IDE like JCreator you might need some time to get used to Eclipse. I remember when I first learned Eclipse, I didn't know how to compile Java source... I would suggest that in order to find the best IDE FOR YOU, try what people recommended (NetBean, Eclipse, and IntelliJ), and see which one you like the most, then stick with it and become an expert of it. Having the right IDE will boost up your productivity a lot in my opinion. A: I am going to have to recommend Oracle JDeveloper. I personally thought that Eclipse was the best Java IDE too at one point. Then I was introduced to Oracle JDeveloper by my job. I find the UI design much better than Eclipse. Also it comes with an incredible amount of features built in including great support for EJB3, JSF, WebServices, etc. It is essentially an IDE for the entire JavaEE stack (and the Oracle ADF framework as well). - All of the tools you will (probably) need for JavaEE development come with this IDE right out of the box, no plugins required (unless you download the minimalist version). A: There is no best IDE. You make it as good as you get used using it. A: Talking about java Ide it is better to go for NetBeans.In My opinion it is better and provide great advantage over other ide but it has disadvantage over Eclipse that it grabs more more while working but do to its features and support i suggest Netbeans than any ide A: Eclipse can't remotely be called an IDE to my opinion. Okay that's exaggerated, I know. It merely reflects my intense agony thanks to eclipse! Whatever you do, it just doesn't work! You always need to fight with it to make it do things the right way. During that time, you're not developing code which is what you're supposed to do, right? eclipse and maven integration: unreliable! Eclipse and ivy integration: unreliable. WTP: buggy buggy buggy! Eclipse and wstl validation: buggy! It complains about not finding URL's out of the blue even though they do exist, and a few days later, without having changed them, it suddenly does find them etc etc. I Could write a frakking book about it. To answer your question: NO ECLIPSE IS NOT EVEN CLOSE THE BEST IDE!!! IntelliJ is supposed to be MUCH better! A: Agreeing with the others. Netbeans is a pretty good IDE which also caters for other languages (PHP, Ruby, C/C++) if you're prone to using any of those. Then you get the added benefit of knowing your way around the IDE when deciding to pick up a new language. To be fair however, I haven't had much time with the eclipse IDE. A: Eclipse was the first IDE to move me off of XEmacs. However, when my employer offered to buy me a Intellij IDEA license if I wanted one it only took 3 days with an evaluation copy to convince me to go for it. It seems like so many small things are just nicer. A: IntelliJ is good one but its not free!!Then NetBeans is also a good option.Also if you are IBM suite WSAD is good A: I'd have to vote for Netbeans as the best one currently. Eclipse is decent, but right now Netbeans is better. A: This is subjective... I find it to be a good tool. It depends what kind of development you're doing - for EJB stuff, many folk would favour Netbeans. It also depends how much you want to spend - I assume you're talking about free IDEs? A: In my opinion if you got the resources to use, then go with eclipse. NetBeans which is awesome like eclipse is another best option, these are the only 2 I've ever used (loved, needed, wanted) Eclipse is hands down the most popular, and for good reason! Hope this helps. A: I'd agree with some of the others out there saying that NetBeans and IntelliJ are both good IDEs. And I'd say that in using all three (Eclipse + other two), that Eclipse is by far my favorite. I found some of the documentation out-dated, but also found the support community very helpful. I started using Eclipse by jumping into the deep end of the pool: writing an RCP before ever learning the IDE. The IDE was intuitive to use, and when I found the right news groups to post to - most of my questions were already answered. The hardest thing for me (and frustrating, admittedly) was knowing how to phrase my search terms in order to get to the answer that was already posted. Remember that Eclipse is still "relatively new" as an IDE player, though given that - it's pretty darn robust. My only complaint about Eclipse is that with each new release, it seems to hog up more resources. With a mid-sized project/workspace, it takes seemingly forever to build (or rebuild) the project. Compared to IntelliJ, it's faster and more intuitive to use. A: Don't forget that Eclipse Platform was started by IBM. There are few platforms out there. * *IBM Websphere Application Developer (WSAD) and/or Rational Application Developer (RAD) which is a Eclipse-type IDE from IBM (actually, that's Eclipse with IBM specialized libraries/plugins). *MyEclipse (never used it but it's another Eclipse-type IDE) *Sun Microsystem's NetBeans. It's too Java-centric as it's designed to create applications purely in java (NetBeans runs in Java). *IntelliJ (to name but a few) *Oracle JDeveloper (I never really liked the directory structure layout JDeveloper creates). The advantage with Eclipse is that it can be customized to your development pleasure, plugins can be written for Eclipse to conform to your needs (e.g. The Eclipse "Easy Explorer" plugin for browsing the directory of your source in Windows Explorer). Eclipse allows you to also incorporate other languages/SDK's, such as C++, Silverlight projects, Android Projects for development. You can also easily manage resources in Eclipse. In my experience NetBeans are resource intensive. Oracle JDeveloper and IntelliJ aren't free though. Oh yes, If you have issues or bugs with Eclipse, Eclipse has the ability to restart and submit the crash to Eclipse servers. A: This is not really an answer, just an anecdote. I worked with guys who used emacs heavily loaded with macros and color coded. Crazy! Why do that when there are so many good IDEs out there? A: I have experience with using JCreator LE. I like it because it is easy to use and it is free. Give it a try if it interests you.
{ "language": "en", "url": "https://stackoverflow.com/questions/152691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "84" }
Q: How can you scan an image with X++ Does anyone know how to scan an image with X++? A: There's no way to do it directly, but you should be able to call the Windows Image Acquisition API via COM
{ "language": "en", "url": "https://stackoverflow.com/questions/152692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Avoid throwing a new exception I have an if condition which checks for value and the it throws new NumberFormatException Is there any other way to code this if (foo) { throw new NumberFormatException } // .. catch (NumberFormatException exc) { // some msg... } A: If you are doing something such as this: try { // some stuff if (foo) { throw new NumberFormatException(); } } catch (NumberFormatException exc) { do something; } Then sure, you could avoid the exception completely and do the 'do something' part inside the conditional block. A: If your aim is to avoid to throw a new exception: if(foo) { //some msg... } else { //do something else } A: Don't throw exceptions if you can handle them in another, more elegant manner. Exceptions are expensive and should only be used for cases where there is something going on beyond your control (e.g. a database server is not responding). If you are trying to ensure that a value is set, and formatted correctly, you should try to handle failure of these conditions in a more graceful manner. For example... if(myObject.value != null && Checkformat(myObject.Value) { // good to go } else { // not a good place to be. Prompt the user rather than raise an exception? } A: In Java, you can try parsing a string with regular expressions before trying to convert it to a number. If you're trying to catch your own exception (why???) you could do this: try { if (foo) throw new NumberFormatException(); } catch(NumberFormatexception) {/* ... */} A: if you are trying to replace the throwing of an exception with some other error handling mechanism your only option is to return or set an error code - the problem is that you then have to go and ensure it is checked elsewhere. the exception is best. A: If you know the flow that will cause you to throw a NumberFormatException, code to handle that case. You shouldn't use Exception hierarchies as a program flow mechanism.
{ "language": "en", "url": "https://stackoverflow.com/questions/152693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: CruiseControl.net : Using SvnLabeller / SvnRevisionLabeller I'm setting up a new project using CruiseControl.net 1.4. I see from ccnet contributions that there are two options for a subversion repository number labeller - a feature that I would really like to make use of. 1) SVNLabeller available from jcxsoftware and 2) Svnrevisionlabeller available from google code My problem is that (1) claims support for ccnet 1.4 but I can't find any documentation on how to configure it. (2) comes with documentation but does not claim to support ccnet 1.4 Can anyone help me with either how to configure SVNLabeller or tell me if Svnrevisionlabeller works with 1.4? A: this is David Keaveny, author/maintainer of SvnRevisionLabeller. I use it against v1.4.2 on a daily basis at work, so I think it's safe to say that it works OK. I should probably update the Google Code site to reflect this. Update: I've updated the project wiki to reflect this. Oh, and I'm also picking up on a bunch of feature requests, so keep an eye open for a new release in the near future. A: Have you looked at David Keaveny’s Blog Post regarding the SVNRevisionLabeller? The link will take you to a detailed post on it's usage. We are currently testing this utility against the current release (1.4) of CCNet without any problems, i.e. it's producing the correct revision and build labels appended to the major/minor digits we specify. Hope this helps A: I'm the author of SVNLabeler. You can get a 1.5 version here: http://svn.jcxsoftware.com/node/216 Here is how you use it: <labeller type="SvnLabeller"> <MajorVersion>1</MajorVersion> <MinorVersion>2</MinorVersion> <BuildNumber>3</BuildNumber> <workingDirectory>c:\path to your code</workingDirectory> <executable>c:\path to\svn.exe</executable> </labeller> The version comes out as: 1.2.3.SVN_REVISION_NUMBER Good luck, Juan
{ "language": "en", "url": "https://stackoverflow.com/questions/152694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open the default browser in Ruby In Python, you can do this: import webbrowser webbrowser.open_new("http://example.com/") It will open the passed in url in the default browser Is there a ruby equivalent? A: Cross-platform solution: First, install the Launchy gem: $ gem install launchy Then, you can run this: require 'launchy' Launchy.open("http://stackoverflow.com") A: Simplest Win solution: `start http://www.example.com` A: Linux-only solution system("xdg-open", "http://stackoverflow.com/") A: This also works: system("start #{link}") A: This should work on most platforms: link = "Insert desired link location here" if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/ system "start #{link}" elsif RbConfig::CONFIG['host_os'] =~ /darwin/ system "open #{link}" elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/ system "xdg-open #{link}" end A: Mac-only solution: system("open", "http://stackoverflow.com/") or `open http://stackoverflow.com/` A: Windows Only Solution: require 'win32ole' shell = WIN32OLE.new('Shell.Application') shell.ShellExecute(...) Shell Execute on MSDN A: You can use the 'os' gem: https://github.com/rdp/os to let your operating system (in the best case you own your OS, meaning not OS X) decide what to do with an URL. Typically this will be a good choice. require 'os' system(OS.open_file_command, 'https://stackoverflow.com') # ~ like `xdg-open stackoverflow.com` on most modern unixoids, # but should work on most other operating systems, too. Note On windows, the argument(s?) to system need to be escaped, see comment section. There should be a function in Rubys stdlib for that, feel free to add it to the comments and I will update the answer. A: If it's windows and it's IE, try this: http://rubyonwindows.blogspot.com/search/label/watir also check out Selenium ruby: http://selenium.rubyforge.org/getting-started.html HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/152699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: How can I search for a multiline pattern in a file? I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using find piped with xargs grep: find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN' But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns. A: @Marcin: awk example non-greedy: awk '{if ($0 ~ /Start pattern/) {triggered=1;}if (triggered) {print; if ($0 ~ /End pattern/) { exit;}}}' filename A: This answer might be useful: Regex (grep) for multi-line search needed To find recursively you can use flags -R (recursive) and --include (GLOB pattern). See: Use grep --exclude/--include syntax to not grep through certain files A: You can use the grep alternative sift here (disclaimer: I am the author). It support multiline matching and limiting the search to specific file types out of the box: sift -m --files '*.py' 'YOUR_PATTERN' (search all *.py files for the specified multiline regex pattern) It is available for all major operating systems. Take a look at the samples page to see how it can be used to to extract multiline values from an XML file. A: perl -ne 'print if (/begin pattern/../end pattern/)' filename A: grep -P also uses libpcre, but is much more widely installed. To find a complete title section of an html document, even if it spans multiple lines, you can use this: grep -P '(?s)<title>.*</title>' example.html Since the PCRE project implements to the perl standard, use the perl documentation for reference: * *http://perldoc.perl.org/perlre.html#Modifiers *http://perldoc.perl.org/perlre.html#Extended-Patterns A: Here is a more useful example: pcregrep -Mi "<title>(.*\n){0,5}</title>" afile.html It searches the title tag in a html file even if it spans up to 5 lines. Here is an example of unlimited lines: pcregrep -Mi "(?s)<title>.*</title>" example.html A: Using ex/vi editor and globstar option (syntax similar to awk and sed): ex +"/string1/,/string3/p" -R -scq! file.txt where aaa is your starting point, and bbb is your ending text. To search recursively, try: ex +"/aaa/,/bbb/p" -scq! **/*.py Note: To enable ** syntax, run shopt -s globstar (Bash 4 or zsh). A: Here is the example using GNU grep: grep -Pzo '_name.*\n.*_description' -z/--null-data Treat the input as a set of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Which has the effect of treating the whole file as one large line. See -z description on grep's manual and also common question no 14 on grep's manual usage page A: Why don't you go for awk: awk '/Start pattern/,/End pattern/' filename A: With silver searcher: ag 'abc.*(\n|.)*efg' Speed optimizations of silver searcher could possibly shine here. A: So I discovered pcregrep which stands for Perl Compatible Regular Expressions GREP. the -M option makes it possible to search for patterns that span line boundaries. For example, you need to find files where the '_name' variable is followed on the next line by the '_description' variable: find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description' Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...
{ "language": "en", "url": "https://stackoverflow.com/questions/152708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "156" }
Q: Could I get in legal trouble for copying a website's stylesheet? I like the simplistic look and design of some of the Microsoft blogs. Alas, I can't join the Microsoft dev party and create my own development blog on the blogs.msdn.com page because I don't work at Microsoft, and I already have my own wordpress blog. I was looking to have my blog styled to one of the default looking themes shown here: http://blogs.msdn.com/jmeier/default.aspx Could Microsoft take legal action against me if I used a stylesheet from their page? If I made my page 'based' off their stylesheet, e.g. written from the ground up, would that be copyright infringement? A: You could. You probably wont. Most importantly: Why bother? CSS is pretty simple, it's essentially positioning a bunch of boxes around, and colouring them.. Just look at their CSS files and layout, and reimplement it yourself.. It'll probably end up easier than reworking their CSS to work with your site (unless you completely copy their site, including the CSS, HTML and layout images), plus you'll learn a lot about CSS while you do it. A: AFAIK, and IANAL, and all those other useful acronyms.... Under UK law, I believe you can get away with this kind of thing as long as there are at least 6 demonstrable and obvious differences between the copied article and the copy. Since I'm not a lawyer, I'm not going to go into what constitutes a demonstrable and obvious difference, but I would imagine a colour change would count as one... You would obviously have to check the laws of your region before taking this advice. A: Could Microsoft take legal action against me if I used a stylesheet from their page? Absolutely, since you infringed their copyright. On the other hand, it's debatable whether the stylesheet alone constitues a sufficient threshold of originality to justify legal actions1. At the least, taking without asking is often considered rude. ;-) 1) No. It certainly doesn't. A sophisticated design however will. A: Of course you will, Microsoft China was in a similar situation back when their Juku Blogging Service was found out to be a rip-off of Plurk, and yes, line by line code copying. Microsoft responded with: “Microsoft takes intellectual property seriously, and we are currently investigating these allegations. It may take some time due to the time zone differences with Beijing.” when they were asked about it. Here's a link to that article I was referring to. A: Yes, you can get in legal trouble for copying a site's stylesheet since it's typically a copyright violation. Worse, you could get publicly bashed on blogs like youthoughtwewouldntnotice.com, making such blog posts about you high-ranked Google results for your name, thus tarnishing your reputation irreversibly. Don't do it, it's not worth the risks. A: I think Microsoft uses one of the templates that come out of the box with community server. But even if they didn't, I haven't heard of a case of someone having a cease and desist based on leveraging someone else's css. A: Technically, they could. It is a violation of their copyright. If they exercised this right, however, it would likely be a PR disaster. I think you're probably safe if you use it. A: This would be a horrible idea, but you couldn't get into any trouble if you simply linked to their css. You could also link to a copy of their css that was located somewhere else that is not associated with your website ;o) Just some thoughts ...
{ "language": "en", "url": "https://stackoverflow.com/questions/152712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Multiple correct results with Hamcrest (is there an or-matcher?) I am relatively new to matchers. I am toying around with hamcrest in combination with JUnit and I kinda like it. Is there a way, to state that one of multiple choices is correct? Something like assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest The method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java? (I am open to hamcrest-alternatives) A: marcos is right, but you have a couple other options as well. First of all, there is an either/or: assertThat(result, either(is(1)).or(is(2))); but if you have more than two items it would probably get unwieldy. Plus, the typechecker gets weird on stuff like that sometimes. For your case, you could do: assertThat(result, isOneOf(1, 2, 3)) or if you already have your options in an array/Collection: assertThat(result, isIn(theCollection)) See also Javadoc. A: assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3))) From Hamcrest tutorial: anyOf - matches if any matchers match, short circuits (like Java ||) See also Javadoc. Moreover, you could write your own Matcher, which is quite easy to do. A: In addition to the anyOf, you could also go for the either option, but it has a slightly different syntax: assertThat(result, either(is(1)).or(is(2)).or(is(3))))
{ "language": "en", "url": "https://stackoverflow.com/questions/152714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "83" }
Q: What online resources are there to learn about VxWorks? What are some of the online resources you have found useful to learn about VxWorks? A: Tornado II/VxWorks FAQ is a good source of basic information, related to the 5.x version of VxWorks. VxWorks Cookbook also has some good stuff VxWorks Usenet Group is good to see the sort of things that stump people Collection of VxWorks tutorials links (not all of them are live) This Google Search brings up a few links to online versions of the reference manuals.
{ "language": "en", "url": "https://stackoverflow.com/questions/152723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: GDI+ / C#: How to save an image as EMF? If you use Image.Save Method to save an image to a EMF/WMF, you get an exception (http://msdn.microsoft.com/en-us/library/ktx83wah.aspx) Is there another way to save the image to an EMF/WMF? Are there any encoders available? A: A metafile is a file which records a sequence of GDI operations. It is scalable because the original sequence of operations that generated the picture are captured, and therefore the co-ordinates that were recorded can be scaled. I think, in .NET, that you should create a Metafile object, create a Graphics object using Graphics.FromImage, then perform your drawing steps. The file is automatically updated as you draw on it. You can find a small sample in the documentation for Graphics.AddMetafileComment. If you really want to store a bitmap in a metafile, use these steps then use Graphics.DrawImage to paint the bitmap. However, when it is scaled it will be stretched using StretchBlt. A: The question was: "Is there another way to save the image to an EMF/WMF?" Not "what is metafile" or "how to create metafile" or "how to use metafile with Graphics". I also look for answer for this question "how to save EMF/WMF" In fact if you use: Graphics grfx = CreateGraphics(); MemoryStream ms = new MemoryStream(); IntPtr ipHdc = grfx.GetHdc(); Metafile mf = new Metafile(ms, ipHdc); grfx.ReleaseHdc(ipHdc); grfx.Dispose(); grfx = Graphics.FromImage(mf); grfx.FillEllipse(Brushes.Gray, 0, 0, 100, 100); grfx.DrawEllipse(Pens.Black, 0, 0, 100, 100); grfx.DrawArc(new Pen(Color.Red, 10), 20, 20, 60, 60, 30, 120); grfx.Dispose(); mf.Save(@"C:\file.emf", ImageFormat.Emf); mf.Save(@"C:\file.png", ImageFormat.Png); In both cases image is saved as format png. And this is the problem which I cannot solve :/ A: Image is an abstract class: what you want to do depends on whether you are dealing with a Metafile or a Bitmap. Creating an image with GDI+ and saving it as an EMF is simple with Metafile. Per Mike's post: var path = @"c:\foo.emf" var g = CreateGraphics(); // get a graphics object from your form, or wherever var img = new Metafile(path, g.GetHdc()); // file is created here var ig = Graphics.FromImage(img); // call drawing methods on ig, causing writes to the file ig.Dispose(); img.Dispose(); g.ReleaseHdc(); g.Dispose(); This is what you want to do most of the time, since that is what EMF is for: saving vector images in the form of GDI+ drawing commands. You can save a Bitmap to an EMF file by using the above method and calling ig.DrawImage(your_bitmap), but be aware that this does not magically covert your raster data into a vector image. A: The answer by erikkallen is correct. I tried this from VB.NET, and had to use 2 different DllImports to get it to work: <System.Runtime.InteropServices.DllImportAttribute("gdi32.dll", EntryPoint:="GetEnhMetaFileBits")> _ Public Shared Function GetEnhMetaFileBits(<System.Runtime.InteropServices.InAttribute()> ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData As IntPtr) As UInteger End Function <System.Runtime.InteropServices.DllImportAttribute("gdi32.dll", EntryPoint:="GetEnhMetaFileBits")> _ Public Shared Function GetEnhMetaFileBits(<System.Runtime.InteropServices.InAttribute()> ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData() As Byte) As UInteger End Function The first import is used for the first call to get the emf size. The second import to get the actual bits. Alternatively you could use: Dim h As IntPtr = mf.GetHenhmetafile() CopyEnhMetaFileW(h, FileName) This copies the emf bits directly to the named file. A: You also need to close the CopyEnhMetaFile handler: IntPtr ptr2 = CopyEnhMetaFile(iptrMetafileHandle, "image.emf"); DeleteEnhMetaFile(ptr2); // Delete the metafile from memory DeleteEnhMetaFile(iptrMetafileHandle); Otherwise, you cannot delete the file because it's still used by the process. A: If I remember correctly, it can be done with a combination of the Metafile.GetHenhmetafile(), the API GetEnhMetaFileBits() and Stream.Write(), something like [DllImport("gdi32")] static extern uint GetEnhMetaFileBits(IntPtr hemf, uint cbBuffer, byte[] lpbBuffer); IntPtr h = metafile.GetHenhMetafile(); int size = GetEnhMetaFileBits(h, 0, null); byte[] data = new byte[size]; GetEnhMetaFileBits(h, size, data); using (FileStream w = File.Create("out.emf")) { w.Write(data, 0, size); } // TODO: I don't remember whether the handle needs to be closed, but I guess not. I think this is how I solved the problem when I had it. A: I was looking for a way to save the GDI instructions in a Metafile object to a EMF file. Han's post helped me solve the problem. This was before I joined SOF. Thank you, Han. Here is what I tried. [DllImport("gdi32.dll")] static extern IntPtr CopyEnhMetaFile( // Copy EMF to file IntPtr hemfSrc, // Handle to EMF String lpszFile // File ); [DllImport("gdi32.dll")] static extern int DeleteEnhMetaFile( // Delete EMF IntPtr hemf // Handle to EMF ); // Code that creates the metafile // Metafile metafile = ... // Get a handle to the metafile IntPtr iptrMetafileHandle = metafile.GetHenhmetafile(); // Export metafile to an image file CopyEnhMetaFile( iptrMetafileHandle, "image.emf"); // Delete the metafile from memory DeleteEnhMetaFile(iptrMetafileHandle); A: I would recommend avoiding such extern's and unmanaged cruft in a managed .NET app. Instead, I'd recommend something a bit more like the managed solution given in this thread: Convert an image into WMF with .NET? P.S. I am answering this old thread because this was the best answer I had found, but then ended up developing a managed solution, which then lead me to the link above. So, to save others that time, I figured I'd point this one to that one. A: It appears there is much confusion over vector vs. bitmap. All of the code in this thread generates bitmap (non-vector) files - it does not preserve the vector GDI calls. To prove this to yourself, download the "EMF Parser" tool and inspect the output files: http://downloads.zdnet.com/abstract.aspx?docid=749645. This issue has caused many developers considering anguish. Sure would be nice if Microsoft would fix this and properly support their own EMF format.
{ "language": "en", "url": "https://stackoverflow.com/questions/152729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Should a client handling process be added to the supervisor tree? in Erlang I have a supervisor-tree of processes, containing one that accepts tcp/ip connections. For each incoming connection I spawn a new process. Should this process be added to the supervisor tree or not? Regards, Steve A: Yes, you should add these processes to the supervision heirarchy as you want them to be correctly/gracefully shutdown when your application is stopped. (Otherwise you end up leaking connections that will fail as the application infrastructure they depend on been shutdown). You could create a simple_one_for_one strategy supervisor say yourapp_client_sup that has a child spec of {Id, {yourapp_client_connection, start_link_with_socket, []}, Restart, Shutdown, worker, temporary}. The temporary type here is important because there's normally no useful restart strategy for a connection handler - you can't connect out to the client to restart the connection. temporary here will cause the supervisor to report the connection handler exit but otherwise ignore it. The process that does gen_tcp:accept will then create the connection handler process by doing supervisor:start_child(yourapp_client_sup, [Socket,Options,...]) rather than yourapp_client_sup:start_link(Socket, Options, ...). Ensure that the youreapp_client_connection:start_link_with_socket function starts the child via gen_server or proc_lib functions (a requirement of the supervisor module) and that the function transfers control of the socket to the child with gen_tcp:controlling_process otherwise the child won't be able to use the socket. An alternate approach is to create a dummy yourapp_client_sup process that yourclient_connection_handler processes can link to at startup. The yourapp_client_sup process will just exist to propagate EXIT messages from its parent to the connection handler processes. It will need to trap exists and ignore all EXIT messages other than those from its parent. On the whole, I prefer to use the simple_one_for_one supervisor approach. A: If you expect these processes to be many, it could be a good idea to add a supervisor under your main supervisor as to separate responsibility (and maybe use the simple_one_for_one setting to make things simpler, maybe even simpler than your current case). The thing is, if you need to control these processes, it's always nice to have a supervisor. If it doesn't matter if they succeed or not, then you might not need one. But then again, I always argue that that is sloppy coding. ;-) The only thing I wouldn't do, is to add them to your existing tree, unless it is very obvious where they come from and they're fairly few.
{ "language": "en", "url": "https://stackoverflow.com/questions/152744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Optimising C++ 2-D arrays I need a way to represent a 2-D array (a dense matrix) of doubles in C++, with absolute minimum accessing overhead. I've done some timing on various linux/unix machines and gcc versions. An STL vector of vectors, declared as: vector<vector<double> > matrix(n,vector<double>(n)); and accessed through matrix[i][j] is between 5% and 100% slower to access than an array declared as: double *matrix = new double[n*n]; accessed through an inlined index function matrix[index(i,j)], where index(i,j) evaluates to i+n*j. Other ways of arranging a 2-D array without STL - an array of n pointers to the start of each row, or defining the whole thing on the stack as a constant size matrix[n][n] - run at almost exactly the same speed as the index function method. Recent GCC versions (> 4.0) seem to be able to compile the STL vector-of-vectors to nearly the same efficiency as the non-STL code when optimisations are turned on, but this is somewhat machine-dependent. I'd like to use STL if possible, but will have to choose the fastest solution. Does anyone have any experience in optimising STL with GCC? A: My guess would be the fastest is, for a matrix, to use 1D STL array and override the () operator to use it as 2D matrix. However, the STL also defines a type specifically for non-resizeable numerical arrays: valarray. You also have various optimisations for in-place operations. valarray accept as argument a numerical type: valarray<double> a; Then, you can use slices, indirect arrays, ... and of course, you can inherit the valarray and define your own operator()(int i, int j) for 2D arrays ... A: If you're using GCC the compiler can analyze your matrix accesses and change the order in memory in certain cases. The magic compiler flag is defined as: -fipa-matrix-reorg Perform matrix flattening and transposing. Matrix flattening tries to replace a m-dimensional matrix with its equivalent n-dimensional matrix, where n < m. This reduces the level of indirection needed for accessing the elements of the matrix. The second optimization is matrix transposing that attemps to change the order of the matrix's dimensions in order to improve cache locality. Both optimizations need fwhole-program flag. Transposing is enabled only if profiling information is avaliable. Note that this option is not enabled by -O2 or -O3. You have to pass it yourself. A: Very likely this is a locality-of-reference issue. vector uses new to allocate its internal array, so each row will be at least a little apart in memory due to each block's header; it could be a long distance apart if memory is already fragmented when you allocate them. Different rows of the array are likely to at least incur a cache-line fault and could incur a page fault; if you're really unlucky two adjacent rows could be on memory lines that share a TLB slot and accessing one will evict the other. In contrast your other solutions guarantee that all the data is adjacent. It could help your performance if you align the structure so it crosses as few cache lines as possible. vector is designed for resizable arrays. If you don't need to resize the arrays, use a regular C++ array. STL operations can generally operate on C++ arrays. Do be sure to walk the array in the correct direction, i.e. across (consecutive memory addresses) rather than down. This will reduce cache faults. A: My recommendation would be to use Boost.UBLAS, which provides fast matrix/vector classes. A: To be fair depends on the algorithms you are using upon the matrix. The double name[n*m] format is very fast when you are accessing data by rows both because has almost no overhead besides a multiplication and addition and because your rows are packed data that will be coherent in cache. If your algorithms access column ordered data then other layouts might have much better cache coherence. If your algorithm access data in quadrants of the matrix even other layouts might be better. Try to make some research directed at the type of usage and algorithms you are using. That is specially important if the matrix are very large, since cache misses may hurt your performance way more than needing 1 or 2 extra math operations to access each address. A: You could just as easily do vector< double >( n*m ); A: You may want to look at the Eigen C++ template library at http://eigen.tuxfamily.org/ . It generates AltiVec or sse2 code to optimize the vector/matrix calculations. A: There is the uBLAS implementation in Boost. It is worth a look. http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/matrix.htm A: Another related library is Blitz++: http://www.oonumerics.org/blitz/docs/blitz.html Blitz++ is designed to optimize array manipulation. A: I have done this some time back for raw images by declaring my own 2 dimensional array classes. In a normal 2D array, you access the elements like: array[2][3]. Now to get that effect, you'd have a class array with an overloaded [] array accessor. But, this would essentially return another array, thereby giving you the second dimension. The problem with this approach is that it has a double function call overhead. The way I did it was to use the () style overload. So instead of array[2][3], change I had it do this style array(2,3). That () function was very tiny and I made sure it was inlined. See this link for the general concept of that: http://www.learncpp.com/cpp-tutorial/99-overloading-the-parenthesis-operator/ You can template the type if you need to. The difference I had was that my array was dynamic. I had a block of char memory I'd declare. And I employed a column cache, so I knew where in my sequence of bytes the next row began. Access was optimized for accessing neighbouring values, because I was using it for image processing. It's hard to explain without the code but essentially the result was as fast as C, and much easier to understand and use.
{ "language": "en", "url": "https://stackoverflow.com/questions/152745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is java object serialization compatible between 1.5 and 1.6 I am wondering whether it is safe to mix jdk 1.5 and 1.6 (Java 6) object serialization (biderctional communication). I searched for an explicit statement from sun concerning this question but did not succeed. So, besides the technical feasability I am searching for an "official" statement concerning the problem. A: The serialization mechanism in 1.5 and 1.6 is compatible. Thus, the same code compiled/running in a 1.5 and 1.6 context can exchange serialized objects. Whether the two VM instances have the same/compatible version of the class (as may be indicated by the serialVersionUID field) is a different question not related to the JDK version. If you have one serializable Foo.java and use this in a 1.5 and 1.6 JDK/VM, serialized instances of Foo created by one V; can be deserialized by the other. A: After testing with a serialized object written to a file using the ObjectOutputStream in a Java 1.5 program, then running a read with a ObjectInputStream in a Java 1.6 program I can say this worked without any issue. A: I would quickly add that it is possible to change the class but forget to change the serialVersionUID. So it is incorrect that "If the class defines a serialVersionUID, and this does not change, the class is guaranteed to be compatible." Rather, having the same serialVersionUID is the way an API promises backward compatibility. A: Unless otherwise stated, this should be part of binary compatibility. Swing classes are explicitly not compatible between versions. If you find a problem with other classes, report a bug on bugs.sun.com. A: Have you read the Java Object Serialization Specification? There is a topic on versioning. There is also an article for class implementers: Discover the secrets of the Java Serialization API. Each release of Java is accompanied by compatibility notes. From the Java 6 spec on serialization: The goals are to: * *Support bidirectional communication between different versions of a class operating in different virtual machines by: * *Defining a mechanism that allows JavaTM classes to read streams written by older versions of the same class. *Defining a mechanism that allows JavaTM classes to write streams intended to be read by older versions of the same class. *Provide default serialization for persistence and for RMI. *Perform well and produce compact streams in simple cases, so that RMI can use serialization. *Be able to identify and load classes that match the exact class used to write the stream. *Keep the overhead low for nonversioned classes. *Use a stream format that allows the traversal of the stream without having to invoke methods specific to the objects saved in the stream. A: The serialization mechanism itself has not changed. For individual classes it will depend on the specific class. If a class has a serialVersionUID field, this is supposed to indicate serialization compatiblity. Something like: private static final long serialVersionUID = 8683452581122892189L; If it is unchanged, the serialized versions are compatible. For JDK classes this is guaranteed, but of course it is always possible to forget to update the serialVersionUID after making a breaking change. When JDK classes are not guaranteed to be compatible, this is usually mentioned in the Javadoc. Warning: Serialized objects of this class will not be compatible with future Swing releases A: Note that the Java Beans specification details a version-independent serialization method which allows for strong backwards-compatibility. It also results in readable "serialized" forms. In fact a serialized object can be created pretty easily using the mechanism. Look up the documentation to the XMLEncoder and XMLDecoder classes. I wouldn't use this for passing an object over the wire necessarily (though if high performance is a requirement,I wouldn't use serialization either) but it's invaluable for persistent object storage. A: It is not safe to mix Java 1.5 and 1.6. For example, I have a Java 1.5 object serialized into a file and tried opening it in Java 1.6 but it came up with the error below. java.io.InvalidClassException: javax.swing.JComponent; local class incompatible: stream classdesc serialVersionUID = 7917968344860800289, local class serialVersionUID = -1030230214076481435 at java.io.ObjectStreamClass.initNonProxy(Unknown Source) at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source) at java.io.ObjectInputStream.readClassDesc(Unknown Source) at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source) at java.io.ObjectInputStream.readClassDesc(Unknown Source) at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source) at java.io.ObjectInputStream.readClassDesc(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readArray(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.defaultReadFields(Unknown Source) at java.io.ObjectInputStream.readSerialData(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.defaultReadFields(Unknown Source) at java.io.ObjectInputStream.readSerialData(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readArray(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.defaultReadFields(Unknown Source) at java.io.ObjectInputStream.readSerialData(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readObject(Unknown Source)
{ "language": "en", "url": "https://stackoverflow.com/questions/152757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Which are the differences between dialog|main/child/mdi windows? I need to understand the differences between windows main/mdi/child/dialogs.... how win32 messages should be propagated... why some messages are present in one type and not other... A: There is reference information available here on the MSDN website. If you want more of an introduction or tutorial, then Charles Petzold's book Programming Windows is excellent. A: Main window The application's top window. It is flagged as the process main window and this information can be readily accessed by calling processes with the appropriate permission. MDI (Multiple document interface) window This is, typically, in an application main window and it contains a set of MDI Children. This is mostly a window class integrated with Win32 API. I believe it's not treated differently by the operating system as any other window class. Those are becoming extinct in favor of multiple SDI windows (Word 2007). Child This is a child window of any other window. Its position, visibility and mostly everything is dependent on the parent window. The children send notifications to their parents. A notification is a specific kind of window message. Dialog Dialogs provides easy child creation and input handling based on what 95% of dialogs need. Dialog functions in the API let you create a window and its children using compiled templates in the PE file (.exe). The message handling is also slightly different since you are working mostly with notifications from children. The main difference with dialogs is when you are using a modal one. The creation call will block until the user closes the dialog. This can make UI updating a little tricky in some situations. A: Im not a windows developer, but heres what I understand: main window - toplevel container which you can active/see in the taskbar. dialog - little box locking (if modal) your window, not seeable in the taskbar. Mostly used to display message to the user. mdi (Multiple Document Interface) - Not directly a window but more a simple container for storing child windows. Each child window can be maximized/minimized/closed inside this container, but you wont find any of these in the taskbar. http://en.wikipedia.org/wiki/Multiple_document_interface
{ "language": "en", "url": "https://stackoverflow.com/questions/152766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transpose a set of rows as columns in SQL Server 2000 Is there any facility of transposing rows to columns in SQL Server (it is possible in MS-Access)? I was befuddled because this facility is available in MS-Access but not in SQL Server. Is it by design that this feature has not been included in SQL Server? A: The example at http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm only works if you know in advance what the row values can be. For example, let's say you have an entity with custom attributes and the custom attributes are implemented as rows in a child table, where the child table is basically variable/value pairs, and those variable/value pairs are configurable. color red size big city Chicago I'm going to describe a technique that works. I've used it. I'm NOT promoting it, but it works. To pivot the data where you don't know what the values can be in advance, create a temp table on the fly with no columns. Then use a cursor to loop through your rows, issuing a dynamically built "alter table" for each variable, so that in the end your temp table has the columns, color, size, city. Then you insert one row in your temp table, update it via another cursor through the variable, value pairs, and then select it, usually joined with its parent entity, in effect making it seem like those custom variable/value pairs were like built-in columns in the original parent entity. A: The cursor method described is probably the least SQL-like to use. As mentioned, SQL 2005 and on has PIVOT which works great. But for older versions and non-MS SQL servers, the Rozenshtein method from "Optimzing Transact-SQL" (edit: out of print, but avail. from Amazon: http://www.amazon.com/Optimizing-Transact-SQL-Advanced-Programming-Techniques/dp/0964981203), is excellent for pivoting and unpivoting data. It uses point characteristics to turn row based data into columns. Rozenshtein describes several cases, here's one example: SELECT RowValueNowAColumn = CONVERT(varchar, MAX( SUBSTRING(myTable.MyVarCharColumn,1,DATALENGTH(myTable.MyVarCharColumn) * CHARINDEX(sa.SearchAttributeName,'MyRowValue')))) FROM myTable This method is a lot more efficient than using case statements and works for a variety of data types and SQL implementations (not just MS SQL). A: Best to limit to small scale for this sort of thing. If you're using SQL 2k though and don't have PIVOT features available, I've drafted a stored proc that should do the job for you. Bit of a botch rush job so pull it apart as much as you like. Paste the below into a sql window and edit the EXEC at the bottom as preferred. If you want to see what's being generated, remove the --s in the middle: IF EXISTS (SELECT * FROM SYSOBJECTS WHERE XTYPE = 'P' AND NAME = 'USP_LIST_CONCAT') DROP PROCEDURE USP_LIST_CONCAT GO CREATE PROCEDURE USP_LIST_CONCAT (@SourceTable NVARCHAR(1000) = '' ,@SplitColumn NVARCHAR(1000) = '' , @Deli NVARCHAR(10) = '', @KeyColumns NVARCHAR(2000) = '' , @Condition NVARCHAR(1000) = '') AS BEGIN SET NOCOUNT ON /* PROCEDURE CREATED 2010 FOR SQL SERVER 2000. SIMON HUGHES. */ /* NOTES: REMOVE --'s BELOW TO LIST GENERATED SQL. */ IF @SourceTable = '' OR @SourceTable = '?' OR @SourceTable = '/?' OR @SplitColumn = '' OR @KeyColumns = '' BEGIN PRINT 'Format for use:' PRINT ' USP_LIST_CONCAT ''SourceTable'', ''SplitColumn'', ''Deli'', ''KeyColumn1,...'', ''Column1 = 12345 AND ...''' PRINT '' PRINT 'Description:' PRINT 'The SourceTable should contain a number of records acting as a list of values.' PRINT 'The SplitColumn should be the name of the column holding the values wanted.' PRINT 'The Delimiter may be any single character or string ie ''/''' PRINT 'The KeyColumn may contain a comma separated list of columns that will be returned before the concatenated list.' PRINT 'The optional Conditions may be left blank or may include the following as examples:' PRINT ' ''Column1 = 12334 AND (Column2 = ''ABC'' OR Column3 = ''DEF'')''' PRINT '' PRINT 'A standard list in the format:' PRINT ' Store1, Employee1, Rabbits' PRINT ' Store1, Employee1, Dogs' PRINT ' Store1, Employee1, Cats' PRINT ' Store1, Employee2, Dogs' PRINT '' PRINT 'Will be returned as:' PRINT ' Store1, Employee1, Cats/Dogs/Rabbits' PRINT ' Store1, Employee2, Dogs' PRINT '' PRINT 'A full ORDER BY and DISTINCT is included' RETURN -1 END DECLARE @SQLStatement NVARCHAR(4000) SELECT @SQLStatement = ' DECLARE @DynamicSQLStatement NVARCHAR(4000) SELECT @DynamicSQLStatement = ''SELECT '+@KeyColumns+', SUBSTRING('' SELECT @DynamicSQLStatement = @DynamicSQLStatement + '' + '' + CHAR(10) + '' MAX(CASE WHEN '+@SplitColumn+' = ''''''+RTRIM('+@SplitColumn+')+'''''' THEN '''''+@Deli+'''+RTRIM('+@SplitColumn+')+'''''' ELSE '''''''' END)'' FROM '+ @SourceTable +' ORDER BY '+@SplitColumn+' SELECT @DynamicSQLStatement = @DynamicSQLStatement + '' ,2,7999) List'' + CHAR(10) + ''FROM '+ @SourceTable+''' + CHAR(10) +'''+CASE WHEN @Condition = '' THEN '/* WHERE */' ELSE 'WHERE '+@Condition END+ '''+ CHAR(10) + ''GROUP BY '+@KeyColumns+''' SELECT @DynamicSQLStatement = REPLACE(@DynamicSQLStatement,''( +'',''('') -- SELECT @DynamicSQLStatement -- DEBUG ONLY EXEC (@DynamicSQLStatement)' EXEC (@SQLStatement) END GO EXEC USP_LIST_CONCAT 'MyTableName', 'ColumnForListing', 'Delimiter', 'KeyCol1, KeyCol2', 'Column1 = 123456' A: For UNPIVOT in sql server 2005, I have found a good article columns-to-rows-in-sql-server A: I have Data in following format Survey_question_ID Email (User) Answer for 1 survey there are 13 question and answers the desired output i wanted was User ---Survey_question_ID1---Survey_question_ID2 email---answers---answer ........so on Here is the solution for SQL Server 2000, Cause field data type is TEXT. DROP TABLE #tmp DECLARE @tmpTable TABLE ( emailno NUMERIC, question1 VARCHAR(80), question2 VARCHAR(80), question3 VARCHAR(80), question4 VARCHAR(80), question5 VARCHAR(80), question6 VARCHAR(80), question7 VARCHAR(80), question8 VARCHAR(80), question9 VARCHAR(80), question10 VARCHAR(80), question11 VARCHAR(80), question12 VARCHAR(80), question13 VARCHAR(8000) ) DECLARE @tmpTable2 TABLE ( emailNumber NUMERIC ) DECLARE @counter INT DECLARE @Email INT SELECT @counter =COUNT(DISTINCT ans.email) FROM answers ans WHERE ans.surveyname=100430 AND ans.qnpkey BETWEEN 233702 AND 233714 SELECT * INTO #tmp FROM @tmpTable INSERT INTO @tmpTable2 (emailNumber) SELECT DISTINCT CAST(ans.email AS NUMERIC) FROM answers ans WHERE ans.surveyname=100430 AND ans.qnpkey BETWEEN 233702 AND 233714 WHILE @counter >0 BEGIN SELECT TOP 1 @Email= emailNumber FROM @tmpTable2 INSERT INTO @tmpTable (emailno) VALUES (@Email ) Update @tmpTable set question1=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233702 and ans.email=@Email Update @tmpTable set question2=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233703 and email=@email Update @tmpTable set question3=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233704 and email=@email Update @tmpTable set question4=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233705 and email=@email Update @tmpTable set question5=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233706 and email=@email Update @tmpTable set question6=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233707 and email=@email Update @tmpTable set question7=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233708 and email=@email Update @tmpTable set question8=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233709 and email=@email Update @tmpTable set question9=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233710 and email=@email Update @tmpTable set question10=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233711 and email=@email Update @tmpTable set question11=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233712 and email=@email Update @tmpTable set question12=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233713 and email=@email Update @tmpTable set question13=CAST(answer as VARCHAR(8000)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233714 and email=@email insert into #tmp select * from @tmpTable DELETE FROM @tmpTable DELETE FROM @tmpTable2 WHERE emailNumber= @Email set @counter =@counter -1 End select * from #tmp
{ "language": "en", "url": "https://stackoverflow.com/questions/152770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Is there a better way to trim a DateTime to a specific precision? What's the best way to trim a DateTime object to a specific precision? For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this? private static DateTime TrimDateToMinute(DateTime date) { return new DateTime( date.Year, date.Month, date.Day, date.Hour, date.Minute, 0); } What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day. A: You could use an enumeration public enum DateTimePrecision { Hour, Minute, Second } public static DateTime TrimDate(DateTime date, DateTimePrecision precision) { switch (precision) { case DateTimePrecision.Hour: return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0); case DateTimePrecision.Minute: return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0); case DateTimePrecision.Second: return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second); default: break; } } and expand as required. A: I like this method. Someone mentioned it was good to preserve the Date Kind, etc. This accomplishes that because you dont have to make a new DateTime. The DateTime is properly cloned from the original DateTime and it simply subtracts the remainder ticks. public static DateTime FloorTime(DateTime dt, TimeSpan interval) { return dt.AddTicks(-1 * (dt.Ticks % interval.Ticks)); } usage: dt = FloorTime(dt, TimeSpan.FromMinutes(5)); // floor to the nearest 5min interval dt = FloorTime(dt, TimeSpan.FromSeconds(1)); // floor to the nearest second dt = FloorTime(dt, TimeSpan.FromDays(1)); // floor to the nearest day A: static class Program { //using extension method: static DateTime Trim(this DateTime date, long roundTicks) { return new DateTime(date.Ticks - date.Ticks % roundTicks, date.Kind); } //sample usage: static void Main(string[] args) { Console.WriteLine(DateTime.Now); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerDay)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerHour)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMillisecond)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMinute)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerSecond)); Console.ReadLine(); } } A: There are some good solutions presented here, but when I need to do this, I simply do: DateTime truncDate; truncDate = date.Date; // trim to day truncDate = date.Date + TimeSpan.Parse(string.Format("{0:HH:00:00}", date)); // trim to hour truncDate = date.Date + TimeSpan.Parse(string.Format("{0:HH:mm}", date)); // trim to minute truncDate = date.Date + TimeSpan.Parse(string.Format("{0:HH:mm:ss}", date)); // trim to second Hope it helps. A: DateTime dt = new DateTime() dt = dt.AddSeconds(-dt.Second) Above code will trim seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/152774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "67" }
Q: What is wrong with this _popen / select example? UPDATE: i updated the code and problem description to reflect my changes. I know now that i'm trying a Socket operation on nonsocket. or that my fd_set is not valid since: select returns -1 and WSAGetLastError()returns 10038. But i can't seem to figure out what it is. Platform is Windows. I have not posted the WSAStartup part. int loop = 0; FILE *output int main() { fd_set fd; output = _popen("tail -f test.txt","r"); while(forceExit == 0) { FD_ZERO(&fd); FD_SET(_fileno(output),&fd); int returncode = select(_fileno(output)+1,&fd,NULL,NULL,NULL); if(returncode == 0) { printf("timed out"); } else if (returncode < 0) { printf("returncode: %d\n",returncode); printf("Last Error: %d\n",WSAGetLastError()); } else { if(FD_ISSET(_fileno(output),&fd)) { if(fgets(buff, sizeof(buff), output) != NULL ) { printf("Output: %s\n", buff); } } else { printf("."); } } Sleep(500); } return 0; } The new outcome now is of course the print out of the returncode and the last error. A: You have some data ready to be read, but you are not actually reading anything. When you poll the descriptor next time, the data will still be there. Drain the pipe before you continue to poll. A: As far as I can tell, Windows anonymous pipes cannot be used with non-blocking calls like select. So, while your _popen and select code looks good independently, you can't join the two together. Here's a similar thread elsewhere. It's possible that calling SetNamedPipeHandleState with the PIPE_NOWAIT flag might work for you, but MSDN is more than a little cryptic on the subject. So, I think you need to look at other ways of achieving this. I'd suggest having the reading in a separate thread, and use normal blocking I/O. A: First of all, as yourself and others have pointed out, select() is only valid for sockets under Windows. select() does not work on streams which is what _popen() returns. Error 10038 clearly identifies this. I don't get what the purpose of your example is. If you simply want to spawn a process and collect it's stdout, just do this (which comes directly from the MSDN _popen page): int main( void ) { char psBuffer[128]; FILE *pPipe; if( (pPipe = _popen("tail -f test.txt", "rt" )) == NULL ) exit( 1 ); /* Read pipe until end of file, or an error occurs. */ while(fgets(psBuffer, 128, pPipe)) { printf(psBuffer); } /* Close pipe and print return value of pPipe. */ if (feof( pPipe)) { printf( "\nProcess returned %d\n", _pclose( pPipe ) ); } else { printf( "Error: Failed to read the pipe to the end.\n"); } } That's it. No select required. And I'm not sure how threads will help you here, this will just complicate your problem. A: The first argument to select needs to be the highest-numbered file descriptor in any of the three sets, plus 1: int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); Also: if(FD_ISSET(filePointer,&exceptfds)) { printf("i have data\n"); } Should be: if(FD_ISSET(filePointer,&fd)) { printf("i have data\n"); } You should check the return code from select(). You also need to reset the fdsets each time you call select(). You don't need timeout since you're not using it. Edit: Apparently on Windows, nfds is ignored, but should probably be set correctly, just so the code is more portable. If you want to use a timeout, you need to pass it into the select call as the last argument: // Reset fd, exceptfds, and timeout before each select()... int result = select(maxFDPlusOne, &fd, NULL, &exceptfds, &timeout); if (result == 0) { // timeout } else if (result < 0) { // error } else { // something happened if (FD_ISSET(filePointer,&fd)) { // Need to read the data, otherwise you'll get notified each time. } } A: The first thing that I notice is wrong is that you are calling FD_ISSET on your exceptfds in each conditional. I think that you want something like this: if (FD_ISSET(filePointer,&fd)) { printf("i have data\n"); } else .... The except field in the select is typically used to report errors or out-of-band data on a socket. When one of the descriptors of your exception is set, it doesn't mean an error necessarily, but rather some "message" (i.e. out-of-band data). I suspect that for your application, you can probably get by without putting your file descriptor inside of an exception set. If you truly want to check for errors, you need to be checking the return value of select and doing something if it returns -1 (or SOCKET_ERROR on Windows). I'm not sure of your platform so I can't be more specific about the return code. A: * *select() first argument is the highest number file descriptor in your set, plus 1. (i.e. output+1) select(output+1, &fd, NULL, &exceptfds, NULL); *The first FD_ISSET(...) should be on the fd_set fd. if (FD_ISSET(filePointer, &fd)) *Your data stream has data, then you need to read that data stream. Use fgets(...) or similar to read from the data source. char buf[1024]; ... fgets(buf, sizeof(buf) * sizeof(char), output); A: since select doesn't work i used threads, specifically _beginthread , _beginthreadex.
{ "language": "en", "url": "https://stackoverflow.com/questions/152807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best way to get data from a DataReader into a Farpoint Spreadsheet? I need to move data from a datareader into a Farpoint Spreadsheet component in a Windows form. The DataSource of an fps sheet can't be set to a datareader. I don't want to change my app to use ADO just for this purpose. Right now I'm looping through the query data and pushing it into the sheet cell-by-cell. That's ugly, and I am sure performance will suffer for large datasets (though I haven't tried it yet). Does anyone here know a better way to get a datareader into one of these components? I'm using VB.NET, but a C# example would be fine. A: I'm not familiar with the product, but you can try loading the reader into a DataTable and binding that if it's supported. Dim dt as Datatable dt.load(reader)
{ "language": "en", "url": "https://stackoverflow.com/questions/152814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "Class does not support automation" error when i call Request.ServerVariables("remote_host") I'm in the process of writing a basic cookie for an ecommerce site which is going to store the user's IP among other details. We'll then record the pages they view in the database and pull out a list of recently viewed pages. However i'm having an issue with the following code. dim caller caller = Response.Cookies("caller") if caller = "" then caller = Request.ServerVariables("remote_host") end if On running this, i get the following error message. "Sun ONE ASP VBScript runtime (0x800A01AE) Class does not support automation" Any ideas? Google has nothing obvious. A: Should be Request.Cookies when checking the value.: dim caller caller = Request.Cookies("caller") if caller = "" then caller = Request.ServerVariables("remote_host") end if
{ "language": "en", "url": "https://stackoverflow.com/questions/152817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to declare a user-defined function returning node-set? I want something like this: <msxsl:script language="C#"> ??? getNodes() { ... return ... } </msxsl:script> <xsl:for-each select="user:getNodes()"> ... </xsl:for-each> What return type should i use for getNodes() and what should i put in it's body? A: In principle you need to use the XPathNodeIterator to return node sets (as Samjudson says). I take it that the example you gave is a degenerated function, as you do not supply it with any parameters. However, I think it is instructive the see how you could fabricate nodes out of thin air. <msxsl:script language="C#"> XPathNodeIterator getNodes() { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml("<root><fld>val</fld><fld>val2</fld></root>"); return doc.CreateNavigator().Select("/root/fld"); } </msxsl:script> However, typically you would want to do something in your function that is not possible in xslt, like filtering a node set based on some criteria. A criteria that is better implemented through code or depends om some external data structure. Another option is just that you would to simplify a wordy expression (as in the example bellow). Then you would pass some parameters to you getNodes function. For simplicity I use a XPath based filtering but it could be anything: <msxsl:script language="C#"> XPathNodeIterator getNodes(XPathNodeIterator NodesToFilter, string Criteria) { XPathNodeIterator x = NodesToFilter.Current.Select("SOMEVERYCOMPLEXPATH["+Criteria+"]"); return x; } </msxsl:script> <xsl:for-each select="user:getNodes(values/val,'SomeCriteria')"> ... </xsl:for-each> Hopes this helps, Boaz A: A quick google for C# xslt msxml revealed a link to the following page which gives many examples of extending XSLT in microsoft environments. http://msdn.microsoft.com/en-us/magazine/cc302079.aspx Specifically the section on Mapping Types between XSLT and .Net gives you exactly the information you need: W3C XPath Type - Equivalent .NET Class (Type) * *String - System.String *Boolean - System.Boolean *Number - System.Double *Result Tree Fragment - System.Xml.XPath.XPathNavigator *Node Set - System.Xml.XPath.XPathNodeIterator So in your example I would try XPathNodeLiterator.
{ "language": "en", "url": "https://stackoverflow.com/questions/152822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: .htaccess files, PHP, includes directories, and windows XAMPP configuration nightmare XAMPP makes configuring a local LAMP stack for windows a breeze. So it's quite disappointing that enabling .htaccess files is such a nightmare. My problem: I've got a PHP application that requires apache/php to search for an /includes/ directory contained within the application. To do this, .htaccess files must be allowed in Apache and the .htaccess file must specify exactly where the includes directory is. Problem is, I can't get my Apache config to view these .htaccess files. I had major hassles installing this app at uni and getting the admins there to help with the setup. This shouldn't be so hard but for some reason I just can't get Apache to play nice. This is my setup: c:\xampp c:\xampp\htdocs c:\xampp\apache\conf\httpd.conf - where I've made the changes listed below c:\xampp\apache\bin\php.ini - where changes to this file affect the PHP installation It is interesting to note that c:\xampp\php\php.ini changes mean nothing - this is NOT the ini that affects the PHP installation. The following lines are additions I've made to the httpd.conf file #AccessFileName .htaccess AccessFileName htaccess.txt # # The following lines prevent .htaccess and .htpasswd # files from being viewed by Web clients. # #<Files ~ "^\.ht"> <Files ~ "^htaccess\."> Order allow,deny Deny from all </Files> <Directory "c:/xampp/htdocs"> # # AllowOverride controls what directives may be placed in # .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride All # # Controls who can get stuff from this server. # Order allow,deny Allow from all </Directory> The following is the entire .htaccess file contained in: c:\xampp\htdocs\application\htaccess.txt <Files ~ "\.inc$"> Order deny,allow Deny from all </Files> php_value default_charset "UTF-8" php_value include_path ".;c:\xampp\htdocs\application\includes" php_value register_globals 0 php_value magic_quotes_gpc 0 php_value magic_quotes_runtime 0 php_value magic_quotes_sybase 0 php_value session.use_cookies 1 php_value session.use_only_cookies 0 php_value session.use_trans_sid 1 php_value session.gc_maxlifetime 3600 php_value arg_separator.output "&amp;" php_value url_rewriter.tags "a=href,area=href,frame=src,input=src,fieldset=" The includes directory exists at the location specified. When I try to access the application I receive the following error: Warning: require(include.general.inc) [function.require]: failed to open stream: No such file or directory in C:\xampp\htdocs\application\menu\logon.php on line 21 Fatal error: require() [function.require]: Failed opening required include.general.inc (include_path='.;C:\xampp\php\pear\random') in C:\xampp\htdocs\application\menu\logon.php on line 21 The include path c..\random\ is specified in the php.ini file listed above. The XAMPP install fails to allow another include path as specified in the htaccess.txt file. I'm guessing there's probably an error with the httpd.conf OR the htaccess.txt file.. but it doesn't seem to be reading the .htaccess file. I've tried to be as thorough as possible so forgive the verbosity of the post. Now I know a workaround could be to simply add the include_path to the PHP file, but I'm not going to have access to the php.ini file on the location I plan to deploy my app. I will, however, be able to request the server admin allows .htaccess files. renamed htacces.txt to .htaccess and ammended the appropriate directives in the httpd.conf file and all seems to work. The application suggested the naming of htaccess.txt and the ammended directives in the httpd. These are obviously wrong (at least for a XAMPP stack). By the way, using ini_set() is a much friendlier way if the app needs to be deployed to multiple locations so thanks especially for that pointer. A: * *Why do you need to rename .htaccess to htaccess.txt *Try setting the include_path using set_include_path() and see if that helps (as an intermediate fix) *Verify which php.ini to use through a phpinfo() A: You can alter the include_path on each request using ini_set(). This would avoid having to use htaccess at all. A: My htaccess works under XAMPP fine - though some modules are disabled by default - are you sure that the modules you want are enabled? A: I think the searchprase you are looking for is: AllowOverride All My guess is that within xampp you need to enable AllowOverride (through an .htaccess) in httpd.conf. It's a simple security measure that prevents newbies from installing a hackable platform :P A: You need to enable AllowOverride All in main http.conf file. Look inside XAMPP_DIR/apache/conf/http.conf) A: Simply Do this: open file ...\xampp\apache\conf\httpd.conf find line "LoadModule rewrite_module modules/mod_rewrite.so" if here is a # before this line remove it.(remove comment) its working
{ "language": "en", "url": "https://stackoverflow.com/questions/152823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to analyse 'noisiness' of an array of points Have done fft (see earlier posting if you are interested!) and got a result, which helps me. Would like to analyse the noisiness / spikiness of an array (actually a vb.nre collection of single). Um, how to explain ... When signal is good, fft power results is 512 data points (frequency buckets) with low values in all but maybe 2 or 3 array entries, and a decent range (i.e. the peak is high, relative to the noise value in the nearly empty buckets. So when graphed, we have a nice big spike in the values in those few buckets. When signal is poor/noisy, data values spread (max to min) is low, and there's proportionally higher noise in many more buckets. What's a good, computationally non-intensive was of analysing the noisiness of this data set? Would some kind of statistical method, standard deviations or something help ? A: The key is defining what is noise and what is signal, for which modelling assumptions must be made. Often an assumption is made of white noise (constant power per frequency band) or noise of some other power spectrum, and that model is fitted to the data. The signal to noise ratio can then be used to measure the amount of noise. Fitting a noise model depends on the nature of your data: if you know that the real signal will have no power in the high frequency components, you can look there for an indication of the noise level, and use the model to predict what the noise will be at the lower frequency components where there is both signal and noise. Alternatively, if your signal is constant in time, taking multiple FFTs at different points in time and comparing them to get a standard deviation for each frequency band can give the level of noise present. I hope I'm not patronising you to mention the issues inherent with windowing functions when performing FFTs: these can have the effect of introducing spurious "noise" into the frequency spectrum which is in fact an artifact of the periodic nature of the FFT. There's a tradeoff between getting sharp peaks and 'sideband' noise - more here www.ee.iitm.ac.in/~nitin/_media/ee462/fftwindows.pdf A: Calculate a standard deviation and then you decide the threshold that will indicate noise. In practice this is usually easy and allows you to easily tweak the "noise level" as needed. There is a nice single pass stddev algorithm in Knuth. Here is link that describes an implementation. Standard Deviation A: calculate the signal to noise ratio http://en.wikipedia.org/wiki/Signal-to-noise_ratio you could also check the stdev for each point and if it's under some level you choose then the signal is good else it's not. A: wouldn't the spike be treated as a noise glitch in SNR, an outlier to be discarded, as it were? If it's clear from the time-domain data that there are such spikes, then they will certainly create a lot of noise in the frequency spectrum. Chosing to ignore them is a good idea, but unfortunately the FFT can't accept data with 'holes' in it where the spikes have been removed. There are two techniques to get around this. The 'dirty trick' method is to set the outlier sample to be the average of the two samples on either site, and compute the FFT with a full set of data. The harder but more-correct method is to use a Lomb Normalised Periodogram (see the book 'Numerical Recipes' by W.H.Press et al.), which does a similar job to the FFT but can cope with missing data properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/152829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Default port for SQL Server I need to know the default port settings for the following services * *SQL Server *SQL Browser *SQL Reporting services *SQL Analysis services I need to know the port settings for these services for different versions of SQL Server (2000,2005,2008) Also let me know whether the default port setting will change based on sql server versions. A: The default, unnamed instance always gets port 1433 for TCP. UDP port 1434 is used by the SQL Browser service to allow named instances to be located. In SQL Server 2000 the first instance to be started took this role. Non-default instances get their own dynamically-allocated port, by default. If necessary, for example to configure a firewall, you can set them explicitly. If you don't want to enable or allow access to SQL Browser, you have to either include the instance's port number in the connection string, or set it up with the Alias tab in cliconfg (SQL Server Client Network Utility) on each client machine. For more information see SQL Server Browser Service on MSDN. A: 1433 the default port hasn't changed yet A: SQL Server default port is 1434. To allow remote access I had to release those ports on my firewall: Protocol | Port --------------------- UDP | 1050 TCP | 1050 TCP | 1433 UDP | 1434 A: If you have access to the server then you can use select local_tcp_port from sys.dm_exec_connections where local_tcp_port is not null For full details see port number of SQL Server A: * *The default SQL Server port is 1433 but only if it's a default install. Named instances get a random port number. *The browser service runs on port UDP 1434. *Reporting services is a web service - so it's port 80, or 443 if it's SSL enabled. *Analysis services is 2382 but only if it's a default install. Named instances get a random port number. A: You can use SQL Configuration Manager to set individual IP addresses to use dynamic ports or not (value of 0 = yes, use dynamic port), and to set the TCP port used for each IP. But be careful: I recommend first mapping out your instances, IPs, and ports, and planning such that no instances or IPs step on each other before starting to make changes willy-nilly. A: We can take a look at three different ways you can identify the port used by an instance of SQL Server. * *Reading SQL Server Error Logs *Using SQL Server Configuration Manager *Using Windows Application Event Viewer USE master GO xp_readerrorlog 0, 1, N'Server is listening on', 'any', NULL, NULL, N'asc' GO Identify Port used by SQL Server Database Engine Using SQL Server Configuration Manager * *Click Start -> Programs -> Microsoft SQL Server 2008 -> Configuration Tools -> SQL Server Configuration Manager *In SQL Server Configuration Manager, expand SQL Server Network Configuration and then select Protocols for on the left panel. To identify the TCP/IP Port used by the SQL Server Instance, right click onTCP/IP and select Properties from the drop down as shown below. For More Help http://sqlnetcode.blogspot.com/2011/11/sql-server-identify-tcp-ip-port-being.html
{ "language": "en", "url": "https://stackoverflow.com/questions/152834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "64" }
Q: How to insert a string which contains an "&" How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database. I'm not sure if it makes a difference, but I'm using Oracle 9i. A: The correct syntax is set def off; insert into tablename values( 'J&J'); A: I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far. Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name. SET DEFINE OFF will stop sqlplus interpreting & this way. But what if you need to use sqlplus variables and literal & characters? * *You need SET DEFINE ON to make variables work *And SET ESCAPE ON to escape uses of &. e.g. set define on set escape on define myvar=/forth select 'back\\ \& &myvar' as swing from dual; Produces: old 1: select 'back\\ \& &myvar' from dual new 1: select 'back\ & /forth' from dual SWING -------------- back\ & /forth If you want to use a different escape character: set define on set escape '#' define myvar=/forth select 'back\ #& &myvar' as swing from dual; When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first: set escape off set escape '#' A: There's always the chr() function, which converts an ascii code to string. ie. something like: INSERT INTO table VALUES ( CONCAT( 'J', CHR(38), 'J' ) ) A: You can insert such an string as 'J'||'&'||'Construction'. It works fine. insert into table_name (col_name) values('J'||'&'||'Construction'); A: INSERT INTO TEST_TABLE VALUES('Jonhy''s Sport &'||' Fitness') This query's output : Jonhy's Sport & Fitness A: SET SCAN OFF is obsolete http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a90842/apc.htm A: In a program, always use a parameterized query. It avoids SQL Injection attacks as well as any other characters that are special to the SQL parser. A: If you are doing it from SQLPLUS use SET DEFINE OFF to stop it treading & as a special case A: I've found that using either of the following options works: SET DEF OFF or SET SCAN OFF I don't know enough about databases to know if one is better or "more right" than the other. Also, if there's something better than either of these, please let me know. A: An alternate solution, use concatenation and the chr function: select 'J' || chr(38) || 'J Construction' from dual; A: If you are using sql plus then I think that you need to issue the command SET SCAN OFF A: SET ESCAPE ON; INSERT VALUES("J\&J Construction") INTO custnames; (Untested, don't have an Oracle box at hand and it has been a while) A: Stop using SQL/Plus, I highly recommend PL/SQL Developer it's much more than an SQL tool. p.s. Some people prefer TOAD. A: Look, Andrew: "J&J Construction": SELECT CONCAT('J', CONCAT(CHR(38), 'J Construction')) FROM DUAL;
{ "language": "en", "url": "https://stackoverflow.com/questions/152837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: What features distinguish Flex from DHTML? I just got started using Adobe Flex SDK. I was very excited because it's the first time I've found a good, free way to create Flash applications. But then I noticed something: Flex doesn't seem to be much about making animations or designs. It seems more like an application to build forms and menus and the like... which I can already do in (D)HTML. What features does Flex have that make it better than HTML in some cases? Also, are there any techniques/software programs that would allow me to add the flash/design components that I mentioned earlier? Thanks! A: Flex, like Silverlight, is marketed for the creation of something called RIA = rich internet application. The idea being that (D)HTML isn't really well-suited to create large-scale, well-responding applications on the web. I'm not sure whether this is really (still) true but historically, it fits. Flex and Silverlight attempt to correct this by providing two things: a different, extensible technology along with a large library and an adapted toolset for the creation of applications. The disadvantage in both cases is the dependency from further (non-free, non-standard) components. The advantage is a potentially much more productive workflow and better performance. A: Flex has a cohesive component model, and the basic building blocks were designed to support applications. HTML, on the other hand was designed for displaying text, and the DOM is a sorry excuse for a component model -- and it was most definitely not designed with applications in mind. There is a plethora of JavaScript libraries that try to implement a workable platform on top of the DOM, and to even out the differences between browsers. While these work fine in many situations most of them don't come near the richness of the Flex component model, or even the more basic Flash API:s. However impressing libraries like Dojo, YUI and jQuery are, they are limited by the platform, and it is limited indeed. Flex has all the benefits of the Flash Player platform, like vector graphics, remote objects, video support, cross-domain loading, sockets, font embedding, etc. but also a very good component model, data binding and skinning capabilities, to name but a few. If you're writing rich internet applications Flex is as rich as it gets. A: Flex is a layer on top of Flash, and was designed from the ground up for building applications. As such it has very powerful capabilities when it comes to interface construction and data manipulation. If you are interested in movies and animation sticking with Flash is more appropriate. The advantages of Flex over DHTML (AJAX) include: - Faster prototyping - Better cross-browser support - Better support for data management - More "serious" Disadvantages include: - Stuck with a single vendor - Requires the Flash plugin A: You can do audio and video in Flex/Flash vs DHTML. Some more details and comparisons are in this The Top 10 Things You Should Know About Flex article. A: If you're interested in leveraging the graphics potential of Flex, why not go check out Degrafa which is an open source graphing and general graphics api. It's pretty cool, very well documented, and quote - "Adobe has asked if the Degrafa team would consider helping directly contribute to the Flex Graphics open source effort." - which they are! It's not just all about charts and graphs. A: Just a quick clarification - to be clear, Flex is built on top of Flash. What that means is that anything you can do in Flash, you can do in Flex when it comes to programming. Flex Builder does not come with any tools that let you make animations with timelines or vector art or anything like that, but all of those elements are still usable provided you have the tools to make them elsewhere. Flex is really about bridging Actionscript 3 as a language and Flash as a runtime into an environment where application programmers can feel truly comfortable with it. A: As stated above, "Better cross-browser support." That's probably the biggest factor right now for me. A few more... * *It's a lot easier to get "pixel perfect" designs in place. *It's really easy to integrate Flash content into Flex. Which makes it easier to work with designers. *Actionscript is better than Javascript (go ahead and flame me!) There aren't any really good alternatives to buying the Flash product for making timeline based animations. The bad sides: * *Sometimes, html is just plain easier / more powerful Make sure to pick the right tool for the right job. Sometimes DHTML, sometimes Flex, sometimes Flash, and many times a combination of those. A: What you're talking about is Flash versus Javascript. Flex is Flash, DHTML is Javascript. Flex allows for rapid prototyping, an alternate IDE for building Flash .swf s, and fits nicely into Air - Javascript only runs in browsers, includes less animation support by default (although there are plenty of well-established libraries that provide that functionality) and doesn't require a plugin to work. A: Also with Flex you don't have to deal with JSON, XMLHttpRequest, compatibility issues and the likes... Everything works like magic. A: * *Unless you need a lot of animations, HTML will feel more lightweight than Flex. *No "loading" screen. *On OS X performance of Flex is abysmal. Even DHTML animations are faster! (see GUIMark). *HTML has wider compatibility than Flex. It may not be as easy as writing for single implementation from single vendor, but OTOH you're not limited to that single implementation: * *No problems with iPhone or 64-bit Linux. *With graceful degradation basic functionality might even be accessible from Lynx or BlackBerry browser. *HTML is better integrated with the browser and OS: * *Form elements can have native look'n'feel. *Text has preferred type of anti-aliasing, no problems with ClearType. *Keyboard shortcuts, context menus and text selection work as expected. *Browser extensions can improve DHTML apps, but Flex is impenetrable. *Accessibility tools have better support for HTML.
{ "language": "en", "url": "https://stackoverflow.com/questions/152846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can you use "external" configuration files (i.e. with configSource) with an MSTest unit test project? For simplicity, I generally split a lot of my configuration (i.e. the contents of app.config and web.config) out into separate .config files, and then reference them from the main config file using the 'configSource' attribute. For example: <appSettings configSource="appSettings.config"/> and then placing all of the key/value pairs in that appSettings.config file instead of having this in-line in the main config file: <appSettings> <add key="FirstKey" value="FirstValue"/> <add key="SecondKey" value="SecondValue"/> ... </appSettings> This typically works great with the application itself, but I run into problems when attempting to write unit tests that, for whatever reason, need to get at some value from a configuration section that is stored in one of these external files. (I understand that most of these would likley be considered "integration tests", as they are relying on the Configuration system, and I do have "pure unit tests" as well, but those are the not the problem. I'm really looking to test that these configuration values are retrieved correctly and impact behavior in the correct way). Due to how MSTest compiles and copies the output to obfuscated-looking folders that are different from every test run (rather than to the 'bin' folder like you might think), it never seems to be able to find those external files while the tests are executing. I've tried messing around with post build actions to make this work but with no luck. Is there a way to have these external files copied over into the correct output folder at run time? A: Found it: If you edit the test run configuration (by double clicking the .testrunconfig file that gets put into the 'Solution Items' solution folder when you add a new unit test), you get a test run configuration dialog. There's a section there called 'Deployment' where you can specifiy files or whole folders from anywhere in the solution that can be copied out with the compiled assemblies at run time to the correct folder. In this way, I can now actually just define most of my configuration in one set of external .config files and have them automatically copied out at the run of each test. A: Test run configurations are a bit awkward when trying to run tests outside of Visual Studio. For command line execution using MSTest they become quite cumbersome to keep "clean". They are also "global" to the solution so external files will be copied for every test project. I much prefer the DeploymentItem attribute. [TestMethod] [DeploymentItem(@"test_data.file")] public void FooTest() {...} Makes the tests independent of the .testrunconfig files. A: * *write this in your connectionString. First ConnectionString.config is not exists. <"connectionStrings configSource="ConnectionString.config"> " *open command prompt (CMD) in administrator privileged. *Create a symbolic links with the name of ConnectionString.config at bin/debug folder. C:\Windows\Systems32> mklink "C:\Link To Folder\....\ConnectionString.config" "C:\Users\Name\Original Folder\.....\...\Secure ConnectionString.config" finally it creates ConnectionString configuration file at the specified location. and works successfully.
{ "language": "en", "url": "https://stackoverflow.com/questions/152866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Using jQuery to Highlight Selected ASP.NET DataGrid Row It is easy to highlight a selected datagrid row, by for example using toggleClass in the tr's click event. But how best to later remove the highlight after a different row has been selected? Iterating over all the rows to unhighlight them could become expensive for larger datagrids. I'd be interested in the simplest solution, as well as the most performant. Thanks, Mike A: If you just want to find items that have toggledClass and turn that off using jQuery: $('.toggledClass').removeClass('toggledClass'); A: This method stores the active row into a variable. The $ at the start of the variable is just my own hungarian notation for jQuery objects. var $activeRow; $('#myGrid tr').click(function() { if ($activeRow) $activeRow.removeClass('active'); $activeRow = $(this).addClass('active'); }); A: For faster performance, you could push your selected element's ID into a var (or an array for multiples), and then use that var/iterate over that array when toggling the classes off.
{ "language": "en", "url": "https://stackoverflow.com/questions/152869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Isn't resource-oriented really object-oriented? When you think about it, doesn't the REST paradigm of being resource-oriented boil down to being object-oriented (with constrained functionality, leveraging HTTP as much as possible)? I'm not necessarily saying it's a bad thing, but rather that if they are essentially the same very similar then it becomes much easier to understand REST and the implications that such an architecture entails. Update: Here are more specific details: * *REST resources are equivalent to public classes. Private classes/resources are simply not exposed. *Resource state is equivalent to class public methods or fields. Private methods/fields/state is simply not exposed (this doesn't mean it's not there). *While it is certainly true that REST does not retain client-specific state across requests, it does retain resource state across all clients. Resources have state, the same way classes have state. *REST resources are are globally uniquely identified by a URI in the same way that server objects are globally uniquely identified by their database address, table name and primary key. Granted there isn't (yet) a URI to represent this, but you can easily construct one. A: REST is similar to OO in that they both model the world as entities that accept messages (i.e., methods) but beyond that they're different. Object orientation emphasizes encapsulation of state and opacity, using as many different methods necessary to operate on the state. REST is about transfer of (representation of) state and transparency. The number of methods used in REST is constrained and uniform across all resources. The closest to that in OOP is the ToString() method which is very roughly equivalent to an HTTP GET. Object orientation is stateful--you refer to an object and can call methods on it while maintaining state within a session where the object is still in scope. REST is stateless--everything you want to do with a resource is specified in a single message and all you ever need to know regarding that message is sent back in a single response. In object-orientation, there is no concept of universal object identity--objects either get identity from their memory address at any particular moment, a framework-specific UUID, or from a database key. In REST all resources are identified with a URI and don't need to be instantiated or disposed--they always exist in the cloud unless the server responds with a 404 Not Found or 410 Gone, in whch case you know there's no resource with that URI. REST has guarantees of safety (e.g., a GET message won't change state) and idempotence (e.g., a PUT request sent multiple times has same effect as just one time). Although some guidelines for particular object-oriented technologies have something to say about how certain constructs affect state, there really isn't anything about object orientation that says anything about safety and idempotence. A: I think there's a difference between saying a concept can be expressed in terms of objects and saying the concept is the same as object orientation. OO offers a way to describe REST concepts. That doesn't mean REST itself implements OO. A: You are right. Dan Connolly wrote an article about it in 1997. The Fielding thesis also talks about it. A: Objects bundle state and function together. Resource-orientation is about explicitly modeling state(data), limiting function to predefined verbs with universal semantics (In the case of HTTP, GET/PUT/POST/DELETE), and leaving the rest of the processing to the client. There is no equivalent for these concepts in the object-orientation world. A: Only if your objects are DTOs (Data Transfer Objects) - since you can't really have behavior other than persistence. A: Yes, your parallel to object-orientation is correct. The thing is, most webservices (REST, RESTful, SOAP,..) can pass information in the form of objects, so that isn't what makes it different. SOAP tends to lead to fewer services with more methods. REST tends to lead to more services (1 per resource type) with a few calls each. A: Yes, REST is about transfer of objects. But it isn't the whole object; just the object's current state. The implicit assumption is that the class definitions on both sides of the REST are potentially similar; otherwise the object state has been coerced into some new object. REST only cares about 4 events in the life on an object, create (POST), retrieve (GET), update (PUT) and delete. They're significant events, but there's only these four. An object can participate in lots of other events with lots of other objects. All the rest of this behavior is completely outside the REST approach. There's a close relationship -- REST moves Objects -- but saying they're the same reduces your objects to passive collections of bits with no methods. A: REST is not just about objects, its also about properties :: a post request to /users/john/phone_number with a new phone number is not adding a new object, its setting a property of the user object 'john' This is not even the whole state of the object, but only a change to a small part of the state. It's certainly not a 1:1 match.
{ "language": "en", "url": "https://stackoverflow.com/questions/152871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do I resolve a merge conflict with SVN properties? This has been bugging me for a long time -- how do I properly resolve a merge conflict within the SVN properties set on a directory? Say for instance there are two developers working on a project where svn:ignore is set on some directory. If both developers make changes to this property, when the second one updates, they will see a merge conflict. Unlike file merge conflicts, a single file is generated in the directory called "dir_conflicts.prej", which the second developer must read and manually correct. Usually, what I end up doing is reverting all my changes to the local copy, then re-setting these properties manually with the info in dir_conflicts.prej. However, this is rather cumbersome when dealing with a big list of URLs in an svn:externals property, as many of our projects use. There has got to be a better way to do this -- does anybody know how? A: I had the same problem. I tried to use Team->Edit Property Conflicts but my STS got hanged and not responded hence I forced close. It is possible to solve with TortoiseSVN This is how I resolved * *select the folder where the dir_conflicts.prej is located *right-click TortoiseSVN -> Resolve... *It will then ask to resolve property conflict *Do Resolve and save A: In the meantime this is possible in Eclipse+Subclipse (Indigo) using the function Team->Edit Property Conflicts (just tried with conflicting svn:ignore properties) This function opens a dialog which shows both properties versions (local and repository), where you can copy&paste and then resolve the conflict using Team->Mark Resolved. A: Just a quick update after some additional research -- it is not possible to easily merge SVN properties. My originally described method (revert, merge data from .prej files, propset, re-commit) appears to be the best way to deal with this type of problem. A: I wish I could offer a more hopeful solution but from my experience its not currently possible to merge svn properties using TortoiseSVN. See http://svn.haxx.se/tsvn/archive-2008-09/0212.shtml. A: Do you mean a merge conflict on commit/update or branch merge? The SVN Book is pretty clear about the svn:ignore property in particular: Subversion does not assume that every file or subdirectory in a working copy directory is intended for version control. Resources must be explicitly placed under Subversion's management using the svn add or svn import commands. ... To force every user of that repository to add patterns for those resources to their run-time configuration areas would be not just a burden, but has the potential to clash with the configuration needs of other working copies that the user has checked out. A: Just to be clear, SVN appears to use the dir_conflicts.prej file to derive the fact that the directory has a conflict. If you intend to manually address the conflict, you can simply delete the dir_conflicts.prej file and then manually set the svn properties as you want them. (Of course making sure to get what you need from the .prej file before you delete it!) A: I had a similar conflict. I opened dir_conflicts.prej in a text editor and saw that the svn ignore list had been changed. Luckily, the contents of the list were the same, only the ordering changed. So in TortoiseSVN 1.9.3, I just right-click on the folder then TortoiseSVN -> Resolve.... And the conflict was fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/152887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: OSI model - What's the presentation and session layer for? So I feel I pretty well understand the application layer, and everything below (and including) the transport layer. The session and presentation layers, though, I don't fully understand. I've read the simplistic descriptions in Wikipedia, but it doesn't have an example of why separating out those layers is useful. So: * *What is the session layer? What does it do, and under what circumstances is it better to have a session layer than simply talk to the transport with your app? *What is the presentation layer? (same questions as above) -Adam A: The reasons there aren't any examples on wikipedia is that there aren't a whole lot of examples of the OSI network model, period. OSI has once again created a standard nobody uses, so nobody really know how one should use it. A: Layers 5-6 are not commonly used in today's web applications, so you don't hear much about them. The TCP/IP stack is slightly different than a pure OSI Model. A: One of the reasons TCP/IP is used today instead of OSI is it was too bloated and theoretical, the session and presentation layer aren't really needed as separate layers as it turned out. A: The session layer is meant to store states between two connections, like what we use cookies for when working with web programming. The presentation layer is meant to convert between different formats. This was simpler when the only format that was worried about was character encoding, ie ASCII and EBCDIC. When you consider all of the different formats that we have today(Quicktime, Flash, Pdf) centralizing this layer is out of the question. TCP/IP doesn't make any allocation to these layers, since they are really out of the scope of a networking protocol. It's up to the applications that take advantage of the stack to implement these. A: I think that presentation layer protocols define the format of data. This means protocols like XML or ASN.1. You could argue that video/audio codecs are part of the presentation layer Although this is probably heading towards the application layer. I can't help you with the session layer. That has always baffled me. To be honest, there are very vague boundaries in everything above the transport layer. This is because it is usually handled by a single software application. Also, these layers are not directly associated with transporting data from A to B. Layers 4 and below each have a very specific purpose in moving the data e.g. switching, routing, ensuring data integrity etc. This makes it easier to distinguish between these layers. A: Presentation Layer The Presentation Layer represents the area that is independent of data representation at the application layer - in general, it represents the preparation or translation of application format to network format, or from network formatting to application format. In other words, the layer “presents” data for the application or the network. A good example of this is encryption and decryption of data for secure transmission - this happens at Layer 6. Session Layer When two devices, computers or servers need to “speak” with one another, a session needs to be created, and this is done at the Session Layer. Functions at this layer involve setup, coordination (how long should a system wait for a response, for example) and termination between the applications at each end of the session. Source A: For the presentation layer :because most of communication done between heterogeneous systems (Operating Systems,programing langages,cpu architectures)we need to use a unified idepedent specification .like ANS1 ans BRE.
{ "language": "en", "url": "https://stackoverflow.com/questions/152889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How would you design a form with many dynamic fields? We have a form that allows a user to dynamically add inputs for fields. For example if you have a form for tracking projects, you want to dynamically add tasks to that project. Just to clarify my language: you dynamically add inputs for the task field. The problem is, we have 50 of those fields. Our current solution presents all 50 fields with a plus (+) next to the field to allow them to add another input box for that field. The labels for the field are to the left of the field and each input box that is added goes below the current input box. Please trust that dynamically adding inputs is the right solution, please trust that it has been thought out, please trust that this is what the users wants, please trust that we have gone down various other roads and this is the best solution. My question is about presentation: How would you do it? Please keep the answers to UI design. We already have the database schema figured out. Update Current Solution is a web based application that uses JavaScript to dynamically add new inputs and looks very similar to Corey Trager's drawing: Task [.............] + [.............] + [.............] + [.............] + Foo [.............] + [.............] + [.............] + Repeat 50 times... A: Thinking on from what @zachary suggested: Display the form as it was designed to the user with the default/ last saved number of fields. At the bottom of the form place a DropDownButton that has a + icon and the words Add Field (+ Add Field). Dropping down this button will show the list of all fields that are available. When the user selects one of these the form will grow (enough to house the new field) the new field with label will be displayed at the bottom of the form and the add field button will show below the new field. Edit: To follow on the theme of ASCII diagrams this was is what I think my suggesting would look like. Task [......................]         [ + Add Task ▼] Foo  [......................]         [ + Add Foo  ▼] A: So, what you described can look something like this? If not, can you try "drawing" it please? Task [.............] + [.............] + [.............] + [.............] + Foo [.............] + [.............] + [.............] + Is this a web page or other technology? A: This may be completely off the mark, but depending on the requirements for the fields, and if this is the configuration or the data entry interface. If the fields do need to be open for data entry, you could leave have them defined as a list of fieldnames and values, and use click-to-edit to dynamically place input boxes on each element as needed. This solution could reduce visual noise as well as save vertical space. As you can see the form input takes up more space than plain text. You can cater for keyboard users by capturing tab events and triggering the next field's click to edit functionality. It could look something like this. ( having just clicked on Foo to edit the content) Name : Joe Blogs Phone : 555-1234 Cheese : Stilton ----------- Foo | SNAFU | ----------- Bar : fubar Fifty : Whatever (+) Add new field... OR If this is a configuration page, ie where you add new fields to be filled in on another screen or stage in the process, you could define a list of fields sequentially, which are then displayed to the user for data entry. ------------------------------------------------- Define Fields | name, phone, cheese, foo, bar ..(etc).. fifty | ------------------------------------------------- Then the fields are displayed in a huge grid as per the current UI. A: Little + icon somewhere near the last task field with a link that says "Add new task". When clicked, new task field appears below current last task. A: I would use a drag-and-drop approach, allowing the user flexibility in positioning. This is possible even using a web-application. See, for example, Dropthings (http://www.dropthings.com/). This provides all the code you'd need to implement drag-n-drop in an ASP.NET environment. What environment are you using? A: If this is a web app then you could use Javascript to dynamically manage the additional fields. Depending on whether you can process the form asynchronously, you could use Ajax which would simplify some aspects of the form management. Basically, each task would need an individually named and then you would need to append a new uniquely named form input element for each new field that they choose to append. Then you would have to loop through the form using Javascript before submitting the form or you would loop through the POST data after its submitted. Of course, this introduces Javascript as a requirement for your web app which isn't always viable. A: Ok, now that you've added my diagram to your question, my answer is.... I'm not saying this is better, but it's an alternative. Here's a different way that replaces horizontal scrolling with clicking. Instead of navigating from "tasks" to "foo" to "bar" by vertical scrolling, use "tabs", even if you have to stack them several rows high. It does make it easier to navigate in a random order. You could even switch back and forth from this tabbed view to your current "show all" view. [task][foo][another tab][another tab][etc][etc][etc][etc][etc][etc] [row2][fred][another tab][etc][etc][etc][etc][etc][etc][etc] [row3][another tab][wilma][etc][etc][etc][etc][etc][etc][etc] [task1 ]+ [task2 }+ [task3 ]+ A: Could you not use a system similar to that implemented by face book, that has a single textbox, but allows multiple items to be added to it? There are pre-coded solutions, such as this one, which is for mootools v1.2, or this one which is for jQuery. And you could even allow auto-complete of the tasks already in the system.
{ "language": "en", "url": "https://stackoverflow.com/questions/152893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: .NET XmlDocument LoadXML and Entities When loading XML into an XmlDocument, i.e. XmlDocument document = new XmlDocument(); document.LoadXml(xmlData); is there any way to stop the process from replacing entities? I've got a strange problem where I've got a TM symbol (stored as the entity #8482) in the xml being converted into the TM character. As far as I'm concerned this shouldn't happen as the XML document has the encoding ISO-8859-1 (which doesn't have the TM symbol) Thanks A: This is a standard misunderstanding of the XML toolset. The whole business with "&#x", is a syntactic feature designed to cope with character encodings. Your XmlDocument isn't a stream of characters - it has been freed of character encoding issues - instead it contains an abstract model of XML type data. Words for this include DOM and InfoSet, I'm not sure exactly which is accurate. The "&#x" gubbins won't exist in this model because the whole issue is irrelevant, it will return - if appropriate - when you transform the Info Set back into a character stream in some specific encoding. This misunderstanding is sufficiently common to have made it into academic literature as part of a collection of similar quirks. Take a look at "Xml Fever" at this location: http://doi.acm.org/10.1145/1364782.1364795 A: What are you writing it to? A TextWriter? a Stream? what? The following keeps the entity (well, it replaces it with the hex equivalent) - but if you do the same with a StringWriter it detects the unicode and uses that instead: XmlDocument doc = new XmlDocument(); doc.LoadXml(@"<xml>&#8482;</xml>"); using (MemoryStream ms = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.GetEncoding("ISO-8859-1"); XmlWriter xw = XmlWriter.Create(ms, settings); doc.Save(xw); xw.Close(); Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); } Outputs: <?xml version="1.0" encoding="iso-8859-1"?><xml>&#x2122;</xml> A: I confess things get a little confusing with XML documents and encodings, but I'd hope that it would get set appropriate when you save it again, if you're still using ISO-8859-1 - but that if you save with UTF-8, it wouldn't need to. In some ways, logically the document really contains the symbol rather the entity reference - the latter is just an encoding matter. (I'm thinking aloud here - please don't take this as authoritative information.) What are you doing with the document after loading it? A: I beleive if you enclose the entity contents in the CDATA section it should leave it all alone e.g. <root> <testnode> <![CDATA[some text &#8482;]]> </testnode> </root> A: Entity references are not encoding specific. According to the W3C XML 1.0 Recommendation: If the character reference begins with "&#x", the digits and letters up to the terminating ; provide a hexadecimal representation of the character's code point in ISO/IEC 10646. A: The &#xxxx; entities are considered to be the character they represent. All XML is converted to unicode on reading and any such entities are removed in favor of the unicode character they represent. This includes any occurance for them in unicode source such as the string passed to LoadXML. Similarly on writing any character that cannot be represented by the stream being written to is converted to a &#xxxx; entity. There is little point trying to preserve them. A common mistake is expect to get a String from a DOM by some means that uses an encoding other then unicode. That just doesn't happen regardless of what the A: Thanks for all of the help. I've fixed my problem by writing a HtmlEncode function which actually replaces all of the characters before it spits them out to the webpage (instead of relying on the somewhat broken HtmlEncode() .NET function which only seems to encode a small subset of the characters necessary)
{ "language": "en", "url": "https://stackoverflow.com/questions/152900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }