source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
42,034 | I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list? | Tuples are used whenever you want to return multiple results from a function. Since they're immutable, they can be used as keys for a dictionary (lists can't). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/42034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
]
} |
42,068 | I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have: var data = '{"count" : 1, "stack" : "sometext\n\n"}';var dataObj = eval('('+data+')'); This gives me an error: unterminated string literal With JSON.parse(data) , I see similar error messages: " Unexpected token ↵ " in Chrome, and " unterminated string literal " in Firefox and IE. When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail. | This is what you want: var data = '{"count" : 1, "stack" : "sometext\\n\\n"}'; You need to escape the \ in your string (turning it into a double- \ ), otherwise it will become a newline in the JSON source, not the JSON data. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/42068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3636/"
]
} |
42,076 | What mechanisms do you know that prevent your site from being abused by anonymous spammers. For example, let's say that I have a site where people can vote something. But I don't want someone to spam something all the way to the top. So I found (a) creating an account and only allowed to vote once and (b) CAPTCHA to decrease spam. What other methods do you know and how good do they work? | The big thing I've noticed is that whatever you do, you want your system to be unique. You want an attacker to have to tailor their automation program for your specific site, rather than just throw a pre-existing script at it that will work almost anywhere. It doesn't even have to be cryptographically secure; it just has to make your site a little different from the norm. This doesn't mean you can't or shouldn't use something like a pre-built captcha widget. Absolutely do use one of those as a staring point! It just means you have to customize it somewhere so that something extra happens that is outside the norm and will break any pre-existing script that could normally defeat it. If your site gets big enough that you have attackers targeting it specifically, then your simple little customization probably won't hold up anymore and you might have do something a little more special and think about real cryptography and all that. But that's one of those things that's a "good" problem to have. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
]
} |
42,102 | I have a Singleton/Factory object that I'd like to write a JUnit test for. The Factory method decides which implementing class to instantiate based upon a classname in a properties file on the classpath. If no properties file is found, or the properties file does not contain the classname key, then the class will instantiate a default implementing class. Since the factory keeps a static instance of the Singleton to use once it has been instantiated, to be able to test the "failover" logic in the Factory method I would need to run each test method in a different classloader. Is there any way with JUnit (or with another unit testing package) to do this? edit: here is some of the Factory code that is in use: private static MyClass myClassImpl = instantiateMyClass();private static MyClass instantiateMyClass() { MyClass newMyClass = null; String className = null; try { Properties props = getProperties(); className = props.getProperty(PROPERTY_CLASSNAME_KEY); if (className == null) { log.warn("instantiateMyClass: Property [" + PROPERTY_CLASSNAME_KEY + "] not found in properties, using default MyClass class [" + DEFAULT_CLASSNAME + "]"); className = DEFAULT_CLASSNAME; } Class MyClassClass = Class.forName(className); Object MyClassObj = MyClassClass.newInstance(); if (MyClassObj instanceof MyClass) { newMyClass = (MyClass) MyClassObj; } } catch (...) { ... } return newMyClass;}private static Properties getProperties() throws IOException { Properties props = new Properties(); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILENAME); if (stream != null) { props.load(stream); } else { log.error("getProperties: could not load properties file [" + PROPERTIES_FILENAME + "] from classpath, file not found"); } return props;} | This question might be old but since this was the nearest answer I found when I had this problem I though I'd describe my solution. Using JUnit 4 Split your tests up so that there is one test method per class (this solution only changes classloaders between classes, not between methods as the parent runner gathers all the methods once per class) Add the @RunWith(SeparateClassloaderTestRunner.class) annotation to your test classes. Create the SeparateClassloaderTestRunner to look like this: public class SeparateClassloaderTestRunner extends BlockJUnit4ClassRunner { public SeparateClassloaderTestRunner(Class<?> clazz) throws InitializationError { super(getFromTestClassloader(clazz)); } private static Class<?> getFromTestClassloader(Class<?> clazz) throws InitializationError { try { ClassLoader testClassLoader = new TestClassLoader(); return Class.forName(clazz.getName(), true, testClassLoader); } catch (ClassNotFoundException e) { throw new InitializationError(e); } } public static class TestClassLoader extends URLClassLoader { public TestClassLoader() { super(((URLClassLoader)getSystemClassLoader()).getURLs()); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (name.startsWith("org.mypackages.")) { return super.findClass(name); } return super.loadClass(name); } }} Note I had to do this to test code running in a legacy framework which I couldn't change. Given the choice I'd reduce the use of statics and/or put test hooks in to allow the system to be reset. It may not be pretty but it allows me to test an awful lot of code that would be difficult otherwise. Also this solution breaks anything else that relies on classloading tricks such as Mockito. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
]
} |
42,125 | I have a library I created, File mylib.c: #include <mylib.h>inttestlib() { printf("Hello, World!\n"); return (0);} File mylib.h: #include <stdio.h>extern int testlib(); In my program, I've attempted to call this library function: File myprogram.c : #include <mylib.h>intmain (int argc, char *argv[]) { testlib(); return (0);} When I attempt to compile this program I get the following error: In file included from myprogram.c:1mylib.h:2 warning: function declaration isn't a prototype I'm using: gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2) What is the proper way to declare a function prototype? | In C int foo() and int foo(void) are different functions. int foo() accepts an arbitrary number of arguments, while int foo(void) accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void consistently when you mean no arguments. If you have a variable a , extern int a; is a way to tell the compiler that a is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function ( extern , static ) only affects its visibility and extern is the default, so extern is actually unnecessary. I suggest removing the extern , it is extraneous and is usually omitted. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/42125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3807/"
]
} |
42,150 | .NET Framework: 2.0Preferred Language: C# I am new to TDD (Test Driven Development). First of all, is it even possible to unit test Windows Service? Windows service class is derived from ServiceBase, which has overridable methods, OnStart OnStop How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order? At this point, am I even doing a Unit testing? or an Integration test? I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service. | I'd probably recommend designing your app so the "OnStart" and "OnStop" overrides in the Windows Service just call methods on a class library assembly. That way you can automate unit tests against the class library methods, and the design also abstracts your business logic from the implementation of a Windows Service. In this scenario, testing the "OnStart" and "OnStop" methods themselves in a Windows Service context would then be an integration test, not something you would automate. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/42150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4035/"
]
} |
42,169 | I converted my company's calendar to XSL and changed all the tables to divs. It worked pretty well, but I had a lot of 8 day week bugs to work out initially owing to precarious cross-browser spacing issues. But I was reading another post regarding when to use tables v. divs and the consensus seemed to be that you should only use divs for true divisions between parts of the webpage, and only use tables for tabular data. I'm not sure I could even have used tables with XSL but I wanted to follow up that discussion of Divs and Tables with a discussion of the ideal way to make a web calendars and maybe a union of the two. | A calendar is the perfect reason to use a table! Calendars inherently present tabular data and HTML tables are good at presenting tabular data. And HTML table markup provides nearly all the CSS hooks you need to associate CSS selectors with various parts of the table to dress it up. I'm all for using DIVs for layout--but stick with tables for tabular data. Here is a cool article on how to dress up tables with CSS: http://www.smashingmagazine.com/2008/08/13/top-10-css-table-designs | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
]
} |
42,182 | I'm trying to write a blog post which includes a code segment inside a <pre> tag. The code segment includes a generic type and uses <> to define that type. This is what the segment looks like: <pre> PrimeCalc calc = new PrimeCalc(); Func<int, int> del = calc.GetNextPrime;</pre> The resulting HTML removes the <> and ends up like this: PrimeCalc calc = new PrimeCalc();Func del = calc.GetNextPrime; How do I escape the <> so they show up in the HTML? | <pre> PrimeCalc calc = new PrimeCalc(); Func<int, int> del = calc.GetNextPrime;</pre> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/42182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
]
} |
42,187 | I have read about partial methods in the latest C# language specification , so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods? | Partial methods have been introduced for similar reasons to why partial classes were in .Net 2. A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs. The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other. The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time. In .Net 1 it was auto-generated code in a #region block In .Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes. In .Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code. The extra bit here is that code needed to provide methods that developers might want to fill in. As developers will extend these classes (with extra partial files) they couldn't use abstract methods here. The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time. Empty methods are not optimised out . So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out. So that it can do this partial methods always return void. If you create a new Linq DBML file it will auto-generate a partial class, something like [System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")]public partial class MyDataContext : System.Data.Linq.DataContext{ ... partial void OnCreated(); partial void InsertMyTable(MyTable instance); partial void UpdateMyTable(MyTable instance); partial void DeleteMyTable(MyTable instance); ... Then in your own partial file you can extend this: public partial class MyDataContext{ partial void OnCreated() { //do something on data context creation }} If you don't extend these methods they get optimised right out. Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer. The example I mentioned before is one possibility: //this code will get optimised out if no body is implementedpartial void DoSomethingIfCompFlag();#if COMPILER_FLAG//this code won't exist if the flag is offpartial void DoSomethingIfCompFlag() { //your code}#endif Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
]
} |
42,197 | The company I work for makes hardware that communicates to the computer though a serial port. Third party companies write software that communicates with our hardware. There are times when I need to diagnose our hardware. However, a third party software app connects to the serial port when Windows starts up, blocking any other connection. I don't know the name of this application/service and it's not always the same one. Is there any way to either: Find the name/pid of the app/service that is currently using a given serial port or Steal the serial port connection from another app. vb.net preferably, but I'll take a language agnostic answer as well. | You can use the process explorer tool also from SysInternals to search for open handles. In this case you would want to search for 'Serial' since it uses device names that may not map to com port numbers. (e.g. COM1 is \Device\Serial0 on my system). If you want to take control of the serial port from another app I think you would need co-operation of the driver. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30/"
]
} |
42,247 | The following code illustrates an object literal being assigned, but with no semicolon afterwards: var literal = { say: function(msg) { alert(msg); }}literal.say("hello world!"); This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed? I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it. | Not technically, JavaScript has semicolons as optional in many situations. But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration. Automatic semicolon insertion is performed by the interpreter, so you can leave them out if you so choose. In the comments, someone claimed that Semicolons are not optional with statements like break/continue/throw but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference. Here is the rest of the standard on semicolon insertion: For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
} |
42,251 | Has anyone worked much with Microsoft's Managed Extensibility Framework (MEF)? Kinda sounds like it's trying to be all things to all people - It's an add-in manager! It's duck typing! I'm wondering if anyone has an experience with it, positive or negative. We're currently planning on using an generic IoC implementation ala MvcContrib for our next big project. Should we throw MEF in the mix? | We are not aiming for MEF to be an all-purpose IoC. The best way to think about the IoC aspects of MEF is an implementation detail. We use IoC as a pattern because it is a great way to address the problems we are looking to solve. MEF is focused on extensibility. When you think of MEF look at it as an investment in taking our platform forward. Our future products and the platform will leverage MEF as a standard mechanism for adding extensibility. Third-party products and frameworks will also be able to leverage this same mechanism. The average "user" of MEF will author components that MEF will consume and will not be directly consuming MEF within their applications. Imagine when you want to extend our platform in the future, you drop a dll in the bin folder and you are done. The MEF enabled app lights up with the new extension. That's the vision for MEF. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3759/"
]
} |
42,254 | I would like to flash a success message on my page. I am using the jQuery fadeOut method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange. What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed. How can you animate this using jQuery? | The new delay() function in jQuery 1.4 should do the trick. $('#foo').fadeIn(200).delay(5000).fadeOut(200).remove(); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3645/"
]
} |
42,286 | It seems like there should be something shorter than this: private string LoadFromFile(string path){ try { string fileContents; using(StreamReader rdr = File.OpenText(path)) { fileContents = rdr.ReadToEnd(); } return fileContents; } catch { throw; }} | First of all, the title asks for "how to write the contents of strnig to a text file"but your code example is for "how to read the contents of a text file to a string. Answer to both questions: using System.IO;...string filename = "C:/example.txt";string content = File.ReadAllText(filename);File.WriteAllText(filename, content); See also ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes if instead of a string you want a string array or byte array. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475/"
]
} |
42,294 | I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case. | To get a sticky footer: Have a <div> with class="wrapper" for your content. Right before the closing </div> of the wrapper place the <div class="push"></div> . Right after the closing </div> of the wrapper place the <div class="footer"></div> . * { margin: 0;}html, body { height: 100%;}.wrapper { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */}.footer, .push { height: 142px; /* .push must be the same height as .footer */} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/42294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
]
} |
42,308 | Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly. | If you have access to GCC/G++, then the -M option will output the dependency list. It doesn't do any of the extra stuff that the other tools do, but since it is coming from the compiler, there is no chance that it will pick up files from the "wrong" place. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/42308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
]
} |
42,357 | I've seen a few attempted SQL injection attacks on one of my web sites. It comes in the form of a query string that includes the "cast" keyword and a bunch of hex characters which when "decoded" are an injection of banner adverts into the DB. My solution is to scan the full URL (and params) and search for the presence of "cast(0x" and if it's there to redirect to a static page. How do you check your URL's for SQL Injection attacks? | I don't. Instead, I use parametrized SQL Queries and rely on the database to clean my input. I know, this is a novel concept to PHP developers and MySQL users, but people using real databases have been doing it this way for years. For Example (Using C#) // Bad!SqlCommand foo = new SqlCommand("SELECT FOO FROM BAR WHERE LOL='" + Request.QueryString["LOL"] + "'");//Good! Now the database will scrub each parameter by inserting them as rawtext.SqlCommand foo = new SqlCommany("SELECT FOO FROM BAR WHERE LOL = @LOL");foo.Parameters.AddWithValue("@LOL",Request.QueryString["LOL"]); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
} |
42,366 | We are working on a winforms app in Visual Studio 2005 and the setup project we created output both an MSI and an EXE. We aren't sure what the EXE file is used for because we are able to install without the EXE. | It's a bootstrapper that checks to make sure that the .NET Framework is installed, before launching the MSI. It's pretty handy. I suggest using something like SFX Compiler to package the two together into one self-extracting .exe and then launch the extracted setup.exe. This way you retain the benefits of the bootstrapper, but your users only download a single thing. Edit : also see The official line: MSDN documentation Some bootstrapper customization: some guy's blog post about what he did | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4437/"
]
} |
42,383 | I am writing an immutable DOM tree in Java, to simplify access from multiple threads.* However, it does need to support inserts and updates as fast as possible. And since it is immutable, if I make a change to a node on the N'th level of the tree, I need to allocate at least N new nodes in order to return the new tree. My question is, would it be dramatically faster to pre-allocate nodes rather than create new ones every time the tree is modified? It would be fairly easy to do - keep a pool of several hundred unused nodes, and pull one out of the pool rather than create one whenever it was required for a modify operation. I can replenish the node pool when there's nothing else going on. (in case it isn't obvious, execution time is going to be much more at a premium in this application than heap space is) Is it worthwhile to do this? Any other tips on speeding it up? Alternatively, does anyone know if an immutable DOM library already? I searched, but couldn't find anything. *Note: For those of you who aren't familiar with the concept of immutability, it basically means that on any operation to an object that changes it, the method returns a copy of the object with the changes in place, rather than the changed object. Thus, if another thread is still reading the object it will continue to happily operate on the "old" version, unaware that changes have been made, rather than crashing horribly. See http://www.javapractices.com/topic/TopicAction.do?Id=29 | These days, object creation is pretty dang fast, and the concept of object pooling is kind of obsolete (at least in general; connection pooling is of course still valid). Avoid premature optimization. Create your nodes when you need them when doing your copies, and then see if that becomes prohibitively slow. If so, then look into some techniques to speed it up. But unless you already know that what you've got isn't fast enough, I wouldn't go introducing all the complexity you're going to need to get pooling going. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3044/"
]
} |
42,396 | Here's the code from the ascx that has the repeater: <asp:Repeater ID="ListOfEmails" runat="server" > <HeaderTemplate><h3>A sub-header:</h3></HeaderTemplate> <ItemTemplate> [Some other stuff is here] <asp:Button ID="removeEmail" runat="server" Text="X" ToolTip="remove" /> </ItemTemplate></asp:Repeater> And in the codebehind for the repeater's databound and events: Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button) removeEmail.CommandArgument = e.Item.ItemIndex.ToString() AddHandler removeEmail.Click, AddressOf removeEmail_Click AddHandler removeEmail.Command, AddressOf removeEmail_Command End IfEnd SubSub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write("<h1>click</h1>")End SubSub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs) Response.Write("<h1>command</h1>")End Sub Neither the click or command is getting called, what am I doing wrong? | Controls nested inside of Repeaters do not intercept events. Instead you need to bind to the Repeater.ItemCommand Event. ItemCommand contains RepeaterCommandEventArgs which has two important fields: CommandName CommandArgument So, a trivial example: void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e){ if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { // Stuff to databind Button myButton = (Button)e.Item.FindControl("myButton"); myButton.CommandName = "Add"; myButton.CommandArgument = "Some Identifying Argument"; }}void rptr_ItemCommand(object source, RepeaterCommandEventArgs e){ if (e.CommandName == "Add") { // Do your event }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
]
} |
42,460 | I'm almost certain I know the answer to this question, but I'm hoping there's something I've overlooked. Certain applications seem to have the Vista Aero look and feel to their caption bars and buttons even when running on Windows XP. (Google Chrome and Windows Live Photo Gallery come to mind as examples.) I know that one way to accomplish this from WinForms would be to create a borderless form and draw the caption bar/buttons yourself, then overriding WndProc to make sure moving, resizing, and button clicks do what they're supposed to do (I'm not clear on the specifics but could probably pull it off given a day to read documentation.) I'm curious if there's a different, easier way that I'm overlooking. Perhaps some API calls or window styles I've overlooked? I believe Google has answered it for me by using the roll-your-own-window approach with Chrome. I will leave the question open for another day in case someone has new information, but I believe I have answered the question myself. | Here's an article with full code sample on how to use your own custom "chrome" for an application: http://geekswithblogs.net/kobush/articles/CustomBorderForms3.aspx This looks like some really good stuff. There are a total of 3 articles in it's series, and it runs great, and on Vista too! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547/"
]
} |
42,466 | As a long time Microsoft developer, I find MSDN to be an invaluable resource. However, when tinkering at home I am not able to play with the best latest technologies and the different offerings coming from Microsoft as I cannot justify paying such a hefty price for what is essentially a pastime. The Express editions are great, but fall flat when trying to use the more advanced feature I am used to from the versions I use at work. I cannot get the latest betas and play with the new offerings, not legally, anyway. Apart from getting an MVP , how would one go about getting an MSDN subscription for an acceptable price for a non-professional environment? I am aware of the Empower program, but I thought it was geared towards getting commercial software to market. If this is not the case, it appears like the way for me to go. Thanks! | There is an Empower program that Microsoft has available. It gives you several Premium subscriptions for cheap, with the catch that you have to be an ISV working towards an actual product. This (Not available anymore - broken link) gives you all the software you'll need for development, and even a few "real world" licenses for certain apps (like Office) After a couple of years, you have to pay full price though. The logic being that you should have a product on the market, and can afford it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
]
} |
42,468 | I am using .NET remoting to retrieve periodic status updates from a Windows service into a 'controller' application which is used to display some live stats about what the service is doing. The resulting network traffic is huge - many times the size of the data for the updates - so clearly I have implemented the remoting code incorrectly in a very inefficient way. As a first step towards fixing it, I need to monitor the traffic on the IP port the service is using to talk to the controller, so that I can establish a baseline and then verify a fix. Can anyone recommend a utility and/or coding technique that I can use to get the traffic stats? A "bytes sent" count for the port would suffice. | There is an Empower program that Microsoft has available. It gives you several Premium subscriptions for cheap, with the catch that you have to be an ISV working towards an actual product. This (Not available anymore - broken link) gives you all the software you'll need for development, and even a few "real world" licenses for certain apps (like Office) After a couple of years, you have to pay full price though. The logic being that you should have a product on the market, and can afford it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3776/"
]
} |
42,482 | Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.) Antiword seems like it might be a reasonable option, but it seems like it might be abandoned. A Python solution would be ideal, but doesn't appear to be available. | I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python). import osdef doc_to_text_catdoc(filename): (fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename) fi.close() retval = fo.read() erroroutput = fe.read() fo.close() fe.close() if not erroroutput: return retval else: raise OSError("Executing the command caused an error: %s" % erroroutput)# similar doc_to_text_antiword() The -w switch to catdoc turns off line wrapping, BTW. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2678/"
]
} |
42,505 | I have a C# singleton class that multiple classes use. Is access through Instance to the Toggle() method thread-safe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it? public class MyClass{ private static readonly MyClass instance = new MyClass(); public static MyClass Instance { get { return instance; } } private int value = 0; public int Toggle() { if(value == 0) { value = 1; } else if(value == 1) { value = 0; } return value; }} | Is access through 'Instance' to the 'Toggle()' class threadsafe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it? No, it's not threadsafe. Basically, both threads can run the Toggle function at the same time, so this could happen // thread 1 is running this code if(value == 0) { value = 1; // RIGHT NOW, thread 2 steps in. // It sees value as 1, so runs the other branch, and changes it to 0 // This causes your method to return 0 even though you actually want 1 } else if(value == 1) { value = 0; } return value; You need to operate with the following assumption. If 2 threads are running, they can and will interleave and interact with eachother randomly at any point. You can be half way through writing or reading a 64 bit integer or float (on a 32 bit CPU) and another thread can jump in and change it out from underneath you. If the 2 threads never access anything in common, it doesn't matter, but as soon as they do, you need to prevent them from stepping on each others toes. The way to do this in .NET is with locks. You can decide what and where to lock by thinking about things like this: For a given block of code, if the value of something got changed out from underneath me, would it matter? If it would, you need to lock that something for the duration of the code where it would matter. Looking at your example again // we read value here if(value == 0) { value = 1; } else if(value == 1) { value = 0; } // and we return it here return value; In order for this to return what we expect it to, we assume that value won't get changed between the read and the return . In order for this assumption to actually be correct, you need to lock value for the duration of that code block. So you'd do this: lock( value ){ if(value == 0) ... // all your code here return value;} HOWEVER In .NET you can only lock Reference Types. Int32 is a Value Type, so we can't lock it. We solve this by introducing a 'dummy' object, and locking that wherever we'd want to lock 'value'. This is what Ben Scheirman is referring to. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
]
} |
42,512 | Is it possible to delete an GAE application after it has been created? I made a mistake while typing the name and now have a dummy application that I haven't been able to remove. | With the new Google Cloud console, you can still disable GAE applications as before (App Engine --> Settings --> Disable). They cannot currently be deleted. However you can delete the entire project by going to IAM --> Settings --> Shut Down. This button is in the header and a bit tricky to spot. It looks like this: As of AppEngine SDK 1.2.6 it's possible to delete apps completely . But beware, the app-id won't be usable again. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/42512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
]
} |
42,515 | I'm thinking about making a networked game. I'm a little new to this, and have already run into a lot of issues trying to put together a good plan for dead reckoning and network latency, so I'd love to see some good literature on the topic. I'll describe the methods I've considered. Originally, I just sent the player's input to the server, simulated there, and broadcast changes in the game state to all players. This made cheating difficult, but under high latency things were a little difficult to control, since you dont see the results of your own actions immediately. This GamaSutra article has a solution that saves bandwidth and makes local input appear smooth by simulating on the client as well, but it seems to throw cheat-proofing out the window. Also, I'm not sure what to do when players start manipulating the environment, pushing rocks and the like. These previously neutral objects would temporarily become objects the client needs to send PDUs about, or perhaps multiple players do at once. Whose PDUs would win? When would the objects stop being doubly tracked by each player (to compare with the dead reckoned version)? Heaven forbid two players engage in a sumo match (e.g. start pushing each other). This gamedev.net bit shows the gamasutra solution as inadequate, but describes a different method that doesn't really fix my collaborative boulder-pushing example. Most other things I've found are specific to shooters. I'd love to see something more geared toward games that play like SNES Zelda, but with a little more physics / momentum involved. Note: I'm not asking about physics simulation here -- other libraries have that covered. Just strategies for making games smooth and reactive despite network latency. | Check out how Valve does it in the Source Engine: http://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking If it's for a first person shooter you'll probably have to delve into some of the topics they mention such as: prediction, compensation, and interpolation. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653/"
]
} |
42,519 | Inspired by Raymond Chen's post , say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff. [1][2][3][4][5][6][7][8][9][0][1][2][3][4][5][6] Becomes: [3][9][5][1][4][0][6][2][5][1][7][3][6][2][8][4] Update : Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000? | O(n^2) time and O(1) space algorithm ( without any workarounds and hanky-panky stuff! ) Rotate by +90: Transpose Reverse each row Rotate by -90: Method 1 : Transpose Reverse each column Method 2 : Reverse each row Transpose Rotate by +180: Method 1 : Rotate by +90 twice Method 2 : Reverse each row and then reverse each column (Transpose) Rotate by -180: Method 1 : Rotate by -90 twice Method 2 : Reverse each column and then reverse each row Method 3 : Rotate by +180 as they are same | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/42519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
]
} |
42,531 | Looking for an example that: Launches an EXE Waits for the EXE to finish. Properly closes all the handles when the executable finishes. | Something like this: STARTUPINFO info={sizeof(info)};PROCESS_INFORMATION processInfo;if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo)){ WaitForSingleObject(processInfo.hProcess, INFINITE); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread);} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/42531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
]
} |
42,566 | I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails? Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer): The [below] code does NOT make a connection or send any packets (to 64.233.187.99 which is google). Since UDP is a stateless protocol connect() merely makes a system call which figures out how to route the packets based on the address and what interface (and therefore IP address) it should bind to. addr() returns an array containing the family (AF_INET), local port, and local address (which is what we want) of the socket. | From coderrr.wordpress.com : require 'socket'def local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last endensure Socket.do_not_reverse_lookup = origend# irb:0> local_ip# => "192.168.0.127" | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/42566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
]
} |
42,581 | The Python docs say: re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string... So what's going on when I get the following unexpected result? >>> import re>>> s = """// The quick brown fox.... // Jumped over the lazy dog.""">>> re.sub('^//', '', s, re.MULTILINE)' The quick brown fox.\n// Jumped over the lazy dog.' | Look at the definition of re.sub : re.sub(pattern, repl, string[, count, flags]) The 4th argument is the count, you are using re.MULTILINE (which is 8) as the count, not as a flag. Either use a named argument: re.sub('^//', '', s, flags=re.MULTILINE) Or compile the regex first: re.sub(re.compile('^//', re.MULTILINE), '', s) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/42581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
]
} |
42,587 | I have heard/read the term but don't quite understand what it means. When should I use this technique and how would I use it? Can anyone provide a good code sample? | The visitor pattern is a way of doing double-dispatch in an object-oriented way. It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time. Double dispatch is a special case of multiple dispatch . When you call a virtual method on an object, that's considered single-dispatch because which actual method is called depends on the type of the single object. For double dispatch, both the object's type and the method sole argument's type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time. In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last. Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren't like generic methods, which use type parameters. To do double-dispatch in C# , you can declare a method with a sole object argument and then specific methods with specific types: using System.Linq; class DoubleDispatch{ public T Foo<T>(object arg) { var method = from m in GetType().GetMethods() where m.Name == "Foo" && m.GetParameters().Length==1 && arg.GetType().IsAssignableFrom (m.GetParameters()[0].GetType()) && m.ReturnType == typeof(T) select m; return (T) method.Single().Invoke(this,new object[]{arg}); } public int Foo(int arg) { /* ... */ } static void Test() { object x = 5; Foo<int>(x); //should call Foo(int) via Foo<T>(object). }} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/42587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
]
} |
42,620 | I once worked with an architect who banned the use of SQL views. His main reason was that views made it too easy for a thoughtless coder to needlessly involve joined tables which, if that coder tried harder, could be avoided altogether. Implicitly he was encouraging code reuse via copy-and-paste instead of encapsulation in views. The database had nearly 600 tables and was highly normalised, so most of the useful SQL was necessarily verbose. Several years later I can see at least one bad outcome from the ban - we have many hundreds of dense, lengthy stored procs that verge on unmaintainable. In hindsight I would say it was a bad decision, but what are your experiences with SQL views? Have you found them bad for performance? Any other thoughts on when they are or are not appropriate? | There are some very good uses for views; I have used them a lot for tuning and for exposing less normalized sets of information, or for UNION-ing results from multiple selects into a single result set. Obviously any programming tool can be used incorrectly, but I can't think of any times in my experience where a poorly tuned view has caused any kind of drawbacks from a performance standpoint, and the value they can provide by providing explicitly tuned selects and avoiding duplication of complex SQL code can be significant. Incidentally, I have never been a fan of architectural "rules" that are based on keeping developers from hurting themselves. These rules often have unintended side-effects -- the last place I worked didn't allow using NULLs in the database, because developers might forget to check for null. This ended up forcing us to work around "1/1/1900" dates and integers defaulted to "0" in all the software built against the databases, and introducing a litany of bugs caused by devs working around places where NULL was the appropriate value. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4200/"
]
} |
42,627 | I am looking to write some C# code for linux/windows/mac/any other platform, and am looking for best practices for portable code. Project mono has some great porting resources. What are the best practices for portable C#? | I've actually used winforms and it was fine. It was BUTT UGLY, but it worked. Obviously, don't use P/Invoke, or any win32 stuff like the registry. Also be aware of any third party DLL's. For example, we use a third party SQLite dll which actually contains native code in it which we have to swap out if we want to run on OSX/linux. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
]
} |
42,648 | How am I supposed to get the IDENTITY of an inserted row? I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY , but don't understand the implications or impacts attached to each. Can someone please explain the differences and when I would be using each? | @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes. You need to be careful here , since it's across scopes. You could get a value from a trigger, instead of your current statement. SCOPE_IDENTITY() returns the last identity value generated for any table in the current session and the current scope. Generally what you want to use . IDENT_CURRENT('tableName') returns the last identity value generated for a specific table in any session and any scope. This lets you specify which table you want the value from, in case the two above aren't quite what you need ( very rare ). Also, as @ Guy Starbuck mentioned, "You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into." The OUTPUT clause of the INSERT statement will let you access every row that was inserted via that statement. Since it's scoped to the specific statement, it's more straightforward than the other functions above. However, it's a little more verbose (you'll need to insert into a table variable/temp table and then query that) and it gives results even in an error scenario where the statement is rolled back. That said, if your query uses a parallel execution plan, this is the only guaranteed method for getting the identity (short of turning off parallelism). However, it is executed before triggers and cannot be used to return trigger-generated values. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/42648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
]
} |
42,706 | Is there a down side? I feel almost dependent on it now. Whenever a project gets past a certain size almost feel an allergic reaction to standard patterns and immediately re-wire it with a Dependency Injection framework. The largest issue I've found is it can be confusing for other developers who are just learning it. Also, I'd feel much better if it were a part of the language I was using. Though, for Java at least, there are a couple very lightweight libraries which are quite good. Thoughts? Bad experiences? Or just stop worrying about it? [EDIT] Re: Description of Dependency Injection itself Sorry for being vague. Martin Fowler probably describes it FAR better than I ever could... no need to waste the effort. Coincidentally, this confirms one point about it, that it's still not widely practiced and might tend to be a barrier when working with teams if everyone is not up to speed on it. | I've taken a stab at describing some of the possible downsides in a blog post here: http://kevin-berridge.blogspot.com/2008/06/ioc-and-di-complexity.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758/"
]
} |
42,740 | What is WCF in simple terms? It's hard to distill the meaning from the Wikipedia page . | WCF - Windows Communication Framework - is Microsoft's framework to make inter-process communication easier. It let's you do this communication through various means, plain old asmx web services, Remoting, MS Message Queuing, and a couple more. It let's you talk with other .NET apps, or non-Microsoft technologies (like J2EE). It's extensible enough to allow for newer stuff, like REST too (I don't think REST is built-in). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2831/"
]
} |
42,763 | Does anyone know how many options a drop down list can have? Is it unlimited? How many before performance degrades? | Does anyone know how many options a drop down list can have? Is it unlimited? I imagine it is unlimited in theory, obviously not in practice as a computer's RAM and the specific browser's limitations come into play. How many before performance degrades? Again, this would depend on a few factors, at the least the specific browser, the computer's memory and processing power. EDIT: From experience, I have had drop down lists with thousands of options. It wasn't ideal though because who wants to scroll through all of those? This is why an auto-complete of some type is more desirable for numerous reasons, especially the end user's experience. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415/"
]
} |
42,778 | Is CPAN DBI the best database interface to use in Perl for general database use? Are there some better options? | If you're just looking for low-level database access—you feed it any SQL string (optionally with place-holders and bind values) and it runs your query and gives you back the results—then yes, DBI is your best bet, by far. If you want a higher-level interface (i.e., one that requires little or no use of raw SQL in your code) then there are several ORMs ( object-relational mappers ) available for Perl. Check out the ORM page at the Perl Foundation's Perl 5 wiki for more information and links. (If you want help choosing among them or have specific questions, you could narrow the focus of this question or perhaps post another one.) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
]
} |
42,793 | What techniques do you know\use to create user-friendly GUI ? I can name following techniques that I find especially useful: Non-blocking notifications (floating dialogs like in Firefox3 or Vista's pop-up messages in tray area) Absence of "Save" button MS OneNote as an example. IM clients can save conversation history automatically Integrated search Search not only through help files but rather make UI elements searchable. Vista made a good step toward such GUI. Scout addin Microsoft Office was a really great idea. Context oriented UI (Ribbon bar in MS Office 2007) Do you implement something like listed techniques in your software? Edit: As Ryan P mentioned, one of the best way to create usable app is to put yourself in user's place. I totally agree with it, but what I want to see in this topic is specific techniques (like those I mentioned above) rather than general recommendations. | If you do give the user a question, don't make it a yes/no question. Take the time to make a new form and put the verbs as choices like in mac. For example: Would you like to save? Yes No Should Be: Would you like to save? Save Don't Save There is a more detailed explanation here. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196/"
]
} |
42,826 | Anyone know a good book or post about how to start in EF? I have seen the DnrTV any other place? | Mike Taulty's Blog: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/category/1024.aspx A great EF intro deck: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/03/13/10235.aspx And these ADO.NET Data Services screencasts are nice too: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/01/25/10152.aspx ADO.NET Entity Framework MSDN: http://msdn.microsoft.com/en-us/library/bb399572.aspx ADO.NET Entity Framework forums: http://forums.microsoft.com/msdn/ShowForum.aspx?ForumID=533&SiteID=1 ADO.NET team blog: http://blogs.msdn.com/adonet/archive/tags/Entity+Framework/default.aspx Programming LINQ and the ADO.NET Entity Framework Webcast: http://blogs.msdn.com/adonet/archive/2008/01/28/programming-linq-and-the-ado-net-entity-framework-webcast.aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
]
} |
42,833 | In the web-application I'm developing I currently use a naive solution when connecting to the database: Connection c = DriverManager.getConnection("url", "username", "password"); This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode? | You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string: http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4464/"
]
} |
42,908 | While browsing with Chrome, I noticed that it responds extremely fast (in comparison with IE and Firefox on my laptop) in terms of rendering pages, including JavaScript heavy sites like gmail. This is what googlebook on Chrome has to say tabs are hosted in process rather than thread. compile javascript using V8 engine as opposed to interpreting. Introduce new virtual machine to support javascript heavy apps introduce "hidden class transitions" and apply dynamic optimization to speed up things. Replace inefficient "Conservative garbage colllection" scheme with more precise garbage collection scheme. Introduce their own task scheduler and memory manager to manage the browser environment. All this sounds so familiar, and Microsoft has been doing such things for long time.. Windows os, C++, C# etc compilers, CLR, and so on. So why isn't Microsoft or any other browser vendor taking Chrome's approach? Is there a flaw in Chrome's approach? If not, is the rest of browser vendor community caught unaware with Google's approach? | Chrome's approach is difficult to write, and requires forethought from the developers. IE and Firefox are both attempting to move to a process-per-tab model, but due to backwards compatibility are not able to transition quickly. Chrome, being an entirely new browser build on a clean rendering engine (WebKit), was easier to write in this way. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/42908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647/"
]
} |
42,934 | It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately. I've mostly only worked in compiled, static typed languages (C, Java, .Net). The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP. Using these technologies has left a bad taste in my mouth when thinking about dynamic languages. Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime. And even then, you may not notice an error, as it just creates a new variable, and assigns some default value. I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type. What I want to know is, what people find so appealing about dynamic languages? What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages. It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code? And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago? | I think the reason is that people are used to statically typed languages that have very limited and inexpressive type systems. These are languages like Java, C++, Pascal, etc. Instead of going in the direction of more expressive type systems and better type inference, (as in Haskell, for example, and even SQL to some extent), some people like to just keep all the "type" information in their head (and in their tests) and do away with static typechecking altogether. What this buys you in the end is unclear. There are many misconceived notions about typechecking, the ones I most commonly come across are these two. Fallacy: Dynamic languages are less verbose. The misconception is that type information equals type annotation. This is totally untrue. We all know that type annotation is annoying. The machine should be able to figure that stuff out. And in fact, it does in modern compilers. Here is a statically typed QuickSort in two lines of Haskell (from haskell.org ): qsort [] = []qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs) And here is a dynamically typed QuickSort in LISP (from swisspig.net ): (defun quicksort (lis) (if (null lis) nil (let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x)))) (append (quicksort (remove-if-not fn r)) (list x) (quicksort (remove-if fn r)))))) The Haskell example falsifies the hypothesis statically typed, therefore verbose . The LISP example falsifies the hypothesis verbose, therefore statically typed . There is no implication in either direction between typing and verbosity. You can safely put that out of your mind. Fallacy: Statically typed languages have to be compiled, not interpreted. Again, not true. Many statically typed languages have interpreters. There's the Scala interpreter, The GHCi and Hugs interpreters for Haskell, and of course SQL has been both statically typed and interpreted for longer than I've been alive. You know, maybe the dynamic crowd just wants freedom to not have to think as carefully about what they're doing. The software might not be correct or robust, but maybe it doesn't have to be. Personally, I think that those who would give up type safety to purchase a little temporary liberty, deserve neither liberty nor type safety. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/42934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
]
} |
42,950 | Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this? | calendar.monthrange provides this information: calendar. monthrange (year, month) Returns weekday of first day of the month and number of days in month, for the specified year and month . >>> import calendar>>> calendar.monthrange(2002, 1)(1, 31)>>> calendar.monthrange(2008, 2) # leap years are handled correctly(4, 29)>>> calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years(0, 28) so: calendar.monthrange(year, month)[1] seems like the simplest way to go. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/42950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
]
} |
42,980 | Does anyone know how to setup Mercurial to use p4merge as the merge/diff tool on OS X 10.5? | This will work for merging: Place this into your ~/.hgrc (or, optionally, your Mercurial.ini on Windows): [merge-tools]p4.priority = 100p4.premerge = True # change this to False if you're don't trust hg's internal mergep4.executable = /Applications/p4merge.app/Contents/MacOS/p4mergep4.gui = Truep4.args = $base $local $other $output Requires Mercurial 1.0 or newer. Clearly you'll need to update the path to that executable to reflect where you'd got p4merge installed. You can't change what hg diff uses ; but you can use the extdiff extension to create new diff commands that use the display you want. So hg pdiff could run p4 merge, etc. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/42980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3547/"
]
} |
43,021 | Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop? For instance, I currently do something like this depending on the circumstances: int i = 0;foreach (Object o in collection){ // ... i++;} | The foreach is for iterating over collections that implement IEnumerable . It does this by calling GetEnumerator on the collection, which will return an Enumerator . This Enumerator has a method and a property: MoveNext() Current Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object. The concept of an index is foreign to the concept of enumeration, and cannot be done. Because of that, most collections are able to be traversed using an indexer and the for loop construct. I greatly prefer using a for loop in this situation compared to tracking the index with a local variable. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/43021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
} |
43,044 | I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc. I've found solutions to this problem but they rely on alternative color palettes than RGB.I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors. Any ideas would be great. | You could average the RGB values of random colors with those of a constant color: (example in Java) public Color generateRandomColor(Color mix) { Random random = new Random(); int red = random.nextInt(256); int green = random.nextInt(256); int blue = random.nextInt(256); // mix the color if (mix != null) { red = (red + mix.getRed()) / 2; green = (green + mix.getGreen()) / 2; blue = (blue + mix.getBlue()) / 2; } Color color = new Color(red, green, blue); return color;} Mixing random colors with white (255, 255, 255) creates neutral pastels by increasing the lightness while keeping the hue of the original color. These randomly generated pastels usually go well together, especially in large numbers. Here are some pastel colors generated using the above method: You could also mix the random color with a constant pastel, which results in a tinted set of neutral colors. For example, using a light blue creates colors like these: Going further, you could add heuristics to your generator that take into account complementary colors or levels of shading, but it all depends on the impression you want to achieve with your random colors. Some additional resources: http://en.wikipedia.org/wiki/Color_theory http://en.wikipedia.org/wiki/Complementary_color | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/43044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415/"
]
} |
43,051 | I have the following C# code: byte rule = 0;...rule = rule | 0x80; which produces the error: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?) [Update: first version of the question was wrong ... I misread the compiler output] Adding the cast doesn't fix the problem: rule = rule | (byte) 0x80; I need to write it as: rule |= 0x80; Which just seems weird. Why is the |= operator any different to the | operator? Is there any other way of telling the compiler to treat the constant as a byte? @ Giovanni Galbo : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much! @ Jonathon Holland : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces: The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type) | C# does not have a literal suffix for byte. u = uint, l = long, ul = ulong, f = float, m = decimal, but no byte. You have to cast it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3631/"
]
} |
43,116 | I've got a utility that outputs a list of files required by a game. How can I run that utility within a C program and grab its output so I can act on it within the same program? UPDATE: Good call on the lack of information. The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux. Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout). | For simple problems in Unix-ish environments try popen() . From the man page: The popen() function opens a process by creating a pipe, forking and invoking the shell. If you use the read mode this is exactly what you asked for. I don't know if it is implemented in Windows. For more complicated problems you want to look up inter-process communication. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/43116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3830/"
]
} |
43,134 | Simple question, but one that I've been curious about...is there a functional difference between the following two commands? String::classString.class They both do what I expect -- that is to say they return Class -- but what is the difference between using the :: and the . ? I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after :: but not after . , but I don't know what the reason for this is... | The . operator basically says "send this message to the object". In your example it is calling that particular member. The :: operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator. When you use :: you have to be referencing members that are defined. When using . you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for . while it does for :: . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/43134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4142/"
]
} |
43,157 | I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer). So, given an InputStream in and an OutputStream out , is there a simpler way to write the following? byte[] buffer = new byte[1024];int len = in.read(buffer);while (len != -1) { out.write(buffer, 0, len); len = in.read(buffer);} | As WMR mentioned, org.apache.commons.io.IOUtils from Apache has a method called copy(InputStream,OutputStream) which does exactly what you're looking for. So, you have: InputStream in;OutputStream out;IOUtils.copy(in,out);in.close();out.close(); ...in your code. Is there a reason you're avoiding IOUtils ? | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/43157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
43,180 | One thing I've always wanted to do is develop my very own operating system (not necessarily fancy like Linux or Windows, but better than a simple boot loader which I've already done). I'm having a hard time finding resources/guides that take you past writing a simple "Hello World" OS. I know lots of people will probably recommend I look at Linux or BSD; but the code base for systems like that is (presumably) so big that I wouldn't know where to start. Any suggestions? Update: To make it easier for people who land on this post through Google here are some OS development resources: Writing Your Own Operating System (Thanks Adam) Linux From Scratch (Thanks John) SharpOS (C# Operating System) (Thanks lomaxx) Minix3 and Minix2 (Thanks Mike) OS Dev Wiki and Forums (Thanks Steve) BonaFide (Thanks Steve) Bran (Thanks Steve) Roll your own toy UNIX-clone OS (Thanks Steve) Broken Thorn OS Development Series Other resources: I found a nice resource named MikeOS , "MikeOS is a learning tool to demonstrate how simple OSes work. It uses 16-bit real mode for BIOS access, so that it doesn't need complex drivers" Updated 11/14/08 I found some resources at Freebyte's Guide to...Free and non-free Operating Systems that links to kits such as OSKit and ExOS library. These seem super useful in getting started in OS development. Updated 2/23/09 Ric Tokyo recommended nanoos in this question . Nanoos is an OS written in C++. Updated 3/9/09 Dinah provided some useful Stack Overflow discussion of aspiring OS developers: Roadblocks in creating a custom operating system discusses what pitfalls you might encounter while developing an OSand OS Development is a more general discussion. Updated 7/9/09 LB provided a link to the Pintos Project , an education OS designed for students learning OS development. Updated 7/27/09 (Still going strong!) I stumbled upon an online OS course from Berkley featuring 23 lectures. TomOS is a fork of MikeOS that includes a little memory manager and mouse support. As MikeOS, it is designed to be an educational project. It is written in NASM assembler. Updated 8/4/09 I found the slides and other materials to go along with the online Berkeley lectures listed above. Updated 8/23/09 All questions tagged osdev on stackoverflow OS/161 is an academic OS written in c that runs on a simulated hardware. This OS is similar in Nachos. Thanks Novelocrat! tangurena recommends http://en.wikipedia.org/wiki/MicroC/OS-II , an OS designed for embedded systems. There is a companion book as well. Linux Kernel Development by Robert Love is suggested by Anders. It is a "widely acclaimed insider's look at the Linux kernel." Updated 9/18/2009 Thanks Tim S. Van Haren for telling us about Cosmos , an OS written entirely in c#. tgiphil tells us about Managed Operating System Alliance (MOSA) Framework , "a set of tools, specifications and source code to foster development of managed operating systems based on the Common Intermediate Language." Update 9/24/2009 Steve found a couple resources for development on windows using Visual Studio, check out BrokenThorn's guide setup with VS 2005 or OSDev's VS Section . Updated 9/5/2012 kerneltrap.org is no longer available. The linux kernel v0.01 is available from kernel.org Updated 12/21/2012 A basic OS development tutorial designed to be a semester's project. It guides you through to build an OS with basic components. Very good start for beginners. Related paper . Thanks Srujan! Updated 11/15/2013 Writing a Simple Operating System From Scratch . Thanks James Moore! Updated 12/8/2013 How to make a computer operating system Thanks ddtoni! Updated 3/18/2014 ToAruOS an OS built mostly from scratch, including GUI Updated Sept 12 2016 Writing your own Toy Operating System Updated Dec 10 2016 Writing a Simple Operating System —from Scratch (thank you @Tyler C) | There are a lot of links after this brief overview of what is involved in writing an OS for the X86 platform. The link that appears to be most promising (www.nondot.org/sabre/os/articles) is no longer available, so you'll need to poke through the Archive.org version to read it. At the end of the day the bootloader takes the machine code of the kernel, puts it in memory, and jumps to it. You can put any machine code in the kernel that you want, but most C programs expect an OS so you'll need to tell your compiler that it won't have all that, or the bootloader has to create some of it. The kernel then does all the heavy lifting, and I suspect it's the example kernel you want. But there's a long way to go between having a kernel that says, "Hello world" to having a kernel that loads a command interpretor, provides disk services, and loads and manages programs. You might want to consider subscribing to ACM to get access to their older literature - there are lots of articles in the late 80's and early 90's in early computing magazines about how to create alternative OSs . There are likely books that are out of print from this era as well. You might be able to get the same information for free by looking up the indexes of those magazines (which are available on that site - click "index" near the magazine name) and then asking around for people with a copy. Lastly, I know that usenet is dead (for so sayeth the prophets of internet doom) but you'll find that many of the craggy old experts from that era still live there. You should search google groups (they have dejanews's old repository) and I expect you'll find many people asking the same questions a decade or 1.5 ago that you're asking now. You may even run across Linus Torvalds' many queries for help as he was developing linux originally. If searches don't bring anything up, ask in the appropriate newsgroup (probably starts with comp.arch, but search for ones with OS in the name). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/43180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050/"
]
} |
43,218 | I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL. However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep. Does anybody have any ideas for resolving this? | If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work. You could also do this in your Page_Load (In your masterpage): Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js")) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
} |
43,224 | Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you) | OK, here's my best pseudo math: The equation for your line is: Y = a + bX Where: b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n) a = sum(y)/n - b(sum(x)/n) Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :) ... and now with added Sigma b = (Σ(xy) - (ΣxΣy)/n) / (Σ(x^2) - (Σx)^2/n) a = (Σy)/n - b((Σx)/n) Where Σ(xy) is the sum of all x*y etc. and n is the number of points | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2646/"
]
} |
43,249 | Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure? For instance, I want departments 1, 2, 5, 7, 20 returned by my stored procedure. In the past, I have passed in a comma delimited list of ids, like the below code, but feel really dirty doing it. SQL Server 2005 is my only applicable limitation I think. create procedure getDepartments @DepartmentIds varchar(max)as declare @Sql varchar(max) select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')' exec(@Sql) | Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: Arrays and Lists in SQL Server . There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons. Table-Valued Parameters . SQL Server 2008 and higher only, and probably the closest to a universal "best" approach. The Iterative Method . Pass a delimited string and loop through it. Using the CLR . SQL Server 2005 and higher from .NET languages only. XML . Very good for inserting many rows; may be overkill for SELECTs. Table of Numbers . Higher performance/complexity than simple iterative method. Fixed-length Elements . Fixed length improves speed over the delimited string Function of Numbers . Variations of Table of Numbers and fixed-length where the number are generated in a function rather than taken from a table. Recursive Common Table Expression (CTE). SQL Server 2005 and higher, still not too complex and higher performance than iterative method. Dynamic SQL . Can be slow and has security implications. Passing the List as Many Parameters . Tedious and error prone, but simple. Really Slow Methods . Methods that uses charindex, patindex or LIKE. I really can't recommend enough to read the article to learn about the tradeoffs among all these options. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/43249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865/"
]
} |
43,253 | What is the best way to measure exception handling overhead/performance in C++? Please give standalone code samples. I'm targeting Microsoft Visual C++ 2008 and gcc. I need to get results from the following cases: Overhead when there are no try/catch blocks Overhead when there are try/catch blocks but exceptions are not thrown Overhead when exceptions are thrown | Section 5.4 of the draft Technical Report on C++ Performance is entirely devoted to the overhead of exceptions. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2948/"
]
} |
43,289 | How can I do this fast? Sure I can do this: static bool ByteArrayCompare(byte[] a1, byte[] a2){ if (a1.Length != a2.Length) return false; for (int i=0; i<a1.Length; i++) if (a1[i]!=a2[i]) return false; return true;} But I'm looking for either a BCL function or some highly optimized proven way to do this. java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2); works nicely, but it doesn't look like that would work for x64. Note my super-fast answer here . | You can use Enumerable.SequenceEqual method. using System;using System.Linq;...var a1 = new int[] { 1, 2, 3};var a2 = new int[] { 1, 2, 3};var a3 = new int[] { 1, 2, 4};var x = a1.SequenceEqual(a2); // truevar y = a1.SequenceEqual(a3); // false If you can't use .NET 3.5 for some reason, your method is OK. Compiler\run-time environment will optimize your loop so you don't need to worry about performance. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/43289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489/"
]
} |
43,290 | In Django's template language, you can use {% url [viewname] [args] %} to generate a URL to a specific view with parameters. How can you programatically do the same in Python code? What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language. | If you need to use something similar to the {% url %} template tag in your code, Django provides the django.core.urlresolvers.reverse() . The reverse function has the following signature: reverse(viewname, urlconf=None, args=None, kwargs=None) https://docs.djangoproject.com/en/dev/ref/urlresolvers/ At the time of this edit the import is django.urls import reverse | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/43290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
]
} |
43,315 | Using PyObjC , you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how? | Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift. There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term. That said, Objective-C and Swift really are not too scary... 2016 edit Javascript with NativeScript framework is available to use now. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/43315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
]
} |
43,320 | One of the things that get me thoroughly confused is the use of session.Flush ,in conjunction with session.Commit , and session.Close . Sometimes session.Close works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs. But sometimes I really get stymied by the logic behind session.Flush . I have seen examples where you have a session.SaveOrUpdate() followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error. Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer. | Briefly: Always use transactions Don't use Close() , instead wrap your calls on an ISession inside a using statement or manage the lifecycle of your ISession somewhere else . From the documentation : From time to time the ISession will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points from some invocations of Find() or Enumerable() from NHibernate.ITransaction.Commit() from ISession.Flush() The SQL statements are issued in the following order all entity insertions, in the same order the corresponding objects were saved using ISession.Save() all entity updates all collection deletions all collection element deletions, updates and insertions all collection insertions all entity deletions, in the same order the corresponding objects were deleted using ISession.Delete() (An exception is that objects using native ID generation are inserted when they are saved.) Except when you explicity Flush() , there are absolutely no guarantees about when the Session executes the ADO.NET calls, only the order in which they are executed . However, NHibernate does guarantee that the ISession.Find(..) methods will never return stale data; nor will they return the wrong data. It is possible to change the default behavior so that flush occurs less frequently. The FlushMode class defines three different modes: only flush at commit time (and only when the NHibernate ITransaction API is used), flush automatically using the explained routine, or never flush unless Flush() is called explicitly. The last mode is useful for long running units of work, where an ISession is kept open and disconnected for a long time. ... Also refer to this section : Ending a session involves four distinct phases: flush the session commit the transaction close the session handle exceptions Flushing the Session If you happen to be using the ITransaction API, you don't need to worry about this step. It will be performed implicitly when the transaction is committed. Otherwise you should call ISession.Flush() to ensure that all changes are synchronized with the database. Committing the database transaction If you are using the NHibernate ITransaction API, this looks like: tx.Commit(); // flush the session and commit the transaction If you are managing ADO.NET transactions yourself you should manually Commit() the ADO.NET transaction. sess.Flush();currentTransaction.Commit(); If you decide not to commit your changes: tx.Rollback(); // rollback the transaction or: currentTransaction.Rollback(); If you rollback the transaction you should immediately close and discard the current session to ensure that NHibernate's internal state is consistent. Closing the ISession A call to ISession.Close() marks the end of a session. The main implication of Close() is that the ADO.NET connection will be relinquished by the session. tx.Commit();sess.Close();sess.Flush();currentTransaction.Commit();sess.Close(); If you provided your own connection, Close() returns a reference to it, so you can manually close it or return it to the pool. Otherwise Close() returns it to the pool. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/43320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372/"
]
} |
43,321 | The default shell in Mac OS X is bash , which I'm generally happy to be using. I just take it for granted. It would be really nice if it auto-completed more stuff , though, and I've heard good things about zsh in this regard. But I don't really have the inclination to spend hours fiddling with settings to improve my command line usage by a tiny amount, since my life on the command line isn't that bad. (As I understand it, bash can also be configured to auto-complete more cleverly. It's the configuring I'm not all that keen on.) Will switching to zsh , even in a small number cases, make my life easier? Or is it only a better shell if you put in the time to learn why it's better? (Examples would be nice, too :) ) @ Rodney Amato &@ Vulcan Eager give two good reasons to respectively stick to bash and switch to zsh . Looks like I'll have to investigate both! Oh well :) Is there anyone with an opinion from both sides of the argument? | For casual use you are probably better off sticking with bash and just installing bash completion. Installing it is pretty easy, grab the bash-completion-20060301.tar.gz from http://www.caliban.org/bash/index.shtml#completion and extract it with tar -xzvf bash-completion-20060301.tar.gz then copy the bash_completion/bash_completion file to /etc with sudo cp bash_completion/bash_completion /etc which will prompt you for your password. You probably will want to make a /etc/bash_completion.d directory for any additional completion scripts (for instance I have the git completion script in there). Once this is done the last step is to make sure the .bash_profile file in your home directory has if [ -f /etc/bash_completion ]; then . /etc/bash_completion fi in it to load the completion file when you login. To test it just open a new terminal, and try completing on cvs and it should show you the cvs options in the list of completions. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/43321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
]
} |
43,322 | Plug-in systems in C++ are hard because the ABI is not properly defined, and each compiler (or version thereof) follows its own rules. However, COM on Windows shows that it's possible to create a minimal plug-in system that allows programmers with different compilers to create plug-ins for a host application using a simple interface. Let's be practical, and leave the C++ standard, which is not very helpful in this respect, aside for a minute. If I want to write an app for Windows and Mac (and optionally Linux) that supports C++ plug-ins, and if I want to give plug-in authors a reasonably large choice of compilers (say less than 2 year old versions of Visual C++, GCC or Intel's C++ compiler), what features of C++ could I count on? Of course, I assume that plug-ins would be written for a specific platform. Off the top of my head, here are some C++ features I can think of, with what I think is the answer: vtable layout, to use objects through abstract classes? (yes) built-in types, pointers? (yes) structs, unions? (yes) exceptions? (no) extern "C" functions? (yes) stdcall non-extern "C" functions with built-in parameter types? (yes) non-stdcall non-extern "C" functions with user-defined parameter types? (no) I would appreciate any experience you have in that area that you could share. If you know of any moderately successful app that has a C++ plug-in system, that's cool too. Carl | Dr Dobb's Journal has an article Building Your Own Plugin Framework: Part 1 which is pretty good reading on the subject. It is the start of a series of articles which covers the architecture, development, and deployment of a C/C++ cross-platform plugin framework. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/43322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2095/"
]
} |
43,427 | Say I have a site on http://example.com . I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words http://example.com & http://example.com/ should be allowed, but http://example.com/anything and http://example.com/someendpoint.aspx should be blocked. Further it would be great if I can allow certain query strings to passthrough to the home page: http://example.com?okparam=true but not http://example.com?anythingbutokparam=true | So after some research, here is what I found - a solution acceptable by the major search providers: google , yahoo & msn (I could on find a validator here) : User-Agent: *Disallow: /*Allow: /?okparam=Allow: /$ The trick is using the $ to mark the end of URL. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/43427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2892/"
]
} |
43,500 | I would like to compare the contents of a couple of collections in my Equals method. I have a Dictionary and an IList. Is there a built-in method to do this? Edited:I want to compare two Dictionaries and two ILists, so I think what equality means is clear - if the two dictionaries contain the same keys mapped to the same values, then they're equal. | Enumerable.SequenceEqual Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer(T). You can't directly compare the list & the dictionary, but you could compare the list of values from the Dictionary with the list | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/43500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2348/"
]
} |
43,511 | I have some classes layed out like this class A{ public virtual void Render() { }}class B : A{ public override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { }}class C : B{ protected override void SpecialRender() { // Do some cool stuff }} Is it possible to prevent the C class from overriding the Render method, without breaking the following code? A obj = new C();obj.Render(); // calls B.Render -> c.SpecialRender | You can seal individual methods to prevent them from being overridable: public sealed override void Render(){ // Prepare the object for rendering SpecialRender(); // Do some cleanup } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/43511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3602/"
]
} |
43,569 | How to restrict the maximum number of characters that can be entered into an HTML <textarea> ? I'm looking for a cross-browser solution. | The TEXTAREA tag does not have a MAXLENGTH attribute the way that an INPUT tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be typed into a TEXTAREA tag is: <textarea onKeyPress="return ( this.value.length < 50 );"></textarea> Note: onKeyPress , is going to prevent any button press, any button including the backspace key. This works because the Boolean expression compares the field's lengthbefore the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more, false if not. Returning false from most events cancels the default action.So if the current length is already 50 (or more), the handler returns false,the KeyPress action is cancelled, and the character is not added. One fly in the ointment is the possibility of pasting into a TEXTAREA ,which does not cause the KeyPress event to fire, circumventing this check.Internet Explorer 5+ contains an onPaste event whose handler can contain thecheck. However, note that you must also take into account how manycharacters are waiting in the clipboard to know if the total is going totake you over the limit or not. Fortunately, IE also contains a clipboardobject from the window object. 1 Thus: <textarea onKeyPress="return ( this.value.length < 50 );"onPaste="return (( this.value.length +window.clipboardData.getData('Text').length) < 50 );"></textarea> Again, the onPaste event and clipboardData object are IE 5+ only. For a cross-browser solution, you will just have to use an OnChange or OnBlur handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly. Source Also, there is another way here, including a finished script you could include in your page: http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512/"
]
} |
43,580 | Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response. Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type. How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. Does the browser add this information when posting the file to the web page? Is there a neat python library for finding this information? A WebService or (even better) a downloadable database? | The python-magic method suggested by toivotuo is outdated. Python-magic's current trunk is at Github and based on the readme there, finding the MIME-type, is done like this. # For MIME typesimport magicmime = magic.Magic(mime=True)mime.from_file("testdata/test.pdf") # 'application/pdf' | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/43580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
]
} |
43,589 | I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this? | $first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));$last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year)); See date() in PHP documentation. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/43589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
43,632 | I've seen lots of examples of making an entire regular expression case-insensitive. What I'm wondering about is having just part of the expression be case-insensitive. For example, let's say I have a string like this: fooFOOfOoFoOBARBARbarbarbAr What if I want to match all occurrences of "foo" regardless of case but I only want to match the upper-case "BAR"s? The ideal solution would be something that works across regex flavors but I'm interested in hearing language-specific ones as well (Thanks Espo ) Edit The link Espo provided was very helpful. There's a good example in there about turning modifiers on and off within the expression. For my contrived example, I can do something like this: (?i)foo*(?-i)|BAR which makes the match case-insensitive for just the foo portion of the match. That seemed to work in most regex implementations except Javascript, Python, and a few others (as Espo mentioned). The big ones that I was wondering about (Perl, PHP, .NET) all support inline mode changes. | Perl lets you make part of your regular expression case-insensitive by using the (?i:) pattern modifier. Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?ism) in the middle of the regex, the modifier only applies to the part of the regex to the right of the modifier. You can turn off modes by preceding them with a minus sign. All modes after the minus sign will be turned off. E.g. (?i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode. Not all regex flavors support this. JavaScript and Python apply all mode modifiers to the entire regular expression. They don't support the (?-ismx) syntax, since turning off an option is pointless when mode modifiers apply to the whole regular expressions. All options are off by default. You can quickly test how the regex flavor you're using handles mode modifiers. The regex (?i)te(?-i)st should match test and TEst, but not teST or TEST. Source | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/43632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
} |
43,643 | Given the code bellow, how do I style the radio buttons to be next to the labels and style the label of the selected radio button differently than the other labels? <link href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="stylesheet"><link href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="stylesheet"><div class="input radio"> <fieldset> <legend>What color is the sky?</legend> <input type="hidden" name="color" value="" id="SubmitQuestion" /> <input type="radio" name="color" id="SubmitQuestion1" value="1" /> <label for="SubmitQuestion1">A strange radient green.</label> <input type="radio" name="color" id="SubmitQuestion2" value="2" /> <label for="SubmitQuestion2">A dark gloomy orange</label> <input type="radio" name="color" id="SubmitQuestion3" value="3" /> <label for="SubmitQuestion3">A perfect glittering blue</label> </fieldset></div> Also let me state that I use the yui css styles as base. If you are not familir with them, they can be found here: reset-fonts-grids.css base-min.css Documentation for them both here : Yahoo! UI Library @pkaeding: Thanks. I tried some floating both thing that just looked messed up. The styling active radio button seemed to be doable with some input[type=radio]:active nomination on a google search, but I didnt get it to work properly. So the question I guess is more: Is this possible on all of todays modern browsers, and if not, what is the minimal JS needed? | The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part. Getting the Label Near the Radio Button I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float: territory): Use <br />s to split the options apart and some CSS to vertically align them: <style type='text/css'> .input input { width: 20px; }</style><div class="input radio"> <fieldset> <legend>What color is the sky?</legend> <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" /> <label for="SubmitQuestion1">A strange radient green.</label> <br /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" /> <label for="SubmitQuestion2">A dark gloomy orange</label> <br /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" /> <label for="SubmitQuestion3">A perfect glittering blue</label> </fieldset></div> Follow A List Apart 's article: Prettier Accessible Forms Applying a Style to the Currently Selected Label + Radio Button Styling the <label> is why you'll need to resort to Javascript. A library like jQuery is perfect for this: <style type='text/css'> .input label.focused { background-color: #EEEEEE; font-style: italic; }</style><script type='text/javascript' src='jquery.js'></script><script type='text/javascript'> $(document).ready(function() { $('.input :radio').focus(updateSelectedStyle); $('.input :radio').blur(updateSelectedStyle); $('.input :radio').change(updateSelectedStyle); }) function updateSelectedStyle() { $('.input :radio').removeClass('focused').next().removeClass('focused'); $('.input :radio:checked').addClass('focused').next().addClass('focused'); }</script> The focus and blur hooks are needed to make this work in IE. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/43643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4013/"
]
} |
43,672 | I think that java executables (jar files) are trivial to decompile and get the source code. What about other languages? .net and all? Which all languages can compile only to a decompile-able code? | In general, languages like Java, C#, and VB.NET are relatively easy to decompile because they are compiled to an intermediary language, not pure machine language. In their IL form, they retain more metadata than C code does when compiled to machine language. Technically you aren't getting the original source code out, but a variation on the source code that, when compiled, will give you the compiled code back. It isn't identical to the source code, as things like comments, annotations, and compiler directives usually aren't carried forward into the compiled code. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
43,711 | I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value? | My preference is to have classes that use time actually rely on an interface, such as interface IClock{ DateTime Now { get; } } With a concrete implementation class SystemClock: IClock{ DateTime Now { get { return DateTime.Now; } }} Then if you want, you can provide any other kind of clock you want for testing, such as class StaticClock: IClock{ DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } }} There may be some overhead in providing the clock to the class that relies on it, but that could be handled by any number of dependency injection solutions (using an Inversion of Control container, plain old constructor/setter injection, or even a Static Gateway Pattern ). Other mechanisms of delivering an object or method that provides desired times also work, but I think the key thing is to avoid resetting the system clock, as that's just going to introduce pain on other levels. Also, using DateTime.Now and including it in your calculations doesn't just not feel right - it robs you of the ability to test particular times, for example if you discover a bug that only happens near a midnight boundary, or on Tuesdays. Using the current time won't allow you to test those scenarios. Or at least not whenever you want. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/43711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404/"
]
} |
43,743 | I found some wild remarks that ASP.NET MVC is 30x faster than ASP.NET WebForms. What real performance difference is there, has this been measured and what are the performance benefits. This is to help me consider moving from ASP.NET WebForms to ASP.NET MVC. | We haven't performed the type of scalability and perf tests necessary to come up with any conclusions. I think ScottGu may have been discussing potential perf targets. As we move towards Beta and RTM, we will internally be doing more perf testing. However, I'm not sure what our policy is on publishing results of perf tests. In any case, any such tests really need to consider real world applications... | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/43743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
43,765 | For my day job, I live in Emacs. Utterly. I also have become pretty dependent on CScope to help me find things in the code. Normally, I have 2 windows in a split (C-x 3): alt text http://bitthicket.com/files/emacs-2split.JPG And I use the right window for code buffers and the left window for the CScope search buffer. When you do a CScope search and select a result, it automatically updates the right-side window to show the buffer referred to by the result. This is all well and good, except that it causes me to lose my place in some other buffer that I was studying. Sometimes this is no biggie, because [C-s u] gets me back to where I was. What would be better, though, is to have 3 split windows like this ([C-x 2] in the left window): alt text http://bitthicket.com/files/emacs-3split.jpg And have the bottom left window contain the CScope search buffer, and the top left window be the only buffer that CScope ever updates. That way, I can see my CScope searches and navigate around the code without losing the buffer I'm focused on. Anyone know how I can do that? | Put this in your .emacs file: ;; Toggle window dedication(defun toggle-window-dedicated ()"Toggle whether the current active window is dedicated or not"(interactive)(message (if (let (window (get-buffer-window (current-buffer))) (set-window-dedicated-p window (not (window-dedicated-p window)))) "Window '%s' is dedicated" "Window '%s' is normal") (current-buffer))) Then bind it to some key - I use the Pause key: (global-set-key [pause] 'toggle-window-dedicated) And then use it to "dedicate" the window you want locked. then cscope can only open files from its result window in some OTHER window. Works a charm. I specifically use it for exactly this purpose - keeping one source file always on screen, while using cscope in a second buffer/window, and looking at cscope results in a third. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/43765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
]
} |
43,775 | Can you please tell me how much is (-2) % 5 ?According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though. | By the way: most programming languages would disagree with Python and give the result -2 . Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of a and b is the (strictly positive) rest r of the division of a / b . More precisely, 0 <= r < b by definition. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876/"
]
} |
43,777 | I recently asked a question about what I called "method calls". The answer referred to "messages". As a self-taught hobby programmer trying to phrase questions that don't make me look like an idiot, I'm realizing that the terminology that I use reveals a lot about how I learned to program. Is there a distinction between the various terms for methods/messages/etc. in OO programming? Is this a difference that comes from different programming languages using different terminology to describe similar concepts? I seem to remember that in pre-OO languages, a distinction would sometimes be made between "subroutines" and "functions" based on whether a return value was expected, but even then, was this a language-by-language distinction? | I've found this to be a language and programming-paradigm thing. One paradigm — OOP — refers to objects with member methods, which conceptually are how you send messages to those objects (this view is reflected in UML, for example). Another paradigm — functional — may or may not involve classes of objects, but functions are the atomic unit of work. In structured programming, you had sub-routines (notice that the prefix "sub" implies structure). In imperative programming (which overlaps with structured quite a lot, but a slightly different way of looking at things), you have a more formulaic view of the world, and so 'functions' represent some operation (often mathematical). All you have to do to not sound like a rube is to use the terminology used by the language reference for the language you're using. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4142/"
]
} |
43,778 | Update: Check out this follow-up question: Gem Update on Windows - is it broken? On Windows, when I do this: gem install sqlite3-ruby I get the following error: Building native extensions. This could take a while...ERROR: Error installing sqlite3-ruby: ERROR: Failed to build gem native extension.c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32checking for fdatasync() in rt.lib... nochecking for sqlite3.h... nonmake'nmake' is not recognized as an internal or external command,operable program or batch file.Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection.Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out Same thing happens with the hpricot gem . I seem to remember these gems installed just fine on < 1.0 gems, but now I'm on 1.2.0, things have gone screwy. I have also tried this: gem install sqlite3-ruby --platform Win32 Needless to say, this doesn't work either (same error) Does anyone know what is going on here and how to fix this? Update: Check out this follow-up question: Gem Update on Windows - is it broken? | As Nathan suggests, this does appear to be related to the fact that the latest versions of the sqlite3-ruby and hpricot gems don't appear to have Windows versions. Here's what to do when faced with this situation (note, the name of the gem is automatically wildcarded, so you can type just sql and get a list of all gems beginning with sql ): $ gem list --remote --all sqlite*** REMOTE GEMS ***sqlite (2.0.1, 2.0.0, 1.3.1, 1.3.0, 1.2.9.1, 1.2.0, 1.1.3, 1.1.2, 1.1.1, 1.1)sqlite-ruby (2.2.3, 2.2.2, 2.2.1, 2.2.0, 2.1.0, 2.0.3, 2.0.2)sqlite3-ruby (1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0, 1.1.0, 1.0.1, 1.0.0, 0.9.0, 0.6.0, 0.5.0) Then you can choose the version you would like to install: gem install sqlite3-ruby -v 1.2.3 To successfully install hpricot, I did this: gem install hpricot -v 0.6 Annoyingly, doing a gem update tries to update the gems to their latest, broken-on-Windows, versions. When the update routine encounters an error, it ditches you out of the whole process. There's a (hacky) solution to this problem here . So, is this issue a bug in gems? Should gems not automatically detect the platform and install the latest compatible version? | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/43778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
]
} |
43,802 | I have a String representation of a date that I need to create a Date or Calendar object from. I've looked through Date and Calendar APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution? | In brief: DateFormat formatter = new SimpleDateFormat("MM/dd/yy");try { Date date = formatter.parse("01/29/02");} catch (ParseException e) { e.printStackTrace();} See SimpleDateFormat javadoc for more. And to turn it into a Calendar , do: Calendar calendar = Calendar.getInstance();calendar.setTime(date); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/43802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
]
} |
43,808 | I have a distributed Java application running on 5 application servers. The servers all use the same Oracle 9i database running on a 6th machine. The application need to prefetch a batch of 100 IDs from a sequence. It's relatively easy to do in a single-threaded, non-distributed environment, you can just issue these queries: SELECT seq.nextval FROM dual;ALTER SEQUENCE seq INCREMENT BY 100;SELECT seq.nextval FROM dual; The first select fetches the first sequence ID that the application can use, the second select returns the last one that can be used. Things get way more interesting in a multithreaded environment. You can't be sure that before the second select another thread doesn't increase the sequence by 100 again. This issue can be solved by synchronizing the access on the Java side - you only let one thread begin fetching the IDs at one time. The situation becomes really hard when you can't synchronize because parts of the application doesn't run on the same JVM, not even on the same physical machine. I found some references on forums that others have problems with solving this problem too, but none of the answers are really working not to mention being reasonable. Can the community provide a solution for this problem? Some more information: I can't really play with the transaction isolation levels. I use JPA and the change would affect the entire application, not only the prefetching queries and that's not acceptable for me. On PostgreSQL I could do the following: SELECT setval('seq', NEXTVAL('seq') + n - 1) The solution by Matthew works when you can use a fixed increment value (which is perfectly acceptable in my case). However is there a solution when you don't want to fix the size of the increment, but want to adjust it dynamically? | Why not just have the sequence as increment by 100 all the time? each "nextval" gives you 100 sequence numbers to work with SQL> create sequence so_test start with 100 increment by 100 nocache;Sequence created.SQL> select so_test.nextval - 99 as first_seq, so_test.currval as last_seq from dual; FIRST_SEQ LAST_SEQ---------- ---------- 1 100SQL> / FIRST_SEQ LAST_SEQ---------- ---------- 101 200SQL> / FIRST_SEQ LAST_SEQ---------- ---------- 201 300SQL> A note on your example.. Watch out for DDL.. It will produce an implicit commit Example of commit produced by DDL SQL> select * from xx;no rows selectedSQL> insert into xx values ('x');1 row created.SQL> alter sequence so_test increment by 100;Sequence altered.SQL> rollback;Rollback complete.SQL> select * from xx;Y-----xSQL> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686/"
]
} |
43,823 | Does anyone have any experience with how well web services build with Microsoft's WCF will scale to a large number of users? The level I'm thinking of is in the region of 1000+ client users connecting to a collection of WCF services providing the business logic for our application, and these talking to a database - similar to a traditional 3-tier architecture. Are there any particular gotchas that have slowed down performance, or any design lessons learnt that have enabled this level of scalability? | To ensure your WCF application can scale to the desired level I think you might need to tweak your thinking about the stats your services have to meet. You mention servicing "1000+ client users" but to gauge if your services can perform at that level you'll also need to have some estimated usage figures, which will help you calculate some simpler stats such as the number of requests per second your app needs to handle. Having just finished working on a WCF project we managed to get 400 requests per second on our test hardware, which combined with our expected usage pattern of each user making 300 requests a day indicated we could handle an average of 100,000 users a day (assuming a flat usage graph across the day). In addition, since it's fairly common to make the WCF service code stateless, it's pretty easy to scale out the actual WCF code by adding additional boxes, which means the overall performance of your system is much more likely to be limited by your business logic and persistence layer than it is by WCF. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078/"
]
} |
43,866 | Why do I need two of them? When I have to use one or another? | Quote by @DAC In short: SID = the unique name ofyour DB, ServiceName = the alias usedwhen connecting Not strictly true. SID = unique name of the INSTANCE (eg the oracle process running on the machine). Oracle considers the "Database" to be the files. Service Name = alias to an INSTANCE (or many instances). The main purpose of this is if you are running a cluster, the client can say "connect me to SALES.acme.com ", the DBA can on the fly change the number of instances which are available to SALES.acme.com requests, or even move SALES.acme.com to a completely different database without the client needing to change any settings. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/43866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4052/"
]
} |
43,870 | I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table: ID COMPANY_ID EMPLOYEE1 1 Anna2 1 Bill3 2 Carol4 2 Dave and I wanted to group by company_id to get something like: COMPANY_ID EMPLOYEE1 Anna, Bill2 Carol, Dave There is a built-in function in mySQL to do this group_concat | PostgreSQL 9.0 or later: Modern Postgres (since 2010) has the string_agg(expression, delimiter) function which will do exactly what the asker was looking for: SELECT company_id, string_agg(employee, ', ')FROM mytableGROUP BY company_id; Postgres 9 also added the ability to specify an ORDER BY clause in any aggregate expression ; otherwise you have to order all your results or deal with an undefined order. So you can now write: SELECT company_id, string_agg(employee, ', ' ORDER BY employee)FROM mytableGROUP BY company_id; PostgreSQL 8.4.x: PostgreSQL 8.4 (in 2009) introduced the aggregate function array_agg(expression) which collects the values in an array. Then array_to_string() can be used to give the desired result: SELECT company_id, array_to_string(array_agg(employee), ', ')FROM mytableGROUP BY company_id; PostgreSQL 8.3.x and older: When this question was originally posed, there was no built-in aggregate function to concatenate strings. The simplest custom implementation ( suggested by Vajda Gabo in this mailing list post , among many others) is to use the built-in textcat function (which lies behind the || operator): CREATE AGGREGATE textcat_all( basetype = text, sfunc = textcat, stype = text, initcond = ''); Here is the CREATE AGGREGATE documentation. This simply glues all the strings together, with no separator. In order to get a ", " inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the "textcat" above. Here is one I put together and tested on 8.3.12: CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$ BEGIN IF acc IS NULL OR acc = '' THEN RETURN instr; ELSE RETURN acc || ', ' || instr; END IF; END;$$ LANGUAGE plpgsql; This version will output a comma even if the value in the row is null or empty, so you get output like this: a, b, c, , e, , g If you would prefer to remove extra commas to output this: a, b, c, e, g Then add an ELSIF check to the function like this: CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$ BEGIN IF acc IS NULL OR acc = '' THEN RETURN instr; ELSIF instr IS NULL OR instr = '' THEN RETURN acc; ELSE RETURN acc || ', ' || instr; END IF; END;$$ LANGUAGE plpgsql; | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/43870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4045/"
]
} |
43,890 | Original Question I want to be able to generate a new (fully valid) MP3 file from an existing MP3 file to be used as a preview -- try-before-you-buy style. The new file should only contain the first n seconds of the track. Now, I know I could just "chop the stream" at n seconds (calculating from the bitrate and header size) when delivering the file, but this is a bit dirty and a real PITA on a VBR track. I'd like to be able to generate a proper MP3 file. Anyone any ideas? Answers Both mp3split and ffmpeg are both good solutions. I chose ffmpeg as it is commonly installed on linux servers and is also easily available for windows . Here's some more good command line parameters for generating previews with ffmpeg -t <seconds> chop after specified number of seconds -y force file overwrite -ab <bitrate> set bitrate e.g. -ab 96k -ar <rate Hz> set sampling rate e.g. -ar 22050 for 22.05kHz -map_meta_data <outfile>:<infile> copy track metadata from infile to outfile instead of setting -ab and -ar, you can copy the original track settings, as Tim Farley suggests, with: -acodec copy | I also recommend ffmpeg, but the command line suggested by John Boker has an unintended side effect: it re-encodes the file to the default bitrate (which is 64 kb/s in the version I have here at least). This might give your customers a false impression of the quality of your sound files, and it also takes longer to do. Here's a command line that will slice to 30 seconds without transcoding: ffmpeg -t 30 -i inputfile.mp3 -acodec copy outputfile.mp3 The -acodec switch tells ffmpeg to use the special "copy" codec which does not transcode. It is lightning fast. NOTE: the command was updated based on comment from Oben Sonne | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/43890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
]
} |
43,926 | A .container can contain many .components , and .components themselves can contain .containers (which in turn can contain .components etc. etc.) Given code like this: $(".container .component").each(function(){ $(".container", this).css('border', '1px solid #f00');}); What do I need to add to the line within the braces to select only the nested .containers that have their width in CSS set to auto ? I'm sure it's something simple, but I haven't really used jQuery all that much. | $(".container .component").each(function(){ $(".container", this).each(function() { if($(this).css('width') == 'auto') { $(this).css('border', '1px solid #f00'); } });}); Similar to the other answer but since components can also have multiple containers, also needs the .each() check in here too for the width. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2268/"
]
} |
43,955 | Is it possible to modify the title of the message box the confirm() function opens in JavaScript? I could create a modal popup box, but I would like to do this as minimalistic as possible.I would like to do something like this: confirm("This is the content of the message box", "Modified title"); The default title in Internet Explorer is "Windows Internet Explorer" and in Firefox it's "[JavaScript-program]." Not very informative. Though I can understand from a browser security stand point that you shouldn't be able to do this. | This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window. There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/43955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2241/"
]
} |
43,970 | I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address. We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall. So how do I configure sendmail to send all mail through mailrelay.example.com? Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying. | @eli: modifying sendmail.cf directly is not usually recommended, since it is generated by the macro compiler. Edit /etc/mail/sendmail.mc to include the line: define(`SMART_HOST',`mailrelay.example.com')dnl After changing the sendmail.mc macro configuration file, it must be recompiledto produce the sendmail configuration file. # m4 /etc/mail/sendmail.mc > /etc/sendmail.cf And restart the sendmail service (Linux): # /etc/init.d/sendmail restart As well as setting the smarthost, you might want to also disable name resolution configuration and possibly shift your sendmail to non-standard port, or disable daemon mode. Disable Name Resolution Servers that are within fire-walled networks or using Network AddressTranslation (NAT) may not have DNS or NIS services available. This createsa problem for sendmail, since it will use DNS by default, and if it is notavailable you will see messages like this in mailq: host map: lookup (mydomain.com): deferred) Unless you are prepared to setup an appropriate DNS or NIS service thatsendmail can use, in this situation you will typically configure nameresolution to be done using the /etc/hosts file. This is done by enablinga 'service.switch' file and specifying resolution by file, as follows: 1: Enable service.switch for sendmailEdit /etc/mail/sendmail.mc to include the lines: define(`confSERVICE_SWITCH_FILE',`/etc/mail/service.switch')dnl 2: Configure service.switch for filesCreate or modify /etc/mail/service.switch to refer only to /etc/hosts for nameresolution: # cat /etc/mail/service.switch hosts files 3: Recompile sendmail.mc and restart sendmail for this setting to take effect. Shift sendmail to non-standard port, or disable daemon mode By default, sendmail will listen on port 25. You may want to change this portor disable the sendmail daemon mode altogether for various reasons:- if there is a security policy prohibiting the use of well-known ports- if another SMTP product/process is to be running on the same host on the standard port- if you don't want to accept mail via smtp at all, just send it using sendmail 1: To shift sendmail to use non-standard port.Edit /etc/mail/sendmail.mc and modify the "Port" setting in the line: DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA') For example, to get sendmail to use port 125: DAEMON_OPTIONS(`Port=125,Addr=127.0.0.1, Name=MTA') This will require sendmail.mc to be recompiled and sendmail to be restarted. 2: Alternatively, to disable sendmail daemon mode altogether (Linux)Edit /etc/sysconfig/sendmail and modify the "DAEMON" setting to: DAEMON=no This change will require sendmail to be restarted. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/43970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
]
} |
43,971 | Let's say I have a web site for hosting community generated content that targets a very specific set of users. Now, let's say in the interest of fostering a better community I have an off-topic area where community members can post or talk about anything they want, regardless of the site's main theme. Now, I want most of the content to get indexed by Google. The notable exception is the off-topic content. Each thread has it's own page, but all the threads are listed in the same folder so I can't just exclude search engines from a folder somewhere. It has to be per-page. A traditional robots.txt file would get huge, so how else could I accomplish this? | This will work for all well-behaving search engines, just add it to the <head> : <meta name="robots" content="noindex, nofollow" /> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/43971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
43,995 | Handling multiple merges onto branches in Subversion or CVS is just one of those things that has to be experienced. It is inordinately easier to keep track of branches and merges in Mercurial (and probably any other distributed system) but I don't know why. Does anyone else know? My question stems from the fact that with Mercurial you can adopt a working practice similar to that of Subversions/CVSs central repository and everything will work just fine. You can do multiple merges on the same branch and you won't need endless scraps of paper with commit numbers and tag names. I know the latest version of Subversion has the ability to track merges to branches so you don't get quite the same degree of hassle but it was a huge and major development on their side and it still doesn't do everything the development team would like it to do. There must be a fundamental difference in the way it all works. | In Subversion (and CVS), the repository is first and foremost. In git and mercurial there is not really the concept of a repository in the same way; here changes are the central theme. +1 The hassle in CVS/SVN comes from the fact that these systems do not remember the parenthood of changes. In Git and Mercurial,not only can a commit have multiple children, it can also have multipleparents! That can easily observed using one of the graphical tools, gitk or hgview . In the following example, branch #2 was forked from #1 atcommit A, and has since been merged once (at M, merged with commit B): o---A---o---B---o---C (branch #1) \ \ o---o---M---X---? (branch #2) Note how A and B have two children, whereas M has two parents . Theserelationships are recorded in the repository. Let's say the maintainer ofbranch #2 now wants to merge the latest changes from branch #1, they canissue a command such as: $ git merge branch-1 and the tool will automatically know that the base is B--because itwas recorded in commit M, an ancestor of the tip of #2--andthat it has to merge whatever happenedbetween B and C. CVS does not record this information, nor did SVN prior toversion 1.5. In these systems, the graphwould look like: o---A---o---B---o---C (branch #1) \ o---o---M---X---? (branch #2) where M is just a gigantic "squashed" commit of everything that happened between A and B,applied on top of M. Note that after the deed is done, there is no traceleft (except potentially in human-readable comments) of where M didoriginate from, nor of how many commits were collapsed together--makinghistory much more impenetrable. Worse still, performing a second merge becomes a nightmare: one has to figure outwhat the merge base was at the time of the first merge (and one has to know that there has been a merge in the first place!), thenpresent that information to the tool so that it does not try to replay A..B ontop of M. All of this is difficult enough when working in close collaboration, but issimply impossible in a distributed environment. A (related) problem is that there is no way to answer the question: "does Xcontain B?" where B is apotentially important bug fix. So, why not just record that information in the commit, sinceit is known at merge time! P.-S. -- I have no experience with SVN 1.5+ merge recording abilities, but the workflow seems to be much morecontrived than in the distributed systems. If that is indeed the case, it's probably because--as mentionedin the above comment--the focus is put on repository organization rather than on the changes themselves. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/43995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003/"
]
} |
44,019 | I need to diff two log files but ignore the time stamp part of each line (the first 12 characters to be exact). Is there a good tool, or a clever awk command, that could help me out? | Depending on the shell you are using, you can turn the approach @Blair suggested into a 1-liner diff <(cut -b13- file1) <(cut -b13- file2) (+1 to @Blair for the original suggestion :-) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
]
} |
44,034 | Unable to find a SQL diff tool that meets my needs, I am writing my own. Between the INFORMATION_SCHEMA and sys tables, I have a mostly-complete working version. But one thing I can't find in the metadata is the definition of a trigger, you know, the actual SQL code. Am I overlooking something? Thanks. Thanks, Pete, I didn't know about that! Scott, I'm working with very basic hosting packages that don't allow remote connections to the DB. I don't know from the specs on RedGate (which I can't afford anyway) whether they provide a workaround for that, and although there are also API's out there (such as the one from Apex), I didn't see the point in investing in a solution that was still going to require more programming on my part. :) My solution is to drop an ASPX page on the site that acts as a kind of "schema service", returning the collected metadata as XML. I set up a little AJAX app that compares any number of catalog instances to a master and shows the diffs. It's not perfect, but a major step forward for me. Thanks again! | sp_helptext works to get the sql that makes up a trigger. The text column in the syscomments view also contains the sql used for object creation. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/44034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4525/"
]
} |
44,046 | I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example: declare @value decimal(18,2)set @value = 123.456 This will automatically round @value to be 123.46 , which is good in most cases. However, for this project, I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the left() function and convert back to a decimal. Are there any other ways? | select round(123.456, 2, 1) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/44046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105/"
]
} |
44,048 | I've got an Apache server that has one access log file that is topping 600MB. This makes it really hard to search the file or parse it. What software or modules for Apache are available that will make a daily copy of my access file to make it more manageable? | Have you looked at logrotate - this is probably the simplest, most widely available and well understood method of achieving this. It is highly configurable and will probably do 90% of what you need. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2863/"
]
} |
44,078 | I am trying to write a regular expression to strip all HTML with the exception of links (the <a href and </a> tags respectively. It does not have to be 100% secure (I am not worried about injection attacks or anything as I am parsing content that has already been approved and published into a SWF movie). The original "strip tags" regular expression I'm using was <(.|\n)+?> , and I tried to modify it to <([^a]|\n)+?> , but that of course will allow any tag that has an a in it rather than one that has it in the beginning, with a space. Not that it should really matter, but in case anyone cares to know I am writing this in ActionScript 3.0 for a Flash movie. | <(?!\/?a(?=>|\s.*>))\/?.*?> Try this. Had something similar for p tags. Worked for them so don't see why not. Uses negative lookahead to check that it doesn't match a (prefixed with an optional / character) where (using positive lookahead) a (with optional / prefix) is followed by a > or a space, stuff and then >. This then matches up until the next > character. Put this in a subst with s/<(?!\/?a(?=>|\s.*>))\/?.*?>//g; This should leave only the opening and closing a tags | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/44078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
]
} |
44,084 | That's it. If you want to document a function or a class, you put a string just after the definition. For instance: def foo(): """This function does nothing.""" pass But what about a module? How can I document what a file.py does? | For the packages, you can document it in __init__.py .For the modules, you can add a docstring simply in the module file. All the information is here: http://www.python.org/dev/peps/pep-0257/ | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679/"
]
} |
44,089 | I have connected to a server via SFTP using FileZilla and accepted adding the server's SSH key to the key cache in FileZilla. How can I extract this cached key to a keyfile so that may use it through other SFTP applications that require a keyfile be made available? I have not been able to find anything in the FileZilla documentation related to this. | If you use the standard openssh console client (cygwin or from linux), host keys are stored, one-per-line, in ~/.ssh/known_hosts. From there, it's a simple matter of figuring out which bit of that host key is needed for your library. Putty also stores host keys, but it appears to encode them in hex. Those can be found at HKCUR\Software\SimonTatham\PuTTY\SshHostKeys | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4311/"
]
} |
44,109 | What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes). I've already seen a few ways to do it, but can't decide on which one is the best. | The least painful and indeed Django-recommended way of doing this is through a OneToOneField(User) property. Extending the existing User model … If you wish to store information related to User , you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user. That said, extending django.contrib.auth.models.User and supplanting it also works... Substituting a custom User model Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username. [Ed: Two warnings and a notification follow , mentioning that this is pretty drastic .] I would definitely stay away from changing the actual User class in your Django source tree and/or copying and altering the auth module. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/44109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
]
} |
44,131 | I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input caret is still shown. The blinking input caret is confusing. How do I hide it? | You can do through a win32 call [DllImport("user32.dll")]static extern bool HideCaret(IntPtr hWnd);public void HideCaret(){ HideCaret(someTextBox.Handle);} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042/"
]
} |
44,135 | What is the best way to layout a large django project? The tutorials provide simple instructions for setting up apps, models, and views, but there is less information about how apps and projects should be broken down, how much sharing is allowable/necessary between apps in a typical project (obviously that is largely dependent on the project) and how/where general templates should be kept. Does anyone have examples, suggestions, and explanations as to why a certain project layout is better than another? I am particularly interested in the incorporation of large numbers of unit tests (2-5x the size of the actual code base) and string externalization / templates. | The major guidelines are similar to any other large code project. Apps should address a single, clearly-defined responsibility. The name "application" is a misnomer; Django apps should be thought of more as reusable components which can be plugged together to create a real application. Tests for each app should be contained within that app. Apps should be decoupled from each other as much as possible, but clearly there will be dependencies, so the goal should be to keep the dependency graph as simple and sane as possible. I prefer to keep all the templates for a project under a single project-wide templates directory, with a subdirectory for each app (using a template subdirectory for each app is a very strong convention in Django, as it avoids template name collisions between apps). The reason for a single project-wide templates directory is that templates, template inheritance trees, and block names can be quite project-specific, so it's hard to provide "default" app templates that can plug in to any project. There have been some attempts to settle on standard naming conventions for base site-wide templates and the blocks they define, but I haven't seen a standard emerge yet (the way they do things over at Pinax is probably the closest we have to a standard). Re "string externalization", if you mean i18n and l10n, Django has strong support for that and standard places where it puts the .po files - check the docs . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
]
} |
44,145 | What's the best way to deal with a sharded database in Rails? Should the sharding be handled at the application layer, the active record layer, the database driver layer, a proxy layer, or something else altogether? What are the pros and cons of each? | FiveRuns have a gem named DataFabric that does application-level sharding and master/slave replication. It might be worth checking out. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.