source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
54,421
If you are writing a program that is executable from the command line, you often want to offer the user several options or flags, along with possibly more than one argument. I have stumbled my way through this many times, but is there some sort of design pattern for looping through args and calling the appropriate handler functions? Consider: myprogram -f filename -d directory -r regex How do you organize the handler functions after you retrieve the arguments using whatever built-ins for your language? (language-specific answers welcomed, if that helps you articulate an answer)
I don't know of any documented "patterns" for processing. I believe one of the oldest libraries/APIs for handling arguments is getopt. Googling "getopt" shows lots of man pages and links to implementations. Generally, I have a preferences or settings service in my application that the argument processor knows how to communicate with. Arguments are then translated into something in this service that the application than then query. This could be as simple as a dictionary of settings (like a string setting named "filename").
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ] }
54,475
I've run into a problem where I make changes to a few JavaScript files that are referenced in an HTML file, but the browser doesn't see the changes. It holds onto the copy cached in the browser, even though the web server has a newer version. Not until I force the browser to clear the cache do I see the changes. Is this a web-server configuration? Do I need to set my JavaScript files to never cache? I've seen some interesting techniques in the Google Web Toolkit where they actually create a new JavaScript file name any time an update is made. I believe this is to prevent proxies and browsers from keeping old versions of the JavaScript files with the same names. Is there a list of best practices somewhere?
We append a product build number to the end of all Javascript (and CSS etc.) like so: <script src="MyScript.js?4.0.8243"> Browsers ignore everything after the question mark but upgrades cause a new URL which means cache-reload. This has the additional benefit that you can set HTTP headers that mean "never cache!"
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/54475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5079/" ] }
54,482
I need to enumerate all the user defined types created in a SQL Server database with CREATE TYPE , and/or find out whether they have already been defined. With tables or stored procedures I'd do something like this: if exists (select * from dbo.sysobjects where name='foobar' and xtype='U') drop table foobar However I can't find the equivalent (or a suitable alternative) for user defined types! I definitely can't see them anywhere in sysobjects . Can anyone enlighten me?
Types and UDTs don't appear in sys.objects.You should be able to get what you're looking for with the following: select * from sys.typeswhere is_user_defined = 1
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/54482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/886/" ] }
54,500
Alright, so I'm working on an application which will use a Linux back-end running PostgreSQL to serve up images to a Windows box with the front end written in C#.NET, though the front-end should hardly matter. My question is: What is the best way to deal with storing images in Postgres? The images are around 4-6 megapixels each, and we're storing upwards of 3000. It might also be good to note: this is not a web application, there will at most be about two front-ends accessing the database at once.
Re jcoby's answer: bytea being a "normal" column also means the value being read completely into memory when you fetch it. Blobs, in contrast, you can stream into stdout. That helps in reducing the server memory footprint. Especially, when you store 4-6 MPix images. No problem with backing up blobs. pg_dump provides "-b" option to include the large objects into the backup. So, I prefer using pg_lo_*, you may guess. Re Kris Erickson's answer: I'd say the opposite :). When images are not the only data you store, don't store them on the file system unless you absolutely have to. It's such a benefit to be always sure about your data consistency, and to have the data "in one piece" (the DB). BTW, PostgreSQL is great in preserving consistency. However, true, reality is often too performance-demanding ;-), and it pushes you to serve the binary files from the file system. But even then I tend to use the DB as the "master" storage for binaries, with all the other relations consistently linked, while providing some file system-based caching mechanism for performance optimization.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/54500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ] }
54,512
varchar(255), varchar(256), nvarchar(255), nvarchar(256), nvarchar(max), etc? 256 seems like a nice, round, space-efficient number. But I've seen 255 used a lot. Why? What's the difference between varchar and nvarchar?
VARCHAR(255). It won't use all 255 characters of storage, just the storage you need. It's 255 and not 256 because then you have space for 255 plus the null-terminator (or size byte). The "N" is for Unicode. Use if you expect non-ASCII characters.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
54,522
I need to print out data into a pre-printed A6 form (1/4 the size of a landsacpe A4). I do not need to print paragraphs of text, just short lines scattered about on the page. All the stuff on MSDN is about priting paragraphs of text. Thanks for any help you can give,Roberto
VARCHAR(255). It won't use all 255 characters of storage, just the storage you need. It's 255 and not 256 because then you have space for 255 plus the null-terminator (or size byte). The "N" is for Unicode. Use if you expect non-ASCII characters.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5648/" ] }
54,536
How do I create a windows application that does the following: it's a regular GUI app when invoked with no command line arguments specifying the optional "--help" command line argument causes the app to write usage text to stdout then terminate it must be a single executable. No cheating by making a console app exec a 2nd executable. assume the main application code is written in C/C++ bonus points if no GUI window is created when "--help" is specified. (i.e., no flicker from a short-lived window) In my experience the standard visual studio template for console app has no GUI capability, and the normal win32 template does not send its stdout to the parent cmd shell.
Microsoft designed console and GUI apps to be mutually exclusive.This bit of short-sightedness means that there is no perfect solution.The most popular approach is to have two executables (eg. cscript / wscript,java / javaw, devenv.com / devenv.exe etc) however you've indicated that you consider this "cheating". You've got two options - to make a "console executable" or a "gui executable",and then use code to try to provide the other behaviour. GUI executable: cmd.exe will assume that your program does no console I/O so won't wait for it to terminatebefore continuing, which in interactive mode (ie not a batch) means displaying the next (" C:\> ") promptand reading from the keyboard. So even if you use AttachConsole your output will be mixedwith cmd 's output, and the situation gets worse if you try to do input. This is basically a non-starter. Console executable: Contrary to belief, there is nothing to stop a console executable from displaying a GUI, but there are two problems. The first is that if you run it from the command line with no arguments (so you want the GUI), cmd will still wait for it to terminate before continuing, so that particularconsole will be unusable for the duration. This can be overcome by launchinga second process of the same executable (do you consider this cheating?), passing the DETACHED_PROCESS flag to CreateProcess() and immediately exiting.The new process can then detect that it has no console and display the GUI. Here's C code to illustrate this approach: #include <stdio.h>#include <windows.h>int main(int argc, char *argv[]){ if (GetStdHandle(STD_OUTPUT_HANDLE) == 0) // no console, we must be the child process { MessageBox(0, "Hello GUI world!", "", 0); } else if (argc > 1) // we have command line args { printf("Hello console world!\n"); } else // no command line args but a console - launch child process { DWORD dwCreationFlags = CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS; STARTUPINFO startinfo; PROCESS_INFORMATION procinfo; ZeroMemory(&startinfo, sizeof(startinfo)); startinfo.cb = sizeof(startinfo); if (!CreateProcess(NULL, argv[0], NULL, NULL, FALSE, dwCreationFlags, NULL, NULL, &startinfo, &procinfo)) MessageBox(0, "CreateProcess() failed :(", "", 0); } exit(0);} I compiled it with cygwin's gcc - YMMV with MSVC. The second problem is that when run from Explorer, your program will for a split seconddisplay a console window. There's no programmatic way around this because the console iscreated by Windows when the app is launched, before it starts executing. The only thing you cando is, in your installer, make the shortcut to your program with a "show command" ofSW_HIDE (ie. 0). This will only affect the console unless you deliberately honour the wShowWindow field of STARTUPINFOin your program, so don't do that. I've tested this by hacking cygwin's "mkshortcut.exe". How you accomplishit in your install program of choice is up to you. The user can still of course run your program by finding the executable in Explorer anddouble-clicking it, bypassing the console-hiding shortcut and seeing the brief black flash of a console window. There's nothing you can do about it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5429/" ] }
54,539
So the SMEs at my current place of employment want to try and disable the back button for certain pages. We have a page where the user makes some selections and submits them to be processed. In some instances they have to enter a comment on another page. What the users have figured out is that they don't have to enter a comment if they submit the information and go to the page with the comment and then hit the back button to return to the previous page. I know there are several different solutions to this (and many of them are far more elegant then disabling the back button), but this is what I'm left with. Is it possible to prevent someone from going back to the previous page through altering the behavior of the back button. (like a submit -> return false sorta thing). Due to double posting information I can't have it return to the previous page and then move to the current one. I can only have it not direct away from the current page. I Googled it, but I only saw posts saying that it will always return to the previous page. I was hoping that someone has some mad kung foo js skills that can make this possible. I understand that everyone says this is a bad idea, and I agree, but sometimes you just have to do what you're told.
Don't do this, just don't. It's bad interface design and forces the user's browser to behave in a way that they don't expect. I would regard any script that successfully stopped my back button from working to be a hack, and I would expect the IE team to release a security-fix for it. The back button is part of their program interface, not your website. In your specific case I think the best bet is to add an unload event to the page that warns the user if they haven't completed the form. The back button would be unaffected and the user would be warned of their action.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942/" ] }
54,566
So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes. class PageAtrributes { private $db_connection; private $page_title; public function __construct($db_connection) { $this->db_connection = $db_connection; $this->page_title = ''; } public function get_page_title() { return $this->page_title; } public function set_page_title($page_title) { $this->page_title = $page_title; }} Later on I call the set_page_title() function like so function page_properties($objPortal) { $objPage->set_page_title($myrow['title']);} When I do I receive the error message: Call to a member function set_page_title() on a non-object So what am I missing?
It means that $objPage is not an instance of an object. Can we see the code you used to initialize the variable? As you expect a specific object type, you can also make use of PHPs type-hinting feature Docs to get the error when your logic is violated: function page_properties(PageAtrributes $objPortal) { ... $objPage->set_page_title($myrow['title']);} This function will only accept PageAtrributes for the first parameter.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/54566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863/" ] }
54,579
Does anyone know of a good example of how to expose a WCF service programatically without the use of a configuration file? I know the service object model is much richer now with WCF, so I know it's possible. I just have not seen an example of how to do so. Conversely, I would like to see how consuming without a configuration file is done as well. Before anyone asks, I have a very specific need to do this without configuration files. I would normally not recommend such a practice, but as I said, there is a very specific need in this case.
Consuming a web service without a config file is very simple, as I've discovered. You simply need to create a binding object and address object and pass them either to the constructor of the client proxy or to a generic ChannelFactory instance. You can look at the default app.config to see what settings to use, then create a static helper method somewhere that instantiates your proxy: internal static MyServiceSoapClient CreateWebServiceInstance() { BasicHttpBinding binding = new BasicHttpBinding(); // I think most (or all) of these are defaults--I just copied them from app.config: binding.SendTimeout = TimeSpan.FromMinutes( 1 ); binding.OpenTimeout = TimeSpan.FromMinutes( 1 ); binding.CloseTimeout = TimeSpan.FromMinutes( 1 ); binding.ReceiveTimeout = TimeSpan.FromMinutes( 10 ); binding.AllowCookies = false; binding.BypassProxyOnLocal = false; binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; binding.MessageEncoding = WSMessageEncoding.Text; binding.TextEncoding = System.Text.Encoding.UTF8; binding.TransferMode = TransferMode.Buffered; binding.UseDefaultWebProxy = true; return new MyServiceSoapClient( binding, new EndpointAddress( "http://www.mysite.com/MyService.asmx" ) );}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/54579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ] }
54,585
In what scenarios is it better to use a struct vs a class in C++?
The differences between a class and a struct in C++ are: struct members and base classes/structs are public by default. class members and base classes/structs are private by default. Both classes and structs can have a mixture of public , protected and private members, can use inheritance, and can have member functions. I would recommend you: use struct for plain-old-data structures without any class-like features; use class when you make use of features such as private or protected members, non-default constructors and operators, etc.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/54585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5436/" ] }
54,674
i'm wondering if there is any nice and neat tool to replace the GNU Autotools or Make to build a very large C++ project, which are such a complicated thing to use. It is simple to generate all the files that de Autotools require if the project is small, but if the source code is divided in many directories, with multiple third party libraries and many dependencies, you fall into the "Autotools Hell".. thanks for any recommendations
The Google V8 JavaScript Engine is written in C++ and uses SCons , so I guess that's one vote for it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1876/" ] }
54,686
Does any one know how do I get the current open windows or process of a local machine using Java? What I'm trying to do is: list the current open task, windows or process open, like in Windows Taskmanager, but using a multi-platform approach - using only Java if it's possible.
This is another approach to parse the the process list from the command " ps -e ": try { String line; Process p = Runtime.getRuntime().exec("ps -e"); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { System.out.println(line); //<-- Parse data here. } input.close();} catch (Exception err) { err.printStackTrace();} If you are using Windows, then you should change the line: "Process p = Runtime.getRun..." etc... (3rd line), for one that looks like this: Process p = Runtime.getRuntime().exec (System.getenv("windir") +"\\system32\\"+"tasklist.exe"); Hope the info helps!
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/54686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358/" ] }
54,725
Sending a message from the Unix command line using mail TO_ADDR results in an email from $USER@$HOSTNAME . Is there a way to change the "From:" address inserted by mail ? For the record, I'm using GNU Mailutils 1.1/1.2 on Ubuntu (but I've seen the same behavior with Fedora and RHEL). [EDIT] $ mail -s Testing [email protected] Cc: From: [email protected]. yields Subject: TestingTo: <[email protected]>X-Mailer: mail (GNU Mailutils 1.1)Message-Id: <E1KdTJj-00025z-RK@localhost>From: <chris@localhost>Date: Wed, 10 Sep 2008 13:17:23 -0400From: [email protected] The "From: [email protected]" line is part of the message body, not part of the header.
In my version of mail ( Debian linux 4.0 ) the following options work for controlling the source / reply addresses the -a switch, for additional headers to apply, supplying a From: header on the command line that will be appended to the outgoing mail header the $REPLYTO environment variable specifies a Reply-To: header so the following sequence export [email protected] -aFrom:[email protected] -s 'Testing' The result, in my mail clients, is a mail from [email protected], which any replies to will default to [email protected] NB: Mac OS users: you don't have -a , but you do have $REPLYTO NB(2): CentOS users, many commenters have added that you need to use -r not -a NB(3): This answer is at least ten years old(1), please bear that in mind when you're coming in from Google.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/54725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ] }
54,753
I have a large legacy codebase with very complicated makefiles, with lots of variables. Sometimes I need to change them, and I find that it's very difficult to figure out why the change isn't working the way I expect. What I'd like to find is a tool that basically does step-through-debugging of the "make" process, where I would give it a directory, and I would be able to see the value of different variables at different points in the process. None of the debug flags to make seem to show me what I want, although it's possible that I'm missing something. Does anyone know of a way to do this?
Have you been looking at the output from running make -n and make -np , and the biggie make -nd ? Are you using a fairly recent version of gmake ? Have you looked at the free chapter on Debugging Makefiles available on O'Reilly's site for their excellent book "Managing Projects with GNU Make" ( Amazon Link ).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/54753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5241/" ] }
54,754
For example, I want to populate a gridview control in an ASP.NET web page with only the data necessary for the # of rows displayed. How can NHibernate support this?
ICriteria has a SetFirstResult(int i) method, which indicates the index of the first item that you wish to get (basically the first data row in your page). It also has a SetMaxResults(int i) method, which indicates the number of rows you wish to get (i.e., your page size). For example, this criteria object gets the first 10 results of your data grid: criteria.SetFirstResult(0).SetMaxResults(10);
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/54754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
54,790
Is it possible to build Visual Studio solutions without having to fire up MonoDevelop?
Current status (Mono 2.10, 2011): xbuild is now able to build all versions of Visual Studio / MSBuild projects, including .sln files. Simply run xbuild just as you would execute msbuild on Microsoft .Net Framework. You don't need Monodevelop installed, xbuild comes with the standard Mono installation. If your build uses custom tasks, they should still work if they don't depend on Windows executables (such as rmdir or xcopy ). When you are editing project files, use standard Windows path syntax - they will be converted by xbuild, if necessary. One important caveat to this rule is case sensitivity - don't mix different casings of the same file name. If you have a project that does this, you can enable compatibility mode by invoking MONO_IOMAP=case xbuild foo.sln (or try MONO_IOMAP=all ). Mono has a page describing more advanced MSBuild project porting techniques. Mono 2.0 answer (2008): xbuild is not yet complete (it works quite well with VS2005 .csproj files, has problems with VS2008 .csproj and does not handle .sln). Mono 2.1 plans to merge the code base of mdtool (MonoDevelop command line build engine) into it, but currently mdtool is a better choice. mdtool build -f:project.sln or man mdtool if you have MonoDevelop installed.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/54790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ] }
54,836
I'm working on some code that uses the System.Diagnostics.Trace class and I'm wondering how to monitor what is written via calls to Trace.WriteLine() both when running in debug mode in Visual Studio and when running outside the debugger.
Try Debug View . It works quite nicely.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ] }
54,837
Does anyone know of a good (preferably open source) library for dealing with the Modbus protocol? I have seen a few libraries, but I am looking for some people's personal experiences, not just the top ten Google hits. I figure there has to be at least one other person who deals with PLCs and automation hardware like I do out there. Open to any other materials that might have been a help to you as well...
I have done a lot of communication with devices for the past few years, since I work for a home automation company, but we don't use Modbus. We do communication in a standard and open way using Web Services for Devices(WSD) which is also know as Devices Profile for Web Services(DPWS) . During this time at one point, I did hear of a project called NModbus . It is an open source library for working with modbus. I have not used it, but looking at the site and the changesets on Google Code, it looks pretty active. You may want to give it a look and even get involved in. This is the only library that I have heard of that targets .Net.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5640/" ] }
54,851
In a follow-up to a previous question regarding exceptions, what are best practices for creating a custom exception in .NET? More specifically should you inherit from System.Exception, System.ApplicationException or some other base exception?
Inherit from System.Exception . System.ApplicationException is useless and the design guidelines say " Do not throw or derive from System.ApplicationException ." See http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ] }
54,864
(I'll begin by making it clear, I am not a .NET developer and am not tied to any other environment.) Recently, I heard that the London Stock Exchange went down for an entire day. I've also heard that the software was written in .NET. Up to this point they would experience performance hits on busy days. People seem to be blaming .NET. I don't want to debate the story, but it brought to mind the question of just how does .NET scale? How big is too big for .NET?
Honestly, I think it boils down to code optimization, apart from just the infrastructure. In StackOverflow Podcast 19 , Jeff discussed about how they had to tweak SQL Server to handle the kinds of loads StackOverflow has; notice that it was not .NET that needed tweaking here. One also has to note that MySpace.com, one of the most massive social networks out there, runs on ASP.NET . The MySpace use of ASP.NET alone is a testament to its scalability. It will boil down to how developers will write their applications in such a way that best leverages that capability.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536194/" ] }
54,866
I have string like this /c SomeText\MoreText "Some Text\More Text\Lol" SomeText I want to tokenize it, however I can't just split on the spaces. I've come up with somewhat ugly parser that works, but I'm wondering if anyone has a more elegant design. This is in C# btw. EDIT: My ugly version, while ugly, is O(N) and may actually be faster than using a RegEx. private string[] tokenize(string input){ string[] tokens = input.Split(' '); List<String> output = new List<String>(); for (int i = 0; i < tokens.Length; i++) { if (tokens[i].StartsWith("\"")) { string temp = tokens[i]; int k = 0; for (k = i + 1; k < tokens.Length; k++) { if (tokens[k].EndsWith("\"")) { temp += " " + tokens[k]; break; } else { temp += " " + tokens[k]; } } output.Add(temp); i = k + 1; } else { output.Add(tokens[i]); } } return output.ToArray(); }
The computer term for what you're doing is lexical analysis ; read that for a good summary of this common task. Based on your example, I'm guessing that you want whitespace to separate your words, but stuff in quotation marks should be treated as a "word" without the quotes. The simplest way to do this is to define a word as a regular expression: ([^"^\s]+)\s*|"([^"]+)"\s* This expression states that a "word" is either (1) non-quote, non-whitespace text surrounded by whitespace, or (2) non-quote text surrounded by quotes (followed by some whitespace). Note the use of capturing parentheses to highlight the desired text. Armed with that regex, your algorithm is simple: search your text for the next "word" as defined by the capturing parentheses, and return it. Repeat that until you run out of "words". Here's the simplest bit of working code I could come up with, in VB.NET. Note that we have to check both groups for data since there are two sets of capturing parentheses. Dim token As StringDim r As Regex = New Regex("([^""^\s]+)\s*|""([^""]+)""\s*")Dim m As Match = r.Match("this is a ""test string""")While m.Success token = m.Groups(1).ToString If token.length = 0 And m.Groups.Count > 1 Then token = m.Groups(2).ToString End If m = m.NextMatchEnd While Note 1: Will's answer, above, is the same idea as this one. Hopefully this answer explains the details behind the scene a little better :)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ] }
54,867
What is the difference between old style and new style classes in Python? When should I use one or the other?
From New-style and classic classes : Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x , but type(x) is always <type 'instance'> . This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance. New-style classes were introduced in Python 2.2 to unify the concepts of class and type . A new-style class is simply a user-defined type, no more, no less. If x is an instance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.__class__ ). The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model . It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties. For compatibility reasons, classes are still old-style by default . New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance. Python 3 only has new-style classes . No matter if you subclass from object or not, classes are new-style in Python 3.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/54867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
54,882
What's the easiest way to print a stacktrace from a debugging printout? Often during testing you would like to know the callstack leading up to the situation provoking a debug message.
Thread.dumpStack();
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/54882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4220/" ] }
54,886
Alright it can be a lame question, but everybody uses these things differently. What's some of the best time savers out there for this IDE. Tom
Don't forget Ctrl + Shift + L , which displays a list of all the keyboard shortcut combinations (just in case you forget any of those listed here).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/54886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5659/" ] }
54,909
I have an ArrayList<String> that I'd like to return a copy of. ArrayList has a clone method which has the following signature: public Object clone() After I call this method, how do I cast the returned Object back to ArrayList<String> ?
Why would you want to clone? Creating a new list usually makes more sense. List<String> strs;...List<String> newStrs = new ArrayList<>(strs); Job done.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/54909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ] }
54,926
Is it possible, in Java, to make a JPanel skip drawing its background thus being transparent except for the components on it?
setOpaque(false) It'll pass off painting the background to its parent, which may draw its own background. You can do a screen capture and then use that to paint the background of the panel.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/54926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ] }
54,929
This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. More info: https://stackoverflow.com/faq There are always features that would be useful in fringe scenarios, but for that very reason most people don't know them. I am asking for features that are not typically taught by the text books. What are the ones that you know?
If you place a file named app_offline.htm in the root of a web application directory, ASP.NET 2.0+ will shut-down the application and stop normal processing any new incoming requests for that application, showing only the contents of the app_offline.htm file for all new requests . This is the quickest and easiest way to display your "Site Temporarily Unavailable" notice while re-deploying (or rolling back) changes to a Production server. Also, as pointed out by marxidad , make sure you have at least 512 bytes of content within the file so IE6 will render it correctly.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/54929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380/" ] }
54,989
Is it possible to change the hostname in Windows 2003 from the command line with out-of-the-box tools?
The previously mentioned wmic command is the way to go, as it is installed by default in recent versions of Windows. Here is my small improvement to generalize it, by retrieving the current name from the environment: wmic computersystem where name="%COMPUTERNAME%" call rename name="NEW-NAME" NOTE: The command must be given in one line, but I've broken it into two to make scrolling unnecessary. As @rbeede mentions you'll have to reboot to complete the update.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/54989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807/" ] }
54,991
When a user on our site loses his password and heads off to the Lost Password page we need to give him a new temporary password. I don't really mind how random this is, or if it matches all the "needed" strong password rules, all I want to do is give them a password that they can change later. The application is a Web application written in C#. so I was thinking of being mean and going for the easy route of using part of a Guid. i.e. Guid.NewGuid().ToString("d").Substring(1,8) Suggesstions? thoughts?
There's always System.Web.Security.Membership.GeneratePassword(int length, int numberOfNonAlphanumericCharacters ) .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/54991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231/" ] }
54,998
I recently read this Question about SQLite vs MySQL and the answer pointed out that SQLite doesn't scale well and the official website sort-of confirms this , however. How scalable is SQLite and what are its upper most limits?
Yesterday I released a small site * to track your rep that used a shared SQLite database for all visitors. Unfortunately, even with the modest load that it put on my host it ran quite slowly. This is because the entire database was locked every time someone viewed the page because it contained updates/inserts. I soon switched to MySQL and while I haven't had much time to test it out, it seems much more scaleable than SQLite. I just remember slow page loads and occasionally getting a database locked error when trying to execute queries from the shell in sqlite. That said, I am running another site from SQLite just fine. The difference is that the site is static (i.e. I'm the only one that can change the database) and so it works just fine for concurrent reads. Moral of the story: only use SQLite for websites where updates to the database happen rarely (less often than every page loaded). edit : I just realized that I may not have been fair to SQLite - I didn't index any columns in the SQLite database when I was serving it from a web page. This partially caused the slowdown I was experiencing. However, the observation of database-locking stands - if you have particularly onerous updates, SQLite performance won't match MySQL or Postgres. another edit: Since I posted this almost 3 months ago I've had the opportunity to closely examine the scalability of SQLite, and with a few tricks it can be quite scalable. As I mentioned in my first edit, database indexes dramatically reduce query time, but this is more of a general observation about databases than it is about SQLite. However, there is another trick you can use to speed up SQLite: transactions . Whenever you have to do multiple database writes, put them inside a transaction. Instead of writing to (and locking) the file each and every time a write query is issued, the write will only happen once when the transaction completes. The site that I mention I released in the first paragraph has been switched back to SQLite, and it's running quite smoothly once I tuned my code in a few places. * the site is no longer available
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/54998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
55,013
Is there ever a circumstance in which I would not want to use the AndAlso operator rather than the And operator? …or in which I would not want to use the OrElse operator rather than the Or operator?
From MSDN : Short-Circuiting Trade-Offs Short-circuiting can improve performance by not evaluating an expression that cannot alter the result of the logical operation. However, if that expression performs additional actions, short-circuiting skips those actions. For example, if the expression includes a call to a Function procedure, that procedure is not called if the expression is short-circuited, and any additional code contained in the Function does not run. If your program logic depends on any of that additional code, you should probably avoid short-circuiting operators.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
55,042
I want to build a bot that asks someone a few simple questions and branches based on the answer. I realize parsing meaning from the human responses will be challenging, but how do you setup the program to deal with the "state" of the conversation? It will be a one-to-one conversation between a human and the bot.
You probably want to look into Markov Chains as the basics for the bot AI. I wrote something a long time ago (the code to which I'm not proud of at all, and needs some mods to run on Python > 1.5) that may be a useful starting place for you: http://sourceforge.net/projects/benzo/ EDIT: Here's a minimal example in Python of a Markov Chain that accepts input from stdin and outputs text based on the probabilities of words succeeding one another in the input. It's optimized for IRC-style chat logs, but running any decent-sized text through it should demonstrate the concepts: import random, sysNONWORD = "\n"STARTKEY = NONWORD, NONWORDMAXGEN=1000class MarkovChainer(object): def __init__(self): self.state = dict() def input(self, input): word1, word2 = STARTKEY for word3 in input.split(): self.state.setdefault((word1, word2), list()).append(word3) word1, word2 = word2, word3 self.state.setdefault((word1, word2), list()).append(NONWORD) def output(self): output = list() word1, word2 = STARTKEY for i in range(MAXGEN): word3 = random.choice(self.state[(word1,word2)]) if word3 == NONWORD: break output.append(word3) word1, word2 = word2, word3 return " ".join(output)if __name__ == "__main__": c = MarkovChainer() c.input(sys.stdin.read()) print c.output() It's pretty easy from here to plug in persistence and an IRC library and have the basis of the type of bot you're talking about.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ] }
55,054
What’s the best way to capitalize the first letter of each word in a string in SQL Server.
From http://www.sql-server-helper.com/functions/initcap.aspx CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) ) RETURNS VARCHAR(4000)ASBEGINDECLARE @Index INTDECLARE @Char CHAR(1)DECLARE @PrevChar CHAR(1)DECLARE @OutputString VARCHAR(255)SET @OutputString = LOWER(@InputString)SET @Index = 1WHILE @Index <= LEN(@InputString)BEGIN SET @Char = SUBSTRING(@InputString, @Index, 1) SET @PrevChar = CASE WHEN @Index = 1 THEN ' ' ELSE SUBSTRING(@InputString, @Index - 1, 1) END IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(') BEGIN IF @PrevChar != '''' OR UPPER(@Char) != 'S' SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char)) END SET @Index = @Index + 1ENDRETURN @OutputStringENDGO There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, "Invalid length parameter passed to the RIGHT function."): http://www.devx.com/tips/Tip/17608
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5170/" ] }
55,056
I'm building a Django project that needs search functionality, and until there's a django.contrib.search , I have to choose a search app. So, which is the best? By "best" I mean... easy to install / set up has a Django- or at least Python-friendly API can perform reasonably complex searches Here are some apps I've heard of, please suggest others if you know of any: djangosearch django-sphinx I'd also like to avoid using a third-party search engine (like Google SiteSearch), because some of the data I'd like to index is for site members only and should not be public.
Check out Haystack Search - a new model based search abstraction layer that currently supports Xapian , Solr and Whoosh . Looks like it's well supported and documented.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/55056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5616/" ] }
55,093
I have a class to parse a matrix that keeps the result in an array member: class Parser{ ... double matrix_[4][4];}; The user of this class needs to call an API function (as in, a function I have no control over, so I can't just change its interface to make things work more easily) that looks like this: void api_func(const double matrix[4][4]); The only way I have come up with for the caller to pass the array result to the function is by making the member public: void myfunc(){ Parser parser; ... api_func(parser.matrix_);} Is this the only way to do things? I'm astounded by how inflexible multidimensional arrays declared like this are. I thought matrix_ would essentially be the same as a double** and I could cast (safely) between the two. As it turns out, I can't even find an unsafe way to cast between the things. Say I add an accessor to the Parser class: void* Parser::getMatrix(){ return (void*)matrix_;} This will compile, but I can't use it, because there doesn't seem to be a way to cast back to the weirdo array type: // A smorgasbord of syntax errors... api_func((double[][])parser.getMatrix()); api_func((double[4][4])parser.getMatrix()); api_func((double**)parser.getMatrix()); // cast works but it's to the wrong type The error is: error C2440: 'type cast' : cannot convert from 'void *' to 'const double [4][4]' ...with an intriguing addendum: There are no conversions to array types, although there are conversions to references or pointers to arrays I can't determine how to cast to a reference or pointer to array either, albeit that it probably won't help me here. To be sure, at this point the matter is purely academic, as the void* casts are hardly cleaner than a single class member left public!
Here's a nice, clean way: class Parser{public: typedef double matrix[4][4]; // ... const matrix& getMatrix() const { return matrix_; } // ...private: matrix matrix_;}; Now you're working with a descriptive type name rather than an array, but since it's a typedef the compiler will still allow passing it to the unchangeable API function that takes the base type.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ] }
55,159
In SQL Server 2005 I have an "id" field in a table that has the "Is Identity" property set to 'Yes'. So, when an Insert is executed on that table the "id" gets set automatically to the next incrementing integer. Is there an easy way when the Insert is executed to get what the "id" was set to without having to do a Select statement right after the Insert? duplicate of: Best way to get identity of inserted row?
In .Net at least, you can send multiple queries to the server in one go. I do this in my app: command.CommandText = "INSERT INTO [Employee] (Name) VALUES (@Name); SELECT SCOPE_IDENTITY()";int id = (int)command.ExecuteScalar(); Works like a charm.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1096640/" ] }
55,206
What is the operator precedence order in Visual Basic 6.0 (VB6)? In particular, for the logical operators.
Arithmetic Operation Precedence Order ^ - (unary negation) * , / \ Mod + , - (binary addition/subtraction) & Comparison Operation Precedence Order = <> < > <= >= Like , Is Logical Operation Precedence Order Not And Or Xor Eqv Imp Source: Sams Teach Yourself Visual Basic 6 in 24 Hours — Appendix A: Operator Precedence
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5472/" ] }
55,210
What would be the best strategy to generate anagrams. An anagram is a type of word play, the result of rearranging the lettersof a word or phrase to produce a new word or phrase, using all the originalletters exactly once; ex. Eleven plus two is anagram of Twelve plus one A decimal point is anagram of I'm a dot in place Astronomers is anagram of Moon starers At first it looks straightforwardly simple, just to jumble the letters and generate all possible combinations. But what would be the efficient approach to generate only the words in dictionary. I came across this page, Solving anagrams in Ruby . But what are your ideas?
Most of these answers are horribly inefficient and/or will only give one-word solutions (no spaces). My solution will handle any number of words and is very efficient. What you want is a trie data structure. Here's a complete Python implementation. You just need a word list saved in a file named words.txt You can try the Scrabble dictionary word list here: http://www.isc.ro/lists/twl06.zip MIN_WORD_SIZE = 4 # min size of a word in the outputclass Node(object): def __init__(self, letter='', final=False, depth=0): self.letter = letter self.final = final self.depth = depth self.children = {} def add(self, letters): node = self for index, letter in enumerate(letters): if letter not in node.children: node.children[letter] = Node(letter, index==len(letters)-1, index+1) node = node.children[letter] def anagram(self, letters): tiles = {} for letter in letters: tiles[letter] = tiles.get(letter, 0) + 1 min_length = len(letters) return self._anagram(tiles, [], self, min_length) def _anagram(self, tiles, path, root, min_length): if self.final and self.depth >= MIN_WORD_SIZE: word = ''.join(path) length = len(word.replace(' ', '')) if length >= min_length: yield word path.append(' ') for word in root._anagram(tiles, path, root, min_length): yield word path.pop() for letter, node in self.children.iteritems(): count = tiles.get(letter, 0) if count == 0: continue tiles[letter] = count - 1 path.append(letter) for word in node._anagram(tiles, path, root, min_length): yield word path.pop() tiles[letter] = countdef load_dictionary(path): result = Node() for line in open(path, 'r'): word = line.strip().lower() result.add(word) return resultdef main(): print 'Loading word list.' words = load_dictionary('words.txt') while True: letters = raw_input('Enter letters: ') letters = letters.lower() letters = letters.replace(' ', '') if not letters: break count = 0 for word in words.anagram(letters): print word count += 1 print '%d results.' % countif __name__ == '__main__': main() When you run the program, the words are loaded into a trie in memory. After that, just type in the letters you want to search with and it will print the results. It will only show results that use all of the input letters, nothing shorter. It filters short words from the output, otherwise the number of results is huge. Feel free to tweak the MIN_WORD_SIZE setting. Keep in mind, just using "astronomers" as input gives 233,549 results if MIN_WORD_SIZE is 1. Perhaps you can find a shorter word list that only contains more common English words. Also, the contraction "I'm" (from one of your examples) won't show up in the results unless you add "im" to the dictionary and set MIN_WORD_SIZE to 2. The trick to getting multiple words is to jump back to the root node in the trie whenever you encounter a complete word in the search. Then you keep traversing the trie until all letters have been used.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ] }
55,218
I looking for a way, specifically in PHP that I will be guaranteed to always get a unique key. I have done the following: strtolower(substr(crypt(time()), 0, 7)); But I have found that once in a while I end up with a duplicate key (rarely, but often enough). I have also thought of doing: strtolower(substr(crypt(uniqid(rand(), true)), 0, 7)); But according to the PHP website, uniqid() could, if uniqid() is called twice in the same microsecond, it could generate the same key. I'm thinking that the addition of rand() that it rarely would, but still possible. After the lines mentioned above I am also remove characters such as L and O so it's less confusing for the user. This maybe part of the cause for the duplicates, but still necessary. One option I have a thought of is creating a website that will generate the key, storing it in a database, ensuring it's completely unique. Any other thoughts? Are there any websites out there that already do this that have some kind of API or just return the key. I found http://userident.com but I'm not sure if the keys will be completely unique. This needs to run in the background without any user input.
There are only 3 ways to generate unique values, rather they be passwords, user IDs, etc.: Use an effective GUID generator - these are long and cannot be shrunk. If you only use part you FAIL . At least part of the number is sequentially generated off of a single sequence. You can add fluff or encoding to make it look less sequential. Advantage is they start short - disadvantage is they require a single source. The work around for the single source limitation is to have numbered sources, so you include the [source #] + [seq #] and then each source can generate its own sequence. Generate them via some other means and then check them against the single history of previously generated values. Any other method is not guaranteed. Keep in mind, fundamentally you are generating a binary number (it is a computer), but then you can encode it in Hexadecimal, Decimal, Base64, or a word list. Pick an encoding that fits your usage. Usually for user entered data you want some variation of Base32 (which you hinted at). Note about GUIDS : They gain their strength of uniqueness from their length and the method used to generate them. Anything less than 128-bits is not secure. Beyond random number generation there are characteristics that go into a GUID to make it more unique. Keep in mind they are only practically unique, not completely unique. It is possible, although practically impossible to have a duplicate. Updated Note about GUIDS : Since writing this I learned that many GUID generators use a cryptographically secure random number generator (difficult or impossible to predict the next number generated, and a not likely to repeat). There are actually 5 different UUID algorithms . Algorithm 4 is what Microsoft currently uses for the Windows GUID generation API. A GUID is Microsoft's implementation of the UUID standard. Update : If you want 7 to 16 characters then you need to use either method 2 or 3. Bottom line : Frankly there is no such thing as completely unique. Even if you went with a sequential generator you would eventually run out of storage using all the atoms in the universe, thus looping back on yourself and repeating. Your only hope would be the heat death of the universe before reaching that point. Even the best random number generator has a possibility of repeating equal to the total size of the random number you are generating. Take a quarter for example. It is a completely random bit generator, and its odds of repeating are 1 in 2. So it all comes down to your threshold of uniqueness. You can have 100% uniqueness in 8 digits for 1,099,511,627,776 numbers by using a sequence and then base32 encoding it. Any other method that does not involve checking against a list of past numbers only has odds equal to n/1,099,511,627,776 (where n=number of previous numbers generated) of not being unique.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ] }
55,273
I have seen the references to VistaDB over the years and with tools like SQLite, Firebird, MS SQL et. al. I have never had a reason to consider it. What are the benefits of paying for VistaDB vs using another technology? Things I have thought of: 1. Compact Framework Support. SQLite+MSSQL support the CF. 2. Need migration path to a 'more robust' system. Firebird+MSSQL. 3. Need more advanced features such as triggers. Firebird+MSSQL
The VistaDB client runtime is free. The runtime will never "expire at 3am" as you put it. Only the developer tools are licensed in that manner. You need 1 license per developer, simple. We even offer a really inexpensive Lite version with no Visual Studio tools. Some other benefits 100% managed code - there are no interop or other unmanaged calls in the engine. This is a big deal to some, and others couldn't care less. No registry access required - Most other in proc databases require registry access to look for parent controls, or permissions. VistaDB only does what you tell it to do, and will even run in Medium Trust. XCopy deployment for runtime and your database (single file). You can xcopy you application, the runtime, and your database and run. Nothing to install or configure on the machine, no special privileges needed (we can run in Medium Trust or higher). Isolated storage - You can put your entire database into Isolated Storage and run it from there directly. This makes it very easy to build secure click once applications that write databases in a domain friendly way for corporate environments. There is no need to store the user data on a shared drive or worry about permission mapping. CLR Triggers / CLR Procs - You can write CLR Code and use them as Triggers or Stored Procs. We have just recently introduced changes to make it even easier to maintain a single CLR Assembly that can run in both VistaDB and SQL Server 2005/2008. T-SQL Procs - VistaDB T-SQL Procs are compatible with SQL Server 2005/2008. Any procedure that works in our engine will run in SQL Server. That does not mean anything that runs there will port to us. We are a subset of the functionality in SQL Server. But we are also the only way to run T-SQL Procs without SQL Server (SQL CE can't do it). I personally think one of the biggest features is the ability to upsize to SQL Server later. All of the VistaDB types, syntax, and CLR Procs, T-SQL procs, etc all will run on SQL Server. (You can't take everything from SQL Server down to VistaDB though, it is a subset) 32/64 bit Deployment - VistaDB is a single assembly deployment that runs both 32 and 64 bit without changes. SQL CE requires two different runtimes depending upon the OS, and cannot run under IIS at all. Access has no 64 bit runtime, and the most recent 32 bit runtime can only be deployed through MSI. The 32 bit version of Windows has the runtime, the 64 bit version does not. Relational Integrity - VistaDB also actually enforces your constraints and Foreign Keys. You can specific cascade update, and delete operations. The person who commented we are like SQLITE is wrong in this regard. They parse constraints, but do not enforce them. EDIT: They do have support for FK's now in SQLite. But they are not compiled in by default, and do not use the same syntax as SQL Server. Medium Trust - The ability to run on a medium trust web server is another feature that many will not care about, but it is a big deal. Many third party controls can't even run in Medium Trust. We can run the complete engine within Medium Trust because of our commitment to 100% managed code and least permission required. - Full disclosure - I am the owner of VistaDB so I may be biased. :)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3683/" ] }
55,296
I'm looking to implement httpOnly in my legacy ASP classic sites.Anyone knows how to do it?
Response.AddHeader "Set-Cookie", "mycookie=yo; HttpOnly" Other options like expires , path and secure can be also added in this way. I don't know of any magical way to change your whole cookies collection, but I could be wrong about that.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385/" ] }
55,313
One thing I really miss about Java is the tool support. FindBugs, Checkstyle and PMD made for a holy trinity of code quality metrics and automatic bug checking. Is there anything that will check for simple bugs and / or style violations of Ruby code? Bonus points if I can adapt it for frameworks such as Rails so that Rails idioms are adhered to.
I've recently started looking for something like this for Ruby. What I've run across so far: Saikuro Roodi Flog These might be places to start. Unfortunately I haven't used any of the three enough yet to offer a good opinion.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5266/" ] }
55,342
I need to quickly (and forcibly) kill off all external sessions connecting to my oracle database without the supervision of and administrator. I don't want to just lock the database and let the users quit gracefully. How would I script this?
This answer is heavily influenced by a conversation here: http://www.tek-tips.com/viewthread.cfm?qid=1395151&page=3 ALTER SYSTEM ENABLE RESTRICTED SESSION;begin for x in ( select Sid, Serial#, machine, program from v$session where machine <> 'MyDatabaseServerName' ) loop execute immediate 'Alter System Kill Session '''|| x.Sid || ',' || x.Serial# || ''' IMMEDIATE'; end loop; end; I skip killing sessions originating on the database server to avoid killing off Oracle's connections to itself.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685/" ] }
55,375
I know this rather goes against the idea of enums, but is it possible to extend enums in C#/Java? I mean "extend" in both the sense of adding new values to an enum, but also in the OO sense of inheriting from an existing enum. I assume it's not possible in Java, as it only got them fairly recently (Java 5?). C# seems more forgiving of people that want to do crazy things, though, so I thought it might be possible some way. Presumably it could be hacked up via reflection (not that you'd every actually use that method)? I'm not necessarily interested in implementing any given method, it just provoked my curiosity when it occurred to me :-)
The reason you can't extend Enums is because it would lead to problems with polymorphism. Say you have an enum MyEnum with values A, B, and C , and extend it with value D as MyExtEnum. Suppose a method expects a myEnum value somewhere, for instance as a parameter. It should be legal to supply a MyExtEnum value, because it's a subtype, but now what are you going to do when it turns out the value is D? To eliminate this problem, extending enums is illegal
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/55375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5296/" ] }
55,391
I want to grab the value of a hidden input field in HTML. <input type="hidden" name="fooId" value="12-3456789-1111111111" /> I want to write a regular expression in Python that will return the value of fooId , given that I know the line in the HTML follows the format <input type="hidden" name="fooId" value="**[id is here]**" /> Can someone provide an example in Python to parse the HTML for the value?
For this particular case, BeautifulSoup is harder to write than a regex, but it is much more robust... I'm just contributing with the BeautifulSoup example, given that you already know which regexp to use :-) from BeautifulSoup import BeautifulSoup#Or retrieve it from the web, etc. html_data = open('/yourwebsite/page.html','r').read()#Create the soup object from the HTML datasoup = BeautifulSoup(html_data)fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tagvalue = fooId.attrs[2][1] #The value of the third attribute of the desired tag #or index it directly via fooId['value']
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5675/" ] }
55,403
I am interested to know whether anyone has written an application that takes advantage of a GPGPU by using, for example, nVidia CUDA . If so, what issues did you find and what performance gains did you achieve compared with a standard CPU?
I have been doing gpgpu development with ATI's stream SDK instead of Cuda.What kind of performance gain you will get depends on a lot of factors, but the most important is the numeric intensity. (That is, the ratio of compute operations to memory references.) A BLAS level-1 or BLAS level-2 function like adding two vectors only does 1 math operation for each 3 memory references, so the NI is (1/3). This is always run slower with CAL or Cuda than just doing in on the cpu. The main reason is the time it takes to transfer the data from the cpu to the gpu and back. For a function like FFT, there are O(N log N) computations and O(N) memory references, so the NI is O(log N). If N is very large, say 1,000,000 it will likely be faster to do it on the gpu; If N is small, say 1,000 it will almost certainly be slower. For a BLAS level-3 or LAPACK function like LU decomposition of a matrix, or finding its eigenvalues, there are O( N^3) computations and O(N^2) memory references, so the NI is O(N). For very small arrays, say N is a few score, this will still be faster to do on the cpu, but as N increases, the algorithm very quickly goes from memory-bound to compute-bound and the performance increase on the gpu rises very quickly. Anything involving complex arithemetic has more computations than scalar arithmetic, which usually doubles the NI and increases gpu performance. (source: earthlink.net ) Here is the performance of CGEMM -- complex single precision matrix-matrix multiplication done on a Radeon 4870.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3305/" ] }
55,411
Running into a problem where on certain servers we get an error that the directory name is invalid when using Path.GetTempFileName. Further investigation shows that it is trying to write a file to c:\Documents and Setting\computername\aspnet\local settings\temp (found by using Path.GetTempPath). This folder exists so I'm assuming this must be a permissions issue with respect to the asp.net account. I've been told by some that Path.GetTempFileName should be pointing to C:\Windows\Microsoft.NET\Framework\v2.0.50727\temporaryasp.net files. I've also been told that this problem may be due to the order in which IIS and .NET where installed on the server. I've done the typical 'aspnet_regiis -i' and checked security on the folders etc. At this point I'm stuck. Can anyone shed some light on this? **Update:**Turns out that providing 'IUSR_ComputerName' access to the folder does the trick. Is that the correct procedure? I don't seem to recall doing that in the past, and obviously, want to follow best practices to maintain security. This is, after all, part of a file upload process.
This is probably a combination of impersonation and a mismatch of different authentication methods occurring. There are many pieces; I'll try to go over them one by one. Impersonation is a technique to "temporarily" switch the user account under which a thread is running. Essentially, the thread briefly gains the same rights and access -- no more, no less -- as the account that is being impersonated. As soon as the thread is done creating the web page, it "reverts" back to the original account and gets ready for the next call. This technique is used to access resources that only the user logged into your web site has access to. Hold onto the concept for a minute. Now, by default ASP.NET runs a web site under a local account called ASPNET . Again, by default, only the ASPNET account and members of the Administrators group can write to that folder. Your temporary folder is under that account's purview. This is the second piece of the puzzle. Impersonation doesn't happen on its own. It needs to be turn on intentionally in your web.config. <identity impersonate="true" /> If the setting is missing or set to false, your code will execute pure and simply under the ASPNET account mentioned above. Given your error message, I'm positive that you have impersonation=true. There is nothing wrong with that! Impersonation has advantages and disadvantages that go beyond this discussion. There is one question left: when you use impersonation, which account gets impersonated ? Unless you specify the account in the web.config ( full syntax of the identity element here ), the account impersonated is the one that the IIS handed over to ASP.NET. And that depends on how the user has authenticated (or not) into the site. That is your third and final piece. The IUSR_ComputerName account is a low-rights account created by IIS. By default, this account is the account under which a web call runs if the user could not be authenticated . That is, the user comes in as an "anonymous". In summary, this is what is happening to you: Your user is trying to access the web site, and IIS could not authenticate the person for some reason. Because Anonymous access is ON, (or you would not see IUSRComputerName accessing the temp folder), IIS allows the user in anyway, but as a generic user. Your ASP.NET code runs and impersonates this generic IUSR___ComputerName "guest" account; only now the code doesn't have access to the things that the ASPNET account had access to, including its own temporary folder. Granting IUSR_ComputerName WRITE access to the folder makes your symptoms go away. But that just the symptoms. You need to review why is the person coming as "Anonymous/Guest"? There are two likely scenarios: a) You intended to use IIS for authentication, but the authentication settings in IIS for some of your servers are wrong. In that case, you need to disable Anonymous access on those servers so that the usual authentication mechanisms take place. Note that you might still need to grant to your users access to that temporary folder, or use another folder instead, one to which your users already have access. I have worked with this scenario many times, and quite frankly it gives you less headaches to forgo the Temp folder; create a dedicated folder in the server, set the proper permissions, and set its location in web.config. b) You didn't want to authenticate people anyway, or you wanted to use ASP.NET Forms Authentication (which uses IIS's Anonymous access to bypass checks in IIS and lets ASP.NET handle the authentication directly) This case is a bit more complicated. You should go to IIS and disable all forms of authentication other than "Anonymous Access". Note that you can't do that in the developer's box, because the debugger needs Integrated Authentication to be enabled. So your debugging box will behave a bit different than the real server; just be aware of that. Then, you need to decide whether you should turn impersonation OFF, or conversely, to specify the account to impersonate in the web.config. Do the first if your web server doesn't need outside resources (like a database). Do the latter if your web site does need to run under an account that has access to a database (or some other outside resource). You have two more alternatives to specify the account to impersonate. One, you could go to IIS and change the "anonymous" account to be one with access to the resource instead of the one IIS manages for you. The second alternative is to stash the account and password encrypted in the registry. That step is a bit complicated and also goes beyond the scope of this discussion. Good luck!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5678/" ] }
55,449
I sometimes use the feature 'Reconcile Offline Work...' found in Perforce's P4V IDE to sync up any files that I have been working on while disconnected from the P4 depot. It launches another window that performs a 'Folder Diff'. I have files I never want to check in to source control (like ones found in bin folder such as DLLs, code generated output, etc.) Is there a way to filter those files/folders out from appearing as "new" that might be added. They tend to clutter up the list of files that I am actually interested in. Does P4 have the equivalent of Subversion's 'ignore file' feature?
As of version 2012.1, Perforce supports the P4IGNORE environment variable. I updated my answer to this question about ignoring directories with an explanation of how it works. Then I noticed this answer, which is now superfluous I guess. Assuming you have a client named "CLIENT", a directory named "foo" (located at your project root), and you wish to ignore all .dll files in that directory tree, you can add the following lines to your workspace view to accomplish this: -//depot/foo/*.dll //CLIENT/foo/*.dll-//depot/foo/.../*.dll //CLIENT/foo/.../*.dll The first line removes them from the directory "foo" and the second line removes them from all sub directories. Now, when you 'Reconcile Offline Work...', all the .dll files will be moved into "Excluded Files" folders at the bottom of the folder diff display. They will be out of your way, but can still view and manipulate them if you really need to. You can also do it another way, which will reduce your "Excluded Files" folder to just one, but you won't be able to manipulate any of the files it contains because the path will be corrupt (but if you just want them out of your way, it doesn't matter). -//depot/foo.../*.dll //CLIENT/foo.../*.dll
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
55,463
I'm building a PHP page with data sent from MySQL. Is it better to have 1 SELECT query with 4 table joins, or 4 small SELECT queries with no table join; I do select from an ID Which is faster and what is the pro/con of each method? I only need one row from each tables.
You should run a profiling tool if you're truly worried cause it depends on many things and it can vary but as a rule its better to have fewer queries being compiled and fewer round trips to the database. Make sure you filter things as well as you can using your where and join on clauses. But honestly, it usually doesn't matter since you're probably not going to be hit all that hard compared to what the database can do, so unless optimization is your spec you should not do it prematurely and do whats simplest.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5196/" ] }
55,502
I have an object in a multi-threaded environment that maintains a collection of information, e.g.: public IList<string> Data { get { return data; }} I currently have return data; wrapped by a ReaderWriterLockSlim to protect the collection from sharing violations. However, to be doubly sure, I'd like to return the collection as read-only, so that the calling code is unable to make changes to the collection, only view what's already there. Is this at all possible?
If your underlying data is stored as list you can use List(T).AsReadOnly method. If your data can be enumerated, you can use Enumerable.ToList method to cast your collection to List and call AsReadOnly on it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5296/" ] }
55,506
As part of my integration strategy, I have a few SQL scripts that run in order to update the database. The first thing all of these scripts do is check to see if they need to run, e.g.: if @version <> @expects begin declare @error varchar(100); set @error = 'Invalid version. Your version is ' + convert(varchar, @version) + '. This script expects version ' + convert(varchar, @expects) + '.'; raiserror(@error, 10, 1); endelse begin ...sql statements here... end Works great! Except if I need to add a stored procedure. The "create proc" command must be the only command in a batch of sql commands. Putting a "create proc" in my IF statement causes this error: 'CREATE/ALTER PROCEDURE' must be the first statement in a query batch. Ouch! How do I put the CREATE PROC command in my script, and have it only execute if it needs to?
Here's what I came up with: Wrap it in an EXEC(), like so: if @version <> @expects begin ...snip... endelse begin exec('CREATE PROC MyProc AS SELECT ''Victory!'''); end Works like a charm!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2527/" ] }
55,510
I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time. int globalgarbage;unsigned int anumber = 42; But what about static ones defined within a function? void doSomething(){ static bool globalish = true; // ...} When is the space for globalish allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when doSomething() is first called?
I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2. include <iostream>#include <string>using namespace std;class test{public: test(const char *name) : _name(name) { cout << _name << " created" << endl; } ~test() { cout << _name << " destroyed" << endl; } string _name;};test t("global variable");void f(){ static test t("static variable"); test t2("Local variable"); cout << "Function executed" << endl;}int main(){ test t("local to main"); cout << "Program start" << endl; f(); cout << "Program end" << endl; return 0;} The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output: global variable createdlocal to main createdProgram startstatic variable createdLocal variable createdFunction executedLocal variable destroyedProgram endlocal to main destroyedstatic variable destroyedglobal variable destroyed
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/55510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ] }
55,517
We are getting very slow compile times, which can take upwards of 20+ minutes on dual core 2GHz, 2G Ram machines. A lot of this is due to the size of our solution which has grown to 70+ projects, as well as VSS which is a bottle neck in itself when you have a lot of files. (swapping out VSS is not an option unfortunately, so I don't want this to descend into a VSS bash) We are looking at merging projects. We are also looking at having multiple solutions to achieve greater separation of concerns and quicker compile times for each element of the application. This I can see will become a DLL hell as we try to keep things in synch. I am interested to know how other teams have dealt with this scaling issue, what do you do when your code base reaches a critical mass that you are wasting half the day watching the status bar deliver compile messages. UPDATE I neglected to mention this is a C# solution. Thanks for all the C++ suggestions, but it's been a few years since I've had to worry about headers. EDIT: Nice suggestions that have helped so far (not saying there aren't other nice suggestions below, just what has helped) New 3GHz laptop - the power of lost utilization works wonders when whinging to management Disable Anti Virus during compile 'Disconnecting' from VSS (actually the network) during compile - I may get us to remove VS-VSS integration altogether and stick to using the VSS UI Still not rip-snorting through a compile, but every bit helps. Orion did mention in a comment that generics may have a play also. From my tests there does appear to be a minimal performance hit, but not high enough to sure - compile times can be inconsistent due to disc activity. Due to time limitations, my tests didn't include as many Generics, or as much code, as would appear in live system, so that may accumulate. I wouldn't avoid using generics where they are supposed to be used, just for compile time performance WORKAROUND We are testing the practice of building new areas of the application in new solutions, importing in the latest dlls as required, them integrating them into the larger solution when we are happy with them. We may also do them same to existing code by creating temporary solutions that just encapsulate the areas we need to work on, and throwing them away after reintegrating the code. We need to weigh up the time it will take to reintegrate this code against the time we gain by not having Rip Van Winkle like experiences with rapid recompiling during development.
The Chromium.org team listed several options for accelerating the build (at this point about half-way down the page): In decreasing order of speedup: Install Microsoft hotfix 935225 . Install Microsoft hotfix 947315 . Use a true multicore processor (ie. an Intel Core Duo 2; not a Pentium 4 HT). Use 3 parallel builds. In Visual Studio 2005, you will find the option in Tools > Options... > Projects and Solutions > Build and Run > maximum number of parallel project builds . Disable your anti-virus software for .ilk, .pdb, .cc, .h files and only check for viruses on modify . Disable scanning the directory where your sources reside. Don't do anything stupid. Store and build the Chromium code on a second hard drive. It won't really speed up the build but at least your computer will stay responsive when you do gclient sync or a build. Defragment your hard drive regularly. Disable virtual memory.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ] }
55,531
Background: Some time ago, I built a system for recording and categorizing application crashes for one of our internal programs. At the time, I used a combination of frequency and aggregated lost time (the time between the program launch and the crash) for prioritizing types of crashes. It worked reasonably well. Now, The Powers That Be want solid numbers on the cost of each type of crash being worked on. Or at least, numbers that look solid. I suppose I could use the aggregate lost time, multiplied by some plausible figure, but it seems dodgy. Question: Are there any established methods of calculating the real-world cost of application crashes? Or failing that, published studies speculating on such costs? Consensus Accuracy is impossible, but an estimate based on uptime should suffice if it is applied consistently and its limitations clearly documented. Thanks, Matt, Orion, for taking time to answer this.
I've not seen any studies, but a reasonable heuristic would be something like : ( Time since last application save when crash occurred + Time to restart application ) * Average hourly rate of application operator. The estimation gets more complex if the crashes have some impact on external customers such, or might delay other things (i.e. create a bottle neck such that another person winds up sitting around waiting because some else's application crashed). That said, your 'powers that be' may well be happy with a very rough estimate so long as it's applied consistently and they can see how it is changing over time.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811/" ] }
55,556
I need to generate some passwords, I want to avoid characters that can be confused for each other. Is there a definitive list of characters I should avoid? my current list is il10o8B3Evu![]{} Are there any other pairs of characters that are easy to confuse? for special characters I was going to limit myself to those under the number keys, though I know that this differs depending on your keyboards nationality! As a rider question, I would like my passwords to be 'wordlike'do you have a favoured algorithm for that? Thanks :)
Here are the character sets that Steve Gibson uses for his "Perfect Paper Password" system. They are "characters to allow" rather than "characters to avoid", but they seem pretty reasonable for what you want: A standard set of 64 characters !#%+23456789:=?@ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnopqrstuvwxyz A larger set of 88 characters !"#$%&'()*+,-./23456789:;<=>?@ABCDEFGHJKLMNOPRSTUVWXYZ[\]^_abcdefghijkmnopqrstuvwxyz{|}~ For pronounceable passwords, I'm not familiar with the algorithms but you might want to look at APG and pwgen as a starting point.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5552/" ] }
55,574
As it stands now, I'm a Java and C# developer. The more and more I look at Ruby on Rails, the more I really want to learn it. What have you found to be the best route to learn RoR? Would it be easier to develop on Windows, or should I just run a virtual machine with Linux? Is there an IDE that can match the robustness of Visual Studio? Any programs to develop that give a good overhead of what to do? Any good books? Seriously, any tips/tricks/rants would be awesome.
I've been moving from C# in my professional career to looking at Ruby and RoR in my personal life, and I've found linux to be slightly more appealing personally for development. Particularly now that I've started using git, the implementation is cleaner on linux. Currently I'm dual booting and getting closer to running Ubuntu full time. I'm using gedit with various plugins for the development environment. And as of late 2010, I'm making the push to use Vim for development, even over Textmate on OS X. A large amount of the Rails developers are using (gasp) Macs, which has actually got me thinking in that direction. Although I haven't tried it, Ruby in Steel gives you a Ruby IDE inside the Visual Studio world, and IronRuby is the .NET flavor of Ruby, if you're interested. As far as books are concerned, the Programming Ruby (also known as the Pickaxe) book from the Pragmatic Programmers is the de-facto for learning Ruby. I bit the bullet and purchased that book and Agile Web Development with Rails ; both books have been excellent. Peepcode screencasts and PDF books have also been great for getting started; at $9 per screencast it's hard to go wrong. I actually bought a 5-pack. Also check out the following: Official Rails Guides Railscasts railsapi.com or Ruby on Rails - APIdock The Ruby Show Rails for Zombies Softies on Rails - Ruby on Rails for .NET Developers Rails Podcast Rails Best Practices I've burned through the backlog of Rails and Rails Envy podcasts in the past month and they have provided wonderful insight into lots of topics, even regarding software development in general.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/55574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066/" ] }
55,577
I want to test the web pages I create in all the modern versions of Internet Explorer (6, 7 and 8 beta) but I work mainly on a Mac and often don't have direct access to a PC.
Update: Microsoft now provide virtual machine images for various versions of IE that are ready to use on all of the major OS X virtualisation platforms ( VirtualBox , VMWare Fusion , and Parallels ). Download the appropriate image from: https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/ On an Intel based Mac you can run Windows within a virtual machine. You will need one virtual machine for each version of IE you want to test against. The instructions below include free and legal virtualisation software and Windows disk images. Download some virtual machine software. The developer disk images we're going to use are will work with either VMWare Fusion or Sun Virtual Box . VMWare has more features but costs $80, Virtual Box on the other hand is more basic but is free for most users (see Virtual Box licensing FAQ for details). Download the IE developer disk images, which are free from Microsoft: http://www.microsoft.com/downloads/... Extract the disk images using cabextract which is available from MacPorts or as source code (Thanks to Clinton ). Download Q.app from http://www.kju-app.org/ and put it in your /Applications folder (you will need it to convert the disk images into a format VMWare/Virtual Box can use) At this point, the process depends on which VM software you're using. Virtual Box users Open a Terminal.app on your Mac (you can find it in /Applications/Utilities) and run the following sequence of commands, replacing input.vhd with the name of the VHD file you're starting from and output.vdi with the name you want your final disk image to have: /Applications/Q.app/Contents/MacOS/qemu-img convert -O raw -f vpc "input.vhd" temp.binVBoxManage convertdd temp.bin "output.vdi"rm temp.binmv "output.vdi" ~/Library/VirtualBox/VDI/VBoxManage modifyvdi "output.vdi" compact Start Virtual Box and create a new virtual machine Select the new VDI file you've just created as the boot hard disk VMWare fusion users Open a Terminal.app on your Mac (you can find it in /Applications/Utilities) and run the following commands, replacing input.vhd and output.vmdk with the name of the VHD file you're working on and the name you want your resulting disk image to have: /Applications/Q.app/Contents/MacOS/qemu-img convert -O vmdk -f vpc "input.vhd" "output.vmdk"mv "output.vmdk" ~/Documents/Virtual\ Machines.localized/ This will probably take a while (It takes around 30 minutes per disk image on my 2.4GHz Core 2 Duo MacBook w/ 2Gb RAM). Start VMWare Fusion and create a new virtual machine In the advanced disk options select "use and existing disk" and find the VMDK file you just created
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5168/" ] }
55,594
When developing (works fine live) the pages for our website don't pick up the correct CSS until the user has authenticated (logged on). So the Logon and Logoff forms look bad, but once inside the site, the CSS works again. I'm guessing it's some kind of authentication issue? Haven't really looked into it too much because it's only when working on dev so not a huge issue, but would be nice to know how to fix it.
Check and make sure that the CSS file itself is not in an area that you are securing. You can manually exclude the file via the web.config if needed.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ] }
55,607
What is the best way to use multiple EVAL fields in a GridView ItemTemplate? Looking to have some control over formatting for appearance as well as setting up hyperlinks/javascript etc.
Even clearer, IMO, is: <%# String.Format("{0} - {1}", Eval("Name1"), Eval("Name2")) %>
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242/" ] }
55,611
To make a JavaScript class with a public method I'd do something like: function Restaurant() {}Restaurant.prototype.buy_food = function(){ // something here}Restaurant.prototype.use_restroom = function(){ // something here} That way users of my class can: var restaurant = new Restaurant();restaurant.buy_food();restaurant.use_restroom(); How do I create a private method that can be called by the buy_food and use_restroom methods but not externally by users of the class? In other words, I want my method implementation to be able to do: Restaurant.prototype.use_restroom = function() { this.private_stuff();} But this shouldn't work: var r = new Restaurant();r.private_stuff(); How do I define private_stuff as a private method so both of these hold true? I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.
You can do it, but the downside is that it can't be part of the prototype: function Restaurant() { var myPrivateVar; var private_stuff = function() { // Only visible inside Restaurant() myPrivateVar = "I can set this here!"; } this.use_restroom = function() { // use_restroom is visible to all private_stuff(); } this.buy_food = function() { // buy_food is visible to all private_stuff(); }}
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/55611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3284/" ] }
55,612
This one has me kind of stumped. I want to make the first word of all the paragraphs in my #content div at 14pt instead of the default for the paragraphs (12pt). Is there a way to do this in straight CSS or am I left wrapping the first word in a span to accomplish this?
What you are looking for is a pseudo-element that doesn't exist. There is :first-letter and :first-line , but no :first-word . You can of course do this with JavaScript. Here's some code I found that does this: http://www.dynamicsitesolutions.com/javascript/first-word-selector/
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/55612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204/" ] }
55,633
WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a console documentation for Firebug , but where can I find the console documentation for Safari/WebKit?
Supported methods were originally: console.log() console.error() console.warn() console.info() Newer versions of WebKit also add the following methods making the WebKit console API almost identical to Firebug's console API : console.count() console.debug() console.profileEnd() console.trace() console.dir() console.dirxml() console.assert() console.time() console.profile() console.timeEnd() console.group() console.groupEnd() (New information based on the WebKit nightly build WebKit-SVN-r37126, at the time of writing these methods aren't available in Safari)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ] }
55,641
What is the best practice of Unicode processing in C++?
Use ICU for dealing with your data (or a similar library) In your own data store, make sure everything is stored in the same encoding Make sure you are always using your unicode library for mundane tasks like string length, capitalization status, etc. Never use standard library builtins like is_alpha unless that is the definition you want. I can't say it enough: never iterate over the indices of a string if you care about correctness, always use your unicode library for this.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5694/" ] }
55,643
I'm going to be implementing a PHP/mySQL setup to store credit card information. It seems like AES_ENCRYPT/AES_DECRYPT is the way to go, but I'm still confused on one point: How do I keep the encryption key secure? Hardwiring it into my PHP scripts (which will live on the same server as the db) seems like a major security hole. What's the "best practice" solution here?
You should think long and hard about whether you REALLY need to keep the CC#. If you don't have a great reason, DON'T! Every other week you hear about some company being compromised and CC#'s being stolen. All these companies made a fatal flaw - they kept too much information. Keep the CC# until the transaction clears. After that, delete it. As far as securing the server, the best course of action is to secure the hardware and use the internal system socket to MySQL, and make sure to block any network access to the MySQL server. Make sure you're using both your system permissions and the MySQL permissions to allow as little access as needed. For some scripts, you might consider write-only authentication. There's really no encryption method that will be foolproof (as you will always need to decrypt, and thus must store the key). This is not to say you shouldn't - you can store your key in one location and if you detect system compromise you can destroy the file and render the data useless.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3578/" ] }
55,677
What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)? No legacy browser compatibility required, Safari, Opera and Firefox will do.
If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but without jQuery . function getCursorPosition(canvas, event) { const rect = canvas.getBoundingClientRect() const x = event.clientX - rect.left const y = event.clientY - rect.top console.log("x: " + x + " y: " + y)}const canvas = document.querySelector('canvas')canvas.addEventListener('mousedown', function(e) { getCursorPosition(canvas, e)})
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/55677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3715/" ] }
55,692
My background is primarily as a Java Developer, but lately I have been doing some work in .NET. So I have been trying to do some simple projects at home to get better at working with .NET. I have been able to transfer much of my Java experience into working with .NET (specifically C#), but the only thing that has really perplexed me is namespaces. I know namespaces are similar to Java packages, but as from what I can tell the main difference is that with Java packages they use actual file folders to show the seperation, while in .NET it does not and all the files reside in a single folder and the namespace is simply declared in each class. I find this odd, because I always saw packages as a way to organize and group related code, making it easier to navigate and comprehend. Since in .NET it does not work this work this way, overtime, the project appears more overcrowded and not as easy to navigate. Am I missing something here? I have to be. Should I be breaking things into separate projects within the solution? Or is there a better way to keep the classes and files organized within a project? Edit: As Blair pointed out this is pretty much the same question asked here .
I can't claim that it's a best practice, but I often see files organized in a directory hierarchy that mirrors the namespace. If it fits your mental model of the code better, then do so - I can't think of any harm. Just because the .NET model doesn't enforce relationships between namespaces, projects, and directory structure doesn't mean you can't have such relationships if you want to. I'd be a little leery of breaking up the code into more projects than you need, as this can slow compilation and add a little bit of overhead when you have to manage multiple assemblies. EDIT: Note that this question is nearly a duplicate of should the folders in a solution match the namespace?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3340/" ] }
55,693
"Evidence-based scheduling" in FogBugz is interesting, but how do I use it w/ an Agile methodology?
As eed3si9n said, if you are consistent in your estimates for EBS, FogBugz will take care of this for you. As to the more general, how does FogBugz fit with the Agile methodology, your best bet is to do sprints as mini-releases. Create a sprint and add the cases you want to achieve for that sprint to that release (or milestone). Give it an end date, say a week away, if you do week long sprints. Then EBS can track it and tell you if you are on schedule. The graphs in the Reports section will also show you a burndown chart. The terminology is a bit different because FogBugz isn't Agile-only but the info is there. You want to see if the expected time you are going to finish your sprint is staying steady or going forward. If it is steady you are on track and your burndown rate is on target. If it is creeping up, you are losing ground and your sprint is getting delayed. Time to move things to the next sprint or figure out why you messed up your estimates :) Essentially I suppose this is a burn-up chart instead of a burndown chart, but it gives you the same answer to the same question. Am I going to finish on time? What do I have left to do? Atalasoft's Lou Franco wrote an excellent post on this as well. Patrick Altman also has an article. Update: fixed link to Altman's article
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ] }
55,709
I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3. Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles. My question is : is there any best practice in how to code a java servlet to stream a large (>200k) response back to a browser when read from a database or other cloud storage? I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy. Any thoughts would be appreciated. Thanks.
When possible, you should not store the entire contents of a file to be served in memory. Instead, aquire an InputStream for the data, and copy the data to the Servlet OutputStream in pieces. For example: ServletOutputStream out = response.getOutputStream();InputStream in = [ code to get source input stream ];String mimeType = [ code to get mimetype of data to be served ];byte[] bytes = new byte[FILEBUFFERSIZE];int bytesRead;response.setContentType(mimeType);while ((bytesRead = in.read(bytes)) != -1) { out.write(bytes, 0, bytesRead);}// do the following in a finally block:in.close();out.close(); I do agree with toby, you should instead "point them to the S3 url." As for the OOM exception, are you sure it has to do with serving the image data? Let's say your JVM has 256MB of "extra" memory to use for serving image data. With Google's help, "256MB / 200KB" = 1310. For 2GB "extra" memory (these days a very reasonable amount) over 10,000 simultaneous clients could be supported. Even so, 1300 simultaneous clients is a pretty large number. Is this the type of load you experienced? If not, you may need to look elsewhere for the cause of the OOM exception. Edit - Regarding: In this use case the images can contain sensitive data... When I read through the S3 documentation a few weeks ago, I noticed that you can generate time-expiring keys that can be attached to S3 URLs. So, you would not have to open up the files on S3 to the public. My understanding of the technique is: Initial HTML page has download links to your webapp User clicks on a download link Your webapp generates an S3 URL that includes a key that expires in, lets say, 5 minutes. Send an HTTP redirect to the client with the URL from step 3. The user downloads the file from S3. This works even if the download takes more than 5 minutes - once a download starts it can continue through completion.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4974/" ] }
55,720
Here's my first question at SO. I have a internal application for my company which I've been recently ask to maintain. The applications is built in PHP and its fairly well coded (OO, DB Abstraction, Smarty) nothing WTF-ish. The problem is the applications is very slow . How do I go about finding out what's slowing the application down? I've optimized the code to make very few DB queries, so I know that it is the PHP code which is taking a while to execute. I need to get some tools which can help me with this and need to devise a strategy for checking my code. I can do the checking/strategy work myself, but I need more PHP tools to figure out where my app is crapping up. Thoughts?
I've used XDebug profiling recently in a similiar situation. It outputs a full profile report that can be read with many common profiling apps ( Can't give you a list though, I just used the one that came with slackware ).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3983/" ] }
55,729
How often should you use git-gc? The manual page simply says: Users are encouraged to run this task on a regular basis within each repository to maintain good disk space utilization and good operating performance. Are there some commands to get some object counts to find out whether it's time to gc?
It depends mostly on how much the repository is used. With one user checking in once a day and a branch/merge/etc operation once a week you probably don't need to run it more than once a year. With several dozen developers working on several dozen projects each checking in 2-3 times a day, you might want to run it nightly. It won't hurt to run it more frequently than needed, though. What I'd do is run it now, then a week from now take a measurement of disk utilization, run it again, and measure disk utilization again. If it drops 5% in size, then run it once a week. If it drops more, then run it more frequently. If it drops less, then run it less frequently.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/55729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
55,754
What is the best way, using Bash, to rename files in the form: (foo1, foo2, ..., foo1300, ..., fooN) With zero-padded file names: (foo00001, foo00002, ..., foo01300, ..., fooN)
In case N is not a priori fixed: for f in foo[0-9]*; do mv "$f" "$(printf 'foo%05d' "${f#foo}")"done
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3020/" ] }
55,828
Is there a simple method of parsing XML files in C#? If so, what?
I'd use LINQ to XML if you're in .NET 3.5 or higher.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/55828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4361/" ] }
55,835
I'm working on a web-based contest which is supposed to allow anonymous users to vote, but we want to prevent them from voting more than once. IP based limits can be bypassed with anonymous proxies, users can clear cookies, etc. It's possible to use a Silverlight application, which would have access to isolated storage, but users can still clear that. I don't think it's possible to do this without some joker voting himself up with a bot or something. Got an idea?
The short answer is: no. The longer answer is: but you can make it arbitrarily difficult. What I would do: Voting requires solving a captcha (to avoid as much as possible automated voting). To be even more effective I would recommend to have prepared multiple types of simple captchas (like "pick the photo with the cat", "what is 2+2", "type in the word", etc) and rotate them both by the time of the day and by IP, which should make automatic systems ineffective (ie if somebody using IP A creates a bot to solve the captcha, this will become useless the next day or if s/he distributes it onto other computers/uses proxies) When filtering by IP you should be careful to consider situations where multiple hosts are behind one public IP (AFAIK AOL proxies all of their customers through a few IPs - so such a limitation would effectively ban AOL users). Also, many proxies send along headers pointing to the original IP (like X-Forwarded-For), so you can take a look at that too. Finally, using something like FSO (Flash Shared Objects - "Flash cookies") is obscure enough for 99.99% of the people not to know about. Silverlight is even more obscure. To be even sneakier, you could buy an other domain and set the FSO from that domain (so, if the user is looking for FSO's set by your domain, they won't see any) None of these methods is 100%, but hopefully combined they give you the level of assurance you need. If you want to take this a level higher, you need to add some kind of user registration (which can be as simple as asking a valid e-mail address when the vote occurs and sending a confirmation link to the given address and not counting the votes for which the link wasn't clicked - so it doesn't need to be a full-fledged "create an account with username / password / firs name / last name / etc").
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ] }
55,855
I am following the M-V-VM pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple. Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class?
First off, you've surely considered two-way data binding to your viewmodel, with an UpdateSourceTrigger of PropertyChanged? That way the property setter of the property you bind to will be called every time the text is changed? If that's not enough, then I would tackle this problem using Attached Behaviours. On Julian Dominguez’s Blog you'll find an article about how to do something very similar in Silverlight, which should be easily adaptable to WPF. Basically, in a static class (called, say TextBoxBehaviours) you define an Attached Property called (perhaps) TextChangedCommand of type ICommand. Hook up an OnPropertyChanged handler for that property, and within the handler, check that the property is being set on a TextBox; if it is, add a handler to the TextChanged event on the textbox that will call the command specified in the property. Then, assuming your viewmodel has been assigned to the DataContext of your View, you would use it like: <TextBox x:Name="MyTextBox" TextBoxBehaviours.TextChangedCommand="{Binding ViewModelTextChangedCommand}" />
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708/" ] }
55,859
In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?
catch (...){ // Handle exceptions not covered.} Important considerations: A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions. catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program. Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the RAII pattern if you choose this route.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195/" ] }
55,862
I'm writing a little desktop app that should be able to encrypt a data file and protect it with a password (i.e. one must enter the correct password to decrypt). I want the encrypted data file to be self-contained and portable, so the authentication has to be embedded in the file (or so I assume). I have a strategy that appears workable and seems logical based on what I know (which is probably just enough to be dangerous), but I have no idea if it's actually a good design or not. So tell me: is this crazy? Is there a better/best way to do it? Step 1: User enters plain-text password, e.g. "MyDifficultPassword" Step 2: App hashes the user-password and uses that value as the symmetric key to encrypt/decrypt the data file. e.g. "MyDifficultPassword" --> "HashedUserPwdAndKey". Step 3: App hashes the hashed value from step 2 and saves the new value in the data file header (i.e. the unencrypted part of the data file) and uses that value to validate the user's password. e.g. "HashedUserPwdAndKey" --> "HashedValueForAuthentication" Basically I'm extrapolating from the common way to implement web-site passwords (when you're not using OpenID, that is), which is to store the (salted) hash of the user's password in your DB and never save the actual password. But since I use the hashed user password for the symmetric encryption key, I can't use the same value for authentication. So I hash it again, basically treating it just like another password, and save the doubly-hashed value in the data file. That way, I can take the file to another PC and decrypt it by simply entering my password. So is this design reasonably secure, or hopelessly naive, or somewhere in between? Thanks! EDIT: clarification and follow-up question re: Salt. I thought the salt had to be kept secret to be useful, but your answers and links imply this is not the case. For example, this spec linked by erickson (below) says: Thus, password-based key derivation as defined here is a function of a password, a salt, and an iteration count, where the latter two quantities need not be kept secret. Does this mean that I could store the salt value in the same place/file as the hashed key and still be more secure than if I used no salt at all when hashing? How does that work? A little more context: the encrypted file isn't meant to be shared with or decrypted by others, it's really single-user data. But I'd like to deploy it in a shared environment on computers I don't fully control (e.g. at work) and be able to migrate/move the data by simply copying the file (so I can use it at home, on different workstations, etc.).
Key Generation I would recommend using a recognized algorithm such as PBKDF2 defined in PKCS #5 version 2.0 to generate a key from your password. It's similar to the algorithm you outline, but is capable of generating longer symmetric keys for use with AES. You should be able to find an open-source library that implements PBE key generators for different algorithms. File Format You might also consider using the Cryptographic Message Syntax as a format for your file. This will require some study on your part, but again there are existing libraries to use, and it opens up the possibility of inter-operating more smoothly with other software, like S/MIME-enabled mail clients. Password Validation Regarding your desire to store a hash of the password, if you use PBKDF2 to generate the key, you could use a standard password hashing algorithm (big salt, a thousand rounds of hashing) for that, and get different values. Alternatively, you could compute a MAC on the content. A hash collision on a password is more likely to be useful to an attacker; a hash collision on the content is likely to be worthless. But it would serve to let a legitimate recipient know that the wrong password was used for decryption. Cryptographic Salt Salt helps to thwart pre-computed dictionary attacks. Suppose an attacker has a list of likely passwords. He can hash each and compare it to the hash of his victim's password, and see if it matches. If the list is large, this could take a long time. He doesn't want spend that much time on his next target, so he records the result in a "dictionary" where a hash points to its corresponding input. If the list of passwords is very, very long, he can use techniques like a Rainbow Table to save some space. However, suppose his next target salted their password. Even if the attacker knows what the salt is, his precomputed table is worthless —the salt changes the hash resulting from each password. He has to re-hash all of the passwords in his list, affixing the target's salt to the input. Every different salt requires a different dictionary, and if enough salts are used, the attacker won't have room to store dictionaries for them all. Trading space to save time is no longer an option; the attacker must fall back to hashing each password in his list for each target he wants to attack. So, it's not necessary to keep the salt secret. Ensuring that the attacker doesn't have a pre-computed dictionary corresponding to that particular salt is sufficient.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4154/" ] }
55,869
I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask). What's the best way to determine the image format in .NET? The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose.
A probably easier approach would be to use Image.FromFile() and then use the RawFormat property, as it already knows about the magic bits in the headers for the most common formats, like this: Image i = Image.FromFile("c:\\foo");if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat)) MessageBox.Show("JPEG");else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(i.RawFormat)) MessageBox.Show("GIF");//Same for the rest of the formats
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277/" ] }
55,871
Is it possible to detect when the user clicks on the browser's back button? I have an Ajax application and if I can detect when the user clicks on the back button I can display the appropriate data back Any solution using PHP, JavaScript is preferable. Hell a solution in any language is fine, just need something that I can translate to PHP/JavaScript Edit: Cut and paste from below: Wow, all excellent answers. I'd like to use Yahoo but I already use Prototype and Scriptaculous libraries and don't want to add more ajax libraries. But it uses iFrames which gives me a good pointer to write my own code.
There are multiple ways of doing it, though some will only work in certain browsers. One that I know off the top of my head is to embed a tiny near-invisible iframe on the page. When the user hits the back button the iframe is navigated back which you can detect and then update your page. Here is another solution. You might also want to go view source on something like gmail and see how they do it. Here's a library for the sort of thing you're looking for by the way
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3983/" ] }
55,899
I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!) I've been asked to define the specs for a variant of an existing report (e.g., apply additional filters to constrain the data set, and modify the layout slightly). This sounds simple enough in principle, but is difficult without any existing documentation. It's my understanding that the logs can't help me because the report only queries the database; it does not actually insert, delete, or update database values, so there is nothing to log (is this correct?). So my question is this: is there a tool or utility (Oracle or otherwise) that I can use to see the actual SQL statement that is being executed while the report generation job is still running? I figure, if I can see what tables are actually being accessed to produce the existing report, I'll have a very good starting point for exploring the schema and determining the correct SQL to use for my own report.
On the data dictionary side there are a lot of tools you can use to such as Schema Spy To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users One thing to note that queries that use parameters will show up once with entries like and TABLETYPE=’:b16’ while others that dont will show up multiple times such as: and TABLETYPE=’MT’ An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the WHERE rownum <= 20 and maybe add ORDER BY module . You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc) SELECT module, sql_text, username, disk_reads_per_exec, buffer_gets, disk_reads, parse_calls, sorts, executions, rows_processed, hit_ratio, first_load_time, sharable_mem, persistent_mem, runtime_mem, cpu_time, elapsed_time, address, hash_value FROM (SELECT module, sql_text , u.username , round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec, s.disk_reads , s.buffer_gets , s.parse_calls , s.sorts , s.executions , s.rows_processed , 100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio, s.first_load_time , sharable_mem , persistent_mem , runtime_mem, cpu_time, elapsed_time, address, hash_value FROM sys.v_$sql s, sys.all_users u WHERE s.parsing_user_id=u.user_id and UPPER(u.username) not in ('SYS','SYSTEM') ORDER BY 4 desc) WHERE rownum <= 20; Note that if the query is long .. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg: SELECT *FROM sys.v_$sqltextWHERE address = 'C0000000372B3C28' and hash_value = '1272580459'ORDER BY address, hash_value, command_type, piece;
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/480/" ] }
55,901
Is there a web service of some sort (or any other way) to pull a current time zone settings for a (US) city. For the parts of the country that don't follow the Daylight Saving Time and basically jump timezones when everyone else is switching summer/winter time... I don't fancy creating own database of the places that don't follow DST. Is there a way to pull this data on demand? I need this for the database server (not for client workstations) - there entities stored in the database that have City, State as properties. I need know current timezone for these entities at any moment of time.
earthtools.org provides a free web service to get the time zone from a city here: http://www.earthtools.org/webservices.htm#timezone You just pass in the long/lat values like this: (This is for New York) http://www.earthtools.org/timezone-1.1/40.71417/-74.00639 EDIT: It seems like earthtools has been shut down. A good alternative (That did not exist in 2008 when this question was answered) is the Google Time Zone API. To use it you must first activate the Time Zone API on your account. It is free if you stay below these limits: 2500 requests per 24 hour period. 5 requests per second. The documentation is available on Google Developers.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/55901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4808/" ] }
55,943
Is their any profilers that support Silverlight? I have tried ANTS (Version 3.1) without any success? Does version 4 support it? Any other products I can try? Updated since the release of Silverlight 4, it is now possible to do full profiling on SL applications... check out this article on the topic At PDC, I announced that Silverlight 4 came with the new CoreCLR capability of being profile-able by the VS2010 profilers: this means that for the first time, we give you the power to profile the managed and native code (user or platform) used by a Silverlight application. woohoo. kudos to the CLR team. Sidenote: From silverlight 1-3, one could only use things like xperf (see XPerf: A CPU Sampler for Silverlight) which is very powerful to see the layout/text/media/gfx/etc pipelines, but only gives the native callstack.) From SilverLite ( PDC video, TechEd Iceland, VS2010, profiling, Silverlight 4 )
Install XPerf and xperfview as available here: http://msdn.microsoft.com/en-us/library/cc305218.aspx (1) Startup your sample (2) xperf -on base (3) wait for a bit (4) xperf –d myprofile.etl (5) when this is done, set your symbol path: set _NT_SYMBOL_PATH= srv C:\symbols http://msdl.microsoft.com/downloads/symbols (6) xperfview myprofile.etl (7) Trace -> Load Symbols Select the area of the CPU graph that you want to see Right-click and select Summary Table (8) Accept the EULA for using symbols, expand IExplore, expand agcore.dll or whatever is your top module
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5147/" ] }
55,956
is there an alternative for mysql_insert_id() php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column....
From the PostgreSQL point of view, in pseudo-code: * $insert_id = INSERT...RETURNING foo_id;-- only works for PostgreSQL >= 8.2. * INSERT...; $insert_id = SELECT lastval(); -- works for PostgreSQL >= 8.1 * $insert_id = SELECT nextval('foo_seq'); INSERT INTO table (foo...) values ($insert_id...) for older PostgreSQL (and newer PostgreSQL) pg_last_oid() only works where you have OIDs. OIDs have been off by default since PostgreSQL 8.1. So, depending on which PostgreSQL version you have, you should pick one of the above method. Ideally, of course, use a database abstraction library which abstracts away the above. Otherwise, in low level code, it looks like: Method one: INSERT... RETURNING // yes, we're not using pg_insert()$result = pg_query($db, "INSERT INTO foo (bar) VALUES (123) RETURNING foo_id");$insert_row = pg_fetch_row($result);$insert_id = $insert_row[0]; Method two: INSERT; lastval() $result = pg_execute($db, "INSERT INTO foo (bar) values (123);");$insert_query = pg_query("SELECT lastval();");$insert_row = pg_fetch_row($insert_query);$insert_id = $insert_row[0]; Method three: nextval(); INSERT $insert_query = pg_query($db, "SELECT nextval('foo_seq');");$insert_row = pg_fetch_row($insert_query);$insert_id = $insert_row[0];$result = pg_execute($db, "INSERT INTO foo (foo_id, bar) VALUES ($insert_id, 123);"); The safest bet would be the third method, but it's unwieldy. The cleanest is the first, but you'd need to run a recent PostgreSQL. Most db abstraction libraries don't yet use the first method though.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5742/" ] }
55,961
I admit it: I don't bother with too much exception handling. I know I should do more but I can never wrap my head around where to start and where to stop. I'm not being lazy. Far from it. It's that I'm overwrought with exception handling ambivalence. It just seems that there is a seemingly infinite number of places in even the smallest app where exception handling can be applied and it can begin to feel like overkill. I've gotten by with careful testing, validating, and silent prayer but this is a bad programming accident waiting to happen. So, what are your exception handling best practices? In particular, where are the most obvious/critical places where exception handling should be applied and where are places where it should be considered? Sorry for the vague the question but I really want to close the book on this once and for all.
Microsoft's Patterns & Practices team did a good job incorporating best practices of exception management into Enterprise Library Exception Handling Application Block Event if wouldn't use Enterprise Library, I highly recommend you to read their documentation. P&P team describes common scenarios and best practices for exceptions handling. To get you started I recommend read following articles: Exception Handling on MSDN Exception Management in .NET on MSDN Exception Handling Best Practices in .NET on CodeProject ASP.NET specific articles: User Friendly ASP.NET Exception Handling Global Exception Handling withASP.NET Exception handling in C# and ASP.Net
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ] }
55,964
How can I make a major upgrade to an installation set (MSI) built with WiX install into the same folder as the original installation? The installation is correctly detected as an upgrade, but the directory selection screen is still shown and with the default value (not necessarily the current installation folder). Do I have to do manual work like saving the installation folder in a registry key upon first installing and then read this key upon upgrade? If so, is there any example? Or is there some easier way to achieve this in MSI or WiX? As reference, I my current WiX file is below: <?xml version="1.0" encoding="utf-8"?><Wix xmlns="http://schemas.microsoft.com/wix/2003/01/wi"> <Product Id="a2298d1d-ba60-4c4d-92e3-a77413f54a53" Name="MyCompany Integration Framework 1.0.0" Language="1033" Version="1.0.0" Manufacturer="MyCompany" UpgradeCode="9071eacc-9b5a-48e3-bb90-8064d2b2c45d"> <!-- Package information --> <Package Keywords="Installer" Id="e85e6190-1cd4-49f5-8924-9da5fcb8aee8" Description="Installs MyCompany Integration Framework 1.0.0" Comments="Installs MyCompany Integration Framework 1.0.0" InstallerVersion="100" Compressed="yes" /> <Upgrade Id='9071eacc-9b5a-48e3-bb90-8064d2b2c45d'> <UpgradeVersion Property="PATCHFOUND" OnlyDetect="no" Minimum="0.0.1" IncludeMinimum="yes" Maximum="1.0.0" IncludeMaximum="yes"/> </Upgrade> <!-- Useless but necessary... --> <Media Id="1" Cabinet="MyCompany.cab" EmbedCab="yes" /> <!-- Precondition: .NET 2 must be installed --> <Condition Message='This setup requires the .NET Framework 2 or higher.'> <![CDATA[MsiNetAssemblySupport >= "2.0.50727"]]> </Condition> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="MyCompany" Name="MyCompany"> <Directory Id="INSTALLDIR" Name="Integrat" LongName="MyCompany Integration Framework"> <Component Id="MyCompanyDllComponent" Guid="4f362043-03a0-472d-a84f-896522ce7d2b" DiskId="1"> <File Id="MyCompanyIntegrationDll" Name="IbIntegr.dll" src="..\Build\MyCompany.Integration.dll" Vital="yes" LongName="MyCompany.Integration.dll" /> <File Id="MyCompanyServiceModelDll" Name="IbSerMod.dll" src="..\Build\MyCompany.ServiceModel.dll" Vital="yes" LongName="MyCompany.ServiceModel.dll" /> </Component> <!-- More components --> </Directory> </Directory> </Directory> <Feature Id="MyCompanyProductFeature" Title='MyCompany Integration Framework' Description='The complete package' Display='expand' Level="1" InstallDefault='local' ConfigurableDirectory="INSTALLDIR"> <ComponentRef Id="MyCompanyDllComponent" /> </Feature> <!-- Task scheduler application. It has to be used as a property --> <Property Id="finaltaskexe" Value="MyCompany.Integration.Host.exe" /> <Property Id="WIXUI_INSTALLDIR" Value="INSTALLDIR" /> <InstallExecuteSequence> <!-- command must be executed: MyCompany.Integration.Host.exe /INITIALCONFIG parameters.xml --> <Custom Action='PropertyAssign' After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom> <Custom Action='LaunchFile' After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom> <RemoveExistingProducts Before='CostInitialize' /> </InstallExecuteSequence> <!-- execute comand --> <CustomAction Id='PropertyAssign' Property='PathProperty' Value='[INSTALLDIR][finaltaskexe]' /> <CustomAction Id='LaunchFile' Property='PathProperty' ExeCommand='/INITIALCONFIG "[INSTALLDIR]parameters.xml"' Return='asyncNoWait' /> <!-- User interface information --> <UIRef Id="WixUI_InstallDir" /> <UIRef Id="WixUI_ErrorProgressText" /> </Product></Wix>
There's an example in the WiX tutorial: https://www.firegiant.com/wix/tutorial/getting-started/where-to-install/ <Property Id="INSTALLDIR"> <RegistrySearch Id='AcmeFoobarRegistry' Type='raw' Root='HKLM' Key='Software\Acme\Foobar 1.0' Name='InstallDir' /></Property> Of course, you've got to set the registry key as part of the install too. Stick this inside a component that's part of the original install: <RegistryKey Key="Software\Software\Acme\Foobar 1.0" Root="HKLM"> <RegistryValue Id="FoobarRegInstallDir" Type="string" Name="InstallDir" Value="[INSTALLDIR]" /></RegistryKey>
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/55964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4683/" ] }
55,978
I know how to test an object to see if it is of a type, using the IS keyword e.g. if (foo is bar){ //do something here} but how do you test for it not being "bar"?, I can't seem to find a keyword that works with IS to test for a negative result. BTW - I have a horrible feeling this is soooo obvious, so apologies in advance...
if (!(foo is bar)) {}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/55978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5175/" ] }
55,984
What is the difference between const and readonly in C#? When would you use one over the other?
Apart from the apparent difference of having to declare the value at the time of a definition for a const VS readonly values can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen. const 's are implicitly static . You use a ClassName.ConstantName notation to access them. There is a subtle difference. Consider a class defined in AssemblyA . public class Const_V_Readonly{ public const int I_CONST_VALUE = 2; public readonly int I_RO_VALUE; public Const_V_Readonly() { I_RO_VALUE = 3; }} AssemblyB references AssemblyA and uses these values in code. When this is compiled: in the case of the const value, it is like a find-replace. The value 2 is 'baked into' the AssemblyB 's IL. This means that if tomorrow I update I_CONST_VALUE to 20, AssemblyB would still have 2 till I recompile it . in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB 's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA and all clients do not need to be recompiled. So if you are confident that the value of the constant won't change, use a const . public const int CM_IN_A_METER = 100; But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a readonly . public readonly float PI = 3.14; Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: Effective C# - Bill Wagner
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/55984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
56,011
According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?
I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed. For example: LIGHT_MESSAGES = { 'English': "There are %(number_of_lights)s lights.", 'Pirate': "Arr! Thar be %(number_of_lights)s lights."}def lights_message(language, number_of_lights): """Return a language-appropriate string reporting the light count.""" return LIGHT_MESSAGES[language] % locals()def is_pirate(message): """Return True if the given message sounds piratical.""" return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/56011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
56,052
EditPad Lite has a nice feature ( CTRL - E , CTRL - I ) which inserts a time stamp e.g. "2008-09-11 10:34:53" into your code. What is the best way to get this functionality in Vim? (I am using Vim 6.1 on a Linux server via SSH. In the current situation a number of us share a login so I don't want to create abbreviations in the home directory if there is another built-in way to get a timestamp.)
http://kenno.wordpress.com/2006/08/03/vim-tip-insert-time-stamp/ Tried it out, it works on my mac: :r! date produces: Thu Sep 11 10:47:30 CEST 2008 This: :r! date "+\%Y-\%m-\%d \%H:\%M:\%S" produces: 2008-09-11 10:50:56
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/56052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ] }
56,078
I got a Function that returns a Collection<string> , and that calls itself recursively to eventually return one big Collection<string> . Now, i just wonder what the best approach to merge the lists? Collection.CopyTo() only copies to string[], and using a foreach() loop feels like being inefficient. However, since I also want to filter out duplicates, I feel like i'll end up with a foreach that calls Contains() on the Collection . I wonder, is there a more efficient way to have a recursive function that returns a list of strings without duplicates? I don't have to use a Collection , it can be pretty much any suitable data type. Only exclusion, I'm bound to Visual Studio 2005 and .net 3.0, so no LINQ. Edit: To clarify: The Function takes a user out of Active Directory, looks at the Direct Reports of the user, and then recursively looks at the direct reports of every user. So the end result is a List of all users that are in the "command chain" of a given user.Since this is executed quite often and at the moment takes 20 Seconds for some users, i'm looking for ways to improve it. Caching the result for 24 Hours is also on my list btw., but I want to see how to improve it before applying caching.
If you're using List<> you can use .AddRange to add one list to the other list. Or you can use yield return to combine lists on the fly like this: public IEnumerable<string> Combine(IEnumerable<string> col1, IEnumerable<string> col2){ foreach(string item in col1) yield return item; foreach(string item in col2) yield return item;}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
56,087
I know about the "cooperative" threading of ruby using green threads . How can I create real "OS-level" threads in my application in order to make use of multiple cpu cores for processing?
Updated with Jörg's Sept 2011 comment You seem to be confusing two very different things here: the Ruby Programming Language and the specific threading model of one specific implementation of the Ruby Programming Language. There are currently around 11 different implementations of the Ruby Programming Language, with very different and unique threading models. (Unfortunately, only two of those 11 implementations are actually ready for production use, but by the end of the year that number will probably go up to four or five.) ( Update : it's now 5: MRI, JRuby, YARV (the interpreter for Ruby 1.9), Rubinius and IronRuby). The first implementation doesn't actually have a name, which makes it quite awkward to refer to it and is really annoying and confusing. It is most often referred to as "Ruby", which is even more annoying and confusing than having no name, because it leads to endless confusion between the features of the Ruby Programming Language and a particular Ruby Implementation. It is also sometimes called "MRI" (for "Matz's Ruby Implementation"), CRuby or MatzRuby. MRI implements Ruby Threads as Green Threads within its interpreter . Unfortunately, it doesn't allow those threads to be scheduled in parallel, they can only run one thread at a time. However, any number of C Threads (POSIX Threads etc.) can run in parallel to the Ruby Thread, so external C Libraries, or MRI C Extensions that create threads of their own can still run in parallel. The second implementation is YARV (short for "Yet Another Ruby VM"). YARV implements Ruby Threads as POSIX or Windows NT Threads , however, it uses a Global Interpreter Lock (GIL) to ensure that only one Ruby Thread can actually be scheduled at any one time. Like MRI, C Threads can actually run parallel to Ruby Threads. In the future, it is possible, that the GIL might get broken down into more fine-grained locks, thus allowing more and more code to actually run in parallel, but that's so far away, it is not even planned yet. JRuby implements Ruby Threads as Native Threads , where "Native Threads" in case of the JVM obviously means "JVM Threads". JRuby imposes no additional locking on them. So, whether those threads can actually run in parallel depends on the JVM: some JVMs implement JVM Threads as OS Threads and some as Green Threads. (The mainstream JVMs from Sun/Oracle use exclusively OS threads since JDK 1.3) XRuby also implements Ruby Threads as JVM Threads . Update : XRuby is dead. IronRuby implements Ruby Threads as Native Threads , where "Native Threads" in case of the CLR obviously means "CLR Threads". IronRuby imposes no additional locking on them, so, they should run in parallel, as long as your CLR supports that. Ruby.NET also implements Ruby Threads as CLR Threads . Update: Ruby.NET is dead. Rubinius implements Ruby Threads as Green Threads within its Virtual Machine . More precisely: the Rubinius VM exports a very lightweight, very flexible concurrency/parallelism/non-local control-flow construct, called a " Task ", and all other concurrency constructs (Threads in this discussion, but also Continuations , Actors and other stuff) are implemented in pure Ruby, using Tasks. Rubinius can not (currently) schedule Threads in parallel, however, adding that isn't too much of a problem: Rubinius can already run several VM instances in several POSIX Threads in parallel , within one Rubinius process. Since Threads are actually implemented in Ruby, they can, like any other Ruby object, be serialized and sent to a different VM in a different POSIX Thread. (That's the same model the BEAM Erlang VM uses for SMP concurrency. It is already implemented for Rubinius Actors .) Update : The information about Rubinius in this answer is about the Shotgun VM, which doesn't exist anymore. The "new" C++ VM does not use green threads scheduled across multiple VMs (i.e. Erlang/BEAM style), it uses a more traditional single VM with multiple native OS threads model, just like the one employed by, say, the CLR, Mono, and pretty much every JVM. MacRuby started out as a port of YARV on top of the Objective-C Runtime and CoreFoundation and Cocoa Frameworks. It has now significantly diverged from YARV, but AFAIK it currently still shares the same Threading Model with YARV . Update: MacRuby depends on apples garbage collector which is declared deprecated and will be removed in later versions of MacOSX, MacRuby is undead. Cardinal is a Ruby Implementation for the Parrot Virtual Machine . It doesn't implement threads yet, however, when it does, it will probably implement them as Parrot Threads . Update : Cardinal seems very inactive/dead. MagLev is a Ruby Implementation for the GemStone/S Smalltalk VM . I have no information what threading model GemStone/S uses, what threading model MagLev uses or even if threads are even implemented yet (probably not). HotRuby is not a full Ruby Implementation of its own. It is an implementation of a YARV bytecode VM in JavaScript. HotRuby doesn't support threads (yet?) and when it does, they won't be able to run in parallel, because JavaScript has no support for true parallelism. There is an ActionScript version of HotRuby, however, and ActionScript might actually support parallelism. Update : HotRuby is dead. Unfortunately, only two of these 11 Ruby Implementations are actually production-ready: MRI and JRuby. So, if you want true parallel threads, JRuby is currently your only choice – not that that's a bad one: JRuby is actually faster than MRI, and arguably more stable. Otherwise, the "classical" Ruby solution is to use processes instead of threads for parallelism. The Ruby Core Library contains the Process module with the Process.fork method which makes it dead easy to fork off another Ruby process. Also, the Ruby Standard Library contains the Distributed Ruby (dRuby / dRb) library, which allows Ruby code to be trivially distributed across multiple processes, not only on the same machine but also across the network.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/56087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205/" ] }
56,107
I'm looking for a library/method to parse an html file with more html specific features than generic xml parsing libraries.
Html Agility Pack This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/56107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ] }
56,121
I have used IPC in Win32 code a while ago - critical sections, events, and semaphores. How is the scene in the .NET environment?Are there any tutorial explaining all available options and when to use and why?
Most recent Microsoft's stuff in IPC is Windows Communication Foundation . Actually there is nothing new in the lower level (tcp, upd, named pipes etc) But WCF simplifies IPC development greatly. Useful resource: Interprocess Communication with WCF on Dr. Dobb's portal WCF Communication Options in the .NET Framework 3.5 and of course MSDN on WCF
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ] }
56,124
Can I run a 64-bit VMware image on a 32-bit machine? I've googled this, but there doesn't seem to be a conclusive answer. I know that it would have to be completely emulated and would run like a dog - but slow performance isn't necessarily an issue as I'm just interested in testing some of my background services code on 64-bit platforms.
The easiest way to check your workstation is to download the VMware Processor Check for 64-Bit Compatibility tool from the VMware website. You can't run a 64-bit VM session on a 32-bit processor. However, you can run a 64-bit VM session if you have a 64-bit processor but have installed a 32-bit host OS and your processor supports the right extensions. The tool linked above will tell you if yours does.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/56124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078/" ] }
56,149
How do you store file permissions in a repository? A few files need to be read-only to stop a third party program from trashing it but after checking out of the repository they are set to read-write. I looked on google and found a blog post from 2005 that states that Subversion doesn't store file-permissions. There are patches and hook-scripts listed (only one url still exists). Three years later does Subversion still not store file permissions and are hooks the only way to go about this? (I've never done hooks and rather use something that is native to Subversion.)
One possible solution would be to write a script that you check in with the rest of your code and which is run as the first step of your build process. This script runs through your copy of the codebase and sets read permissions on certain files. Ideally the script would read the list of files from a simple input file.This would make it easy to maintain and easy for other developers to understand which files get marked as read-only.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ] }
56,227
I would like to start tagging my deployed binaries with the latest SVN revision number. However, because SVN is file-based and not directory/project-based, I need to scan through all the directory's and subdirectory's files in order to determine the highest revision number. Using svn info on the root doesn't work (it just reports the version of that directory, not files in subdirectories): I was wondering if there is a shortcut using the svn command to do this. Otherwise, can anyone suggest a simple script that is network-efficient (I would prefer if it didn't hit the remote server at all)? I also understand that one alternative approach is to keep a version file with the svn:keywords . This works (I've used it on other projects), but I get tired of dealing with making sure the file is dirty and dealing with the inevitable merge conflicts. Answer I see my problem lied with not doing a proper svn up before calling svn info in the root directory: $ svn infoPath: ....Last Changed Author: fakLast Changed Rev: 713Last Changed Date: 2008-08-29 00:40:53 +0300 (Fri, 29 Aug 2008)$ svn upAt revision 721.$ svn infoPath: ....Revision: 721Last Changed Author: reubenLast Changed Rev: 721Last Changed Date: 2008-08-31 22:55:22 +0300 (Sun, 31 Aug 2008)
One way. When you check out the code, look at the last line of svn output: $ svn up...stuff...Updated to revision 66593. A more direct way: $ svn infoPath: .URL: https://svn.example.com/svn/myproject/trunkRepository Root: https://svn.example.com/svn/Repository UUID: d2a7a951-c712-0410-832a-9abccabd3052Revision: 66593Node Kind: directorySchedule: normalLast Changed Author: bnguyenLast Changed Rev: 66591Last Changed Date: 2008-09-11 18:25:27 +1000 (Thu, 11 Sep 2008)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ] }
56,229
I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of? This is similar to what I'm actually doing: import xml.etree.ElementTree as ETroot = ET.Element('html')head = ET.SubElement(root,'head')script = ET.SubElement(head,'script')script.set('type','text/javascript')script.text = "var a = 'I love &aacute; letters'"body = ET.SubElement(root,'body')h1 = ET.SubElement(body,'h1')h1.text = "And I like the fact that 3 > 1"tree = ET.ElementTree(root)tree.write('foo.xhtml')# more foo.xhtml<html><head><script type="text/javascript">var a = 'I love &amp;aacute;letters'</script></head><body><h1>And I like the fact that 3 &gt; 1</h1></body></html>
Another way is using the E Factory builder from lxml (available in Elementtree too) >>> from lxml import etree>>> from lxml.builder import E>>> def CLASS(*args): # class is a reserved word in Python... return {"class":' '.join(args)}>>> html = page = (... E.html( # create an Element called "html"... E.head(... E.title("This is a sample document")... ),... E.body(... E.h1("Hello!", CLASS("title")),... E.p("This is a paragraph with ", E.b("bold"), " text in it!"),... E.p("This is another paragraph, with a", "\n ",... E.a("link", href="http://www.python.org"), "."),... E.p("Here are some reserved characters: <spam&egg>."),... etree.XML("<p>And finally an embedded XHTML fragment.</p>"),... )... )... )>>> print(etree.tostring(page, pretty_print=True))<html> <head> <title>This is a sample document</title> </head> <body> <h1 class="title">Hello!</h1> <p>This is a paragraph with <b>bold</b> text in it!</p> <p>This is another paragraph, with a <a href="http://www.python.org">link</a>.</p> <p>Here are some reservered characters: &lt;spam&amp;egg&gt;.</p> <p>And finally an embedded XHTML fragment.</p> </body></html>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ] }
56,249
From what I've seen the tag is ignored when hosting a WCF service in IIS. I understand that when self-hosting this is required but is this harmful or even used when operating under IIS? ex. <system.serviceModel> <service blah blah blah> <host> <baseAddresses> <add baseAddress="http://localhost/blah" /> </baseAddresses> </host> </service></system.serviceModel> From what I've seen you can take a config file describing a service from one machine and use that on a completely different machine and it works fine. It looks as if IIS completely ignores this section. Thanks,kyle
As you have guessed, the baseAddresses element is completely ignored when hosting in IIS. The service's base address is determined by the web site & virtual directory into which your wcf service is placed. Even when self-hosting, baseAddresses is not required. It is merely a convenience that avoids you having to enter a full address for each endpoint. If it is present, the endpoints can have relative addresses (relative to the base address, that is).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5772/" ] }
56,256
I've got my brand new VS2008 and decided to convert my main solution from VS2005. One of the projects is a SQL2005 reporting services project. Now that I've converted I cannot load it in VS2008. Is there anyway around this? My problem is that my solution is a hybrid and has websites libraries and reports in there.Separating it out breaks the logic the solution entity.
As you have guessed, the baseAddresses element is completely ignored when hosting in IIS. The service's base address is determined by the web site & virtual directory into which your wcf service is placed. Even when self-hosting, baseAddresses is not required. It is merely a convenience that avoids you having to enter a full address for each endpoint. If it is present, the endpoints can have relative addresses (relative to the base address, that is).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1116/" ] }
56,303
I need to specify a date value in a sybase where clause. For example: select * from datawhere dateVal < [THE DATE]
Use the convert function, for example: select * from data where dateVal < convert(datetime, '01/01/2008', 103) Where the convert style (103) determines the date format to use.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3512/" ] }