source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
35,375 | I recently installed Ubuntu on a VirtualBox VM it installed just fine (much easier than on VirtualPC). However I'm unable to get internet access from the guest OS (ie. Ubuntu). Can anyone give me any pointers on how I might enable this? The Host OS is Windows Vista and the hardware is an IBM Lenovo. | How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3433/"
]
} |
35,490 | In one of the answers to Broadcast like UDP with the Reliability of TCP , a user mentions the Spread messaging API. I've also run across one called ØMQ . I also have some familiarity with MPI . So, my main question is: why would I choose one over the other? More specifically, why would I choose to use Spread or ØMQ when there are mature implementations of MPI to be had? | MPI was deisgned tightly-coupled compute clusters with fast, reliable networks. Spread and ØMQ are designed for large distributed systems. If you're designing a parallel scientific application, go with MPI, but if you are designing a persistent distributed system that needs to be resilient to faults and network instability, use one of the others. MPI has very limited facilities for fault tolerance; the default error handling behavior in most implementations is a system-wide fail. Also, the semantics of MPI require that all messages sent eventually be consumed. This makes a lot of sense for simulations on a cluster, but not for a distributed application. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/35490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
]
} |
35,530 | Graphics and audio editing and processing software often contain functions called "High-Pass Filter" and "Low-Pass Filter". Exactly what do these do, and what are the algorithms for implementing them? | Wikipedia: High-pass filter Low-pass filter Band-pass filter These "high", "low", and "band" terms refer to frequencies . In high-pass, you try to remove low frequencies. In low-pass, you try to remove high. In band pass, you only allow a continuous frequency range to remain. Choosing the cut-off frequency depends upon your application. Coding these filters can either be done by simulating RC circuits or by playing around with Fourier transforms of your time-based data. See the wikipedia articles for code examples. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/35530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
]
} |
35,538 | What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app. | XHTML is easy, use lxml . from lxml import etreefrom StringIO import StringIOetree.parse(StringIO(html), etree.HTMLParser(recover=False)) HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as nsgmls or OpenJade , and then parse their output. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
]
} |
35,551 | In a project I'm working on FxCop shows me lots of (and I mean more than 400) errors on the InitializeComponent() methods generated by the Windows Forms designer. Most of those errors are just the assignment of the Text property of labels. I'd like to suppress those methods in source, so I copied the suppression code generated by FxCop into AssemblyInfo.cs, but it doesn't work. This is the attribute that FxCop copied to the clipboard. [module: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "WindowsClient.MainForm.InitializeComponent():System.Void", MessageId = "System.Windows.Forms.Control.set_Text(System.String)")] Anyone knows the correct attribute to suppress this messages? PS: I'm using Visual Studio 2005, C#, FxCop 1.36 beta. | You've probably got the right code, but you also need to add CODE_ANALYSIS as a precompiler defined symbol in the project properties. I think those SuppressMessage attributes are only left in the compiled binaries if CODE_ANALYSIS is defined. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
]
} |
35,563 | Using Terminal.app on OS X 10.5, often you see the commands get garbled when you do a reverse-search with Bash. Is there some kind of termcap or perhaps a bash shopt command that can fix this? It is very annoying. Steps to reproduce: Open Terminal.app, reverse-search to a longish command. Hit <ctrl>-E once you've found the command. The cursor goes to the end of the line, but the display doesn't update. I'm guessing this is some kind of problem with the readline library on OS X. It's more of a problem with updating the cursor position after a search than anything else. Basically, ctrl-a and ctrl-e tend to break the search output. os x terminal failure image http://involution.com/images/osxterminal.png In the above, the first part of the command should be displayed, and the cursor should be at the end of the line, but it isn't. You literally can't see what you're editing when this happens. | I was able to set my TERM to xterm instead of xterm-color and it solves the problem. (export TERM=xterm). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
]
} |
35,634 | Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location). | Use a.equal? b http://www.ruby-doc.org/core/classes/Object.html Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
]
} |
35,646 | Suppose you're developing a software product that has periodic releases. What are the best practices with regard to branching and merging? Slicing off periodic release branches to the public (or whomever your customer is) and then continuing development on the trunk, or considering the trunk the stable version, tagging it as a release periodically, and doing your experimental work in branches. What do folks think is the trunk considered "gold" or considered a "sand box"? | I have tried both methods with a large commercial application. The answer to which method is better is highly dependent on your exact situation, but I will write what my overall experience has shown so far. The better method overall (in my experience): The trunk should be always stable. Here are some guidelines and benefits of this method: Code each task (or related set of tasks) in its own branch, then you will have the flexibility of when you would like to merge these tasks and perform a release. QA should be done on each branch before it is merged to the trunk. By doing QA on each individual branch, you will know exactly what caused the bug easier. This solution scales to any number of developers. This method works since branching is an almost instant operation in SVN. Tag each release that you perform. You can develop features that you don't plan to release for a while and decide exactly when to merge them. For all work you do, you can have the benefit of committing your code. If you work out of the trunk only, you will probably keep your code uncommitted a lot, and hence unprotected and without automatic history. If you try to do the opposite and do all your development in the trunk you'll have the following issues: Constant build problems for daily builds Productivity loss when a a developer commits a problem for all other people on the project Longer release cycles, because you need to finally get a stable version Less stable releases You simply will not have the flexibility that you need if you try to keep a branch stable and the trunk as the development sandbox. The reason is that you can't pick and chose from the trunk what you want to put in that stable release. It would already be all mixed in together in the trunk. The one case in particular that I would say to do all development in the trunk, is when you are starting a new project. There may be other cases too depending on your situation. By the way distributed version control systems provide much more flexibility and I highly recommend switching to either hg or git. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/35646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
]
} |
35,670 | I am ready to start using SVN, but I have NO (as in the money required for free beer) experience with source control. I have installed subversion on my server (that was easy, 'apt-get install subversion') but now I don't know what to do, how to configure it, or how to use it. What suggestions do you have, and where can I find good resources to learn to start using it? Update: O.K. So the feedback has been great and I have read through a bit of it but I want to clarify my question by saying that I am looking for more information on how to actually go about setting my up my repositories, clients, server, etc. I know that I could do a quick Google search and find dozens (or more) resources but I'm hoping that someone whom has experience with subversion and a client(I have installed tortoise) could suggest a good reference that will be reliable, and have quality content. | Eric Sink has an excellent series on source code control aimed at beginners. For Subversion specifics, including setting up and administering a server, the Subversion book is a great resource, and includes a section with examples of a typical session with Subversion (checkout, commit, merging and updating basics). Update: I forgot to mention that for beginners, I'd also recommend messing around in a graphical client, which removes the command-line hassle from the learning experience. RapidSVN is a reasonable cross-platform client. You'll also find that common IDEs either come with Subversion support, or have plugins which can be installed, which allow most version control operations to be performed within that environment. @John Millikin: While setting up a Subversion server can be complicated, depending on one's general admin experience, don't forget that you don't need to do that just to mess about with a repository and get to grips with the basics - the client can interact with a repository in the local filesystem. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
35,753 | Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)? What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion. | We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at Resolver Systems , so I'd definitely say it's ready for production use of complex apps. There are two ways in which this might not be a useful answer to you :-) We're using IronPython, not the more usual CPython. This gives us the huge advantage of being able to use .NET class libraries. I may be setting myself up for flaming here, but I would say that I've never really seen a CPython application that looked "professional" - so having access to the WinForms widget set was a huge win for us. IronPython also gives us the advantage of being able to easily drop into C# if we need a performance boost. (Though to be honest we have never needed to do that. All of our performance problems to date have been because we chose dumb algorithms rather than because the language was slow.) Using C# from IP is much easier than writing a C Extension for CPython. We're an Extreme Programming shop, so we write tests before we write code. I would not write production code in a dynamic language without writing the tests first; the lack of a compile step needs to be covered by something, and as other people have pointed out, refactoring without it can be tough. (Greg Hewgill's answer suggests he's had the same problem. On the other hand, I don't think I would write - or especially refactor - production code in any language these days without writing the tests first - but YMMV.) Re: the IDE - we've been pretty much fine with each person using their favourite text editor; if you prefer something a bit more heavyweight then WingIDE is pretty well-regarded. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/35753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3373/"
]
} |
35,762 | I have a large GUI project that I'd like to port to Linux.What is the most recommended framework to utilize for GUI programming in Linux? Are Frameworks such as KDE / Gnome usable for this objective Or is better to use something more generic other than X? I feel like if I chose one of Gnome or KDE, I'm closing the market out for a chunk of the Linux market who have chosen one over the other. (Yes I know there is overlap) Is there a better way? Or would I have to create 2 complete GUI apps to have near 100% coverage? It's not necessary to have a cross-platform solution that will also work on Win32. | Your best bet may be to port it to a cross-platform widget library such as wxWidgets , which would give you portability to any platform wxWidgets supports. It's also important to make the distinction between Gnome libraries and GTK, and likewise KDE libraries and Qt. If you write the code to use GTK or Qt, it should work fine for users of any desktop environment, including less popular ones like XFCE. If you use other Gnome or KDE-specific libraries to do non-widget-related tasks, your app would be less portable between desktop environments. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
35,785 | What is the Java analogue of .NET's XML serialization? | 2008 Answer The "Official" Java API for this is now JAXB - Java API for XML Binding. See Tutorial by Oracle . The reference implementation lives at http://jaxb.java.net/ 2018 Update Note that the Java EE and CORBA Modules are deprecated in SE in JDK9 and to be removed from SE in JDK11 . Therefore, to use JAXB it will either need to be in your existing enterprise class environment bundled by your e.g. app server, or you will need to bring it in manually. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/35785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3583/"
]
} |
35,805 | If I create a class A as follows: class A: def __init__(self): self.name = 'A' Inspecting the __dict__ member looks like {'name': 'A'} If however I create a class B : class B: name = 'B' __dict__ is empty. What is the difference between the two, and why doesn't name show up in B 's __dict__ ? | B.name is a class attribute, not an instance attribute. It shows up in B.__dict__ , but not in b = B(); b.__dict__ . The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, b.name will give you the value of B.name . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/35805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154/"
]
} |
35,817 | When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash. I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option: def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")os.system("cat %s | grep something | sort > %s" % (sh_escape(in_filename), sh_escape(out_filename))) Edit: I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently. Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me). | This is what I use: def shellquote(s): return "'" + s.replace("'", "'\\''") + "'" The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter. Update : If you are using Python 3.3 or later, use shlex.quote instead of rolling your own. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/35817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
]
} |
35,837 | I've been using git for some time now on Windows (with msysGit) and I like the idea of distributed source control. Just recently I've been looking at Mercurial (hg) and it looks interesting. However, I can't wrap my head around the differences between hg and git. Has anyone made a side-by-side comparison between git and hg? I'm interested to know what differs hg and git without having to jump into a fanboy discussion. | These articles may help: Git vs. Mercurial: Please Relax (Git is MacGyver and Mercurial is James Bond) The Differences Between Mercurial and Git Edit : Comparing Git and Mercurial to celebrities seems to be a trend. Here's one more: Git is Wesley Snipes, Mercurial is Denzel Washington | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/35837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713/"
]
} |
35,842 | How do I get the id of my Java process? I know there are several platform-dependent hacks, but I would prefer a more generic solution. | There exists no platform-independent way that can be guaranteed to work in all jvm implementations. ManagementFactory.getRuntimeMXBean().getName() looks like the best (closest) solution, and typically includes the PID. It's short, and probably works in every implementation in wide use. On linux+windows it returns a value like "12345@hostname" ( 12345 being the process id). Beware though that according to the docs , there are no guarantees about this value: Returns the name representing the running Java virtual machine. Thereturned name string can be any arbitrary string and a Java virtualmachine implementation can choose to embed platform-specific usefulinformation in the returned name string. Each running virtual machinecould have a different name. In Java 9 the new process API can be used: long pid = ProcessHandle.current().pid(); | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/35842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3583/"
]
} |
35,879 | I am building an open search add-on for Firefox/IE and the image needs to be Base64 Encoded so how can I base 64 encode the favicon I have? I am only familiar with PHP | As far as I remember there is an xml element for the image data. You can use this website to encode a file (use the upload field). Then just copy and paste the data to the XML element. You could also use PHP to do this like so: <?php $im = file_get_contents('filename.gif'); $imdata = base64_encode($im); ?> Use Mozilla's guide for help on creating OpenSearch plugins. For example, the icon element is used like this: <img width="16" height="16">data:image/x-icon;base64,imageData</> Where imageData is your base64 data. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/35879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
35,922 | I've played around with GTK, TK, wxPython, Cocoa, curses and others. They are are fairly horrible to use.. GTK/TK/wx/curses all seem to basically be direct-ports of the appropriate C libraries, and Cocoa basically mandates using both PyObjC and Interface Builder, both of which I dislike.. The Shoes GUI library for Ruby is great.. It's very sensibly designed, and very "rubyish", and borrows some nice-to-use things from web development (like using hex colours codes, or :color => rgb(128,0,0) ) As the title says: are there any nice, "Pythonic" GUI toolkits? | Have you looked at Qt / PyQt ? Although PyQt is a direct port from the C++ library, I find it much more pythonic and nice to program with compared to the others you listed. It also has very good documentation. Dabo has a nice ui library implemented on top of wxPython. It's a framework intended mostly for database-centric applications, but the ui library can be used separately. There are/were several other attempts to create a very pythonic gui as a layer on top of PyGtk or wxPython, such as wax and PyGui , which seem to be "stuck" at various degrees of being complete. Also, an exhaustive list of Python GUI toolkits can be found here . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
]
} |
35,948 | I'm using Google App Engine and Django templates. I have a table that I want to display the objects look something like: Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] The Django template is: <table><tr align="center"> <th>user</th> {% for item in result.items %} <th>{{item}}</th> {% endfor %}</tr>{% for user in result.users %} <tr align="center"> <td>{{user.name}}</td> {% for item in result.items %} <td>{{ user.item }}</td> {% endfor %} </tr>{% endfor %}</table> Now the Django documention states that when it sees a . in variables It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen... | I found a "nicer"/"better" solution for getting variables insideIts not the nicest way, but it works. You install a custom filter into django which gets the key of your dict as a parameter To make it work in google app-engine you need to add a file to your main directory,I called mine django_hack.py which contains this little piece of code from google.appengine.ext import webappregister = webapp.template.create_template_register()def hash(h,key): if key in h: return h[key] else: return Noneregister.filter(hash) Now that we have this file, all we need to do is tell the app-engine to use it...we do that by adding this little line to your main file webapp.template.register_template_library('django_hack') and in your template view add this template instead of the usual code {{ user|hash:item }} And its should work perfectly =) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/35948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3117/"
]
} |
35,983 | Let's say I have committed some bad changes to Subversion repository. Then I commit good changes, that I want to keep. What would be easiest way to roll back those bad changes in Eclipse, and keep the good changes? Assuming that files relating to bad changes are not same as those relating to the good changes. How things change if good changes were made to same files as bad changes? I am mostly looking a way to do this via Eclipse plugins (Subclipse or Subversive) but commandline commands are also interesting. | You have two choices to do this. The Quick and Dirty is selecting your files (using ctrl ) in Project Explorer view, right-click them, choose Replace with... and then you choose the best option for you, from Latest from Repository , or some Branch version. After getting those files you modify them (with a space, or fix something, your call and commit them to create a newer revision. A more clean way is choosing Merge at team menu and navigate through the wizard that will help you to recovery the old version in the actual revision. Both commands have their command-line equivalents: svn revert and svn merge . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/35983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431/"
]
} |
35,988 | Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like: class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 | Use a named tuple , which was added to the collections module in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's named tuple recipe if you need to support Python 2.4. It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as: from collections import namedtupleMyStruct = namedtuple("MyStruct", "field1 field2 field3") The newly created type can be used like this: m = MyStruct("foo", "bar", "baz") You can also use named arguments: m = MyStruct(field1="foo", field2="bar", field3="baz") | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/35988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3738/"
]
} |
35,991 | I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using syncdb to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework).I was already thinking this was too good to be true when I saw this in the documentation : Syncdb will not alter existing tables syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: As the documentation suggests, make the changes manually in the DB; Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas? | Manually doing the SQL changes and dump/reload are both options, but you may also want to check out some of the schema-evolution packages for Django. The most mature options are django-evolution and South . EDIT : And hey, here comes dmigrations . UPDATE : Since this answer was originally written, django-evolution and dmigrations have both ceased active development and South has become the de-facto standard for schema migration in Django. Parts of South may even be integrated into Django within the next release or two. UPDATE : A schema-migrations framework based on South (and authored by Andrew Godwin, author of South) is included in Django 1.7+. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/35991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
]
} |
35,999 | How can I execute a.exe using the Cygwin shell? I created a C file in Eclipse on Windows and then used Cygwin to navigate to the directory. I called gcc on the C source file and a.exe was produced. I would like to run a.exe . | ./a.exe at the prompt | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/35999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
36,001 | I have a table defined (see code snippet below). How can I add a constraint or whatever so that the LastUpdate column is automatically updated anytime the row is changed? CREATE TABLE dbo.Profiles( UserName varchar(100) NOT NULL, LastUpdate datetime NOT NULL CONSTRAINT DF_Profiles_LastUpdate DEFAULT (getdate()), FullName varchar(50) NOT NULL, Birthdate smalldatetime NULL, PageSize int NOT NULL CONSTRAINT DF_Profiles_PageSize DEFAULT ((10)), CONSTRAINT PK_Profiles PRIMARY KEY CLUSTERED (UserName ASC), CONSTRAINT FK_Profils_Users FOREIGN KEY (UserName) REFERENCES dbo.Users (UserName) ON UPDATE CASCADE ON DELETE CASCADE ) | I agree with the others -- set a default value of GetDate() on the LastUpdate column and then use a trigger to handle any updates. Just something simple like this: CREATE TRIGGER KeepUpdated on ProfilesFOR UPDATE, INSERT AS UPDATE dbo.Profiles SET LastUpdate = GetDate()WHERE Username IN (SELECT Username FROM inserted) If you want to get really fancy, have it evaluate what's being changed versus what's in the database and only modify LastUpdate if there was a difference. Consider this... 7am - User 'jsmith' is created with a last name of 'Smithe' (oops), LastUpdate defaults to 7am 8am - 'jsmith' emails IT to say his name is incorrect. You immediately perform the update, so the last name is now 'Smith' and (thanks to the trigger) LastUpdate shows 8am 2pm - Your slacker coworker finally gets bored with StumbleUpon and checks his email. He sees the earlier message from 'jsmith' regarding the name change. He runs: UPDATE Profiles SET LastName='Smith' WHERE Username='jsmith' and then goesback to surfing MySpace. The trigger doesn't care that the last name was already 'Smith', however, so LastUpdate now shows 2pm. If you just blindly change LastUpdate whenever an update statement runs, it's TECHNICALLY correct because an update did happen, but it probably makes more sense to actually compare the changes and act accordingly. That way, the 2pm Update statement by the coworker would still run, but LastUpdate would still show 8am. --Kevin | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
]
} |
36,014 | I'm working on a project using the ANTLR parser library for C#. I've built a grammar to parse some text and it works well. However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions. The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception. The issue for me is that I can't replicate this issue anywhere else but in my full code. The call stack shows that the exception definitely occurs within my try/catch(Exception) block. The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it. I wonder if non-debuggable assemblies inhibit exception bubbling? The call stack looks like this; external assembly calls are in Antlr.Runtime: Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C# Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes C# Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C# The code snippet from the bottom-most call in Parse() looks like: try { // Execution stopped at parser.prog() TimeDefParser.prog_return prog_ret = parser.prog(); return prog_ret == null ? null : prog_ret.value; } catch (Exception ex) { throw new ParserException(ex.Message, ex); } To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't? Update: I traced through the external assembly with Reflector and found no evidence of threading whatsoever. The assembly seems to just be a runtime utility class for ANTLR's generated code. The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception. This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input. This exception is SUPPOSED to happen, however it should've been caught by my try/catch block. Also, the rethrowing of ParserException is really irrelevant to this situation. That is a layer of abstraction that takes any exception during parse and convert to my own ParserException. The exception handling problem I'm experiencing is never reaching that line of code. In fact, I commented out the "throw new ParserException" portion and still received the same result. One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion. I still received the same result. Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode. Man, I'm still stumped! I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5. The external assembly is 2.0. Also, some of my code subclasses a class in the 2.0 assembly. Could a version mismatch cause this issue? Update 2: I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario. I was able to replicate the same unhandled exception when running consistently in .NET 2.0. I learned that ANTLR has recently released 3.1. So, I upgraded from 3.0.1 and retried. It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases. Update 3: I've replicated this scenario in a simplified VS 2008 project . Feel free to download and inspect the project for yourself. I've applied all the great suggestions, but have not been able to overcome this obstacle yet. If you can find a workaround, please do share your findings. Thanks again! Thank you, but VS 2008 automatically breaks on unhandled exceptions. Also, I don't have a Debug->Exceptions dialog. The NoViableAltException that is thrown is fully intended, and designed to be caught by user code. Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception. The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR. | I believe I understand the problem. The exception is being caught, the issue is confusion over the debugger's behavior and differences in the debugger settings among each person trying to repro it. In the 3rd case from your repro I believe you are getting the following message: "NoViableAltException was unhandled by user code" and a callstack that looks like this: [External Code] > TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C# [External Code] TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C# [External Code] If you right click in the callstack window and run turn on show external code you see this: Antlr3.Runtime.dll!Antlr.Runtime.DFA.NoViableAlt(int s = 0x00000000, Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x80 bytes Antlr3.Runtime.dll!Antlr.Runtime.DFA.Predict(Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x21e bytes > TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C# Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xc4 bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x147 bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 0x00000001) + 0x2d bytes TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C# [Native to Managed Transition] [Managed to Native Transition] mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x39 bytes Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x2b bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x3b bytes mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x81 bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x40 bytes The debugger's message is telling you that an exception originating outside your code (from NoViableAlt) is going through code you own in TestAntlr-3.1.exe!TimeDefLexer.mTokens() without being handled. The wording is confusing, but it does not mean the exception is uncaught. The debugger is letting you know that code you own mTokens()" needs to be robust against this exception being thrown through it. Things to play with to see how this looks for those who didn't repro the problem: Go to Tools/Options/Debugging andturn off "Enable Just My code(Managed only)". or option. Go to Debugger/Exceptions and turn off "User-unhandled" forCommon-Language Runtime Exceptions. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/36014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3347/"
]
} |
36,039 | C++ seems to be rather grouchy when declaring templates across multiple files. More specifically, when working with templated classes, the linker expect all method definitions for the class in a single compiler object file. When you take into account headers, other declarations, inheritance, etc., things get really messy. Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files? | Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files? Yes; don't. The C++ spec permits a compiler to be able to "see" the entire template (declaration and definition) at the point of instantiation, and (due to the complexities of any implementation) most compilers retain this requirement. The upshot is that #inclusion of any template header must also #include any and all source required to instantiate the template. The easiest way to deal with this is to dump everything into the header, inline where posible, out-of-line where necessary. If you really regard this as an unacceptable affront, a common option is to split the template into the usual header/implementation pair, and then #include the implementation file at the end of the header. C++'s "export" feature may or may not provide another workaround. The feature is poorly supported and poorly defined; although it in principle should permit some kind of separate compilation of templates, it doesn't necessarily obviate the demand that the compiler be able to see the entire template body. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/36039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4381/"
]
} |
36,077 | I'm looking for an answer in MS VC++. When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want. Example in pseudo code: FunctionB(){ ... throw e; ...}FunctionA(){ ... FunctionB() ...}try{ Function A()}catch(e){ (<--- breakpoint) ...} I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in FunctionA() or FunctionB() , or some other function. (Assuming extensive exception use and a huge version of the above example). One solution to my problem is to determine and save the call stack in the exception constructor (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program. Is there an easier way that requires less work? Without having to change my large code base? Are there better solutions to this problem in other languages? | If you are just interested in where the exception came from, you could just write a simple macro like #define throwException(message) \ { \ std::ostringstream oss; \ oss << __FILE __ << " " << __LINE__ << " " \ << __FUNC__ << " " << message; \ throw std::exception(oss.str().c_str()); \ } which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros). Then throw exceptions using throwException("An unknown enum value has been passed!"); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
36,106 | I have an information retrieval application that creates bit arrays on the order of 10s of million bits. The number of "set" bits in the array varies widely, from all clear to all set. Currently, I'm using a straight-forward bit array ( java.util.BitSet ), so each of my bit arrays takes several megabytes. My plan is to look at the cardinality of the first N bits, then make a decision about what data structure to use for the remainder. Clearly some data structures are better for very sparse bit arrays, and others when roughly half the bits are set (when most bits are set, I can use negation to treat it as a sparse set of zeroes). What structures might be good at each extreme? Are there any in the middle? Here are a few constraints or hints: The bits are set only once, and in index order. I need 100% accuracy, so something like a Bloom filter isn't good enough. After the set is built, I need to be able to efficiently iterate over the "set" bits. The bits are randomly distributed, so run-length–encoding algorithms aren't likely to be much better than a simple list of bit indexes. I'm trying to optimize memory utilization, but speed still carries some weight. Something with an open source Java implementation is helpful, but not strictly necessary. I'm more interested in the fundamentals. | Unless the data is truly random and has a symmetric 1/0 distribution, then this simply becomes a lossless data compression problem and is very analogous to CCITT Group 3 compression used for black and white (i.e.: Binary) FAX images. CCITT Group 3 uses a Huffman Coding scheme. In the case of FAX they are using a fixed set of Huffman codes, but for a given data set, you can generate a specific set of codes for each data set to improve the compression ratio achieved. As long as you only need to access the bits sequentially, as you implied, this will be a pretty efficient approach. Random access would create some additional challenges, but you could probably generate a binary search tree index to various offset points in the array that would allow you to get close to the desired location and then walk in from there. Note : The Huffman scheme still works well even if the data is random, as long as the 1/0 distribution is not perfectly even. That is, the less even the distribution, the better the compression ratio. Finally, if the bits are truly random with an even distribution, then, well, according to Mr. Claude Shannon , you are not going to be able to compress it any significant amount using any scheme. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3474/"
]
} |
36,108 | Some WPF controls (like the Button ) seem to happily consume all the available space in its' container if you don't specify the height it is to have. And some, like the ones I need to use right now, the (multiline) TextBox and the ListBox seem more worried about just taking the space necessary to fit their contents, and no more. If you put these guys in a cell in a UniformGrid , they will expand to fit the available space. However, UniformGrid instances are not right for all situations. What if you have a grid with some rows set to a * height to divide the height between itself and other * rows? What if you have a StackPanel and you have a Label , a List and a Button , how can you get the list to take up all the space not eaten by the label and the button? I would think this would really be a basic layout requirement, but I can't figure out how to get them to fill the space that they could (putting them in a DockPanel and setting it to fill also doesn't work, it seems, since the DockPanel only takes up the space needed by its' subcontrols). A resizable GUI would be quite horrible if you had to play with Height , Width , MinHeight , MinWidth etc. Can you bind your Height and Width properties to the grid cell you occupy? Or is there another way to do this? | There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say: HorizontalContentAlignment="Stretch" ... to force the contents of a control to stretch horizontally. Or you can say: HorizontalAlignment="Stretch" ... to force the control itself to stretch horizontally to fill its parent. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/36108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2122/"
]
} |
36,139 | What is the best way of creating an alphabetically sorted list in Python? | Basic answer: mylist = ["b", "C", "A"]mylist.sort() This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted() function: for x in sorted(mylist): print x However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter key to specify custom sorting order (the alternative, using cmp , is a deprecated solution, as it has to be evaluated multiple times - key is only computed once per element). So, to sort according to the current locale, taking language-specific rules into account ( cmp_to_key is a helper function from functools): sorted(mylist, key=cmp_to_key(locale.strcoll)) And finally, if you need, you can specify a custom locale for sorting: import localelocale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/localeassert sorted((u'Ab', u'ad', u'aa'), key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad'] Last note: you will see examples of case-insensitive sorting which use the lower() method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data: # this is incorrect!mylist.sort(key=lambda x: x.lower())# alternative notation, a bit faster, but still wrongmylist.sort(key=str.lower) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/36139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
]
} |
36,183 | I'm trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances. For example, I have this string: 12||34||56 I want to replace the second set of pipes with ampersands to get this string: 12||34&&56 The regex function needs to be able to handle x amount of pipes and allow me to replace the nth set of pipes, so I could use the same function to make these replacements: 23||45||45||56||67 -> 23&&45||45||56||6723||34||98||87 -> 23||34||98&&87 I know that I could just split/replace/concat the string at the pipes, and I also know that I can match on /\|\|/ and iterate through the resulting array, but I'm interested to know if it's possible to write a single expression that can do this. Note that this would be for Javascript, so it's possible to generate a regex at runtime using eval() , but it's not possible to use any Perl-specific regex instructions. | here's something that works: "23||45||45||56||67".replace(/^((?:[0-9]+\|\|){n})([0-9]+)\|\|/,"$1$2&&") where n is the one less than the nth pipe, (of course you don't need that first subexpression if n = 0) And if you'd like a function to do this: function pipe_replace(str,n) { var RE = new RegExp("^((?:[0-9]+\\|\\|){" + (n-1) + "})([0-9]+)\|\|"); return str.replace(RE,"$1$2&&");} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2289/"
]
} |
36,239 | I would like to think that some of the software I'm writing today will be used in 30 years. But I am also aware that a lot of it is based upon the UNIX tradition of exposing time as the number of seconds since 1970. #include <stdio.h>#include <time.h>#include <limits.h>void print(time_t rt) { struct tm * t = gmtime(&rt); puts(asctime(t));}int main() { print(0); print(time(0)); print(LONG_MAX); print(LONG_MAX+1);} Execution results in: Thu Jan 1 00:00:00 1970 Sat Aug 30 18:37:08 2008 Tue Jan 19 03:14:07 2038 Fri Dec 13 20:45:52 1901 The functions ctime(), gmtime(), and localtime() all take as an argument a time value representing the time in seconds since the Epoch (00:00:00 UTC, January 1, 1970; see time(3) ). I wonder if there is anything proactive to do in this area as a programmer, or are we to trust that all software systems (aka Operating Systems) will some how be magically upgraded in the future? Update It would seem that indeed 64-bit systems are safe from this: import java.util.*;class TimeTest { public static void main(String[] args) { print(0); print(System.currentTimeMillis()); print(Long.MAX_VALUE); print(Long.MAX_VALUE + 1); } static void print(long l) { System.out.println(new Date(l)); }} Wed Dec 31 16:00:00 PST 1969 Sat Aug 30 12:02:40 PDT 2008 Sat Aug 16 23:12:55 PST 292278994 Sun Dec 02 08:47:04 PST 292269055 But what about the year 292278994? | I have written portable replacement for time.h (currently just localtime(), gmtime(), mktime() and timegm()) which uses 64 bit time even on 32 bit machines. It is intended to be dropped into C projects as a replacement for time.h. It is being used in Perl and I intend to fix Ruby and Python's 2038 problems with it as well. This gives you a safe range of +/- 292 million years. You can find the code at the y2038 project . Please feel free to post any questions to the issue tracker . As to the "this isn't going to be a problem for another 29 years", peruse this list of standard answers to that. In short, stuff happens in the future and sometimes you need to know when. I also have a presentation on the problem, what is not a solution, and what is . Oh, and don't forget that many time systems don't handle dates before 1970. Stuff happened before 1970, sometimes you need to know when. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/36239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
]
} |
36,260 | I'm writing an interpreter for an experimental language. Three of the main constructs of the language are definitions, statements, and expressions. Definitions can contain statements and expressions, statements can contain definitions and expressions, and one kind of expression can contain statements. I represent all of these using union types so I can easily use pattern matching on them. Ideally, I would like to put the code for these in different files, but OMake complains about circular dependency issues. As far as I know, circular type definitions across modules are not allowed. The only way I know of to solve this is to define all three types at once: type defn = ...and stmt = ...and expr = ... It seems like this requires all the code for types to be in the same file. Is there any way around this? How do you deal with circular definitions in your code? | Recursive definitions need to appear in the same file. If you want to separate definitions, statements, and expressions into separate modules, you can do so using recursive modules , but they will still need to appear in the same file. DAG-ifying inter-file dependencies is one of the annoyances of OCaml. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
]
} |
36,274 | What is Lazy Loading? [Edit after reading a few answers]Why do people use this term so often? Say you just use a ASP/ADO recordset and load it with data or ADO.NET Datasource for a gridview. I guess I should have asked why people use the term Lazy Loading, what "other" types are their? | It's called lazy loading because, like a lazy person, you are putting off doing something you don't want to. The opposite is Eager Loading, where you load something right away, long before you need it. If you are curious why people might use lazy loading, consider an application that takes a LOOOOONG time to start. This application is probably doing a lot of eager loading... loading things from disk, and doing calculations and whatnot long before it is ever needed. Compare this to lazy loading, the application would start much faster, but then the first time you need to do something that requires some long running load, there may be a slight pause while it is loaded for the first time. Thus, with lazy loading, you are amortizing the load time throughout the course of running your application... and you may actually save from loading things that the user may never intend to use. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/36274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
]
} |
36,294 | Looks like here in StackOveflow there is a group of F# enthusiasts. I'd like to know better this language, so, apart from the functional programming theory , can you point me to the better starting points to start using the F# language? I mean, tutorials, how-tos, but first of all working samples to have the chance to start doing something and enjoy the language. Thanks a lot Andrea | Not to whore myself horribly but I wrote a couple F# overview posts on my blog here and here . Chris Smith (guy on the F# team at MS) has an article called 'F# in 20 minutes' - part 1 and part 2 . Note you have to be careful as the latest CTP of F# (version 1.9.6.0) has some seriously breaking changes compared to previous versions, so some examples/tutorials out there might not work without modification. Here's a quick run-down of some cool stuff, maybe I can give you a few hints here myself which are clearly very brief and probably not great but hopefully gives you something to play with!:- First note - most examples on the internet will assume 'lightweight syntax' is turned on. To achieve this use the following line of code:- #light This prevents you from having to insert certain keywords that are present for OCaml compatibility and also having to terminate each line with semicolons. Note that using this syntax means indentation defines scope. This will become clear in later examples, all of which rely on lightweight syntax being switched on. If you're using the interactive mode you have to terminate all statements with double semi-colons, for example:- > #light;; > let f x y = x + y;; val f : int -> int -> int > f 1 2;; val it : int = 3 Note that interactive mode returns a 'val' result after each line. This gives important information about the definitions we are making, for example 'val f : int -> int -> int' indicates that a function which takes two ints returns an int. Note that only in interactive do we need to terminate lines with semi-colons, when actually defining F# code we are free of that :-) You define functions using the 'let' keyword. This is probably the most important keyword in all of F# and you'll be using it a lot. For example:- let sumStuff x y = x + ylet sumStuffTuple (x, y) = x + y We can call these functions thus:- sumStuff 1 23sumStuffTuple (1, 2)3 Note there are two different ways of defining functions here - you can either separate parameters by whitespace or specify parameters in 'tuples' (i.e. values in parentheses separated by commas). The difference is that we can use 'partial function application' to obtain functions which take less than the required parameters using the first approach, and not with the second. E.g.:- let sumStuff1 = sumStuff 1sumStuff 23 Note we are obtaining a function from the expression 'sumStuff 1'. When we can pass around functions just as easily as data that is referred to as the language having 'first class functions', this is a fundamental part of any functional language such as F#. Pattern matching is pretty darn cool, it's basically like a switch statement on steroids (yeah I nicked that phrase from another F#-ist :-). You can do stuff like:- let someThing x = match x with | 0 -> "zero" | 1 -> "one" | 2 -> "two" | x when x < 0 -> "negative = " + x.ToString() | _ when x%2 = 0 -> "greater than two but even" | _ -> "greater than two but odd" Note we use the '_' symbol when we want to match on something but the expression we are returning does not depend on the input. We can abbreviate pattern matching using if, elif, and else statements as required:- let negEvenOdd x = if x < 0 then "neg" elif x % 2 = 0 then "even" else "odd" F# lists (which are implemented as linked lists underneath) can be manipulated thus:- let l1 = [1;2;3]l1.[0]1let l2 = [1 .. 10]List.length l210let squares = [for i in 1..10 -> i * i]squares[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]let square x = x * x;;let squares2 = List.map square [1..10]squares2[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]let evenSquares = List.filter (fun x -> x % 2 = 0) squaresevenSqares[4; 16; 36; 64; 100] Note the List.map function 'maps' the square function on to the list from 1 to 10, i.e. applies the function to each element. List.filter 'filters' a list by only returning values in the list that pass the predicate function provided. Also note the 'fun x -> f' syntax - this is the F# lambda. Note that throughout we have not defined any types - the F# compiler/interpreter 'infers' types, i.e. works out what you want from usage. For example:- let f x = "hi " + x Here the compiler/interpreter will determine x is a string since you're performing an operation which requires x to be a string. It also determines the return type will be string as well. When there is ambiguity the compiler makes assumptions, for example:- let f x y = x + y Here x and y could be a number of types, but the compiler defaults to int. If you want to define types you can using type annotation:- let f (x:string) y = x + y Also note that we have had to enclose x:string in parentheses, we often have to do this to separate parts of a function definition. Two really useful and heavily used operators in F# are the pipe forward and function composition operators |> and >> respectively. We define |> thus:- let (|>) x f = f x Note that you can define operators in F#, this is pretty cool :-). This allows you to write things in a clearer way, e.g.:- [1..10] |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0) Will allow you to obtain the first 10 even squares. That is clearer than:- List.filter (fun x -> x % 2 = 0) (List.map (fun x -> x * x) [1..10]) Well, at least I think so :-) Function composition defined by the >> operator is defined as follows:- let (>>) f g x = g(f(x)) I.e. you forward-pipe an operation only the parameter of the first function remains unspecified. This is useful as you can do the following:- let mapFilter = List.map (fun x -> x * x) >> List.filter (fun x -> x % 2 = 0) Here mapFilter will accept a list an input and return the list filtered as before. It's an abbreviated version of:- let mapFilter = l |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0) If we want to write recursive functions we have to define the function as recursive by placing 'rec' after the let. Examples below. Some cool stuff:- Factorial let rec fact x = if x <= 1 then 1 else x * fact (x-1) nth Fibonacci Number let rec fib n = if n <= 1 then n else fib (n-1) + fib (n-2) FizzBuzz let (/%) x y = x % y = 0let fb = function | x when x /% 15 -> "FizzBuzz" | x when x /% 3 -> "Fizz" | x when x /% 5 -> "Buzz" | x -> x.ToString()[1..100] |> List.map (fb >> printfn "%s") Anyway that's a very brief overview, hopefully it helps a little!! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/36294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
]
} |
36,314 | I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!) | Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript: function add (a, b) { return a + b;}add(3, 4); // returns 7 This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function: function add (a) { return function (b) { return a + b; }} This is a function that takes one argument, a , and returns a function that takes another argument, b , and that function returns their sum. add(3)(4); // returns 7var add3 = add(3); // returns a functionadd3(4); // returns 7 The first statement returns 7, like the add(3, 4) statement. The second statement defines a new function called add3 that willadd 3 to its argument. (This is what some may call a closure.) The third statement uses the add3 operation to add 3 to 4, againproducing 7 as a result. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/36314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3786/"
]
} |
36,315 | It'd be really nice to target my Windows Forms app to the .NET 3.5 SP1 client framework. But, right now I'm using the HttpUtility.HtmlDecode and HttpUtility.UrlDecode functions, and the MSDN documentation doesn't point to any alternatives inside of, say, System.Net or something. So, short from reflectoring the source code and copying it into my assembly---which I don't think would be worth it---are there alternatives inside of the .NET 3.5 SP1 client framework that you know of, to replace this functionality? It seems a bit strange that they'd restrict these useful functions to server-only code. | Found today from this here little site that HtmlEncode/Decode can be done using System.Net library in C# 4.0 Client Profile: Uri.EscapeDataString(...)WebUtility.HtmlEncode(...) Edit: I re-read that the question applied for the 3.5 Client Framework but maybe this can be useful those who have updated 4.0.. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
]
} |
36,347 | Java has generics and C++ provides a very strong programming model with template s.So then, what is the difference between C++ and Java generics? | There is a big difference between them. In C++ you don't have to specify a class or an interface for the generic type. That's why you can create truly generic functions and classes, with the caveat of a looser typing. template <typename T> T sum(T a, T b) { return a + b; } The method above adds two objects of the same type, and can be used for any type T that has the "+" operator available. In Java you have to specify a type if you want to call methods on the objects passed, something like: <T extends Something> T sum(T a, T b) { return a.add ( b ); } In C++ generic functions/classes can only be defined in headers, since the compiler generates different functions for different types (that it's invoked with). So the compilation is slower. In Java the compilation doesn't have a major penalty, but Java uses a technique called "erasure" where the generic type is erased at runtime, so at runtime Java is actually calling ... Something sum(Something a, Something b) { return a.add ( b ); } Nevertheless, Java's generics help with type-safety. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/36347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556/"
]
} |
36,350 | I have a method which takes params object[] such as: void Foo(params object[] items){ Console.WriteLine(items[0]);} When I pass two object arrays to this method, it works fine: Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } );// Output: System.Object[] But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one: Foo(new object[]{ (object)"1", (object)"2" });// Output: 1, expected: System.Object[] How do I pass a single object[] as a first argument to a params array? | A simple typecast will ensure the compiler knows what you mean in this case. Foo((object)new object[]{ (object)"1", (object)"2" })); As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/36350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
]
} |
36,407 | What Firefox add-ons do you use that are useful for programmers? | I guess it's silly to mention Firebug -- doubt any of us could live without it. Other than that I use the following (only listing dev-related): Console 2 : next-generation error console DOM inspector: as the title might indicate, allows you to browse the DOM Edit Cookies: change cookies on the fly Execute JS: ad-hoc Javascript execution IE Tab: render a page in IE Inspect This: brings the selected object into the DOM inspector JSView: display linked javascript and CSS LORI (Life of Request Info): shows how long it takes to render a page Measure IT: a popup ruler. URL Params: shows GET and POST variables Web Developer: a myriad of tools for the web developer | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3305/"
]
} |
36,417 | What is a good way to remove the code from display pages when developing with PHP. Often the pages I work on need to be editted by an outside person. This person is often confused by lots of blocks of PHP, and also likes to break my code. I've tried moving blocks of code out into functions, so now there are functions spread out all throughout the HTML now. As some pages become more complex it becomes a program again, and processing POSTs are questionable. What can I be doing better in my PHP development? | You don't need a "system" to do templating.You can do it on your own by keeping presentation & logic separate.This way the designer can screw up the display, but not the logic behind it. Here's a simple example: <?php $people = array('derek','joel','jeff');$people[0] = 'martin'; // all your logic goes hereinclude 'templates/people.php';?> Now here's the people.php file (which you give your designer): <html> <body><?php foreach($people as $name):?> <b>Person:</b> <?=$name?> <br /><?php endforeach;?> </body></html> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3800/"
]
} |
36,430 | I'm not sure of all of them, but what are the commands to do things like update Ruby, download a new gem, or update an existing gem? What other important things are there? Since it might matter, I'm running Windows. | Useful command: Rake In addition to the commands listed by Joseph Pecoraro, the 'rake' command is also pretty standard when working with Ruby. Rake makes it easy to automate (simple) tasks; like building a RubyGem or running your unit tests. With rake, the only important command to remember is 'rake -T', which shows a list of rake tasks available in the current directory. Updating a Ruby gem To get back to your specific question: To update a specific gem, you can do two things: simply update the gem: gem update <gemname> This will update the gem to the latest version. Install a Ruby gem If you want to update to a specific version, you must install it: gem install <gemname> -v <gemversion> You can leave out the -v options. Rubygems then installs the latest version. How to help yourself Two useful gem commands to remember are: gem help This shows how to get help with rubygems. gem help commands This shows all commands available to rubygems.From here you can get more specific help on a command by using gem help: gem help update | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
36,504 | I see a lot of talk on here about functional languages and stuff. Why would you use one over a "traditional" language? What do they do better? What are they worse at? What's the ideal functional programming application? | Functional languages use a different paradigm than imperative and object-oriented languages. They use side-effect-free functions as a basic building block in the language. This enables lots of things and makes a lot of things more difficult (or in most cases different from what people are used to). One of the biggest advantages with functional programming is that the order of execution of side-effect-free functions is not important. For example, in Erlang this is used to enable concurrency in a very transparent way. And because functions in functional languages behave very similar to mathematical functions it's easy to translate those into functional languages. In some cases, this can make code more readable. Traditionally, one of the big disadvantages of functional programming was also the lack of side effects. It's very difficult to write useful software without IO, but IO is hard to implement without side effects in functions. So most people never got more out of functional programming than calculating a single output from a single input. In modern mixed-paradigm languages like F# or Scala this is easier. Lots of modern languages have elements from functional programming languages. C# 3.0 has a lot functional programming features and you can do functional programming in Python too. I think the reasons for the popularity of functional programming is mostly because of two reasons: Concurrency is getting to be a real problem in normal programming because we're getting more and more multiprocessor computers; and the languages are getting more accessible. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/36504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655/"
]
} |
36,585 | I have a column which is of type nvarchar(max). How do I find the length of the string (or the number of bytes) for the column for each row in the table? | SELECT LEN(columnName) AS MyLength FROM myTable | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/36585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1208/"
]
} |
36,608 | I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set. Something like: Record.find(:all).date.unique.count but of course, that doesn't seem to work. | What you're going for is the following SQL: SELECT COUNT(DISTINCT date) FROM records ActiveRecord has this built in: Record.count('date', :distinct => true) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/36608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
]
} |
36,621 | I'm taking the leap: my PHP scripts will ALL fail gracefully! At least, that's what I'm hoping for...` I don't want to wrap (practically) every single line in try...catch statements, so I think my best bet is to make a custom error handler for the beginning of my files. I'm testing it out on a practice page: function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.<br />"; echo "The function that caused the error says $message.<br />"; die();}set_error_handler("customError");echo($imAFakeVariable); This works fine, returning: Sorry, an error has occurred on line 17. The function that caused the error says Undefined variable: imAFakeVariable. However, this setup doesn't work for undefined functions. function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.<br />"; echo "The function that caused the error says $message.<br />"; die();}set_error_handler("customError");imAFakeFunction(); This returns: Fatal error: Call to undefined function: imafakefunction() in /Library/WebServer/Documents/experimental/errorhandle.php on line 17 Why isn't my custom error handler catching undefined functions? Are there other problems that this will cause? | set_error_handler is designed to handle errors with codes of: E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE . This is because set_error_handler is meant to be a method of reporting errors thrown by the user error function trigger_error . However, I did find this comment in the manual that may help you: "The following error types cannot be handled with a user defined function: E_ERROR , E_PARSE , E_CORE_ERROR , E_CORE_WARNING , E_COMPILE_ERROR , E_COMPILE_WARNING , and most of E_STRICT raised in the file where set_error_handler() is called." This is not exactly true. set_error_handler() can't handle them, but ob_start() can handle at least E_ERROR . <?phpfunction error_handler($output){ $error = error_get_last(); $output = ""; foreach ($error as $info => $string) $output .= "{$info}: {$string}\n"; return $output;}ob_start('error_handler');will_this_undefined_function_raise_an_error();?> Really though these errors should be silently reported in a file, for example. Hopefully you won't have many E_PARSE errors in your project! :-) As for general error reporting, stick with Exceptions (I find it helpful to make them tie in with my MVC system). You can build a pretty versatile Exception to provide options via buttons and add plenty of description to let the user know what's wrong. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
]
} |
36,636 | I asked a question about Currying and closures were mentioned.What is a closure? How does it relate to currying? | Variable scope When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them. function() { var a = 1; console.log(a); // works} console.log(a); // fails If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope. var a = 1;function() { console.log(a); // works} console.log(a); // works When a block or function is done with, its local variables are no longer needed and are usually blown out of memory. This is how we normally expect things to work. A closure is a persistent local variable scope A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere. The scope object and all its local variables are tied to the function and will persist as long as that function persists. This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context. For example Here's a really simple example in JavaScript that illustrates the point: outer = function() { var a = 1; var inner = function() { console.log(a); } return inner; // this returns a function}var fnc = outer(); // execute outer to get inner fnc(); Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a . The variable a is in scope for the inner function. Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist . The variable a has been closed over -- it is within a closure. Note that the variable a is totally private to fnc . This is a way of creating private variables in a functional programming language such as JavaScript. As you might be able to guess, when I call fnc() it prints the value of a , which is "1". In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists. In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist. a belongs to the scope of outer . The scope of inner has a parent pointer to the scope of outer . fnc is a variable which points to inner . a persists as long as fnc persists. a is within the closure. Further reading (watching) I made a YouTube video looking at this code with some practical examples of usage. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/36636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3786/"
]
} |
36,646 | Does anyone use Phing to deploy PHP applications, and if so how do you use it? We currently have a hand-written "setup" script that we run whenever we deploy a new instance of our project. We just check out from SVN and run it. It sets some basic configuration variables, installs or reloads the database, and generates a v-host for the site instance. I have often thought that maybe we should be using Phing . I haven't used ant much, so I don't have a real sense of what Phing is supposed to do other than script the copying of files from one place to another much as our setup script does. What are some more advanced uses that you can give examples of to help me understand why we would or would not want to integrate Phing into our process? | From Federico Cargnelutti's blog post : Features include file transformations (e.g. token replacement, XSLT transformation, Smarty template transformations), file system operations, interactive build support, SQL execution, CVS operations, tools for creating PEAR packages, and much more. Of course you could write custom scripts for all of the above. However, using a specialized build tool like Phing gives you a number of benefits. You'll be using a proven framework so instead of having to worry about setting up "infrastructure" you can focus on the code you need to write. Using Phing will also make it easier for when new members join your team, they'll be able to understand what is going on if they've used Phing (or Ant, which is what Phing is based on) before. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
]
} |
36,647 | Does Python have a unit testing framework compatible with the standard xUnit style of test framework? If so, what is it, where is it, and is it any good? | Python has several testing frameworks, including unittest , doctest , and nose . The most xUnit-like is unittest , which is documented on Python.org. unittest documentation doctest documentation | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/36647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
]
} |
36,656 | I'm parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains ASCII art and whatnot that I would like to preserve. When I print out the string on the HTML page , even if it does have the same formatting and everything since it is in HTML , the spacing and line breaks are not preserved. What is the best way to print out the text in HTML exactly as it was in the original text file? I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor :P Basically, I would like suggestions on how to display ASCII art in HTML . | use the <pre> tag (pre formatted), that will use a mono spaced font (for your art) and keep all the white space <pre>text goes here and here and here and here Some out here ▄ ▄█▄ █▄ ▄ ▄█▀█▓ ▄▓▀▀█▀ ▀▀▀█▓▀▀ ▀▀ ▄█▀█▓▀▀▀▀▀▓▄▀██▀▀██ ██ ▀██▄▄ ▄█ ▀ ░▒ ░▒ ██ ██ ▄█▄ █▀ ███▓▄▀██ ▄ ▀█▌▓█ ▒▓ ▒▓ █▓▄▀██ ▓█ ▀▄ █▓█▒ █▓ ██▄▓▀ ▀█▄▄█▄▓█ ▓█ █▒ █▓ ▒█ ▓█▄ ▒ ▀▒ ▀ ▀ █▀ ▀▒ ▀ █▀ ░</pre> You might have to convert any <'s to < 's | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/36656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3831/"
]
} |
36,701 | Is it completely against the Java way to create struct like objects? class SomeData1 { public int x; public int y;} I can see a class with accessors and mutators being more Java like. class SomeData2 { int getX(); void setX(int x); int getY(); void setY(int y); private int x; private int y;} The class from the first example is notationally convenient. // a function in a classpublic int f(SomeData1 d) { return (3 * d.x) / d.y;} This is not as convenient. // a function in a classpublic int f(SomeData2 d) { return (3 * d.getX()) / d.getY();} | Use common sense really. If you have something like: public class ScreenCoord2D{ public int x; public int y;} Then there's little point in wrapping them up in getters and setters. You're never going to store an x, y coordinate in whole pixels any other way. Getters and setters will only slow you down. On the other hand, with: public class BankAccount{ public int balance;} You might want to change the way a balance is calculated at some point in the future. This should really use getters and setters. It's always preferable to know why you're applying good practice, so that you know when it's ok to bend the rules. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/36701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3836/"
]
} |
36,707 | Are there good reasons why it's a better practice to have only one return statement in a function? Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function? | I often have several statements at the start of a method to return for "easy" situations. For example, this: public void DoStuff(Foo foo){ if (foo != null) { ... }} ... can be made more readable (IMHO) like this: public void DoStuff(Foo foo){ if (foo == null) return; ...} So yes, I think it's fine to have multiple "exit points" from a function/method. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/36707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
]
} |
36,760 | I have three tables: page, attachment, page-attachment I have data like this: pageID NAME1 first page2 second page3 third page4 fourth pageattachmentID NAME1 foo.word2 test.xsl3 mm.pptpage-attachmentID PAGE-ID ATTACHMENT-ID1 2 12 2 23 3 3 I would like to get the number of attachments per page also when that number is 0 . I have tried with: select page.name, count(page-attachment.id) as attachmentsnumber from page inner join page-attachment on page.id=page-id group by page.id I am getting this output: NAME ATTACHMENTSNUMBERsecond page 2third page 1 I would like to get this output: NAME ATTACHMENTSNUMBERfirst page 0second page 2third page 1fourth page 0 How do I get the 0 part? | Change your "inner join" to a "left outer join", which means "get me all the rows on the left of the join, even if there isn't a matching row on the right." select page.name, count(page-attachment.id) as attachmentsnumber from page left outer join page-attachment on page.id=page-id group by page.name | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/36760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
} |
36,831 | I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is " GetBestInterface " that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representation. I've found some examples via Google, like this one or this one , but I'm pretty sure there should be a standard way to achieve this with .NET. Only problem is, I can't find this standard way. IPAddress.Parse seems to be in the right direction, but it doesn't supply any way of getting a 'uint' representation... There is also a way of doing this using IP Helper, using the ParseNetworkString , but again, I'd rather use .NET - I believe the less I rely on pInvoke the better. So, anyone knows of a standard way to do this in .NET? | MSDN says that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use GetAddressBytes method. You can convert IP address to numeric value using following code: var ipAddress = IPAddress.Parse("some.ip.address");var ipBytes = ipAddress.GetAddressBytes();var ip = (uint)ipBytes [3] << 24;ip += (uint)ipBytes [2] << 16;ip += (uint)ipBytes [1] <<8;ip += (uint)ipBytes [0]; EDIT: As other commenters noticed above-mentioned code is for IPv4 addresses only.IPv6 address is 128 bits long so it's impossible to convert it to 'uint' as question's author wanted. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1596/"
]
} |
36,832 | In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function. I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense: As long as the derived constructor has not been executed the object is not yet a derived instance. So how can a derived function be called? The preconditions haven't had the chance to be set up. Example: class base {public: base() { std::cout << "foo is " << foo() << std::endl; } virtual int foo() { return 42; }};class derived : public base { int* ptr_;public: derived(int i) : ptr_(new int(i*i)) { } // The following cannot be called before derived::derived due to how C++ behaves, // if it was possible... Kaboom! virtual int foo() { return *ptr_; } }; It's exactly the same for Java and .NET yet they chose to go the other way, and is possibly the only reason for the principle of least surprise ? Which do you think is the correct choice? | There's a fundamental difference in how the languages define an object's life time. In Java and .Net the object members are zero/null initialized before any constructor is run and is at this point that the object life time begins. So when you enter the constructor you've already got an initialized object. In C++ the object life time only begins when the constructor finishes (although member variables and base classes are fully constructed before it starts). This explains the behaviour when virtual functions are called and also why the destructor isn't run if there's an exception in the constructor's body. The problem with the Java/.Net definition of object lifetime is that it's harder to make sure the object always meets its invariant without having to put in special cases for when the object is initialized but the constructor hasn't run. The problem with the C++ definition is that you have this odd period where the object is in limbo and not fully constructed. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
]
} |
36,862 | With SVN, I had a single big repository I kept on a server, and checked-out on a few machines. This was a pretty good backup system, and allowed me easily work on any of the machines. I could checkout a specific project, commit and it updated the 'master' project, or I could checkout the entire thing. Now, I have a bunch of git repositories, for various projects, several of which are on github. I also have the SVN repository I mentioned, imported via the git-svn command.. Basically, I like having all my code (not just projects, but random snippets and scripts, some things like my CV, articles I've written, websites I've made and so on) in one big repository I can easily clone onto remote machines, or memory-sticks/harddrives as backup. The problem is, since it's a private repository, and git doesn't allow checking out of a specific folder (that I could push to github as a separate project, but have the changes appear in both the master-repo, and the sub-repos) I could use the git submodule system, but it doesn't act how I want it too (submodules are pointers to other repositories, and don't really contain the actual code, so it's useless for backup) Currently I have a folder of git-repos (for example, ~/code_projects/proj1/.git/ ~/code_projects/proj2/.git/), and after doing changes to proj1 I do git push github , then I copy the files into ~/Documents/code/python/projects/proj1/ and do a single commit (instead of the numerous ones in the individual repos). Then do git push backupdrive1 , git push mymemorystick etc So, the question: How do your personal code and projects with git repositories, and keep them synced and backed-up? | I would strongly advise against putting unrelated data in a givenGit repository. The overhead of creating new repositories is quitelow, and that is a feature that makes it possible to keepdifferent lineages completely separate. Fighting that idea means ending up with unnecessarily tangled history,which renders administration more difficult and--moreimportantly--"archeology" tools less useful because of the resultingdilution. Also, as you mentioned, Git assumes that the "unit ofcloning" is the repository, and practically has to do so because ofits distributed nature. One solution is to keep every project/package/etc. as its own bare repository (i.e., without working tree) under a blessed hierarchy,like: /repos/a.git/repos/b.git/repos/c.git Once a few conventions have been established, it becomes trivial toapply administrative operations (backup, packing, web publishing) tothe complete hierarchy, which serves a role not entirely dissimilar to"monolithic" SVN repositories. Working with these repositories alsobecomes somewhat similar to SVN workflows, with the addition that one can use local commits and branches: svn checkout --> git clonesvn update --> git pullsvn commit --> git push You can have multiple remotes in each working clone, for the ease ofsynchronizing between the multiple parties: $ cd ~/dev$ git clone /repos/foo.git # or the one from github, ...$ cd foo$ git remote add github ...$ git remote add memorystick ... You can then fetch/pull from each of the "sources", work and commitlocally, and then push ("backup") to each of these remotes when youare ready with something like (note how that pushes the same commitsand history to each of the remotes!): $ for remote in origin github memorystick; do git push $remote; done The easiest way to turn an existing working repository ~/dev/foo into such a bare repository is probably: $ cd ~/dev$ git clone --bare foo /repos/foo.git$ mv foo foo.old$ git clone /repos/foo.git which is mostly equivalent to a svn import --but does not throw theexisting, "local" history away. Note: submodules are a mechanism to include shared related lineages, so I indeed wouldn't consider them an appropriate tool forthe problem you are trying to solve. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/36862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
]
} |
36,877 | How can I set the cookies in my PHP apps as HttpOnly cookies ? | For your cookies , see this answer. For PHP's own session cookie ( PHPSESSID , by default), see @richie's answer The setcookie() and setrawcookie() functions, introduced the boolean httponly parameter, back in the dark ages of PHP 5.2.0, making this nice and easy. Simply set the 7th parameter to true, as per the syntax Function syntax simplified for brevity setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly ) In PHP < 8, specify NULL for parameters you wish to remain as default. In PHP >= 8 you can benefit from using named parameters. See this question about named params . setcookie( $name, $value, httponly:true ) It is also possible using the older, lower-level header() function: header( "Set-Cookie: name=value; HttpOnly" ); You may also want to consider if you should be setting the Secure parameter. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/36877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3871/"
]
} |
36,881 | I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header. The TabSpecs are created in this way within a setupTabs() method which loops to create the appropriate number of tabs: TabSpec ts = mTabs.newTabSpec("tab");ts.setIndicator("TabTitle", iconResource);ts.setContent(new TabHost.TabContentFactory({ public View createTabContent(String tag) { ... } });mTabs.addTab(ts); There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them. mTabs.getTabWidget().removeAllViews();mTabs.clearAllTabs(true);setupTabs(); Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs? | The short answer is, you're not missing anything. The Android SDK doesn't provide a direct method to change the indicator of a TabHost after it's been created. The TabSpec is only used to build the tab, so changing the TabSpec after the fact will have no effect. I think there's a workaround, though. Call mTabs.getTabWidget() to get a TabWidget object. This is just a subclass of ViewGroup , so you can call getChildCount() and getChildAt() to access individual tabs within the TabWidget . Each of these tabs is also a View, and in the case of a tab with a graphical indicator and a text label, it's almost certainly some other ViewGroup (maybe a LinearLayout , but it doesn't matter) that contains an ImageView and a TextView . So with a little fiddling with the debugger or Log.i , you should be able to figure out a recipe to get the ImageView and change it directly. The downside is that if you're not careful, the exact layout of the controls within a tab could change and your app could break. Your initial solution is perhaps more robust, but then again it might lead to other unwanted side effects like flicker or focus problems. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/36881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1197/"
]
} |
36,901 | What do *args and **kwargs mean? def foo(x, y, *args):def bar(x, y, **kwargs): | The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation. The *args will give you all function parameters as a tuple : def foo(*args): for a in args: print(a) foo(1)# 1foo(1,2,3)# 1# 2# 3 The **kwargs will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary. def bar(**kwargs): for a in kwargs: print(a, kwargs[a]) bar(name='one', age=27)# name one# age 27 Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments: def foo(kind, *args, **kwargs): pass It is also possible to use this the other way around: def foo(a, b, c): print(a, b, c)obj = {'b':10, 'c':'lee'}foo(100,**obj)# 100 10 lee Another usage of the *l idiom is to unpack argument lists when calling a function. def foo(bar, lee): print(bar, lee)l = [1,2]foo(*l)# 1 2 In Python 3 it is possible to use *l on the left side of an assignment ( Extended Iterable Unpacking ), though it gives a list instead of a tuple in this context: first, *rest = [1,2,3,4]first, *l, last = [1,2,3,4] Also Python 3 adds new semantic (refer PEP 3102 ): def func(arg1, arg2, arg3, *, kwarg1, kwarg2): pass For example the following works in python 3 but not python 2: >>> x = [1, 2]>>> [*x][1, 2]>>> [*x, 3, 4][1, 2, 3, 4]>>> x = {1:1, 2:2}>>> x{1: 1, 2: 2}>>> {**x, 3:3, 4:4}{1: 1, 2: 2, 3: 3, 4: 4} Such function accepts only 3 positional arguments, and everything after * can only be passed as keyword arguments. Note: A Python dict , semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. "The order of elements in **kwargs now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6 In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7. | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/36901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2572/"
]
} |
36,906 | I want to swap two integers, and I want to know which of these two implementations will be faster:The obvious way with a temp variable: void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} Or the xor version that I'm sure most people have seen: void swap(int* a, int* b){ *a ^= *b; *b ^= *a; *a ^= *b;} It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each. Can someone tell me which is faster and why? The why being more important. | The XOR method fails if a and b point to the same address. The first XOR will clear all of the bits at the memory address pointed to by both variables, so once the function returns (*a == *b == 0), regardless of the initial value. More info on the Wiki page: XOR swap algorithm Although it's not likely that this issue would come up, I'd always prefer to use the method that's guaranteed to work, not the clever method that fails at unexpected moments. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/36906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3869/"
]
} |
36,915 | We have been working with CVS for years, and frequently find it useful to "sticky" a single file here and there. Is there any way to do this in subversion, specifically from TortoiseSVN? | The XOR method fails if a and b point to the same address. The first XOR will clear all of the bits at the memory address pointed to by both variables, so once the function returns (*a == *b == 0), regardless of the initial value. More info on the Wiki page: XOR swap algorithm Although it's not likely that this issue would come up, I'd always prefer to use the method that's guaranteed to work, not the clever method that fails at unexpected moments. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/36915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
]
} |
36,932 | I'm mainly a C# developer, but I'm currently working on a project in Python. How can I represent the equivalent of an Enum in Python? | Enums have been added to Python 3.4 as described in PEP 435 . It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi. For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as enum34 . Code is not perfectly compatible between py2 and py3, e.g. you'll need __order__ in python 2 ). To use enum34 , do $ pip install enum34 To use aenum , do $ pip install aenum Installing enum (no numbers) will install a completely different and incompatible version. from enum import Enum # for enum34, or the stdlib version# from aenum import Enum # for the aenum versionAnimal = Enum('Animal', 'ant bee cat dog')Animal.ant # returns <Animal.ant: 1>Animal['ant'] # returns <Animal.ant: 1> (string lookup)Animal.ant.name # returns 'ant' (inverse lookup) or equivalently: class Animal(Enum): ant = 1 bee = 2 cat = 3 dog = 4 In earlier versions, one way of accomplishing enums is: def enum(**enums): return type('Enum', (), enums) which is used like so: >>> Numbers = enum(ONE=1, TWO=2, THREE='three')>>> Numbers.ONE1>>> Numbers.TWO2>>> Numbers.THREE'three' You can also easily support automatic enumeration with something like this: def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) and used like so: >>> Numbers = enum('ZERO', 'ONE', 'TWO')>>> Numbers.ZERO0>>> Numbers.ONE1 Support for converting the values back to names can be added this way: def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.iteritems()) enums['reverse_mapping'] = reverse return type('Enum', (), enums) This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a KeyError if the reverse mapping doesn't exist. With the first example: >>> Numbers.reverse_mapping['three']'THREE' If you are using MyPy another way to express "enums" is with typing.Literal . For example: from typing import Literal #python >=3.8from typing_extensions import Literal #python 2.7, 3.4-3.7Animal = Literal['ant', 'bee', 'cat', 'dog']def hello_animal(animal: Animal): print(f"hello {animal}")hello_animal('rock') # errorhello_animal('bee') # passes | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/36932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3880/"
]
} |
36,953 | Can people point me to resources on lexing, parsing and tokenising with Python? I'm doing a little hacking on an open source project ( hotwire ) and wanted to do a few changes to the code that lexes , parses and tokenises the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out. I haven't worked on code to lex/parse/tokenise before, so I was thinking one approach would be to work through a tutorial or two on this aspect. I would hope to learn enough to navigate around the code I actually want to alter. Is there anything suitable out there? (Ideally it could be done in an afternoon without having to buy and read the dragon book first ...) Edit: (7 Oct 2008) None of the below answers quite give what I want. With them I could generate parsers from scratch, but I want to learn how to write my own basic parser from scratch, not using lex and yacc or similar tools. Having done that I can then understand the existing code better. So could someone point me to a tutorial where I can build a basic parser from scratch, using just python? | I'm a happy user of PLY . It is a pure-Python implementation of Lex & Yacc, with lots of small niceties that make it quite Pythonic and easy to use. Since Lex & Yacc are the most popular lexing & parsing tools and are used for the most projects, PLY has the advantage of standing on giants' shoulders. A lot of knowledge exists online on Lex & Yacc, and you can freely apply it to PLY. PLY also has a good documentation page with some simple examples to get you started. For a listing of lots of Python parsing tools, see this . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/36953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3189/"
]
} |
36,959 | In MS SQL Server, I create my scripts to use customizable variables: DECLARE @somevariable int SELECT @somevariable = -1INSERT INTO foo VALUES ( @somevariable ) I'll then change the value of @somevariable at runtime, depending on the value that I want in the particular situation. Since it's at the top of the script it's easy to see and remember. How do I do the same with the PostgreSQL client psql ? | Postgres variables are created through the \set command, for example ... \set myvariable value ... and can then be substituted, for example, as ... SELECT * FROM :myvariable.table1; ... or ... SELECT * FROM table1 WHERE :myvariable IS NULL; edit: As of psql 9.1, variables can be expanded in quotes as in: \set myvariable value SELECT * FROM table1 WHERE column1 = :'myvariable'; In older versions of the psql client: ... If you want to use the variable as the value in a conditional string query, such as ... SELECT * FROM table1 WHERE column1 = ':myvariable'; ... then you need to include the quotes in the variable itself as the above will not work. Instead define your variable as such ... \set myvariable 'value' However, if, like me, you ran into a situation in which you wanted to make a string from an existing variable, I found the trick to be this ... \set quoted_myvariable '\'' :myvariable '\'' Now you have both a quoted and unquoted variable of the same string! And you can do something like this .... INSERT INTO :myvariable.table1 SELECT * FROM table2 WHERE column1 = :quoted_myvariable; | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/36959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
]
} |
36,999 | I'm starting to work with my model almost exclusively in WCF and wanted to get some practical approaches to versioning these services over time. Can anyone point me in the right direction? | There is a good writeup on Craig McMurtry's WebLog . Its from 2006, but most of it is still relevant. As well as a decision tree to walk through the choices, he shows how to implement those changes using Windows Communication Foundation | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/36999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
]
} |
37,011 | Should you ever use protected member variables? What are the the advantages and what issues can this cause? | Should you ever use protected member variables? Depends on how picky you are about hiding state. If you don't want any leaking of internal state, then declaring all your member variables private is the way to go. If you don't really care that subclasses can access internal state, then protected is good enough. If a developer comes along and subclasses your class they may mess it up because they don't understand it fully. With private members, other than the public interface, they can't see the implementation specific details of how things are being done which gives you the flexibility of changing it later. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/37011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3305/"
]
} |
37,026 | If one Googles for "difference between notify() and notifyAll() " then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in notify() and all in notifyAll() . However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer. What's the useful difference between notify() and notifyAll() then? Am I missing something? | However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition. That is not correct. o.notifyAll() wakes all of the threads that are blocked in o.wait() calls. The threads are only allowed to return from o.wait() one-by-one, but they each will get their turn. Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time? In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use notifyAll() to wake up all waiting threads at the same time. Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use notify() . Properly implemented, you could use notifyAll() in this situation as well, but you would unnecessarily wake threads that can't do anything anyway. In many cases, the code to await a condition will be written as a loop: synchronized(o) { while (! IsConditionTrue()) { o.wait(); } DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();} That way, if an o.notifyAll() call wakes more than one waiting thread, and the first one to return from the o.wait() makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/37026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3894/"
]
} |
37,043 | I'm currently using and enjoying using the Flex MVC framework PureMVC . I have heard some good things about Cairngorm, which is supported by Adobe and has first-to-market momentum. And there is a new player called Mate, which has a good deal of buzz. Has anyone tried two or three of these frameworks and formed an opinion? Thanks! | Mate is my pick. The first and foremost reason is that it is completely unobtrusive. My application code has no dependencies on the framework, it is highly decoupled, reusable and testable. One of the nicest features of Mate is the declarative configuration, essentially you wire up your application in using tags in what is called an event map -- basically a list of events that your application generates, and what actions to take when they occur. The event map gives a good overview of what your application does. Mate uses Flex' own event mechanism, it does not invent its own like most other frameworks. You can dispatch an event from anywhere in the view hierarchy and have it bubble up to the framework automatically, instead of having to have a direct line, like Cairngorms CairngormEventDispatcher or PureMVC's notification system. Mate also uses a form of dependency injection (leveraging bindings) that makes it possible to connect your models to your views without either one knowing about the other. This is probably the most powerful feature of the framework. In my view none of the other Flex application frameworks come anywhere near Mate. However, these are the contenders and why I consider them to be less useful: PureMVC actively denies you many of the benefits of Flex (for example bindings and event bubbling) in order for the framework to be portable -- a doubious goal in my view. It is also over-engineered, and as invasive as they come. Every single part of your application depends on the framework. However, PureMVC isn't terrible, just not a very good fit for Flex. An alternative is FlexMVCS , an effort to make PureMVC more suitable for Flex (unfortunately there's no documentation yet, just source). Cairngorm is a bundle of anti-patterns that lead to applications that are tightly coupled to global variables. Nuff said (but if you're interested, here are some more of my thoughts , and here too ). Swiz is a framework inspired by the Spring framework for Java and Cairngorm (trying to make up for the worst parts of the latter). It provides a dependency injection container and uses metadata to enable auto-wiring of dependencies. It is interesting, but a little bizzare in that goes to such lengths to avoid the global variables of Cairngorm by using dependency injection but then uses a global variable for central event dispatching. Those are the ones I've tried or researched. There are a few others that I've heard about, but none that I think are widely used. Mate and Swiz were both presented at the recent 360|Flex conference, and there are videos available ( the Mate folks have instructions on how to watch them ) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/37043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2885/"
]
} |
37,059 | Has anyone used Lucene.NET rather than using the full text search that comes with sql server? If so I would be interested on how you implemented it. Did you for example write a windows service that queried the database every hour then saved the results to the lucene.net index? | Yes, I've used it for exactly what you are describing. We had two services - one for read, and one for write, but only because we had multiple readers. I'm sure we could have done it with just one service (the writer) and embedded the reader in the web app and services. I've used lucene.net as a general database indexer, so what I got back was basically DB id's (to indexed email messages), and I've also use it to get back enough info to populate search results or such without touching the database. It's worked great in both cases, tho the SQL can get a little slow, as you pretty much have to get an ID, select an ID etc. We got around this by making a temp table (with just the ID row in it) and bulk-inserting from a file (which was the output from lucene) then joining to the message table. Was a lot quicker. Lucene isn't perfect, and you do have to think a little outside the relational database box, because it TOTALLY isn't one, but it's very very good at what it does. Worth a look, and, I'm told, doesn't have the "oops, sorry, you need to rebuild your index again" problems that MS SQL's FTI does. BTW, we were dealing with 20-50million emails (and around 1 million unique attachments), totaling about 20GB of lucene index I think, and 250+GB of SQL database + attachments. Performance was fantastic, to say the least - just make sure you think about, and tweak, your merge factors (when it merges index segments). There is no issue in having more than one segment, but there can be a BIG problem if you try to merge two segments which have 1mil items in each, and you have a watcher thread which kills the process if it takes too long..... (yes, that kicked our arse for a while). So keep the max number of documents per thinggie LOW (ie, dont set it to maxint like we did!) EDIT Corey Trager documented how to use Lucene.NET in BugTracker.NET here . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/37059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041/"
]
} |
37,069 | On Mac OS X 10.5 I downloaded the latest version of Apache 2.2.9. After the usual configure, make, make install dance I had a build of apache without mod_rewrite. This wasn't statically linked and the module was not built in the /modules folder either. I had to do the following to build Apache and mod_rewrite: ./configure --prefix=/usr/local/apache2 --enable-rewrite=shared Is there a way to tell Apache to build all modules as Shared Modules (DSOs) so I can control loading from the Apache config? Now that I have built Apache and the mod_rewrite DSO, how can I build another shared module without building all of Apache? (The last time I built Apache (2.2.8) on Solaris, by default it built everything as a shared module.) | Try the ./configure option --enable-mods-shared="all" , or --enable-mods-shared="<list of modules>" to compile modules as shared objects. See further details in Apache 2.2 docs To just compile Apache with the ability to load shared objects (and add modules later), use --enable-so , then consult the documentation on compiling modules seperately in the Apache 2.2. DSO docs . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/37069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
]
} |
37,070 | This is a somewhat low-level question. In x86 assembly there are two SSE instructions: MOVDQA xmmi, m128 and MOVNTDQA xmmi, m128 The IA-32 Software Developer's Manual says that the NT in MOVNTDQA stands for Non-Temporal , and that otherwise it's the same as MOVDQA. My question is, what does Non-Temporal mean? | Non-Temporal SSE instructions (MOVNTI, MOVNTQ, etc.), don't follow the normal cache-coherency rules. Therefore non-temporal stores must be followed by an SFENCE instruction in order for their results to be seen by other processors in a timely fashion. When data is produced and not (immediately) consumed again, the fact that memory store operations read a full cache line first and then modify the cached data is detrimental to performance. This operation pushes data out of the caches which might be needed again in favor of data which will not be used soon. This is especially true for large data structures, like matrices, which are filled and then used later. Before the last element of the matrix is filled the sheer size evicts the first elements, making caching of the writes ineffective. For this and similar situations, processors provide support for non-temporal write operations. Non-temporal in this context means the data will not be reused soon, so there is no reason to cache it. These non-temporal write operations do not read a cache line and then modify it; instead, the new content is directly written to memory. Source: http://lwn.net/Articles/255364/ | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/37070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
]
} |
37,073 | What is currently the best way to get a favicon to display in all browsers that currently support it? Please include: Which image formats are supported by which browsers. Which lines are needed in what places for the various browsers. | I go for a belt and braces approach here. I create a 32x32 icon in both the .ico and .png formats called favicon.ico and favicon.png . The icon name doesn't really matter unless you are dealing with older browsers. Place favicon.ico at your site root to support the older browsers (optional and only relevant for older browsers. Place favicon.png in my images sub-directory (just to keep things tidy). Add the following HTML inside the <head> element. <link rel="icon" href="/images/favicon.png" type="image/png" /><link rel="shortcut icon" href="/favicon.ico" /> Please note that: The MIME type for .ico files was registered as image/vnd.microsoft.icon by the IANA . Internet Explorer will ignore the type attribute for the shortcut icon relationship and this is the only browser to support this relationship, it doesn't need to be supplied. Reference | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/37073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177/"
]
} |
37,103 | I have a container div with a fixed width and height , with overflow: hidden . I want a horizontal row of float: left divs within this container. Divs which are floated left will naturally push onto the 'line' below after they read the right bound of their parent. This will happen even if the height of the parent should not allow this. This is how this looks: How I would like it to look: ![Right][2] - removed image shack image that had been replaced by an advert Note: the effect I want can be achieved by using inline elements & white-space: no-wrap (that is how I did it in the image shown). This, however, is no good to me (for reasons too lengthy to explain here), as the child divs need to be floated block level elements. | You may put an inner div in the container that is enough wide to hold all the floated divs. #container { background-color: red; overflow: hidden; width: 200px;}#inner { overflow: hidden; width: 2000px;}.child { float: left; background-color: blue; width: 50px; height: 50px;} <div id="container"> <div id="inner"> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div></div> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/37103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349865/"
]
} |
37,122 | How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time. Edit: These users do want to be distracted when a new message arrives. | this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab. newExcitingAlerts = (function () { var oldTitle = document.title; var msg = "New!"; var timeoutId; var blink = function() { document.title = document.title == msg ? ' ' : msg; }; var clear = function() { clearInterval(timeoutId); document.title = oldTitle; window.onmousemove = null; timeoutId = null; }; return function () { if (!timeoutId) { timeoutId = setInterval(blink, 1000); window.onmousemove = clear; } };}()); Update : You may want to look at using HTML5 notifications . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/37122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191/"
]
} |
37,157 | Is there a simple way to cache MySQL queries in PHP or failing that, is there a small class set that someone has written and made available that will do it? I can cache a whole page but that won't work as some data changes but some do not, I want to cache the part that does not. | This is a great overview of how to cache queries in MySQL: The MySQL Query Cache | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/37157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
37,219 | Suppose your git history looks like this: 12345 1–5 are separate revisions. You need to remove 3 while still keeping 1, 2, 4 and 5. How can this be done? Is there an efficient method when there are hundreds of revisions after the one to be deleted? | To combine revision 3 and 4 into a single revision, you can use git rebase. If you want to remove the changes in revision 3, you need to use the edit command in the interactive rebase mode. If you want to combine the changes into a single revision, use squash. I have successfully used this squash technique, but have never needed to remove a revision before. The git-rebase documentation under "Splitting commits" should hopefully give you enough of an idea to figure it out. (Or someone else might know). From the git documentation : Start it with the oldest commit you want to retain as-is: git rebase -i <after-this-commit> An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit. You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this: pick deadbee The oneline of this commitpick fa1afe1 The oneline of the next commit... The oneline descriptions are purely for your pleasure; git-rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names. By replacing the command "pick" with the command "edit", you can tell git-rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing. If you want to fold two or more commits into one, replace the command "pick" with "squash" for the second and subsequent commit. If the commits had different authors, it will attribute the squashed commit to the author of the first commit. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/37219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
]
} |
37,248 | While the C# spec does include a pre-processor and basic directives (#define, #if, etc), the language does not have the same flexible pre-processor found in languages such as C/C++. I believe the lack of such a flexible pre-processor was a design decision made by Anders Hejlsberg (although, unfortunately, I can't find reference to this now). From experience, this is certainly a good decision, as there were some really terrible un-maintainable macros created back when I was doing a lot of C/C++. That said, there are a number of scenarios where I could find a slightly more flexible pre-processor to be useful. Code such as the following could be improved by some simple pre-processor directives: public string MyProperty{ get { return _myProperty; } set { if (value != _myProperty) { _myProperty = value; NotifyPropertyChanged("MyProperty"); // This line above could be improved by replacing the literal string with // a pre-processor directive like "#Property", which could be translated // to the string value "MyProperty" This new notify call would be as follows: // NotifyPropertyChanged(#Property); } }} Would it be a good idea to write a pre-processor to handle extremely simple cases like this? Steve McConnell wrote in Code Complete (p208): Write your own preprocessor If a language doesn't include a preprocessor, it's fairly easy to write one... I am torn. It was a design decision to leave such a flexible pre-processor out of C#. However, an author I highly respect mentions it may be ok in some circumstances. Should I build a C# pre-processor? Is there one available that does the simple things I want to do? | Consider taking a look at an aspect-oriented solution like PostSharp , which injects code after the fact based on custom attributes. It's the opposite of a precompiler but can give you the sort of functionality you're looking for (PropertyChanged notifications etc). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/37248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
]
} |
37,275 | What is the SQL query to select all of the MSSQL Server's logins? Thank you. More than one of you had the answer I was looking for: SELECT * FROM syslogins | Is this what you're after? select * from master.syslogins | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/37275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1208/"
]
} |
37,299 | What's the instruction to cause a hard-break in Xcode? For example under Visual Studio I could do '_asm int 3' or 'DebugBreak()'. Under some GCC implementations it's asm("break 0") or asm("trap"). I've tried various combos under Xcode without any luck. (inline assembler works fine so it's not a syntax issue). For reference this is for an assert macro. I don't want to use the definitions in assert.h both for portability, and because they appear to do an abort() in the version XCode provides. John - Super, cheers. For reference the int 3 syntax is the one required for Intel Macs and iPhone. Chris - Thanks for your comment but there are many reasons to avoid the standard assert() function for codebases ported to different platforms. If you've gone to the trouble of rolling your own assert it's usually because you have additional functionality (logging, stack unwinding, user-interaction) that you wish to retain. Your suggestion of attempting to replace the hander via an implementation of '__assert" or similar is not going to be portable. The standard 'assert' is usually a macro and while it may map to __assert on the Mac it doesn't on other platforms. | http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html asm {trap} ; Halts a program running on PPC32 or PPC64.__asm {int 3} ; Halts a program running on IA-32. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/37299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
]
} |
37,310 | I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object.What is the best way to test that the factory has worked correctly? I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it. Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used. | Since I don't know how your factory method looks like, all I can advise right now is to Check to see the object is the correct concrete implementation you were looking for: IMyInterface fromFactory = factory.create(...); Assert.assertTrue(fromFactory instanceof MyInterfaceImpl1); You can check if the factory setup the concrete instances with valid instance variables. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/37310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3576/"
]
} |
37,317 | I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about: The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked. I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now: public partial class Form1 : Form { Control _lastEnteredControl; private void textBox_Enter(object sender, EventArgs e) { _lastEnteredControl = (Control)sender; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Do something here"); _lastEnteredControl.Focus(); } } So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this? | For a bit of 'simplicity' maybe try. public Form1() { InitializeComponent(); foreach (Control ctrl in Controls) { if (ctrl is TextBox) { ctrl.Enter += delegate(object sender, EventArgs e) { _lastEnteredControl = (Control)sender; }; } } } then you don't have to worry about decorating each textbox manually (or forgetting about one too). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/37317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3452/"
]
} |
37,324 | I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#. How do you represent the following in LINQ to SQL: select DealerContact.*from Dealer inner join DealerContact on Dealer.DealerID = DealerContact.DealerID | It goes something like: from t1 in db.Table1join t2 in db.Table2 on t1.field equals t2.fieldselect new { t1.field2, t2.field3} It would be nice to have sensible names and fields for your tables for a better example. :) Update I think for your query this might be more appropriate: var dealercontacts = from contact in DealerContact join dealer in Dealer on contact.DealerId equals dealer.ID select contact; Since you are looking for the contacts, not the dealers. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/37324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
]
} |
37,335 | I am writing a client-side Swing application (graphical font designer) on Java 5 . Recently, I am running into java.lang.OutOfMemoryError: Java heap space error because I am not being conservative on memory usage. The user can open unlimited number of files, and the program keeps the opened objects in the memory. After a quick research I found Ergonomics in the 5.0 Java Virtual Machine and others saying on Windows machine the JVM defaults max heap size as 64MB . Given this situation, how should I deal with this constraint? I could increase the max heap size using command line option to java, but that would require figuring out available RAM and writing some launching program or script. Besides, increasing to some finite max does not ultimately get rid of the issue. I could rewrite some of my code to persist objects to file system frequently (using database is the same thing) to free up the memory. It could work, but it's probably a lot work too. If you could point me to details of above ideas or some alternatives like automatic virtual memory, extending heap size dynamically , that will be great. | Ultimately you always have a finite max of heap to use no matter what platform you are running on. In Windows 32 bit this is around 2GB (not specifically heap but total amount of memory per process). It just happens that Java chooses to make the default smaller (presumably so that the programmer can't create programs that have runaway memory allocation without running into this problem and having to examine exactly what they are doing). So this given there are several approaches you could take to either determine what amount of memory you need or to reduce the amount of memory you are using. One common mistake with garbage collected languages such as Java or C# is to keep around references to objects that you no longer are using, or allocating many objects when you could reuse them instead. As long as objects have a reference to them they will continue to use heap space as the garbage collector will not delete them. In this case you can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place. One option which I have used in the past is "JMP" http://www.khelekore.org/jmp/ . If you determine that you are allocating these objects for a reason and you need to keep around references (depending on what you are doing this might be the case), you will just need to increase the max heap size when you start the program. However, once you do the memory profiling and understand how your objects are getting allocated you should have a better idea about how much memory you need. In general if you can't guarantee that your program will run in some finite amount of memory (perhaps depending on input size) you will always run into this problem. Only after exhausting all of this will you need to look into caching objects out to disk etc. At this point you should have a very good reason to say "I need Xgb of memory" for something and you can't work around it by improving your algorithms or memory allocation patterns. Generally this will only usually be the case for algorithms operating on large datasets (like a database or some scientific analysis program) and then techniques like caching and memory mapped IO become useful. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/37335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
]
} |
37,346 | If I create a class like so: // B.h#ifndef _B_H_#define _B_H_class B{private: int x; int y;};#endif // _B_H_ and use it like this: // main.cpp#include <iostream>#include <vector>class B; // Forward declaration.class A{public: A() { std::cout << v.size() << std::endl; }private: std::vector<B> v;};int main(){ A a;} The compiler fails when compiling main.cpp . Now the solution I know is to #include "B.h" , but I'm curious as to why it fails. Neither g++ or cl 's error messages were very enlightening in this matter. | The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said std::vector<B*> , then the compiler wouldn't need to know how big B is because it knows how big a pointer is. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/37346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
]
} |
37,374 | We've just started using LINQ to SQL at work for our DAL & we haven't really come up with a standard for out caching model. Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that. I'm wondering if anyone has come up with a 'standard' approach to caching LINQ to SQL results? We're working in a web environment (IIS) if that makes a difference. I know this may well end up being a subjective question, but I still think the info would be valuable. EDIT: To clarify, I'm not talking about caching an individual result, I'm after more of an architecture solution, as in how do you set up caching so that all your link methods use the same caching architecture. | My LINQ query result cache is probably just what you're looking for. var q = from c in context.Customers where c.City == "London" select new { c.Name, c.Phone };var result = q.Take(10).FromCache(); Pete. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/37374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
]
} |
37,398 | My current preferred C++ environment is the free and largely excellent Microsoft Visual Studio 2005 Express edition. From time to time I have sent release .exe files to other people with pleasing results. However recently I made the disturbing discovery that the pleasing results were based on more luck that I would like. Attempting to run one of these programs on an old (2001 vintage, not scrupulously updated) XP box gave me nothing but a nasty "System cannot run x.exe" (or similar) message. Some googling revealed that with this toolset, even specifying static linking results in a simple hello-world.exe actually relying on extra .dll files (msvcm80.dll etc.). An incredibly elaborate version scheming system (manifest files anyone?) then will not let the .exe run without exactly the right .dll versions. I don't want or need this stuff, I just want an old fashioned self contained .exe that does nothing but lowest common denominator Win32 operations and runs on any old win32 OS. Does anyone know if its possible to do what I want to do with my existing toolset ? Thank you. | For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'. If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/37398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3955/"
]
} |
37,464 | If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store? It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store. | Official Developer Program For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using Ad Hoc Helper available from the App Store. For further details on this method, see Craig Hockenberry's Beta testing on iPhone 2.0 article Jailbroken iPhone For jailbroken iPhones, you can use the following method which I have personally tested using the AccelerometerGraph sample app on iPhone OS 3.0. Create Self-Signed Certificate First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate: Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate. Name: iPhone Developer Certificate Type: Code Signing Let me override defaults: Yes Click Continue Validity: 3650 days Click Continue Blank out the Email address field. Click Continue until complete. You should see "This root certificate is not trusted". This is expected. Set the iPhone SDK to allow the self-signed certificate to be used: sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist If you have Xcode open, restart it for this change to take effect. Manual Deployment over WiFi The following steps require openssh , and uikittools to be installed first. Replace jasoniphone.local with the hostname of the target device. Be sure to set your own password on both the mobile and root users after installing SSH. To manually compile and install your application on the phone as a system app (bypassing Apple's installation system): Project, Set Active SDK, Device and Set Active Build Configuration, Release. Compile your project normally (using Build, not Build & Go). In the build/Release-iphoneos directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device. scp -r AccelerometerGraph.app root@jasoniphone:/Applications/ Let SpringBoard know the new application has been installed: ssh [email protected] uicache This only has to be done when you add or remove applications. Updated applications just need to be relaunched. To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project. Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard: ssh [email protected] rm -r /Applications/AccelerometerGraph.app &&ssh [email protected] uicache | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/37464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752/"
]
} |
37,473 | If I use assert() and the assertion fails then assert() will call abort() , ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully? | Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s assert() is exactly C's assert() , with the abort() "feature" bundled in. Fortunately, this is surprisingly straightforward. Assert.hh template <typename X, typename A>inline void Assert(A assertion){ if( !assertion ) throw X();} The above function will throw an exception if a predicate doesn't hold. You will then have the chance to catch the exception. If you don't catch the exception, terminate() will be called, which will end the program similarly to abort() . You may wonder what about optimizing away the assertion when we're building for production. In this case, you can define constants that will signify that you're building for production and then refer to the constant when you Assert() . debug.hh #ifdef NDEBUG const bool CHECK_WRONG = false;#else const bool CHECK_WRONG = true;#endif main.cc #include<iostream>struct Wrong { };int main(){ try { Assert<Wrong>(!CHECK_WRONG || 2 + 2 == 5); std::cout << "I can go to sleep now.\n"; } catch( Wrong e ) { std::cerr << "Someone is wrong on the internet!\n"; } return 0;} If CHECK_WRONG is a constant then the call to Assert() will be compiled away in production, even if the assertion is not a constant expression. There is a slight disadvantage in that by referring to CHECK_WRONG we type a little more. But in exchange we gain an advantage in that we can classify various groups of assertions and enable and disable each of them as we see fit. So, for example we could define a group of assertions that we want enabled even in production code, and then define a group of assertions that we only want to see in development builds. The Assert() function is equivalent to typing if( !assertion ) throw X(); but it clearly indicates the intent of the programmer: make an assertion. Assertions are also easier to grep for with this approach, just like plain assert() s. For more details on this technique see Bjarne Stroustrup's The C++ Programming Language 3e, section 24.3.7.2. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/37473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456/"
]
} |
37,486 | Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python. | Use lxml which is the best xml/html library for python. import lxml.htmlt = lxml.html.fromstring("...")t.text_content() And if you just want to sanitize the html look at the lxml.html.clean module | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/37486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3971/"
]
} |
37,538 | How do I determine the size of my array in C? That is, the number of elements the array can hold? | Executive summary: int a[17];size_t n = sizeof(a)/sizeof(a[0]); Full answer: To determine the size of your array in bytes, you can use the sizeof operator: int a[17];size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can dividethe total size of the array by the size of the array element.You could do this with the type, like this: int a[17];size_t n = sizeof(a) / sizeof(int); and get the proper answer (68 / 4 = 17), but if the type of a changed you would have a nasty bug if you forgot to changethe sizeof(int) as well. So the preferred divisor is sizeof(a[0]) or the equivalent sizeof(*a) , the size of the first element of the array. int a[17];size_t n = sizeof(a) / sizeof(a[0]); Another advantage is that you can now easily parameterizethe array name in a macro and get: #define NELEMS(x) (sizeof(x) / sizeof((x)[0]))int a[17];size_t n = NELEMS(a); | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/37538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
]
} |
37,564 | I am trying to figure out what exactly is Appdomain recycling?When a aspx page is requested for the first time from a DotNet application, i understand that an appdomain for that app is created, and required assemblies are loaded into that appdomain, and the request will be served. Now, if the web.config file or the contents of the bin folder, etc are modified, the appdomain will be "recycled".My question is, at the end of the recycling process, will the appdomain be loaded with assemblies and ready to serve the next request? or a page has to be requested to trigger the assemblies to load?. | Well, I think the thread was getting smoothly to a final conclusion, but in the end, it was otherwise. I'll try to answer the question based on my understanding and leveraging what i've just read about in other web sites. First of all, I myself try to avoid the term recycle other than for Application Pools since this may render someone confused. Now, getting to process, pools and AppDomain, I see the picture as follows: An Application Pool is, in short, a region of memory that is maintained up and running by a process called W3WP.exe, aka Worker Process. Recycling an Application Pool means bringing that process down, eliminating it from memory and then originating a brand new Worker Process, with a newly assigned process ID. Regarding Application Domains, I see it as subsets of memory regions, within the aforementioned region that plays the role of a container. In other words, the process in memory, W3WP.exe in this case, is a macro memory region for applications that stores subset regions, called Application Domains. Having said that, one process in memory may store different Application Domains, one for each application that is assigned to run within a given Application Pool. When it comes to recycling, as I initially told, it's something that I myself reserve only for Application Pools. For AppDomains, I prefer using the term 'restart', in order to avoid misconception. Based on this, restarting a AppDomain means starting over a given application with the newly added settings, such as refreshing the existing configuration. That happens within the boundaries of that sub-region of memory, called AppDomain, that ultimately lies within the process associated with a respective Application Pool. Those new settings may come from files such as web.config,machine.config,global.asax,Bin directory,App_Code, and there may be others. AppDomain are isolated from each other, that makes total sense. If not so, if changes to a web.config, let's say, of application 1, requited recycle of the pool, all other applications assigned to that pool would get restarted, what was definitely not desired by Microsoft and by anyone else. Summarizing my point, Process (W3WP.exe) AppDomain 1 AppDomain 2 AppDomain 3 AppDomain n n = the number of assigned applications to the Application Pool managed by the given W3WP.exe Processes are memory regions isolated from one another AppDomains are sub-memory regions isolated from one another, within the same process Global IIS settings changes may require Application Pool recycle (killing and starting a new Worker Process, W3WP.exe) Application-wide settings changes AppDomains concerns, and they may get restarted after changes in some specific files such as the ones outline above For further information, I recommend: http://blogs.msdn.com/b/david.wang/archive/2006/03/12/thoughts-on-iis-configuration-changes-and-when-it-takes-effect.aspx What causes an application pool in IIS to recycle? http://blogs.msdn.com/b/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx Regards from Brazil! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/37564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647/"
]
} |
37,579 | If you want to use a queuing product for durable messaging under Windows, running .NET 2.0 and above, which alternatives to MSMQ exist today? I know of ActiveMQ ( http://activemq.apache.org/ ), and I've seen references to WSMQ (pointing to http://wsmq.net ), but the site seems to be down. Are there any other alternatives? | I can't begin to say enough good things about Tibco EMS - an implementation of the Java JMS messaging spec. Tibco EMS has superb support for .NET clients - including Compact Framework .NET on WinCE. (They also have C client libraries too.) So if you're building a heterogeneous distributed application involving messaging code running on Windows, Unix (AIX/Solaris), Linux, or Mac OS X, then Tibco EMS is the ticket. Check out my article here: Using JMS For Distributed Software Development I used to work at Microsoft and did some implementation with MSMQ while there. But you know, Microsoft just concerns itself with Windows. They depended on 3rd parties to provide MSMQ clients to other platforms. My encounter with Tibco EMS was a much better experience. It was very evident that Tibco understood messaging much more so than Microsoft. And Tibco put the effort into supporting diverse client bindings themselves. That is why they eventually changed the product name from Tibco JMS to Tibco EMS (Enterprise Messaging Service). And I did build heterogeneous software systems around Tibco EMS. Rolled C# .NET Winform clients interacting with Java/JBoss middle-tier via Tibco EMS messaging. (And also have WinCE industrial embedded computers that use the Compact Framework .NET Tibco client.) Links To My JMS Writings | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/37579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3985/"
]
} |
37,628 | What is reflection, and why is it useful? I'm particularly interested in Java, but I assume the principles are the same in any language. | The name reflection is used to describe code which is able to inspect other code in the same system (or itself). For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to. So, to give you a code example of this in Java (imagine the object in question is foo) : Method method = foo.getClass().getMethod("doSomething", null);method.invoke(foo, null); One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test. There are some good reflection examples to get you started at http://docs.oracle.com/javase/tutorial/reflect/index.html And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common. Update from a comment: The ability to inspect the code in the system and see object types is not reflection, but rather Type Introspection. Reflection is then the ability to make modifications at runtime by making use of introspection. The distinction is necessary here as some languages support introspection, but do not support reflection. One such example is C++ | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/37628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142/"
]
} |
37,644 | I have a set of Berkeley DB files on my Linux file system that I'd like to examine. What useful tools exist for getting a quick overview of the contents? I can write Perl scripts that use BDB modules for examining them, but I'm looking for some CLI utility to be able to take a look inside without having to start writing scripts. | Check out the db-utils package. If you use apt, you can install it with the following: apt-get install db-util (or apt-get install db4.8-util or whatever version you have or prefer.) Additional links: http://rpmfind.net/linux/rpm2html/search.php?query=db-utils https://packages.ubuntu.com/search?suite=default§ion=all&arch=any&keywords=db-util&searchon=names Man page of db4.4_dump | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/37644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1951/"
]
} |
37,649 | I have a MySQL table with coordinates, the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that. Is this possible to do with UPDATE in some way? UPDATE table SET X=Y, Y=X obviously won't do what I want. Edit: Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options. | I just had to deal with the same and I'll summarize my findings. The UPDATE table SET X=Y, Y=X approach obviously doesn't work, as it'll just set both values to Y. Here's a method that uses a temporary variable. Thanks to Antony from the comments of http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/ for the "IS NOT NULL" tweak. Without it, the query works unpredictably. See the table schema at the end of the post. This method doesn't swap the values if one of them is NULL. Use method #3 that doesn't have this limitation. UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL; This method was offered by Dipin in, yet again, the comments of http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/ . I think it’s the most elegant and clean solution. It works with both NULL and non-NULL values. UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp; Another approach I came up with that seems to work: UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id; Essentially, the 1st table is the one getting updated and the 2nd one is used to pull the old data from. Note that this approach requires a primary key to be present. This is my test schema: CREATE TABLE `swap_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `x` varchar(255) DEFAULT NULL, `y` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;INSERT INTO `swap_test` VALUES ('1', 'a', '10');INSERT INTO `swap_test` VALUES ('2', NULL, '20');INSERT INTO `swap_test` VALUES ('3', 'c', NULL); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/37649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/890/"
]
} |
37,650 | What is the best way to implement, from a web page a download action using asp.net 2.0? Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc. | Does this help: http://www.west-wind.com/weblog/posts/76293.aspx Response.ContentType = "application/octet-stream";Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt");Response.TransmitFile( Server.MapPath("~/logfile.txt") );Response.End(); Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/37650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3416/"
]
} |
37,666 | I have a few Visual Studio Solutions/Projects that are being worked on in my company, which now require a scheme for automatic nightly builds. Such a scheme needs to be able to check the latest versions from SVN, build the solutions, create the appropriate downloadable files (including installers, documentation, etc.), send e-mails to the developers upon errors and all sorts of other nifty things. What tool, or tool-set, should I use for this? I used to use FinalBuilder a few years ago and I liked that a lot but I'm not sure if they support such features as nightly-builds and email messages. | At my work we use CCNET, but with builds on check-in more than nightly - although it's easily configured for either or both. You can very easily set up unit testing to run on every checkin as well, FXCop testing, and a slew of other products. I would also advise checking out Team City as an option, because it has a free version, and the reporting and setup is reportedly much simpler (it does look nice to me). It does have a limit of somewhere around 20 team members/projects, before it hits a pay-for window. That said, we started with CCNET, and have grown several products too large to look at Team City on the free version and are very happy with what we have. Features that help with CCNET include: XML based configuration - you can usually copy and paste most of what you need. More or less you'll be able to plug your treesurgeon script in as your build script, and point CCNET at that as an executable task to run the compilation. Lots of documentation and very easy to set up nunit, ncover, fxcop, etc. Taskbar app that will let you know the status of your projects at any time, and it can also fire off an email or keep an RSS feed with the same information. But I'd definitely go with running a CI build on every check-in - for the most part will run the unit tests before checking in, but let the CCNET server handle run any applications/assemblies that would have dependencies on the assembly we're checking in, and they get re-built, and re-tested on every checkin. Given that CCNET is free free and takes very little time to set up - I'd highly recommend just going for it and seeing if it suits you, then expanding from there. (There's another thread here where I posted pretty much the same/with a few alterations - but some of the other comments may help too! Automated Builds ) Edit to add: You can easily set up your own deployment scheme for CCNET, and there are a tonne of blog posts out there to assist, and email notifications can really be set up fairly granularly, either on all successes, all failures, when it changes from success to fail, etc. There's also built in RSS, and you could even set up your own notifiers for other systems. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/37666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3379/"
]
} |
37,684 | I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing the first match. How I can replace all the URL? I guess I should be using the exec command, but I did not really figure how to do it. function replaceURLWithHTMLLinks(text) { var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i; return text.replace(exp,"<a href='$1'>$1</a>"); } | First off, rolling your own regexp to parse URLs is a terrible idea . You must imagine this is a common enough problem that someone has written, debugged and tested a library for it, according to the RFCs . URIs are complex - check out the code for URL parsing in Node.js and the Wikipedia page on URI schemes . There are a ton of edge cases when it comes to parsing URLs: international domain names , actual ( .museum ) vs. nonexistent ( .etc ) TLDs, weird punctuation including parentheses , punctuation at the end of the URL, IPV6 hostnames etc. I've looked at a ton of libraries , and there are a few worth using despite some downsides: Soapbox's linkify has seen some serious effort put into it, and a major refactor in June 2015 removed the jQuery dependency . It still has issues with IDNs . AnchorMe is a newcomer that claims to be faster and leaner. Some IDN issues as well. Autolinker.js lists features very specifically (e.g. "Will properly handle HTML input. The utility will not change the href attribute inside anchor () tags" ). I'll thrown some tests at it when a demo becomes available . Libraries that I've disqualified quickly for this task: Django's urlize didn't handle certain TLDs properly (here is the official list of valid TLDs . No demo . autolink-js wouldn't detect "www.google.com" without http://, so it's not quite suitable for autolinking "casual URLs" (without a scheme/protocol) found in plain text. Ben Alman's linkify hasn't been maintained since 2009. If you insist on a regular expression, the most comprehensive is the URL regexp from Component , though it will falsely detect some non-existent two-letter TLDs by looking at it. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/37684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
} |
37,702 | Sorry for this not being a "real" question, but Sometime back i remember seeing a post here about randomizing a randomizer randomly to generate truly random numbers, not just pseudo random. I dont see it if i search for it. Does anybody know about that article? | I believe that was on thedailywtf.com - ie. not something that you want to do. It is not possible to get a truly random number from pseudorandom numbers, no matter how many times you call randomize(). You can get "true" random numbers from special hardware . You could also collect entropy from mouse movements and things like that. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/37702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
]
} |
37,732 | What is the RegEx pattern for DateTime (2008-09-01 12:35:45 ) ? I get this error: No ending delimiter '^' found Using: preg_match('(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(?<sep>[/.-])(?<month>0?[1-9]|1[012])\2(?<year>(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45'); Gives this error: Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19 | @Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed. It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed: (\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) If you're using perl, then you can get the values out with something like this: $year = $1;$month = $2;$day = $3;$hour = $4;$minute = $5;$second = $6; Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/37732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4013/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.