source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
87,359
I have a page which spawns a popup browser window. I have a JavaScript variable in the parent browser window and I would like to pass it to the popped-up browser window. Is there a way to do this? I know this can be done across frames in the same browser window but I'm not sure if it can be done across browser windows.
Provided the windows are from the same security domain, and you have a reference to the other window, yes. Javascript's open() method returns a reference to the window created (or existing window if it reuses an existing one). Each window created in such a way gets a property applied to it "window.opener" pointing to the window which created it. Either can then use the DOM (security depending) to access properties of the other one, or its documents,frames etc.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/87359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ] }
87,372
I'm asking for a template trick to detect if a class has a specific member function of a given signature. The problem is similar to the one cited here http://www.gotw.ca/gotw/071.htm but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else". A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization. I don't like that solution for two reasons: To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization! The stack to resolve thatmess was 10 to 12 function invocations. I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one) Can you give me a hint to solve this puzzle?
I'm not sure if I understand you correctly, but you may exploit SFINAE to detect function presence at compile-time. Example from my code (tests if class has member function size_t used_memory() const). template<typename T>struct HasUsedMemoryMethod{ template<typename U, size_t (U::*)() const> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &U::used_memory>*); template<typename U> static int Test(...); static const bool Has = sizeof(Test<T>(0)) == sizeof(char);};template<typename TMap>void ReportMemUsage(const TMap& m, std::true_type){ // We may call used_memory() on m here.}template<typename TMap>void ReportMemUsage(const TMap&, std::false_type){}template<typename TMap>void ReportMemUsage(const TMap& m){ ReportMemUsage(m, std::integral_constant<bool, HasUsedMemoryMethod<TMap>::Has>());}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/87372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10120/" ] }
87,380
I need to write a function that receives a string and a regex. I need to check if there is a match and return the start and end location of a match. (The regex was already compiled by qr// .) The function might also receive a "global" flag and then I need to return the (start,end) pairs of all the matches. I cannot change the regex, not even add () around it as the user might use () and \1 . Maybe I can use (?:) . Example: given "ababab" and the regex qr/ab/ , in the global case I need to get back 3 pairs of (start, end).
The built-in variables @- and @+ hold the start and end positions, respectively, of the last successful match. $-[0] and $+[0] correspond to entire pattern, while $-[N] and $+[N] correspond to the $N ( $1 , $2 , etc.) submatches.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/87380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11827/" ] }
87,381
With ViEmu you really need to unbind a lot of resharpers keybindings to make it work well. Does anyone have what they think is a good set of keybindings that work well for resharper when using ViEmu? What I'm doing at the moment using the Visual Studio bindings from Resharper. Toasting all the conflicting ones with ViEmu, and then just driving the rest through the menu modifiers ( Alt-R keyboard shortcut for the menu item ). I also do the same with Visual Assist shortcuts ( for C++ ) if anyones got any tips and tricks for ViEmu / Resharper or Visual Assist working together well I'd most apprciate it!
You can also create mappings in ViEmu that will call the VS and R# actions. For example, I have these lines in my _viemurc file for commenting and uncommenting a selection: map <C-S-c> gS:vsc Edit.CommentSelection<CR>map <C-A-c> gS:vsc Edit.UncommentSelection<CR> The :vsc is for "visual studio command," and then you enter the exact text of the command, as it appears in the commands list when you go to Tool>Options>Keyboard I don't use any of the R# ones in this way, but it does work, as with: map <C-S-A-f> gS:vsc ReSharper.FindUsages<CR>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/87381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10431/" ] }
87,422
I am writing an application that if the user hits back, it may resend the same information and mess up the flow and integrity of data. How do I disable it for users who are with and without javascript on?
It's not possible, sadly. However, consider your applications navigation model. Are you using Post/Redirect/Get PRG Model? http://en.wikipedia.org/wiki/Post/Redirect/Get ? This model is more back button friendly than the Postback model.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/87422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088/" ] }
87,425
Do you generally assume that toString() on any given object has a low cost (i.e. for logging)? I do. Is that assumption valid? If it has a high cost should that normally be changed? What are valid reasons to make a toString() method with a high cost? The only time that I get concerned about toString costs is when I know that it is on some sort of collection with many members.From: http://jamesjava.blogspot.com/2007/08/tostring-cost.html Update: Another way to put it is: Do you usually look into the cost of calling toString on any given class before calling it?
No it's not. Because ToString() can be overloaded by anyone, they can do whatever they like. It's a reasonable assumption that ToString() SHOULD have a low cost, but if ToString() accesses properties that do "lazy loading" of data, you might even hit a database inside your ToString().
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/87425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770/" ] }
87,442
I know that you can make a virtual network interface in Windows (see here ), and in Linux it is also pretty easy with ip-aliases, but does something similar exist for Mac OS X ? I've been looking for loopback adapters, virtual interfaces and couldn't find a good solution. You can create a new interface in the networking panel, based on an existing interface, but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive). This scenario is needed when working in a completely disconnected situation. Even then, it makes sense to have networking capabilities when running servers in a VMWare installation. Those virtual machines can be reached by their IP address, but not by their DNS name, even if I run a DNS server in one of those virtual machines. By configuring an interface to use the virtual DNS server, I thought I could test some DNS scenario's. Unfortunately, no interface is resolving DNS names if none of them are inactive...
The loopback adapter is always up. ifconfig lo0 alias 172.16.123.1 will add an alias IP 172.16.123.1 to the loopback adapter ifconfig lo0 -alias 172.16.123.1 will remove it
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/87442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9504/" ] }
87,561
I'd like to add some pie, bar and scatter charts to my Ruby on Rails web application. I want want them to be atractive, easy to add and not introduce much overhead. What charting solution would you recommend? What are its drawbacks (requires Javascript, Flash, expensive, etc)?
Google Charts is an excellent choice if you don't want to use Flash. It's pretty easy to use on its own, but for Rails, it's even easier with the gchartrb gem. An example: GoogleChart::PieChart.new('320x200', "Things I Like To Eat", false) do |pc| pc.data "Broccoli", 30 pc.data "Pizza", 20 pc.data "PB&J", 40 pc.data "Turnips", 10 puts pc.to_url end
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/87561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16779/" ] }
87,621
I have an XML that I want to load to objects, manipulate those objects (set values, read values) and then save those XMLs back.It is important for me to have the XML in the structure (xsd) that I created. One way to do that is to write my own serializer, but is there a built in support for it or open source in C# that I can use?
You can generate serializable C# classes from a schema (xsd) using xsd.exe: xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir If the schema has dependencies (included/imported schemas), they must all be included on the same command line.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/87621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9855/" ] }
87,676
Every time I need to work with date and/or timstamps in Java I always feel like I'm doing something wrong and spend endless hours trying to find a better way of working with the APIs without having to code my own Date and Time utility classes. Here's a couple of annoying things I just ran into: 0-based months. I realize that best practice is to use Calendar.SEPTEMBER instead of 8, but it's annoying that 8 represents September and not August. Getting a date without a timestamp. I always need the utility that Zeros out the timestamp portion of the date. I know there's other issues I've had in the past, but can't recall. Feel free to add more in your responses. So, my question is ... What third party APIs do you use to simplify Java's usage of Date and Time manipulation, if any? Any thoughts on using Joda ? Anyone looked closer at JSR-310 Date and Time API?
This post has a good discussion on comparing the Java Date/Time API vs JODA. I personally just use Gregorian Calendar and SimpleDateFormat any time I need to manipulate dates/times in Java. I've never really had any problems in using the Java API and find it quite easy to use, so have not really looked into any alternatives.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/87676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917/" ] }
87,734
If the major axis of the ellipse is vertical or horizontal, it's easy to calculate the bounding box, but what about when the ellipse is rotated? The only way I can think of so far is to calculate all the points around the perimeter and find the max/min x and y values. It seems like there should be a simpler way. If there's a function (in the mathematical sense) that describes an ellipse at an arbitrary angle, then I could use its derivative to find points where the slope is zero or undefined, but I can't seem to find one. Edit: to clarify, I need the axis-aligned bounding box, i.e. it should not be rotated with the ellipse, but stay aligned with the x axis so transforming the bounding box won't work.
You could try using the parametrized equations for an ellipse rotated at an arbitrary angle: x = h + a*cos(t)*cos(phi) - b*sin(t)*sin(phi) [1]y = k + b*sin(t)*cos(phi) + a*cos(t)*sin(phi) [2] ...where ellipse has centre (h,k) semimajor axis a and semiminor axis b, and is rotated through angle phi. You can then differentiate and solve for gradient = 0: 0 = dx/dt = -a*sin(t)*cos(phi) - b*cos(t)*sin(phi) => tan(t) = -b*tan(phi)/a [3] Which should give you many solutions for t (two of which you are interested in), plug that back into [1] to get your max and min x. Repeat for [2]: 0 = dy/dt = b*cos(t)*cos(phi) - a*sin(t)*sin(phi) => tan(t) = b*cot(phi)/a [4] Lets try an example: Consider an ellipse at (0,0) with a=2, b=1, rotated by PI/4: [1] => x = 2*cos(t)*cos(PI/4) - sin(t)*sin(PI/4) [3] => tan(t) = -tan(PI/4)/2 = -1/2 => t = -0.4636 + n*PI We are interested in t = -0.4636 and t = -3.6052 So we get: x = 2*cos(-0.4636)*cos(PI/4) - sin(-0.4636)*sin(PI/4) = 1.5811 and x = 2*cos(-3.6052)*cos(PI/4) - sin(-3.6052)*sin(PI/4) = -1.5811
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/87734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2214/" ] }
87,735
I have a simple SQL 'Select' query, and I'd like to dump the results into an Excel file. I'm only able to save as .csv and converting to .xls creates some super ugly output. In any case, as far as I can tell (using Google) this doesn't seem to be so straight forward. Any help would be greatly appreciated.
Use "External data" from Excel. It can use ODBC connection to fetch data from external source: Data/Get External Data/New Database Query That way, even if the data in the database changes, you can easily refresh.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/87735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16830/" ] }
87,747
I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL. Results would be something like: TableName, ColumnName
Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use theINFORMATION_SCHEMA views: select COLUMN_NAME, TABLE_NAMEfrom INFORMATION_SCHEMA.COLUMNSwhere COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1order by TABLE_NAME
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/87747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
87,753
How can I resize an image, with the image quality unaffected?
As rcar says, you can't without losing some quality, the best you can do in c# is: Bitmap newImage = new Bitmap(newWidth, newHeight);using (Graphics gr = Graphics.FromImage(newImage)){ gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/87753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ] }
87,771
How would I go about... multiplying two 64-bit numbers multiplying two 16-digit hexadecimal numbers ...using Assembly Language. I'm only allowed to use registers %eax, %ebx, %ecx, %edx, and the stack. EDIT: Oh, I'm using ATT Syntax on the x86 EDIT2: Not allowed to decompile into assembly...
Use what should probably be your course textbook, Randall Hyde's "The Art of Assembly Language". See 4.2.4 - Extended Precision Multiplication Although an 8x8, 16x16, or 32x32 multiply is usually sufficient, there are times when you may want to multiply larger values together. You will use the x86 single operand MUL and IMUL instructions for extended precision multiplication .. Probably the most important thing to remember when performing an extended precision multiplication is that you must also perform a multiple precision addition at the same time . Adding up all the partial products requires several additions that will produce the result. The following listing demonstrates the proper way to multiply two 64 bit values on a 32 bit processor .. (See the link for full assembly listing and illustrations.)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/87771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13597/" ] }
87,794
I use the Boost Test framework for my C++ code but there are two problems with it that are probably common to all C++ test frameworks: There is no way to create automatic test stubs (by extracting public functions from selected classes for example). You cannot run a single test - you have to run the entire 'suite' of tests (unless you create lots of different test projects I guess). Does anyone know of a better testing framework or am I forever to be jealous of the test tools available to Java/.NET developers?
I've just pushed my own framework, CATCH , out there. It's still under development but I believe it already surpasses most other frameworks.Different people have different criteria but I've tried to cover most ground without too many trade-offs.Take a look at my linked blog entry for a taster. My top five features are: Header only Auto registration of function and method based tests Decomposes standard C++ expressions into LHS and RHS (so you don't need a whole family of assert macros). Support for nested sections within a function based fixture Name tests using natural language - function/ method names are generated It doesn't do generation of stubs - but that's a fairly specialised area. I think Isolator++ is the first tool to truly pull that off. Note that Mocking/ stubbing frameworks are usually independent of unit testing frameworks. CATCH works particularly well with mock objects as test state is not passed around by context. It also has Objective-C bindings. [update] Just happened back across this answer of mine from a few years ago. Thanks for all the great comments!Obviously Catch has developed on a lot in that time. It now has support for BDD style testing (given/ when/ then), tags, now in a single header, and loads of internal improvements and refinements (e.g. richer command line, clear and expressive output etc). A more up-to-date blog post is here.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/87794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ] }
87,795
All I want is to update an ListViewItem's text whithout seeing any flickering. This is my code for updating (called several times): listView.BeginUpdate();listViewItem.SubItems[0].Text = state.ToString(); // update the statelistViewItem.SubItems[1].Text = progress.ToString(); // update the progresslistView.EndUpdate(); I've seen some solutions that involve overriding the component's WndProc(): protected override void WndProc(ref Message m){ if (m.Msg == (int)WM.WM_ERASEBKGND) { m.Msg = (int)IntPtr.Zero; } base.WndProc(ref m);} They say it solves the problem, but in my case It didn't . I believe this is because I'm using icons on every item.
To end this question, here is a helper class that should be called when the form is loading for each ListView or any other ListView's derived control in your form. Thanks to "Brian Gillespie" for giving the solution. public enum ListViewExtendedStyles{ /// <summary> /// LVS_EX_GRIDLINES /// </summary> GridLines = 0x00000001, /// <summary> /// LVS_EX_SUBITEMIMAGES /// </summary> SubItemImages = 0x00000002, /// <summary> /// LVS_EX_CHECKBOXES /// </summary> CheckBoxes = 0x00000004, /// <summary> /// LVS_EX_TRACKSELECT /// </summary> TrackSelect = 0x00000008, /// <summary> /// LVS_EX_HEADERDRAGDROP /// </summary> HeaderDragDrop = 0x00000010, /// <summary> /// LVS_EX_FULLROWSELECT /// </summary> FullRowSelect = 0x00000020, /// <summary> /// LVS_EX_ONECLICKACTIVATE /// </summary> OneClickActivate = 0x00000040, /// <summary> /// LVS_EX_TWOCLICKACTIVATE /// </summary> TwoClickActivate = 0x00000080, /// <summary> /// LVS_EX_FLATSB /// </summary> FlatsB = 0x00000100, /// <summary> /// LVS_EX_REGIONAL /// </summary> Regional = 0x00000200, /// <summary> /// LVS_EX_INFOTIP /// </summary> InfoTip = 0x00000400, /// <summary> /// LVS_EX_UNDERLINEHOT /// </summary> UnderlineHot = 0x00000800, /// <summary> /// LVS_EX_UNDERLINECOLD /// </summary> UnderlineCold = 0x00001000, /// <summary> /// LVS_EX_MULTIWORKAREAS /// </summary> MultilWorkAreas = 0x00002000, /// <summary> /// LVS_EX_LABELTIP /// </summary> LabelTip = 0x00004000, /// <summary> /// LVS_EX_BORDERSELECT /// </summary> BorderSelect = 0x00008000, /// <summary> /// LVS_EX_DOUBLEBUFFER /// </summary> DoubleBuffer = 0x00010000, /// <summary> /// LVS_EX_HIDELABELS /// </summary> HideLabels = 0x00020000, /// <summary> /// LVS_EX_SINGLEROW /// </summary> SingleRow = 0x00040000, /// <summary> /// LVS_EX_SNAPTOGRID /// </summary> SnapToGrid = 0x00080000, /// <summary> /// LVS_EX_SIMPLESELECT /// </summary> SimpleSelect = 0x00100000}public enum ListViewMessages{ First = 0x1000, SetExtendedStyle = (First + 54), GetExtendedStyle = (First + 55),}/// <summary>/// Contains helper methods to change extended styles on ListView, including enabling double buffering./// Based on Giovanni Montrone's article on <see cref="http://www.codeproject.com/KB/list/listviewxp.aspx"/>/// </summary>public class ListViewHelper{ private ListViewHelper() { } [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SendMessage(IntPtr handle, int messg, int wparam, int lparam); public static void SetExtendedStyle(Control control, ListViewExtendedStyles exStyle) { ListViewExtendedStyles styles; styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0); styles |= exStyle; SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles); } public static void EnableDoubleBuffer(Control control) { ListViewExtendedStyles styles; // read current style styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0); // enable double buffer and border select styles |= ListViewExtendedStyles.DoubleBuffer | ListViewExtendedStyles.BorderSelect; // write new style SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles); } public static void DisableDoubleBuffer(Control control) { ListViewExtendedStyles styles; // read current style styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0); // disable double buffer and border select styles -= styles & ListViewExtendedStyles.DoubleBuffer; styles -= styles & ListViewExtendedStyles.BorderSelect; // write new style SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles); }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/87795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10833/" ] }
87,812
Say I have the following class MyComponent : IMyComponent { public MyComponent(int start_at) {...}} I can register an instance of it with castle windsor via xml as follows <component id="sample" service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample"> <parameters> <start_at>1</start_at > </parameters> </component> How would I go about doing the exact same thing but in code? (Notice, the constructor parameter)
Edit: Used the answers below code with the Fluent Interface :) namespace WindsorSample{ using Castle.MicroKernel.Registration; using Castle.Windsor; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; public class MyComponent : IMyComponent { public MyComponent(int start_at) { this.Value = start_at; } public int Value { get; private set; } } public interface IMyComponent { int Value { get; } } [TestFixture] public class ConcreteImplFixture { [Test] void ResolvingConcreteImplShouldInitialiseValue() { IWindsorContainer container = new WindsorContainer(); container.Register( Component.For<IMyComponent>() .ImplementedBy<MyComponent>() .Parameters(Parameter.ForKey("start_at").Eq("1"))); Assert.That(container.Resolve<IMyComponent>().Value, Is.EqualTo(1)); } }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/87812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ] }
87,821
Is it possible to use an IF clause within a WHERE clause in MS SQL? Example: WHERE IF IsNumeric(@OrderNumber) = 1 OrderNumber = @OrderNumber ELSE OrderNumber LIKE '%' + @OrderNumber + '%'
Use a CASE statement UPDATE: The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows: WHERE OrderNumber LIKE CASE WHEN IsNumeric(@OrderNumber) = 1 THEN @OrderNumber ELSE '%' + @OrderNumber END Or you can use an IF statement like @ N. J. Reed points out.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/87821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ] }
87,849
I am about to move to SVN as my RCS of choice (after many years using CVS) and have a basic question... I have a number of shared projects - code that I want to use with lots of different projects. Is it possible to 'link' these shared folders to the projects that need them, so checking out a project will also checkout the shared code? For example, suppose my repository looks like this: root --project1 --project2 --shared --smtp When I checkout project1, I also want to checkout shared and smtp. Back in my CVS days I would of used a Unix symbolic link in one of the project folders, but as my new SVN repository won't necessarily be hosted on a Unix box, I can't do the same.
SVN Externals are what you want to do. The SVN book explains it in great detail here . That's one thing I love about SVN, the wonderful documentation.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/87849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ] }
87,892
There are pages scattered around the web that describe POSIX AIO facilities in varying amounts of detail. None of them are terribly recent. It's not clear what, exactly, they're describing. For example, the "official" (?) web site for Linux kernel asynchronous I/O support here says that sockets don't work, but the "aio.h" manual pages on my Ubuntu 8.04.1 workstation all seem to imply that it works for arbitrary file descriptors. Then there's another project that seems to work at the library layer with even less documentation. I'd like to know: What is the purpose of POSIX AIO? Given that the most obvious example of an implementation I can find says it doesn't support sockets, the whole thing seems weird to me. Is it just for async disk I/O? If so, why the hyper-general API? If not, why is disk I/O the first thing that got attacked? Where are there example complete POSIX AIO programs that I can look at? Does anyone actually use it, for real? What platforms support POSIX AIO? What parts of it do they support? Does anyone really support the implied "Any I/O to any FD" that <aio.h> seems to promise? The other multiplexing mechanisms available to me are perfectly good, but the random fragments of information floating around out there have made me curious.
Network I/O is not a priority for AIO because everyone writing POSIX network servers uses an event based, non-blocking approach. The old-style Java "billions of blocking threads" approach sucks horribly. Disk write I/O is already buffered and disk read I/O can be prefetched into buffer using functions like posix_fadvise. That leaves direct, unbuffered disk I/O as the only useful purpose for AIO. Direct, unbuffered I/O is only really useful for transactional databases, and those tend to write their own threads or processes to manage their disk I/O. So, at the end that leaves POSIX AIO in the position of not serving any useful purpose. Don't use it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/87892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13564/" ] }
87,934
In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working. I has used the auto-complete plugin provided with Notepad++, which presented me with onClick . When I changed the capital C to a small c , it did work. So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals. But when you change getElementById to getelementbyid , you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters. So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't?
Javascript is ALWAYS case-sensitive, html is not. It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive. The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is. So, you can do this: <div id='divYo' onClick="alert('yo!');">Say Yo</div> // Upper-case 'C' or: <div id='divYo' onclick="alert('yo!');">Say Yo</div> // Lower-case 'C' but through the DOM you must use the correct case. So this works: getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C' but you cannot do this: getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C' EDIT: CMS makes a great point that most DOM methods and properties are in camelCase . The one exception that comes to mind are event handler properties and these are generally accepted to be the wrong way to attach to events anyway. Prefer using addEventListener as in: document.getElementById('divYo').addEventListener('click', modifyText, false);
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/87934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11795/" ] }
87,950
I've been attempting move a directory structure from one location to another in Subversion, but I get an Item '*' is out of date commit error. I have the latest version checked out (so far as I can tell). svn st -u turns up no differences other than the mv commands.
I sometimes get this with TortoiseSVN on windows. The solution for me is to svn update the directory, even though there are no revisions to download or update. It does something to the metadata, which magically fixes it.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/87950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ] }
87,999
Well the docs finally said it, I need to take it easy on my wrist for a few months. Being that I'm a .NET Developer this could end my livelihood for a little while, something I'm not anxious to do. That said, are there any good handsfree options for developers? Anyone had success using any of the speech recognition software out there? POSTSCRIPT: I've recovered my arm again to the point where two-handed programming isn't a problem. Dragon Naturally speaking worked well enough, but was slower, not like the keyboard where I was programming faster than I thought.
It's out there, and it works... There are quite a few speech recognition programs out there, of which Dragon NaturallySpeaking is, I think, one of the most widely used ones. I've used it myself, and have been impressed with its quality. That being a couple of years ago, I guess things have improved even further by now. ...but it ain't easy... Even though it works amazingly well, I won't say it's an easy solution. It takes time to train the program, and even then, it'll make mistakes. It's painstakingly slow compared to typing, so I had to keep saying to myself "Don't grab the keyboard, don't grab the keyboard, ..." (after which I'd grab the keyboard anyway). I myself tend to mumble a bit, which didn't make things much better, either ;-). Especially the first weeks can be frustrating. You can even get voice-related problems if you strain your voice too much . ...especially for programmers! All in all, it's certainly a workable solution for people writing normal text/prose . As a programmer, you're in a completely different realm, for which there are no real solutions. Things might have changed by now, but I'd be surprised if they have. What's the problem? Most SR software is built to recognize normal language. Programmers write very cryptic stuff, and it's hard, if not impossible, to find software that does the conversion between normal language and code. For example, how would you dictate: if (somevar == 'a'){ print('You pressed a!');} Using the commands in your average SR program, this is a huge pain: "if space left bracket equal sign equal sign apostrophe spell a apostrophe ...". And I'm not even talking about navigating your code. Ever noticed how much you're using the keyboard while programming, and how different that usage is from how a 'normal' user uses the keyboard? How to make the best of it Thus far, I've only worked with Dragon NaturallySpeaking (DNS), so I can only speak for that product. There are some interesting add-ons and websites targeted for people like programmers: Vocola is an unofficial plugin that allows you to easily add your own commands to DNS. I found it essential, basically. You'll also be able to find command sets written by other programmers, for e.g. navigating code. It's based on a software package written in Python, so there are also some more advanced and fancy packages around. Also check out Vocola's Resources page . (Warning: when I used it, there were some problems with installing Vocola; check out the newsgroup below for info!) SpeechComputing.com is a forum/newsgroup with lots of interesting discussions. A good place to start. Closing remarks It seems that the best solution to this problem is, really: Find ways around actual coding. Try to recover. I'm somewhat reluctant to recommend this book, but it seems to work amazingly well for people with RSI/carpal tunnel and other chronic pain issues: J.E. Sarno, Mindbody prescription . I'm working with it right now, and I think it's definitely worth reading.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/87999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16868/" ] }
88,235
Recently I ran into this error in my web application: java.lang.OutOfMemoryError: PermGen space It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6.Apparently this can occur after redeploying an application a few times. What causes it and what can be done to avoid it?How do I fix the problem?
The solution was to add these flags to JVM command line when Tomcat is started: -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the "Java" tab, add the arguments to the "Java Options" box. Click "OK" and then restart the service. If you get an error the specified service does not exist as an installed service you should run: tomcat6w //ES//servicename where servicename is the name of the server as viewed in services.msc Source: orx's comment on Eric's Agile Answers .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/88235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16907/" ] }
88,259
I tend to use SQLite when doing Django development, but on a live server something more robust isoften needed ( MySQL / PostgreSQL , for example).Invariably, there are other changes to make to the Djangosettings as well: different logging locations / intensities,media paths, etc. How do you manage all these changes to make deployment asimple, automated process?
Update: django-configurations has been released which is probably a better option for most people than doing it manually. If you would prefer to do things manually, my earlier answer still applies: I have multiple settings files. settings_local.py - host-specific configuration, such as database name, file paths, etc. settings_development.py - configuration used for development, e.g. DEBUG = True . settings_production.py - configuration used for production, e.g. SERVER_EMAIL . I tie these all together with a settings.py file that firstly imports settings_local.py , and then one of the other two. It decides which to load by two settings inside settings_local.py - DEVELOPMENT_HOSTS and PRODUCTION_HOSTS . settings.py calls platform.node() to find the hostname of the machine it is running on, and then looks for that hostname in the lists, and loads the second settings file depending on which list it finds the hostname in. That way, the only thing you really need to worry about is keeping the settings_local.py file up to date with the host-specific configuration, and everything else is handled automatically. Check out an example here .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
88,302
After reading Practical Common Lisp I finally understood what the big deal about macros was, and I have been looking for a language for the .NET platform that supports this. There are a few lisp dialects for .NET but from what I have been able to gather all are either very beta or abandoned. Recently my interest has been sparked by Clojure, but it's for the java platform and while on probably could use ikvm it doesn't feel some integrated. Especially when you want to do stuff like WPF. Recently I have been hearing whisper about F#, I tried to look at the documentation if I could find anything about macro support, but haven't found it. So does anyone know? Thanks :)
Well, F# is based on OCaml and OCaml has a rather extensive macro system . Given the syntactic and semantic similarities of F# and OCaml you may be able to port over the Ocaml macro system to F#. Other than stealing Ocaml's macro system I'm unaware of a canned macro system for F#.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/88302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13995/" ] }
88,311
I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z": value = ""; 8.times{value << (65 + rand(25)).chr} but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to: value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr} but it looks like trash. Does anyone have a better method?
(0...8).map { (65 + rand(26)).chr }.join I spend too much time golfing. (0...50).map { ('a'..'z').to_a[rand(26)] }.join And a last one that's even more confusing, but more flexible and wastes fewer cycles: o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flattenstring = (0...50).map { o[rand(o.length)] }.join If you want to generate some random text then use the following: 50.times.map { (0...(rand(10))).map { ('a'..'z').to_a[rand(26)] }.join }.join(" ") this code generates 50 random word string with words length less than 10 characters and then join with space
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/88311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10157/" ] }
88,325
I have a class: class MyClass:def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error: def testInsufficientArgs(self): foo = 0 self.assertRaises((Error), myClass = MyClass(Error, foo)) But I get... NameError: global name 'Error' is not defined Why? Where should I be defining this Error object? I thought it was built-in as a default exception type, no?
'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, "The Appropriate Exception Class". The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of error involved, such as 'OSError', 'ValueError', 'NameError', 'TypeError'. In this case, the appropriate error is 'ValueError' (the value of foo was wrong, therefore a ValueError). I would recommend replacing 'Error' with 'ValueError' in your script. Here is a complete version of the code you are trying to write, I'm duplicating everything because you have a weird keyword argument in your original example that you seem to be conflating with an assignment, and I'm using the 'failUnless' function name because that's the non-aliased name of the function: class MyClass: def __init__(self, foo): if foo != 1: raise ValueError("foo is not equal to 1!")import unittestclass TestFoo(unittest.TestCase): def testInsufficientArgs(self): foo = 0 self.failUnlessRaises(ValueError, MyClass, foo)if __name__ == '__main__': unittest.main() The output is: .----------------------------------------------------------------------Ran 1 test in 0.007sOK There is a flaw in the unit testing library 'unittest' that other unit testing frameworks fix. You'll note that it is impossible to gain access to the exception object from the calling context. If you want to fix this, you'll have to redefine that method in a subclass of UnitTest: This is an example of it in use: class TestFoo(unittest.TestCase): def failUnlessRaises(self, excClass, callableObj, *args, **kwargs): try: callableObj(*args, **kwargs) except excClass, excObj: return excObj # Actually return the exception object else: if hasattr(excClass,'__name__'): excName = excClass.__name__ else: excName = str(excClass) raise self.failureException, "%s not raised" % excName def testInsufficientArgs(self): foo = 0 excObj = self.failUnlessRaises(ValueError, MyClass, foo) self.failUnlessEqual(excObj[0], 'foo is not equal to 1!') I have copied the failUnlessRaises function from unittest.py from python2.5 and modified it slightly.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ] }
88,326
Does ELMAH logged exceptions even when they do not bubble up to the application? I'd like to pop up a message when an exception occurs and still log the exception. Currently I've been putting everything in try catch blocks and spitting out messages, but this gets tedious.
ELMAH has been updated to support a new feature called Signaling . This allows you to handle exceptions how you want, while still logging them to ELMAH. try{ int i = 5; int j = 0; i = i / j; //Throws exception}catch (Exception ex){ MyPersonalHandlingCode(ex); ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling} Re-throwing exceptions can be a bad practice as it makes it difficult to trace the flow of an application. Using Signaling is a much better approach if you intended to handle the error in some fashion and simply want to document it. Please check out this excellent guide by DotNetSlackers on ELMAH
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/88326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891/" ] }
88,359
While searching the interweb for a solution for my VB.net problems I often find helpful articles on a specific topic, but the code is C#. That is no big problem but it cost some time to convert it to VB manually.There are some sites that offer code converters from C# to VB and vice versa, but to fix all the flaws after the code-conversion is nearly as time-consuming as doing it by myself in the first place. Till now I am using http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx Do you know something better?
If you cannot find a good converter, you could always compile the c# code and use the dissasembler in Reflector to see Visual Basic code. Some of the variable names will change.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/88359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12336/" ] }
88,399
I saw this same question for VIM and it has been something that I myself wanted to know how to do for Emacs. In ReSharper I use CTRL-D for this action. What is the least number of commands to perform this in Emacs?
I use C-a C-SPACE C-n M-w C-y which breaks down to C-a : move cursor to start of line C-SPACE : begin a selection ("set mark") C-n : move cursor to next line M-w : copy region C-y : paste ("yank") The aforementioned C-a C-k C-k C-y C-y amounts to the same thing (TMTOWTDI) C-a : move cursor to start of line C-k : cut ("kill") the line C-k : cut the newline C-y : paste ("yank") (we're back at square one) C-y : paste again (now we've got two copies of the line) These are both embarrassingly verbose compared to C-d in your editor, but in Emacs there's always a customization. C-d is bound to delete-char by default, so how about C-c C-d ? Just add the following to your .emacs : (global-set-key "\C-c\C-d" "\C-a\C- \C-n\M-w\C-y") (@Nathan's elisp version is probably preferable, because it won't break if any of the key bindings are changed.) Beware: some Emacs modes may reclaim C-c C-d to do something else.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/88399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
88,434
I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on. Is this possible? And if so I'd like to have it detected before the client types their first letter. Is there a non-platform specific way to do this?
Try this, from java.awt.Toolkit, returns a boolean: Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ] }
88,476
I'm a little hesitant to post this, as I'm not completely sure what I'm doing. Any help would be wonderful. I'm on a computer with a firewall/filter on it. I can download files without any difficulty. When I try to clone files from Github, though, the computer just hangs. Nothing happens. It creates a git file in the folder, but the key files don't get loaded in. For context, I'm working on a Rails app, trying to load in Restful Authentication. Have any of you dealt with this? Any suggestions for getting the clone to work? Disabling the firewall might be an option, but if I can do something without going through that process, I'd appreciate it.
Github supports cloning using both the git protocol over port 9418 and HTTP over port 80. Using the later is very slow ( Reference ).You should open port 9418 on your firewall or use HTTP cloning otherwise.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69299/" ] }
88,488
Is there a way to get a DrawingContext (or something similar) for a WriteableBitmap ? I.e. something to allow you to call simple DrawLine / DrawRectangle /etc kinds of methods, rather than manipulate the raw pixels directly.
I found sixlettervariables' solution the most workable one. However, there's a "drawingContext.Close()" missing. According to MSDN, "A DrawingContext must be closed before its content can be rendered".The result is the following utility function: public static BitmapSource CreateBitmap( int width, int height, double dpi, Action<DrawingContext> render){ DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { render(drawingContext); } RenderTargetBitmap bitmap = new RenderTargetBitmap( width, height, dpi, dpi, PixelFormats.Default); bitmap.Render(drawingVisual); return bitmap;} This can then easily be used like this: BitmapSource image = ImageTools.CreateBitmap( 320, 240, 96, drawingContext => { drawingContext.DrawRectangle( Brushes.Green, null, new Rect(50, 50, 200, 100)); drawingContext.DrawLine( new Pen(Brushes.White, 2), new Point(0, 0), new Point(320, 240)); });
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/88488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ] }
88,489
Keep in mind that I'm not looking for a list of current browsers to support, I'm looking for logical ways to make that list, backed by some kind of hard statistics. Since it's been a while since my last web job, I decided to do this latest site up from scratch. Now I have to decide again what to support in terms of browsers. Certainly I have a list of what I'd like to support, but the decisions that went into that list seem to be a little arbitrary to me. Where can I go to get a reliable picture of browser usage and what seems to be a good point at which to cut off an old version of a browser from support?
Browsers don't die out completely for about a decade. The first thing you must realise is that you will have some visitors that are using a browser you don't support. The question is not which browsers are not dead, but which browsers are worth supporting (the benefit) relative to the work it takes to do so (the cost). I've never seen browser statistics I'm comfortable recommending, they all seem to be snake oil. A rule of thumb I feel is appropriate is that a browser isn't worth supporting if somebody using that browser is going to regularly run into problems on other websites as well. In other words "stick with what everybody else is supporting". To that end, Yahoo's graded browser support is useful. Ultimately, the best choice depends on your individual circumstances and will change over time. For instance, 37signals have recently dropped support for Internet Explorer 6 and Facebook are slowly heading in the same direction . This isn't a decision that most organisations can make yet, but give it a year or two and you'll see a lot more organisations follow suit. Right now, it's a bold step that you probably can't justify, but give it time. Don't fall into the trap of thinking that supporting as many browsers as possible is automatically the best choice - it may be that you are doing your visitors a disservice by wasting time working on compatibility with a browser used by five people when you could be improving the experience for the other million users you have. Also, it's worth considering that you can "officially" not support a browser. For example, one thing I've done in the past is use JavaScript served only to Internet Explorer 5.5 and below (via a conditional comment), to automatically remove stylesheets, JavaScript and replace images with their alt text. Without those measures, the site would be unreadable due to Internet Explorer's many layout bugs, but with it, the site at least works, even if it's too much work to "support" it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16398/" ] }
88,490
Is there a difference between just saying throw; and throw ex; assuming ex is the exception you're catching?
throw ex; will erase your stacktrace. Don't do this unless you mean to clear the stacktrace. Just use throw;
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891/" ] }
88,518
I'm a complete perl novice, am running a perl script using perl 5.10 and getting this warning: $* is no longer supported at migrate.pl line 380. Can anyone describe what $* did and what the recommended replacement of it is now?Alternatively if you could point me to documentation that describes this that would be great. The script I'm running is to migrate a source code database from vss to svn and can be found here: http://www.x2systems.com/files/migrate.pl.txt The two snippets of code that use it are: $* = 1; $/ = ':'; $cmd = $SSCMD . " Dir -I- \"$proj\""; $_ = `$cmd`; # what this next expression does is to merge wrapped lines like: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/excep # tion: # into: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/exception: s/\n((\w*\-*\.*\w*\/*)+\:)/$1/g; $* = 0; and then some ways later on: $cmd = $SSCMD . " get -GTM -W -I-Y -GL\"$localdir\" -V$version \"$file\" 2>&1"; $out = `$cmd`; # get rid of stupid VSS warning messages $* = 1; $out =~ s/\n?Project.*rebuilt\.//g; $out =~ s/\n?File.*rebuilt\.//g; $out =~ s/\n.*was moved out of this project.*rebuilt\.//g; $out =~ s/\nContinue anyway.*Y//g; $* = 0; many thanks, Rory
From perlvar : Use of $* is deprecated in modern Perl, supplanted by the /s and /m modifiers on pattern matching. If you have access to the place where it's being matched just add it to the end: $haystack =~ m/.../sm; If you only have access to the string, you can surround the expression with qr/(?ms-ix:$expr)/; Or in your case: s/\n((\w*\-*\.*\w*\/*)+\:)/$1/gsm;
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/88518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ] }
88,573
In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example: void foo() throw(); // guaranteed not to throw an exceptionvoid bar() throw(int); // may throw an exception of type intvoid baz() throw(...); // may throw an exception of some unspecified type I'm doubtful about actually using them because of the following: The compiler doesn't really enforce exception specifiers in any rigorous way, so the benefits are not great. Ideally, you would like to get a compile error. If a function violates an exception specifier, I think the standard behaviour is to terminate the program. In VS.Net, it treats throw(X) as throw(...), so adherence to the standard is not strong. Do you think exception specifiers should be used? Please answer with "yes" or "no" and provide some reasons to justify your answer.
No. Here are several examples why: Template code is impossible to write with exception specifications, template<class T>void f( T k ){ T x( k ); x.x();} The copies might throw, the parameter passing might throw, and x() might throw some unknown exception. Exception-specifications tend to prohibit extensibility. virtual void open() throw( FileNotFound ); might evolve into virtual void open() throw( FileNotFound, SocketNotReady, InterprocessObjectNotImplemented, HardwareUnresponsive ); You could really write that as throw( ... ) The first is not extensible, the second is overambitious and the third is really what you mean, when you write virtual functions. Legacy code When you write code which relies on another library, you don't really know what it might do when something goes horribly wrong. int lib_f();void g() throw( k_too_small_exception ){ int k = lib_f(); if( k < 0 ) throw k_too_small_exception();} g will terminate, when lib_f() throws. This is (in most cases) not what you really want. std::terminate() should never be called. It is always better to let the application crash with an unhandled exception, from which you can retrieve a stack-trace, than to silently/violently die. Write code that returns common errors and throws on exceptional occasions. Error e = open( "bla.txt" );if( e == FileNotFound ) MessageUser( "File bla.txt not found" );if( e == AccessDenied ) MessageUser( "Failed to open bla.txt, because we don't have read rights ..." );if( e != Success ) MessageUser( "Failed due to some other error, error code = " + itoa( e ) );try{ std::vector<TObj> k( 1000 ); // ...}catch( const bad_alloc& b ){ MessageUser( "out of memory, exiting process" ); throw;} Nevertheless, when your library just throws your own exceptions, you can use exception specifications to state your intent.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/88573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ] }
88,582
For a small project I have to parse pdf files and take a specific part of them (a simple chain of characters). I'd like to use python to do this and I've found several libraries that are capable of doing what I want in some ways. But now after a few researches, I'm wondering what is the real structure of a pdf file, does anyone know if there is a spec or some explanations anywhere online? I've found a link on adobe but it seems that it's a dead link :(
Here is a link to Adobe's reference material http://www.adobe.com/devnet/pdf/pdf_reference.html You should know though that PDF is only about presentation, not structure. Parsing will not come easy.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/88582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11544/" ] }
88,613
How do I tokenize the string: "2+24*48/32" Into a list: ['2', '+', '24', '*', '48', '/', '32']
It just so happens that the tokens you want split are already Python tokens, so you can use the built-in tokenize module. It's almost a one-liner; this program: from io import StringIOfrom tokenize import generate_tokensSTRING = 1print( list( token[STRING] for token in generate_tokens(StringIO("2+24*48/32").readline) if token[STRING] )) produces this output: ['2', '+', '24', '*', '48', '/', '32']
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
88,626
I'm looking to learn about embedded programming (in C mainly, but I hope to brush up on my ASM as well) and I was wondering what the best platform would be. I have some experience in using Atmel AVR's and programming them with the stk500 and found that to be relatively easy. I especially like AVR Studio and the debugger that lets you view that state of registers. However, If I was to take the time to learn, I would rather learn about something that is prevalent in industry. I am thinking ARM, that is unless someone has a better suggestion. I would also be looking for some reference material, I have found the books section on the ARM website and if one is a technically better book than another I would appreciate a heads up. The last thing I would be looking for is a prototyping/programming board like the STK500 that has some buttons and so forth. Thanks =]
"embedded programming" is a very broad term. AVR is pretty well in that category, but it's a step below ARM, in that it's both simpler to use, as well as less powerful. If you just want to play around with ARM, buy a Nintendo DS or a Gameboy Advance. These are very cheap compared to the hardware inside (wonders of mass production), and they both have free development toolchains based off of gcc which can compile to them. If you want to play around with embedded linux, BeagleBoard is looking to be a good option, only $150 and it has a ton of features. Personally I think AVR is best for the smaller-sized 8-bit platforms, and ARM is best for the larger, more powerful 32-bit based platforms. Like many AVR fans, I don't like PIC. It just seems worse in pretty much every way. Also avoid anything that requires you to write any type of BASIC.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15534/" ] }
88,710
I need to create a repeatable process for deploying SQL Server Reporting Services reports. I am not in favor of using Visual Studio and or Business Development Studio to do this. The rs.exe method of scripting deployments also seems rather clunky. Does anyone have a very elegant way that they have been able to deploy reports. The key here is that I want the process to be completely automated.
We use rs.exe, once we developed the script we have not needed to touch it anymore, it just works. Here is the source (I slightly modified it by hand to remove sensitive data without a chance to test it, hope I did not brake anything), it deploys reports and associated images from subdirectories for various languages. Also datasource is created. '=====================================================================' File: PublishReports.rss'' Summary: Script that can be used with RS.exe to ' publish the reports.'' Rss file spans from beginnig of this comment to end of module' (except of "End Module").'=====================================================================Dim langPaths As String() = {"en", "cs", "pl", "de"}Dim filePath As String = Environment.CurrentDirectoryPublic Sub Main() rs.Credentials = System.Net.CredentialCache.DefaultCredentials 'Create parent folder Try rs.CreateFolder(parentFolder, "/", Nothing) Console.WriteLine("Parent folder created: {0}", parentFolder) Catch e As Exception Console.WriteLine(e.Message) End Try PublishLanguagesFromFolder(filePath)End SubPublic Sub PublishLanguagesFromFolder(ByVal folder As String) Dim Lang As Integer Dim langPath As String For Lang = langPaths.GetLowerBound(0) To langPaths.GetUpperBound(0) langPath = langPaths(Lang) 'Create the lang folder Try rs.CreateFolder(langPath, "/" + parentFolder, Nothing) Console.WriteLine("Parent lang folder created: {0}", parentFolder + "/" + langPath) Catch e As Exception Console.WriteLine(e.Message) End Try 'Create the shared data source CreateDataSource("/" + parentFolder + "/" + langPath) 'Publish reports and images PublishFolderContents(folder + "\" + langPath, "/" + parentFolder + "/" + langPath) Next 'LangEnd SubPublic Sub CreateDataSource(ByVal targetFolder As String) Dim name As String = "data source" 'Data source definition. Dim definition As New DataSourceDefinition definition.CredentialRetrieval = CredentialRetrievalEnum.Store definition.ConnectString = "data source=" + dbServer + ";initial catalog=" + db definition.Enabled = True definition.EnabledSpecified = True definition.Extension = "SQL" definition.ImpersonateUser = False definition.ImpersonateUserSpecified = True 'Use the default prompt string. definition.Prompt = Nothing definition.WindowsCredentials = False 'Login information definition.UserName = "user" definition.Password = "password" Try 'name, folder, overwrite, definition, properties rs.CreateDataSource(name, targetFolder, True, definition, Nothing) Catch e As Exception Console.WriteLine(e.Message) End TryEnd SubPublic Sub PublishFolderContents(ByVal sourceFolder As String, ByVal targetFolder As String) Dim di As New DirectoryInfo(sourceFolder) Dim fis As FileInfo() = di.GetFiles() Dim fi As FileInfo Dim fileName As String For Each fi In fis fileName = fi.Name Select Case fileName.Substring(fileName.Length - 4).ToUpper Case ".RDL" PublishReport(sourceFolder, fileName, targetFolder) Case ".JPG", ".JPEG" PublishResource(sourceFolder, fileName, "image/jpeg", targetFolder) Case ".GIF", ".PNG", ".BMP" PublishResource(sourceFolder, fileName, "image/" + fileName.Substring(fileName.Length - 3).ToLower, targetFolder) End Select Next fiEnd SubPublic Sub PublishReport(ByVal sourceFolder As String, ByVal reportName As String, ByVal targetFolder As String) Dim definition As [Byte]() = Nothing Dim warnings As Warning() = Nothing Try Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + reportName) definition = New [Byte](stream.Length) {} stream.Read(definition, 0, CInt(stream.Length)) stream.Close() Catch e As IOException Console.WriteLine(e.Message) End Try Try 'name, folder, overwrite, definition, properties warnings = rs.CreateReport(reportName.Substring(0, reportName.Length - 4), targetFolder, True, definition, Nothing) If Not (warnings Is Nothing) Then Dim warning As Warning For Each warning In warnings Console.WriteLine(warning.Message) Next warning Else Console.WriteLine("Report: {0} published successfully with no warnings", targetFolder + "/" + reportName) End If Catch e As Exception Console.WriteLine(e.Message) End TryEnd SubPublic Sub PublishResource(ByVal sourceFolder As String, ByVal resourceName As String, ByVal resourceMIME As String, ByVal targetFolder As String) Dim definition As [Byte]() = Nothing Dim warnings As Warning() = Nothing Try Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + resourceName) definition = New [Byte](stream.Length) {} stream.Read(definition, 0, CInt(stream.Length)) stream.Close() Catch e As IOException Console.WriteLine(e.Message) End Try Try 'name, folder, overwrite, definition, MIME, properties rs.CreateResource(resourceName, targetFolder, True, definition, resourceMIME, Nothing) Console.WriteLine("Resource: {0} with MIME {1} created successfully", targetFolder + "/" + resourceName, resourceMIME) Catch e As Exception Console.WriteLine(e.Message) End TryEnd Sub Here is the batch to call the rs.exe: SET ReportServer=%1SET DBServer=%2SET DBName=%3SET ReportFolder=%4rs -i PublishReports.rss -s %ReportServer% -v dbServer="%DBServer%" -v db="%DBName%" -v parentFolder="%ReportFolder%" >PublishReports.log 2>&1pause
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16980/" ] }
88,711
I want to use CSS sprites on a web site instead of separate image files, for a large collection of small icons that are all the same size. How can I concatenate (tile) them into one big image using ImageMagick ?
From the page you linked, 'montage' is the tool you want. It'll take a bunch of images and concatenate/tile them into a single output. Here's an example image I've made before using the tool: (source: davr.org )
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2670/" ] }
88,717
I want to load one or more DLLs dynamically so that they run with a different security or basepath than my main application. How do I load these DLLs into a separate AppDomain and instantiate objects from them?
More specifically AppDomain domain = AppDomain.CreateDomain("New domain name");//Do other things to the domain like set the security policystring pathToDll = @"C:\myDll.dll"; //Full path to dll you want to loadType t = typeof(TypeIWantToLoad);TypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName); If all that goes properly (no exceptions thrown) you now have an instance of TypeIWantToLoad loaded into your new domain. The instance you have is actually a proxy (since the actual object is in the new domain) but you can use it just like your normal object. Note: As far as I know TypeIWantToLoad has to inherit from MarshalByRefObject.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16979/" ] }
88,763
When I first heard about StackOverflow, and heard that it was being built in ASP.Net MVC, I was a little confused. I thought ASP.Net was always an example of an MVC architecture. You have the .aspx page that provides the view, the .aspx.vb page that provides the controller, and you can create another class to be the model. The process for using MVC in ASP.Net is described in this Microsoft article . So my question is. What Does ASP.Net MVC provide that you wouldn't be able to do with regular ASP.Net (even as far back as ASP.Net 1.1)? It is just fancy URLs? Is it just for bragging rights for MS to be able to compare themselves with new technologies like Ruby On Rails, and say, "We can do that too"? Is there something more that ASP.Net MVC actually provides, rather than a couple extra templates in the File->New menu? I'm probably sounding really skeptical and negative right now, so I'll just stop. But I really want to know what ASP.Net MVC actually provides. Also, if anybody can tell me why it's Model-View-Controller and not in order of the layers of View-Controller-Model or Model-Control-View depending on whether you are going top to bottom, or vice versa, I'd really appreciate that too. EDIT Also, it's probably worth pointing out that I've never really cared for the web forms (AKA server controls) model either. I've only used it minimally, and never on the job.
.aspx doesn't fulfill the MVC pattern because the aspx page (the 'view') is called before the code behind (the 'controller'). This means that the controller has a 'hard dependency' on the view, which is very much against MVC principles. One of the core benefits of MVC is that it allows you to test your controller (which contains a lot of logic) without instantiating a real view. You simply can't do this in the .aspx world. Testing the controller all by itself is much faster than having to instantiate an entire asp.net pipeline (application, request, response, view state, session state etc).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/88763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ] }
88,838
In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?
Convert from String to byte[] : String s = "some text here";byte[] b = s.getBytes(StandardCharsets.UTF_8); Convert from byte[] to String : byte[] b = {(byte) 99, (byte)97, (byte)116};String s = new String(b, StandardCharsets.US_ASCII); You should, of course, use the correct encoding name. My examples used US-ASCII and UTF-8, two commonly-used encodings.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/88838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14570/" ] }
88,850
Is there a polynomial time algorithm for finding a Hamiltonian walk in a graph? My algorithm is N factorial and is really slow.
You just asked the million dollar question . Finding a Hamilton path is an NP-complete problem. Some NP-hard problems can be solved in polynomial time using dynamic programming, but (to my knowledge) this is not one of them.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/88850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13813/" ] }
88,852
Does the Java virtual machine ever move objects in memory, and if so, how does it handle updating references to the moved object? I ask because I'm exploring an idea of storing objects in a distributed fashion (ie. across multiple servers), but I need the ability to move objects between servers for efficiency reasons. Objects need to be able to contain pointers to each-other, even to objects on remote servers. I'm trying to think of the best way to update references to moved objects. My two ideas so far are: Maintain a reference indirection somewhere that doesn't move for the lifetime of the object, which we update if the object moves. But - how are these indirections managed? Keep a list of reverse-references with each object, so we know what has to be updated if the object is moved. Of course, this creates a performance overhead. I'd be interested in feedback on these approaches, and any suggestions for alternative approaches.
In reference to the comment above about walking the heap. Different GC's do it different ways. Typically copying collectors when they walk the heap, they don't walk all of the objects in the heap. Rather they walk the LIVE objects in the heap. The implication is that if it's reachable from the "root" object, the object is live. So, at this stage is has to touch all of the live objects anyway, as it copies them from the old heap to the new heap. Once the copy of the live objects is done, all that remains in the old heap are either objects already copied, or garbage. At that point the old heap can be discarded completely. The two primary benefits of this kind of collector are that it compacts the heap during the copy phase, and that it only copies living objects. This is important to many systems because with this kind of collector, object allocation is dirt cheap, literally little more than incrementing a heap pointer. When GC happens, none of the "dead" objects are copied, so they don't slow the collector down. It also turns out in dynamic systems that there's a lot more little, temporary garbage, than there is long standing garbage. Also, by walking the live object graph, you can see how the GC can "know" about every object, and keep track of them for any address adjustment purposes performed during the copy. This is not the forum to talk deeply about GC mechanics, as it's a non-trivial problem, but that's the basics of how a copying collector works. A generational copying GC will put "older" objects in different heaps, and those end up being collected less often than "newer" heaps. The theory is that the long lasting objects get promoted to older generations and get collected less and less, improving overall GC performance.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/88852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16050/" ] }
88,904
We're working on a very large .NET WinForms composite application - not CAB, but a similar home grown framework. We're running in a Citrix and RDP environment running on Windows Server 2003. We're starting to run into random and difficult to reproduct "Error creating window handle" error that seems to be an old fashion handle leak in our application. We're making heavy use of 3rd Party controls (Janus GridEX, Infralution VirtualTree, and .NET Magic docking) and we do a lot of dynamic loading and rendering of content based on metadata in our database. There's a lot of info on Google about this error, but not a lot of solid guidance about how to avoid issues in this area. Does the stackoverflow community have any good guidance for me for building handle-friendly winforms apps?
I have tracked down a lot of issues with UIs not unloading as expected in WinForms. Here are some general hints: alot of the time, a control will stay in use because controls events are not properly removed (the tooltip provider caused us really large issues here) or the controls are not properly Disposed. use 'using' blocks around all modal dialogs to ensure that they are Disposed there are some control properties that will force the creation of the window handle before it is necessary (for example setting the ReadOnly property of a TextBox control will force the control to be realized) use a tool like the .Net Memory profiler to get counts of the classes that are created. Newer versions of this tool will also track GDI and USER objects. try to minimize your use of Win API calls (or other DllImport calls). If you do need to use interop, try to wrap these calls in such a way that the using/Dispose pattern will work correctly.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/88904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8133/" ] }
88,929
Is there a command that would allow me to check if the string "xyz" was ever in file foo.c in the repository and print which revisions they were found in?
This will print any commits where the diff contains xyz git log -Sxyz foo.c
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/88929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
88,942
Why in this millennium should Python PEP-8 specify a maximum line length of 79 characters? Pretty much every code editor under the sun can handle longer lines. What to do with wrapping should be the choice of the content consumer, not the responsibility of the content creator. Are there any (legitimately) good reasons for adhering to 79 characters in this age?
Much of the value of PEP-8 is to stop people arguing about inconsequential formatting rules, and get on with writing good, consistently formatted code. Sure, no one really thinks that 79 is optimal, but there's no obvious gain in changing it to 99 or 119 or whatever your preferred line length is. I think the choices are these: follow the rule and find a worthwhile cause to battle for, or provide some data that demonstrates how readability and productivity vary with line length. The latter would be extremely interesting, and would have a good chance of changing people's minds I think.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/88942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15992/" ] }
88,957
When {0} is used to initialize an object, what does it mean? I can't find any references to {0} anywhere, and because of the curly braces Google searches are not helpful. Example code: SHELLEXECUTEINFO sexi = {0}; // what does this do?sexi.cbSize = sizeof(SHELLEXECUTEINFO);sexi.hwnd = NULL;sexi.fMask = SEE_MASK_NOCLOSEPROCESS;sexi.lpFile = lpFile.c_str();sexi.lpParameters = args;sexi.nShow = nShow;if(ShellExecuteEx(&sexi)){ DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE); if(wait == WAIT_OBJECT_0) GetExitCodeProcess(sexi.hProcess, &returnCode);} Without it, the above code will crash on runtime.
What's happening here is called aggregate initialization. Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec: An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions. Now, using {0} to initialize an aggregate like this is basically a trick to 0 the entire thing. This is because when using aggregate initialization you don't have to specify all the members and the spec requires that all unspecified members be default initialized, which means set to 0 for simple types. Here is the relevant quote from the spec: If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be default-initialized. Example: struct S { int a; char* b; int c; };S ss = { 1, "asdf" }; initializes ss.a with 1 , ss.b with "asdf" , and ss.c with the value of an expression of the form int() , that is, 0 . You can find the complete spec on this topic here
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/88957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17027/" ] }
89,056
I have heard of some methods, but none of them have stuck. Personally I try to avoid complex types in C and try to break them into component typedef. I'm now faced with maintaining some legacy code from a so called 'three star programmer', and I'm having a hard time reading some of the ***code[][]. How do you read complex C declarations?
This article explains a relatively simple 7 rules which will let you read any C declaration, if you find yourself wanting or needing to do so manually: http://www.ericgiguere.com/articles/reading-c-declarations.html Find the identifier. This is your starting point. On a piece of paper, write "declare identifier as". Look to the right. If there is nothing there, or there is a right parenthesis ")", goto step 4. You are now positioned either on an array (left bracket) or function (left parenthesis) descriptor. There may be a sequence of these, ending either with an unmatched right parenthesis or the end of the declarator (a semicolon or a "=" for initialization). For each such descriptor, reading from left to right: if an empty array "[]", write "array of" if an array with a size, write "array size of" if a function "()", write "function returning" Stop at the unmatched parenthesis or the end of the declarator, whichever comes first. Return to the starting position and look to the left. If there is nothing there, or there is a left parenthesis "(", goto step 6. You are now positioned on a pointer descriptor, "*". There may be a sequence of these to the left, ending either with an unmatched left parenthesis "(" or the start of the declarator. Reading from right to left, for each pointer descriptor write "pointer to". Stop at the unmatched parenthesis or the start of the declarator, whichever is first. At this point you have either a parenthesized expression or the complete declarator. If you have a parenthesized expression, consider it as your new starting point and return to step 2. Write down the type specifier. Stop. If you're fine with a tool, then I second the suggestion to use the program cdecl : http://gd.tuwien.ac.at/linuxcommand.org/man_pages/cdecl1.html
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4319/" ] }
89,101
I have heard that Microsoft SharePoint was used by many companies. Could someone tell me briefly what is SharePoint and why is it popular?
What is SharePoint? The latest version of Microsoft SharePoint software is really two different products: Windows SharePoint Services is a free download for Windows Server. In the latest version, known as WSS v3, collaborative web sites templates include basic blog and wiki services along with list templates for Image Libraries, Document Libraries, Contact lists, Calendars, Tasks and much more. Microsoft Office SharePoint Server 2007 or MOSS for short is built on Windows SharePoint Services. As a member of the Office Server product platform, it leverages the Microsoft Office client software to provide content on the web. Integration with Word, PowerPoint, Excel, Access and InfoPath provide rich web content from familiar content creation tools. Why is it so popular File Sharing SharePoint originally became popular because it was an easy way to share documents on the web. Many organizations that adopted SharePoint in the 2003 versions capitalized on the ability to upload documents to Document Libaries and share those documents with others. Company Extranets One great example of this web based sharing, is a company extranet where users are not all in one location or authentication domain. Using form based authentication, accounts can be created for people across physical and company boundaries. By allowing one place for shared documents around a task rather than a corporate entity, SharePoint goes way beyond the common file share. Content Management There are plenty of other Content Management Systems, but MOSS incorporated the functionality of the previously name Microsoft Content Management System which itself often cost more than MOSS alone. Search Search is greatly improved in SharePoint 2007 technologies. Search results are security trimmed, relevant and performant unlike the previous 2003 version. Bad search in SharePoint 2003 products lead to a lot of dissatisfaction with the product.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/89101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17053/" ] }
89,118
I am getting an 403 access forbidden when attempting to open a page under a vhost where the document root is sitting on a different drive than where apache is sitting. I installed using the apachefriends release. This is my httpd-vhosts.conf file: NameVirtualHost 127.0.0.1 <VirtualHost 127.0.0.1> ServerName foo.localhost DocumentRoot "C:/xampp/htdocs/foo/public"</VirtualHost> <VirtualHost 127.0.0.1> ServerName bar.localhost DocumentRoot "F:/bar/public"</VirtualHost> When opening bar.localhost in my browser, Apache is giving me 403 Access Forbidden. I tried setting lots of different access rights, even full rights to everyone, but nothing I tried helped. Edit: Thanks! For future reference, add 'Options indexes' within to show directory indexes.
You did not need Options Indexes FollowSymLinks MultiViews Includes ExecCGIAllowOverride AllOrder Allow,DenyAllow from allRequire all granted the only thing what you need is... Require all granted ...inside the directory section. See Apache 2.4 upgrading side: http://httpd.apache.org/docs/2.4/upgrading.html
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/89118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6752/" ] }
89,178
For example: >>> x = [1, 1, 2, 'a', 'a', 3]>>> unique(x)[1, 2, 'a', 3] Assume list elements are hashable. Clarification: The result should keep the first duplicate in the list. For example, [1, 2, 3, 2, 3, 1] becomes [1, 2, 3].
def unique(items): found = set() keep = [] for item in items: if item not in found: found.add(item) keep.append(item) return keepprint unique([1, 1, 2, 'a', 'a', 3])
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16976/" ] }
89,181
How do i check out a specific directory from CVS and omit the tree leading up to that directory? EX. Id like to checkout to this directoryC:/WebHost/MyWebApp/www My CVS Project directory structure isMyWebApp/Trunk/www How do i omit the Trunk and MyWebApp directories?
Use cvs -d/cvsroot checkout -d directory project/path/directory . The first -d can be omitted if you set the root with the environment. This is called "shortening the path" and can be avoided with the -N option to checkout .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/89181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16703/" ] }
89,193
Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following: var people = from p in Person where p.age < 18 select pvar otherPeople = from p in people where p.firstName equals "Daniel" select p Assuming that Person is an ADO entity which defines the age and firstName fields, what would this do from a database standpoint? Specifically, would the people query be run to produce an in-memory structure, which would then be queried by the otherPeople query? Or would the construction of otherPeople merely pull the data regarding the query from people and then produce a new database-peered query? So, if I iterated over both of these queries, how many SQL statements would be executed?
They are composable. This is possible because LINQ queries are actually expressions (code as data), which LINQ providers like LINQ-to-SQL can evaluate and generate corresponding SQL. Because LINQ queries are lazily evaluated (e.g. won't get executed until you iterate over the elements), the code you showed won't actually touch the database. Not until you iterate over otherPeople or people will SQL get generated and executed.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9815/" ] }
89,203
What is the difference in C# between Convert.ToDecimal(string) and Decimal.Parse(string) ? In what scenarios would you use one over the other? What impact does it have on performance? What other factors should I be taking into consideration when choosing between the two?
From bytes.com : The Convert class is designed to convert a wide range of Types, so you can convert more types to Decimal than you can with Decimal.Parse, which can only deal with String. On the other hand Decimal.Parse allows you to specify a NumberStyle. Decimal and decimal are aliases and are equal. For Convert.ToDecimal(string), Decimal.Parse is called internally. Morten Wennevik [C# MVP] Since Decimal.Parse is called internally by Convert.ToDecimal, if you have extreme performance requirements you might want to stick to Decimal.Parse, it will save a stack frame.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/89203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3821/" ] }
89,212
I'm familiar with object-oriented architecture, including use of design patterns and class diagrams for visualization, and I know of service-oriented architecture with its contracts and protocol bindings, but is there anything characteristic about a software architecture for a system written in a functional programming language? I know that FP has been used for medium-size to large scale projects. Paul Graham wrote the first incarnation of Yahoo! Store in Common Lisp. Some lisp development systems are complex. Artifical intelligence and financial systems written in functional languages can get pretty big. They all have at least some kind of inherent architecture, though, I'm wondering if they have anything in common? What does an architecture based on the evaluation of expressions look like? Are FP architectures more composable? Update: Kyle reminded me that SICP is a good resource for this subject. Update 2: I found a good post on the subject: How does functional programming affect the structure of your code?
The common thread in the "architecture" of projects that use functional languages is that they tend to be separated into layers of algebras rather than subsystems in the traditional systems architecture sense. For great examples of such projects, check out XMonad , Yi , and HappS . If you examine how they are structured, you will find that they comprise layers of monadic structure with some combinator glue in between. Also look at The Scala Experiment paper which outlines an architecture where a system is composed of components that abstract over their dependencies.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/89212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ] }
89,228
How do I call an external command within Python as if I'd typed it in a shell or command prompt?
Use the subprocess module in the standard library: import subprocesssubprocess.run(["ls", "-l"]) The advantage of subprocess.run over os.system is that it is more flexible (you can get the stdout , stderr , the "real" status code , better error handling , etc...). Even the documentation for os.system recommends using subprocess instead: The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes. On Python 3.4 and earlier, use subprocess.call instead of .run : subprocess.call(["ls", "-l"])
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/89228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17085/" ] }
89,245
Suppose a large composite application built on several foundation components packaged in their own assemblies: (database reading, protocol handlers, etc.). For some deployments, this can include over 20 assemblies. Each of these assemblies has settings or configuration information. Our team tends to like the VS settings editor (and the easy-to-use code it generates!), and the application vs. user distinction meets most of our needs. BUT.... It is very tedious to copy & paste the many configuration sections into our application's .xml. Furthermore, for shared components that tend to have similar configurations across applications, this means we need to maintain duplicate settings in multiple .config files. Microsoft's EntLib solves this problem with an external tool to generate the monster .config file, but this feels klunky as well. What techniques do you use to manage large .NET .config files with sections from multiple shared assemblies? Some kind of include mechanism? Custom configuration readers? FOLLOWUP: Will's answer was exactly what I was getting at, and looks elegant for flat key/value pair sections. Is there a way to combine this approach with custom configuration sections ? Thanks also for the suggestions about managing different .configs for different build targets. That's also quite useful. Dave
You use one master config file that points to other config files. Here's an example of how to do this. In case the link rots, what you do is specify the configSource for a particular configuration section. This allows you to define that particular section within a separate file. <pages configSource="pages.config"/> which implies that there is a file called "pages.config" within the same directory that contains the entire <pages /> node tree.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6996/" ] }
89,275
What is the best C++ IDE or editor for using on Windows? I use Notepad++, but am missing IntelliSense from Visual Studio.
Um, that's because Visual Studio is the best IDE. Come back to the darkside.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/89275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2039/" ] }
89,320
The scenario is this We have two applications A and B, both which are running in separate database (Oracle 9i ) transactions Application A - inserts some data into the database, then calls Application BApplication B - inserts some data into the database, related (via foreign keys) to A's data. Returns an "ID" to Application AApplication A - uses ID to insert further data, including the ID from B Now, because these are separate transactions, but both rely on data from each others transactions, we need to commit between the calls to each application. This of course makes it very difficult to rollback if anything goes wrong. How would you approach this problem, with minimal refactoring of the code. Surely this kind of this is a common problem in the SOA world? ------ Update -------- I have not been able to find anything in Oracle 9i, however Oracle 11g provides DBMS_XA , which does exactly what I was after.
You have three options: Redesign the application so that you don't have two different processes (both with database connections) writing to the database and roll it into a single app. Create application C that handles all the database transactions for A and B. Roll your own two phase commit. Application C acts as the coordinator. C signals A and B to ask if they're ready to commit. A and B do their processing, and respond to C with either a "ready" or a "fail" reply (note that there should be a timeout on C to avoid an infinite wait if one process hangs or dies). If both reply ready then C tells them to commit. Otherwise it sends a rollback signal. Note that you may run into issues with option 3 if app A is relying on foreign keys from app B (which you didn't state, so this may not be an issue). Oracle's read consistency would probably prevent this from being allowed, since app A's transaction will begin before app B. Just a warning.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ] }
89,332
I frequently use git stash and git stash pop to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but git stash pop appears to remove all references to the associated commit. I know that if I use git stash then .git/refs/stash contains the reference of the commit used to create the stash. And .git/logs/refs/stash contains the whole stash. But those references are gone after git stash pop . I know that the commit is still in my repository somewhere, but I don't know what it was. Is there an easy way to recover yesterday's stash commit reference?
Once you know the hash of the stash commit you dropped, you can apply it as a stash: git stash apply $stash_hash Or, you can create a separate branch for it with git branch recovered $stash_hash After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away. Finding the hash If you have only just popped it and the terminal is still open, you will still have the hash value printed by git stash pop on screen (thanks, Dolda). Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows: git fsck --no-reflog | awk '/dangling commit/ {print $3}' ...or using PowerShell for Windows: git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(" ")[2] } This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph. The easiest way to find the stash commit you want is probably to pass that list to gitk : gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' ) ...or see the answer from emragins if using PowerShell for Windows. This will launch a repository browser showing you every single commit in the repository ever , regardless of whether it is reachable or not. You can replace gitk there with something like git log --graph --oneline --decorate if you prefer a nice graph on the console over a separate GUI app. To spot stash commits, look for commit messages of this form: WIP on somebranch : commithash Some old commit message Note : The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did git stash .
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/89332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893/" ] }
89,480
For reasons I won't go into, I wish to ban an entire company from accessing my web site. Checking the remote hostname in php using gethostbyaddr() works, but this slows down the page load too much. Large organizations (eg. hp.com or microsoft.com) often have blocks of IP addresses. Is there anyway I get the full list, or am I stuck with the slow reverse-DNS lookup? If so, can I speed it up? Edit: Okay, now I know I can use the .htaccess file to ban a range. Now, how can I figure out what that range should be for a given organization?
How about an .htaccess: Deny from x.x.x.x if you need to deny a range say: 192.168.0.x then you would use Deny from 192.168.0 and the same applies for hostnames: Deny from sub.domain.tld or if you want a PHP solution $ips = array('1.1.1.1', '2.2.2.2', '3.3.3.3');if(in_array($_SERVER['REMOTE_ADDR'])){die();} For more info on the htaccess method see this page. Now to determine the range is going to be hard, most companies (unless they are big corperate) are going to have a dynamic IP just like you and me. This is a problem I have had to deal with before and the best thing is either to ban the hostname, or the entire range, for example if they are on 192.168.0.123 then ban 192.168.0.123, unfortunatly you are going to get a few innocent people with either method.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15947/" ] }
89,487
I suppose it allows for moving changes from one branch to the next but that's what cherry picking is for and if you're not making a commit of your changes, perhaps you shouldn't be moving them around? I have on occasion applied the wrong stash at the wrong branch, which left me wondering about this question.
As mentioned, if you want a “per-branch stash,” you really want a new branch forking off from the existing branch. Also, besides the already mentioned fact that the stash allows you to pull into a branch that you’re working on, it also allows you to switch branches before you have committed everything. This is useful not for cherry-picking in the usual sense so much as for cherry-picking your working copy . F.ex., while working on a feature branch, I will often notice minor bugs or cosmetic impurities in the code that aren’t relevant to that branch. Well, I just fix those right away. When time comes to commit, I selectively commit the relevant changes but not the fixes and cosmetics. Instead I stash those, which allows me to switch to my minor-fixes-on-stable branch, where I can then apply the stash and commit each minor fix separately. (Depending on the changes in question, I will also stash some of them yet again, to switch to a different feature branch, where I apply those .) This allows me to go deep into programming mode when I am working, and not worry about proper librarianship of my code. Then when I take a mental break, I can go back and carefully sort my changes into all the right shelves. If the stash weren’t global, this type of workflow would be far more difficult to do.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/89487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2108922/" ] }
89,489
I was following along with the railscast regarding the restful_authentication plugin. He recommended running the command: script/generate authenticated user session Which I did, and everything generated "fine", but then sessions wouldn't work. Checking the site again, he mentions a naming standard and listed updated code which stated: script/generate authenticated user sessions With sessions being pluralized. So now I have session_controller.rb with a SessionController in it, but I guess by naming standards, it is looking for SessionsController, causing the code to fail out with the error "NameError in SessionsController#create " I see the problem, which is pretty obvious, but what I don't know is, how do I fix this without regenerating the content? Is there a way to reverse the generation process to clear out all changes made by the generation? I tried just renaming the files to sessions_controller with e SessionsController class, but that failed. While writing this, I solved my own problem. I had to rename session to sessions in the routes file as a map.resource and rename the view directory from session to sessions, and update session_path in the html.erb file to sessions_path. So I solved my problem, but my answer regarding removing generated content still remains. Is it possible to ungenerate content?
Actually, script/destroy works for any generator - generators work by reading a script of sorts on what files to create; script/destroy just reads that script in reverse and removes all the files created, as long as you give it the same arguments you passed to script/generate . To sum up: script/destroy authenticated user session would have removed all the generated files for you, after which you could have run script/generate user sessions without a problem.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ] }
89,570
So I'm having a really weird issue with my App_Code folder on a new website I'm designing. I have a basic class inside of a namespace in the App_Code folder. Everything works fine in the IDE when I setup the namespace and make an object from the class. It brings up the class summary on hover, and when you click on "go to deffinition" it goes to the class file.And it also works fine localy. However, when I load the site onto my server, I get this error message when I access that page: Line 10: using System.Web.UI.WebControls; Line 11: using System.Web.UI.WebControls.WebParts; Line 12: using xxxx.xxxx Compiler Error Message: CS0246: The type or namespace name 'xxxxxx' could not be found (are you missing a using directive or an assembly reference?) I know for a fact that the class file is there. Anyone have any idea of whats going on? Edits: John, yes it is a 2.0 site.
The problem that your classes are not compiled, You'll solve this issue simply by going to the properties of any class in the App_Code folder and change it's 'Build Action' property from "Content" to "Compile"
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/89570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066/" ] }
89,576
I am trying to connect to a Microsoft SQL 2005 server which is not on port 1433. How do I indicate a different port number when connecting to the server using SQL Management Studio?
127.0.0.1,6283 Add a comma between the ip and port
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/89576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5836/" ] }
89,588
You do AssignProcessToJobObject and it fails with "access denied" but only when you are running in the debugger. Why is this?
This one puzzled me for for about 30 minutes. First off, you probably need a UAC manifest embedded in your app ( as suggested here ). Something like this: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <!-- Identify the application security requirements. --> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> Secondly (and this is the bit I got stuck on), when you are running your app under the debugger, it creates your process in a job object. Which your child process needs to be able to breakaway from before you can assign it to your job. So (duh), you need to specify CREATE_BREAKAWAY_FROM_JOB in the flags for CreateProcess ). If you weren't running under the debugger, or your parent process were in the job, this wouldn't have happened.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/89588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ] }
89,603
When writing C/C++ code, in order to debug the binary executable the debug option must be enabled on the compiler/linker. In the case of GCC, the option is -g. When the debug option is enabled, how does the affect the binary executable? What additional data is stored in the file that allows the debugger function as it does?
-g tells the compiler to store symbol table information in the executable. Among other things, this includes: symbol names type info for symbols files and line numbers where the symbols came from Debuggers use this information to output meaningful names for symbols and to associate instructions with particular lines in the source. For some compilers, supplying -g will disable certain optimizations. For example, icc sets the default optimization level to -O0 with -g unless you explicitly indicate -O[123]. Also, even if you do supply -O[123], optimizations that prevent stack tracing will still be disabled (e.g. stripping frame pointers from stack frames. This has only a minor effect on performance). With some compilers, -g will disable optimizations that can confuse where symbols came from (instruction reordering, loop unrolling, inlining etc). If you want to debug with optimization, you can use -g3 with gcc to get around some of this. Extra debug info will be included about macros, expansions, and functions that may have been inlined. This can allow debuggers and performance tools to map optimized code to the original source, but it's best effort. Some optimizations really mangle the code. For more info, take a look at DWARF , the debugging format originally designed to go along with ELF (the binary format for Linux and other OS's).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/89603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10216/" ] }
89,606
I have a table that got into the "db_owner" schema, and I need it in the "dbo" schema. Is there a script or command to run to switch it over?
In SQL Server Management Studio: Right click the table and select modify (it's called "Design" now) On the properties panel choose the correct owning schema.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/89606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ] }
89,607
I have added some code which compiles cleanly and have just received this Windows error: ---------------------------(MonTel Administrator) 2.12.7: MtAdmin.exe - Application Error---------------------------The exception Privileged instruction. (0xc0000096) occurred in the application at location 0x00486752. I am about to go on a bug hunt, and I am expecting it to be something silly that I have done which just happens to produce this message. The code compiles cleanly with no errors or warnings. The size of the EXE file has grown to 1,454,132 bytes and includes links to ODCS.lib , but it is otherwise pure C to the Win32 API, with DEBUG on (running on a P4 on Windows 2000).
To answer the question, a privileged instruction is a processor op-code (assembler instruction) which can only be executed in "supervisor" (or Ring-0) mode.These types of instructions tend to be used to access I/O devices and protected data structures from the windows kernel. Regular programs execute in "user mode" (Ring-3) which disallows direct access to I/O devices, etc... As others mentioned, the cause is probably a corrupted stack or a messed up function pointer call.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/89607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3137/" ] }
89,609
I'm looking for the best way to take a simple input: echo -n "Enter a string here: "read -e STRING and clean it up by removing non-alphanumeric characters, lower(case), and replacing spaces with underscores. Does order matter? Is tr the best / only way to go about this?
As dj_segfault points out, the shell can do most of this for you. Looks like you'll have to fall back on something external for lower-casing the string, though. For this you have many options, like the perl one-liners above, etc., but I think tr is probably the simplest. # first, strip underscoresCLEAN=${STRING//_/}# next, replace spaces with underscoresCLEAN=${CLEAN// /_}# now, clean out anything that's not alphanumeric or an underscoreCLEAN=${CLEAN//[^a-zA-Z0-9_]/}# finally, lowercase with TRCLEAN=`echo -n $CLEAN | tr A-Z a-z` The order here is somewhat important. We want to get rid of underscores, plus replace spaces with underscores, so we have to be sure to strip underscores first. By waiting to pass things to tr until the end, we know we have only alphanumeric and underscores, and we can be sure we have no spaces, so we don't have to worry about special characters being interpreted by the shell.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/89609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16248/" ] }
89,650
I would like to pass an argument(s) to a method being defined using define_method, how would I do that?
The block that you pass to define_method can include some parameters. That's how your defined method accepts arguments. When you define a method you're really just nicknaming the block and keeping a reference to it in the class. The parameters come with the block. So: define_method(:say_hi) { |other| puts "Hi, " + other }
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/89650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ] }
89,696
I have Oracle SQL Developer already installed and am able to connect to and query Oracle databases. Using Help -> Check for Updates I was able to install the Oracle MySQL Browser extension but there are no connection options for MySQL databases.
Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog. Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/89696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5808/" ] }
89,741
I'd like to know what the currently checked out revision number is for a file or directory. Is there a way to do this in TortoiseSVN on Windows ?
Right-click on the working directory in windows explorer, and select "Properties" (Not TortoiseSVN->Properties). You will see the Properties dialog, which will have a tab called "Subversion". Click on it, and you will see the version number, and other info.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/89741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ] }
89,791
When I start my process from Visual Studio, it is always created inside a job object. I would like to know how to turn this behaviour off. Any ideas? I expect that it is created in a job object to be debugged. I want to place my program in a different job object. It's not the hosting process. I'm talking about a Job Object . This is an unmanaged C++ application.
This happens when devenv.exe or VSLauncher.exe run in compatibility mode. The Program Compatibility Assistant (PCA) attaches a job object to the Visual Studio process, and every child process inherits it. Check if the job name (as reported by Process Explorer) starts with PCA . If so, PCA can be disabled as described in the link. You can globally disable PCA using Run -> gpedit.msc -> Administrative Templates\Windows Components\Application Compatibility -> Turn off Program Compatibility Assistant -> Enable . You can disable PCA for specific executables by adding a registry entry. For Windows 7, the appropriate registry key is HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant . In regedit, right-click that key, select New -> Multi-String Value , name it ExecutablesToExclude . Set the value to the full path of denenv.exe and VSLauncher.exe , on separate lines and without quotes. For me, these were: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exeC:\Program Files (x86)\Common Files\microsoft shared\MSEnv\VSLauncher.exe A related issue, on Windows 7, is that executables you build in Visual Studio and run from Explorer (not Visual Studio or the command line) may run in compatibility mode, and again get job objects wrapped around them. To prevent this, your executable needs a manifest that declares compatibility with Windows 7, using the new Application Manifest Compability section . The link gives an example of a Windows 7 compatible manifest. The default manifest provided by Visual Studio 2010 does not include this Compatibility section.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ] }
89,886
Specifically in .NET, but I'm leaving it open.
MSDN: Enumerating Installed Fonts
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4094/" ] }
89,891
I just learned about how the Java Collections Framework implements data structures in linked lists. From what I understand, Iterators are a way of traversing through the items in a data structure such as a list. Why is this interface used? Why are the methods hasNext() , next() and remove() not directly coded to the data structure implementation itself? From the Java website: link text public interface Iterator<E> An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. This interface is a member of the Java Collections Framework. I tried googling around and can't seem to find a definite answer. Can someone shed some light on why Sun chose to use them? Is it because of better design? Increased security? Good OO practice? Any help will be greatly appreciated. Thanks.
Why is this interface used? Because it supports the basic operations that would allow a client programmer to iterate over any kind of collection (note: not necessarily a Collection in the Object sense). Why are the methods... not directly coded to the data structure implementation itself? They are, they're just marked Private so you can't reach into them and muck with them. More specifically: You can implement or subclass an Iterator such that it does something the standard ones don't do, without having to alter the actual object it iterates over. Objects that can be traversed over don't need to have their interfaces cluttered up with traversal methods, in particular any highly specialized methods. You can hand out Iterators to however many clients you wish, and each client may traverse in their own time, at their own speed. Java Iterators from the java.util package in particular will throw an exception if the storage that backs them is modified while you still have an Iterator out. This exception lets you know that the Iterator may now be returning invalid objects. For simple programs, none of this probably seems worthwhile. The kind of complexity that makes them useful will come up on you quickly, though.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17182/" ] }
89,909
I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.
A regular expression will do the trick with very little code: import re...if re.match("^[A-Za-z0-9_-]*$", my_little_string): # do something here
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/89909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4527/" ] }
89,989
I want to download a lot of urls in a script but I do not want to save the ones that lead to HTTP errors. As far as I can tell from the man pages, neither curl or wget provide such functionality.Does anyone know about another downloader who does?
I think the -f option to curl does what you want: -f , --fail (HTTP) Fail silently (no output at all) on server errors. This is mostly done to better enable scripts etc to better deal with failed attempts. In normal cases when an HTTP server fails to deliver a document, it returns an HTML document stating so (which often also describes why and more). This flag will prevent curl from outputting that and return error 22. [...] However, if the response was actually a 301 or 302 redirect, that still gets saved, even if its destination would result in an error: $ curl -fO http://google.com/aoeu$ cat aoeu<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"><TITLE>301 Moved</TITLE></HEAD><BODY><H1>301 Moved</H1>The document has moved<A HREF="http://www.google.com/aoeu">here</A>.</BODY></HTML> To follow the redirect to its dead end, also give the -L option: -L , --location (HTTP/HTTPS) If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make curl redo the request on the new place. [...]
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/89989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65724/" ] }
90,002
If you were to mandate a minimum percentage code-coverage for unit tests, perhaps even as a requirement for committing to a repository, what would it be? Please explain how you arrived at your answer (since if all you did was pick a number, then I could have done that all by myself ;)
This prose by Alberto Savoia answers precisely that question (in a nicely entertaining manner at that!): http://www.artima.com/forums/flat.jsp?forum=106&thread=204677 Testivus On Test Coverage Early one morning, a programmer asked the great master: “I am ready to write some unit tests. What code coverage should I aim for?” The great master replied: “Don’t worry about coverage, just write some good tests.” The programmer smiled, bowed, and left. ... Later that day, a second programmer asked the same question. The great master pointed at a pot of boiling water and said: “How many grains of rice should I put in that pot?” The programmer, looking puzzled, replied: “How can I possibly tell you? It depends on how many people you need to feed, how hungry they are, what other food you are serving, how much rice you have available, and so on.” “Exactly,” said the great master. The second programmer smiled, bowed, and left. ... Toward the end of the day, a third programmer came and asked the same question about code coverage. “Eighty percent and no less!” Replied the master in a stern voice, pounding his fist on the table. The third programmer smiled, bowed, and left. ... After this last reply, a young apprentice approached the great master: “Great master, today I overheard you answer the same question about code coverage with three different answers. Why?” The great master stood up from his chair: “Come get some fresh tea with me and let’s talk about it.” After they filled their cups with smoking hot green tea, the great master began to answer: “The first programmer is new and just getting started with testing. Right now he has a lot of code and no tests. He has a long way to go; focusing on code coverage at this time would be depressing and quite useless. He’s better off just getting used to writing and running some tests. He can worry about coverage later.” “The second programmer, on the other hand, is quite experience both at programming and testing. When I replied by asking her how many grains of rice I should put in a pot, I helped her realize that the amount of testing necessary depends on a number of factors, and she knows those factors better than I do – it’s her code after all. There is no single, simple, answer, and she’s smart enough to handle the truth and work with that.” “I see,” said the young apprentice, “but if there is no single simple answer, then why did you answer the third programmer ‘Eighty percent and no less’?” The great master laughed so hard and loud that his belly, evidence that he drank more than just green tea, flopped up and down. “The third programmer wants only simple answers – even when there are no simple answers … and then does not follow them anyway.” The young apprentice and the grizzled great master finished drinking their tea in contemplative silence.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/90002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16050/" ] }
90,052
Ok, so i'm working on a regular expression to search out all the header information in a site. I've compiled the regular expression: regex = re.compile(r''' <h[0-9]>\s? (<a[ ]href="[A-Za-z0-9.]*">)?\s? [A-Za-z0-9.,:'"=/?;\s]*\s? [A-Za-z0-9.,:'"=/?;\s]?''', re.X) When i run this in python reg ex. tester, it works out wonderfully. Sample data: <body> <h1>Dog </h1> <h2>Cat </h2> <h3>Fancy </h3> <h1>Tall cup of lemons</h1> <h1><a href="dog.com">Dog thing</a></h1></body> Now, in the REDemo, it works wonderfully. When i put it in my python code, however, it only prints <a href="dog.com"> Here's my python code, I'm not sure if i'm doing something wrong or if something is lost in translation. I appreciate your help. stories=[]response = urllib2.urlopen('http://apricotclub.org/duh.html')html = response.read().lower()p = re.compile('<h[0-9]>\\s?(<a href=\"[A-Za-z0-9.]*\">)?\\s?[A-Za-z0-9.,:\'\"=/?;\\s]*\\s?[A-Za-z0-9.,:\'\"=/?;\\s]?')stories=re.findall(p, html)for i in stories: if len(i) >= 5: print i I should also note, that when i take out the (<a href=\"[A-Za-z0-9.]*\">)? from the regular expression it works fine for non-link <hN> lines.
This question has been asked in several forms over the last few days, so I'm going to say this very clearly. Q: How do I parse HTML with Regular Expressions? A: Please Don't. Use BeautifulSoup , html5lib or lxml.html . Please.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
90,075
Businesses Analyst from my team keeps sending us the updated Requirements documents often and I end up hunting the recent changes by comparing the old version. Is their a good way of comparing the Word documents? Note: We have the track changes option ON, but now the documents looks like a blood bath, complicating it much more :(
Use this option in Word 2003: T ools | Compare and Merge D ocuments Or this in Word 2007: R eview | Co m pare It prompts you for a file with which to compare the file you're editing.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4718/" ] }
90,112
I was planning to use url routing for a Web Forms application. But, after reading some posts , I am not sure if it is an easy approach. Is it better to use the URL Rewrite module for web forms? But, it is only for IIS7. Initially, there was some buzz that URL routing is totally decoupled from Asp.Net MVC and it could be used for web forms. Would love to hear any suggestions..
There's a great post here about the differences between the two from a member of the IIS team. One caveat I would advise is that for WebForms, you need to be careful when using Routing. I've written a sample implementation of how you'd use routing with WebForms that addresses these concerns and hopefully helps answer your question.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/90112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4337/" ] }
90,176
I am writing a simple checkers game in Java. When I mouse over the board my processor ramps up to 50% (100% on a core). I would like to find out what part of my code(assuming its my fault) is executing during this. I have tried debugging, but step-through debugging doesn't work very well in this case. Is there any tool that can tell me where my problem lies? I am currently using Eclipse.
This is called "profiling". Your IDE probably comes with one: see Open Source Profilers in Java .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ] }
90,178
I am working on a web application where I want the content to fill the height of the entire screen. The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom. I have a header div and a content div . At the moment I am using a table for the layout like so: CSS and HTML #page { height: 100%; width: 100%}#tdcontent { height: 100%;}#content { overflow: auto; /* or overflow: hidden; */} <table id="page"> <tr> <td id="tdheader"> <div id="header">...</div> </td> </tr> <tr> <td id="tdcontent"> <div id="content">...</div> </td> </tr></table> The entire height of the page is filled, and no scrolling is required. For anything inside the content div, setting top: 0; will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting header inside content will not allow this to work. Is there a way to achieve the same effect without using the table ? Update: Elements inside the content div will have heights set to percentages as well. So something at 100% inside the div will fill it to the bottom. As will two elements at 50%. Update 2: For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside #content would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works.
2015 update: the flexbox approach There are two other answers briefly mentioning flexbox ; however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now. Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status. (taken from https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes ) All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim. To check current support you can also see here: http://caniuse.com/#feat=flexbox Working example With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space. html,body { height: 100%; margin: 0;}.box { display: flex; flex-flow: column; height: 100%;}.box .row { border: 1px dotted grey;}.box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */}.box .row.content { flex: 1 1 auto;}.box .row.footer { flex: 0 1 40px;} <!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --><div class="box"> <div class="row header"> <p><b>header</b> <br /> <br />(sized to content)</p> </div> <div class="row content"> <p> <b>content</b> (fills remaining space) </p> </div> <div class="row footer"> <p><b>footer</b> (fixed height)</p> </div></div> In the CSS above, the flex property shorthands the flex-grow , flex-shrink , and flex-basis properties to establish the flexibility of the flex items. Mozilla has a good introduction to the flexible boxes model .
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/90178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16299/" ] }
90,181
I've just run into a display glitch in IE6 with the ExtJS framework. - Hopefully someone can point me in the right direction. In the following example, the bbar for the panel is displayed 2ems narrower than the panel it is attached to (it's left aligned) in IE6, where as in Firefox it is displayed as the same width as the panel. Can anyone suggest how to fix this? I seem to be able to work around either by specifying the width of the panel in ems or the padding in pixels, but I assume it would be expected to work as I have it below. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head> <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css"/> <script type="text/javascript" src="ext/ext-base.js"></script> <script type="text/javascript" src="ext/ext-all-debug.js"></script> <script type="text/javascript"> Ext.onReady(function(){ var main = new Ext.Panel({ renderTo: 'content', bodyStyle: 'padding: 1em;', width: 500, html: "Alignment issue in IE - The bbar's width is 2ems less than the main panel in IE6.", bbar: [ "->", {id: "continue", text: 'Continue'} ] }); }); </script></head><body> <div id="content"></div></body></html>
2015 update: the flexbox approach There are two other answers briefly mentioning flexbox ; however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now. Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status. (taken from https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes ) All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim. To check current support you can also see here: http://caniuse.com/#feat=flexbox Working example With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space. html,body { height: 100%; margin: 0;}.box { display: flex; flex-flow: column; height: 100%;}.box .row { border: 1px dotted grey;}.box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */}.box .row.content { flex: 1 1 auto;}.box .row.footer { flex: 0 1 40px;} <!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --><div class="box"> <div class="row header"> <p><b>header</b> <br /> <br />(sized to content)</p> </div> <div class="row content"> <p> <b>content</b> (fills remaining space) </p> </div> <div class="row footer"> <p><b>footer</b> (fixed height)</p> </div></div> In the CSS above, the flex property shorthands the flex-grow , flex-shrink , and flex-basis properties to establish the flexibility of the flex items. Mozilla has a good introduction to the flexible boxes model .
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/90181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ] }
90,203
What is the difference between different optimization levels in GCC? Assuming I don't care to have any debug hooks, why wouldn't I just use the highest level of optimization available to me? does a higher level of optimization necessarily (i.e. provably) generate a faster program?
Yes, a higher level can sometimes mean a better performing program. However, it can cause problems depending on your code. For example, branch prediction (enabled in -O1 and up) can break poorly written multi threading programs by causing a race condition. Optimization will actually decide something that's better than what you wrote, which in some cases might not work. And sometimes, the higher optimizations (-O3) add no reasonable benefit but a lot of extra size. Your own testing can determine if this size tradeoff makes a reasonable performance gain for your system. As a final note, the GNU project compiles all of their programs at -O2 by default , and -O2 is fairly common elsewhere.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17231/" ] }
90,238
As an example in pseudocode: if ((a mod 2) == 0){ isEven = true;}else{ isEven = false;}
Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the remainder operator % . For your exact example: if ((a % 2) == 0){ isEven = true;}else{ isEven = false;} This can be simplified to a one-liner: isEven = (a % 2) == 0;
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/90238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17245/" ] }
90,413
I want to encrypt few files using python what is the best wayI can use gpg/pgp using any standard/famous python libraries?
PyCrypto seems to be the best one around.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6946/" ] }
90,418
I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?
After each command, the exit code can be found in the $? variable so you would have something like: ls -al file.extrc=$?; if [[ $rc != 0 ]]; then exit $rc; fi You need to be careful of piped commands since the $? only gives you the return code of the last element in the pipe so, in the code: ls -al file.ext | sed 's/^/xx: /" will not return an error code if the file doesn't exist (since the sed part of the pipeline actually works, returning 0). The bash shell actually provides an array which can assist in that case, that being PIPESTATUS . This array has one element for each of the pipeline components, that you can access individually like ${PIPESTATUS[0]} : pax> false | true ; echo ${PIPESTATUS[0]}1 Note that this is getting you the result of the false command, not the entire pipeline. You can also get the entire list to process as you see fit: pax> false | true | false; echo ${PIPESTATUS[*]}1 0 1 If you wanted to get the largest error code from a pipeline, you could use something like: true | true | false | true | falsercs=${PIPESTATUS[*]}; rc=0; for i in ${rcs}; do rc=$(($i > $rc ? $i : $rc)); doneecho $rc This goes through each of the PIPESTATUS elements in turn, storing it in rc if it was greater than the previous rc value.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/90418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ] }
90,423
I have some experience making multiplayer turn-based games using sockets, but I've never attempted a realtime action game. What kind of extra issues would I have to deal with? Do I need to keep a history of player actions in case lagged players do something in the past? Do I really need to use UDP packets or will TCP suffice? What else? I haven't really decided what to make, but for the purpose of this question you can consider a 10-player 2D game with X Y movement.
'client server' or 'peer to peer' or something in between: which computer has authority over which game actions. With turn based games, normally it's very easy to just say 'the server has ultimate authority and we're done'. With real time games, often that design is a great place to start, but as soon as you add latency the client movement/actions feels unresponsive. So you add some sort of 'latency hiding' allowing the clients input to affect their character or units immediately to solve that problem, and now you have to deal with reconciling issues when the client and servers gamestate starts to diverge. 9 times outta 10 that just fine, you pop or lerp the objects the client has affected over to the authoritative position, but that 1 out of 10 times is when the object is the player avatar or something, that solution is unacceptable, so you start give the client authority over some actions. Now you have to reconcile the multiple gamestates on the server, and open yourself up to a potentially 'cheating' via a malicious client, if you care about that sort of thing. This is basically where every teleport/dupe/whatever bug/cheat comes up. Of course you could start with a model where 'every client has authority over 'their' objects' and ignore the cheating problem (fine in quite a few cases). But now you're vulnerable to a massive affect on the game simulation if that client drops out, or even 'just falls a little behind in keeping up with the simulation' - effectively every players game will end up being/feeling the effects of a lagging or otherwise underperforming client, in the form of either waiting for lagging client to catch up, or having the gamestate they control out of sync. 'synchronized' or 'asynchronus' A common strategy to ensure all players are operating on the same gamestate is to simply agree on the list of player inputs (via one of the models described above) and then have the gameplay simulation play out synchronously on all machines. This means the simulation logic has to match exactly, or the games will go out of sync. This is actually both easier and harder than it sounds. It's easier because a game is just code, and code pretty much executes exactly the same when it's give the same input (even random number generators). It's harder because there are two cases where that's not the case: (1) when you accidently use random outside of your game simulation and (2) when you use floats. The former is rectified by having strict rules/assertions over what RNGs are use by what game systems. The latter is solved by not using floats. (floats actually have 2 problems, one they work very differently based on optimization configuration of your project, but even if that was worked out, they work inconsistently across different processor architectures atm, lol). Starcraft/Warcraft and any game that offers a 'replay' most likely use this model. In fact, having a replay system is a great way to test that your RNGs are staying in sync. With an asynchronus solution the game state authorities simply broadcast that entire state to all the other clients at some frequency. The clients take that data and slam that into their gamestate (and normaly do some simplistic extrapolation until they get the next update). Here's where 'udp' becomes a viable option, because you are spamming the entire gamestate every ~1sec or so, dropping some fraction of those updates is irrelevant. For games that have relatively little game state (quake, world of warcraft) this is often the simplest solution.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8005/" ] }
90,451
Attended an interesting demo on REST today, however, I couldn't think of a single reason (nor was one presented) why REST is in anyway better or simpler to use and implement than a SOAP based Services stack. What are some of the reasons Why anyone in the "real world" use REST instead of the SOAP based Services?
Less overhead (no SOAP envelope to wrap every call in) Less duplication (HTTP already represents operations like DELETE, PUT, GET, etc. that have to otherwise be represented in a SOAP envelope). More standardized - HTTP operations are well understood and operate consistently. Some SOAP implementations can get finicky. More human readable and testable (harder to test SOAP with just a browser). Don't need to use XML (well you kind of don't have to for SOAP either but it hardly makes sense since you're already doing parsing of the envelope). Libraries have made SOAP (kind of) easy. But you are abstracting away a lot of redundancy underneath as I have noted. yes in theory SOAP can go over other transports so as to avoid riding atop a layer doing similar things, but in reality just about all SOAP work you'll ever do is over HTTP.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/90451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9382/" ] }
90,503
I'm working with a team that's building an engine for a variety of 2D and eventually 3D mini-games. The problem we're facing is a solid, cross-platform, sound API. Obviously, DirectX is out of the question due to our needs for cross-platform capabilities. SDL is nice, and works great, but let's face it SDL_Mixer is a bit limited in what it can do. We're currently using it, but when we eventually expand to 3D, it's going to be a problem. I've been messing with OpenAL, but most of the documentation I've found is fairly out of date, and doesn't seem to work all that great. I'm willing to learn OpenAL, and fight my way through it, but I'd like to be a bit more certain that I'm not wasting my time. Other than the DevMaster tutorials though, I haven't seen much documentation that's blown me away. If someone has some better material than I've found, that'd be awesome. I've also seen projects such as FMOD, which seems decent despite the licensing. However, like OpenAL, they have nearly non-existant documentation. Granted, I can pour over the code to deduce my options, but it seems like a bit of a pain considering I might eventually be paying for it. Anyways, thoughts, comments, concerns? Thanks a lot!
(note: I have experience with FMOD, BASS, OpenAL and DirectSound; and while I list other libraries below, I haven't used them). BASS and FMOD are both good (and actually I liked FMOD's documentation a lot; why would you say it's "non existing"?). There are also Miles Sound System , Wwise , irrKlang and some more middleware packages. OpenAL is supposedly cross platform, and on each platform it has it's own quirks. It's not exactly "open", either. And I'm not sure what is the future for it; it seems like it got stuck when Creative got hold of it. There's a recent effort to built the implementation from ground up, though: OpenAL Soft . Then there are native platform APIs, like DirectSound or XAudio2 for Windows, Core Audio for OS X, ALSA for Linux, proprietary APIs for consoles etc. I think using native APIs on each platform makes a lot of sense; you just abstract it under common interface that you need, and have different implementations on each platform. Sure, it's more work than just using OpenAL, but OpenAL is not even available on some platforms, and has various quirks on other platforms that you can't even fix (because there's no source code you can fix). Licensing a commercial library like FMOD or Miles is an option in a sense that all this platform dependent work is already done for you. We're using OpenAL at work right now, but are considering switching away from it, because it's just not going anywhere and we can't fix the quirks. So while OpenAL is easy to get started, it does not get my vote as a good option.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14838/" ] }
90,578
I've recently started developing applications for the Blackberry. Consequently, I've had to jump to Java-ME and learn that and its associated tools. The syntax is easy, but I keep having issues with various gotchas and the environment. For instance, something that surprised me and wasted a lot of time is absence of real properties on a class object (something I assumed all OOP languages had). There are many gotchas. I've been to various places where they compare Java syntax vs C#, but there don't seem to be any sites that tell of things to look out for when moving to Java. The environment is a whole other issue all together. The Blackberry IDE is simply horrible. The look reminds me Borland C++ for Windows 3.1 - it's that outdated. Some of the other issues included spotty intellisense, weak debugging, etc... Blackberry does have a beta of the Eclipse plugin, but without debugging support, it's just an editor with fancy refactoring tools. So, any advice on how to blend in to Java-ME?
This guy here had to make the inverse transition. So he listed the top 10 differences of Java and C#. I'll take his topics and show how it is made in Java: Gotcha #10 - Give me my standard output! To print to the standard output in Java: System.out.println("Hello"); Gotcha #9 - Namespaces == Freedom In Java you don't have the freedom of namespaces. The folder structure of your class must match the package name. For example, a class in the package org.test must be in the folder org/test Gotcha #8 - What happened to super? In Java to refer to the superclass you use the reserved word super instead of base Gotcha #7 - Chaining constructors to a base constructor You don't have this in Java. You have to call the constructor by yourself Gotcha #6 - Dagnabit, how do I subclass an existing class? To subclass a class in Java do this: public class A extends B {} That means class A is a subclass of class B . In C# would be class A : B Gotcha #5 - Why don’t constants remain constant? To define a constant in Java use the keyword final instead of const Gotcha #4 - Where is ArrayList , Vector or Hashtable ? The most used data structures in java are HashSet , ArrayList and HashMap . They implement Set , List and Map . Of course, there is a bunch more. Read more about collections here Gotcha #3 - Of Accessors and Mutators (Getters and Setters) You don't have the properties facility in Java. You have to declare the gets and sets methods for yourself. Of course, most IDEs can do that automatically. Gotcha #2 - Can't I override!? You don't have to declare a method virtual in Java. All methods - except those declared final - can be overridden in Java. And the #1 gotcha… In Java the primitive types int , float , double , char and long are not Object s like in C#. All of them have a respective object representation, like Integer , Float , Double , etc. That's it. Don't forget to see the original link , there's a more detailed discussion.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/90578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9382/" ] }
90,579
How to center text over an image in a table cell using javascript, css, and/or html? I have an HTML table containing images - all the same size - and I want to center a text label over each image. The text in the labels may vary in size. Horizontal centering is not difficult, but vertical centering is. ADDENDUM: i did end up having to use javascript to center the text reliably using a fixed-size div with absolute positioning; i just could not get it to work any other way
you could try putting the images in the background. <table> <tr> <td style="background: url(myImg.jpg) no-repeat; vertical-align: middle; text-align: center"> Here is my text </td> </tr></table> You'll just need to set the height and width on the cell and that should be it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/90579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ] }