source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
151,005
How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?
You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code: ExcelLibrary This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in. It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data. ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats. You can also use EPPlus , which works only for Excel 2007/2010 format files (.xlsx files). There's also NPOI which works with both. There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well. Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support ( Pivot table issue in ExcelLibrary ) Here are a couple links for quick reference: ExcelLibrary - GNU Lesser GPL EPPlus - GNU (LGPL) - No longer maintained EPPlus 5 - Polyform Noncommercial - Starting May 2020 NPOI - Apache License Here some example code for ExcelLibrary: Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom: //Create the data set and tableDataSet ds = new DataSet("New_DataSet");DataTable dt = new DataTable("New_DataTable");//Set the locale for eachds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;//Open a DB connection (in this example with OleDB)OleDbConnection con = new OleDbConnection(dbConnectionString);con.Open();//Create a query and fill the data table with the data from the DBstring sql = "SELECT Whatever FROM MyDBTable;";OleDbCommand cmd = new OleDbCommand(sql, con);OleDbDataAdapter adptr = new OleDbDataAdapter();adptr.SelectCommand = cmd;adptr.Fill(dt);con.Close();//Add the table to the data setds.Tables.Add(dt);//Here's the easy part. Create the Excel worksheet from the data setExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds); Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/151005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19242/" ] }
151,021
At the moment I am working on a project admin application in C# 3.5 on ASP.net. In order to reduce hits to the database, I'm caching a lot of information using static variables. For example, a list of users is kept in memory in a static class. The class reads in all the information from the database on startup, and will update the database whenever changes are made, but it never needs to read from the datebase. The class pings other webservers (if they exist) with updated information at the same time as a write to the database. The pinging mechanism is a Windows service to which the cache object registers using a random available port. It is used for other things as well. The amount of data isn't all that great. At the moment I'm using it just to cache the users (password hashes, permissions, name, email etc.) It just saves a pile of calls being made to the database. I was wondering if there are any pitfalls to this method and/or if there are better ways to cache the data?
A pitfall: A static field is scoped per app domain, and increased load will make the server generate more app domains in the pool. This is not necessarily a problem if you only read from the statics, but you will get duplicate data in memory, and you will get a hit every time an app domain is created or recycled. Better to use the Cache object - it's intended for things like this. Edit: Turns out I was wrong about AppDomains (as pointed out in comments) - more instances of the Application will be generated under load, but they will all run in the same AppDomain. (But you should still use the Cache object!)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16299/" ] }
151,026
sqlite> DELETE FROM mails WHERE (`id` = 71);SQL error: database is locked How do I unlock the database so this will work?
In windows you can try this program http://www.nirsoft.net/utils/opened_files_view.html to find out the process is handling db file. Try closed that program for unlock database In Linux and macOS you can do something similar, for example, if your locked file is development.db: $ fuser development.db This command will show what process is locking the file: > development.db: 5430 Just kill the process... kill -9 5430 ...And your database will be unlocked.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/151026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/823/" ] }
151,030
When I load script/console , sometimes I want to play with the output of a controller or a view helper method. Are there ways to: simulate a request? call methods from a controller instance on said request? test helper methods, either via said controller instance or another way?
To call helpers, use the helper object: $ ./script/console>> helper.number_to_currency('123.45')=> "R$ 123,45" If you want to use a helper that's not included by default (say, because you removed helper :all from ApplicationController ), just include the helper. >> include BogusHelper>> helper.bogus=> "bogus output" As for dealing with controllers , I quote Nick's answer: > app.get '/posts/1'> response = app.response# you now have a rails response object much like the integration tests> response.body # get you the HTML> response.cookies # hash of the cookies# etc, etc
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/151030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ] }
151,046
I'm trying to figure out the best way to determine whether I'm in the last iteration of a loop over a map in order to do something like the following: for (iter = someMap.begin(); iter != someMap.end(); ++iter) { bool last_iteration; // do something for all iterations if (!last_iteration) { // do something for all but the last iteration }} There seem to be several ways of doing this: random access iterators, the distance function, etc. What's the canonical method? Edit: no random access iterators for maps!
Canonical? I can't claim that, but I'd suggest final_iter = someMap.end();--final_iter;if (iter != final_iter) ... Edited to correct as suggested by KTC . (Thanks! Sometimes you go too quick and mess up on the simplest things...)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ] }
151,051
In .NET, under which circumstances should I use GC.SuppressFinalize() ? What advantage(s) does using this method give me?
SuppressFinalize should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that this object was cleaned up fully. The recommended IDisposable pattern when you have a finalizer is: public class MyClass : IDisposable{ private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // called via myClass.Dispose(). // OK to use any private object references } // Release unmanaged resources. // Set large fields to null. disposed = true; } } public void Dispose() // Implement IDisposable { Dispose(true); GC.SuppressFinalize(this); } ~MyClass() // the finalizer { Dispose(false); }} Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). SuppressFinalize tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one. The SuppressFinalize optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call SuppressFinalize on other objects mind you. That's a serious defect waiting to happen. Design guidelines inform us that a finalizer isn't necessary if your object implements IDisposable , but if you have a finalizer you should implement IDisposable to allow deterministic cleanup of your class. Most of the time you should be able to get away with IDisposable to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up. Note: Sometimes coders will add a finalizer to debug builds of their own IDisposable classes in order to test that code has disposed their IDisposable object properly. public void Dispose() // Implement IDisposable{ Dispose(true);#if DEBUG GC.SuppressFinalize(this);#endif}#if DEBUG~MyClass() // the finalizer{ Dispose(false);}#endif
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/151051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ] }
151,079
My app generates PDFs for user consumption. The "Content-Disposition" http header is set as mentioned here . This is set to "inline; filename=foo.pdf", which should be enough for Acrobat to give "foo.pdf" as the filename when saving the pdf. However, upon clicking the "Save" button in the browser-embedded Acrobat, the default name to save is not that filename but instead the URL with slashes changed to underscores. Huge and ugly. Is there a way to affect this default filename in Adobe? There IS a query string in the URLs, and this is non-negotiable. This may be significant, but adding a "&foo=/title.pdf" to the end of the URL doesn't affect the default filename. Update 2: I've tried both content-disposition inline; filename=foo.pdfContent-Type application/pdf; filename=foo.pdf and content-disposition inline; filename=foo.pdfContent-Type application/pdf; name=foo.pdf (as verified through Firebug) Sadly, neither worked. A sample url is /bar/sessions/958d8a22-0/views/1493881172/export?format=application/pdf&no-attachment=true which translates to a default Acrobat save as filename of http___localhost_bar_sessions_958d8a22-0_views_1493881172_export_format=application_pdf&no-attachment=true.pdf Update 3: Julian Reschke brings actual insight and rigor to this case. Please upvote his answer.This seems to be broken in FF ( https://bugzilla.mozilla.org/show_bug.cgi?id=433613 ) and IE but work in Opera, Safari, and Chrome. http://greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf
Part of the problem is that the relevant RFC 2183 doesn't really state what to do with a disposition type of "inline" and a filename. Also, as far as I can tell, the only UA that actually uses the filename for type=inline is Firefox (see test case ). Finally, it's not obvious that the plugin API actually makes that information available (maybe someboy familiar with the API can elaborate). That being said, I have sent a pointer to this question to an Adobe person; maybe the right people will have a look. Related: see attempt to clarify Content-Disposition in HTTP in draft-reschke-rfc2183-in-http -- this is early work in progress, feedback appreciated. Update: I have added a test case , which seems to indicate that the Acrobat reader plugin doesn't use the response headers (in Firefox), although the plugin API provides access to them.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9365/" ] }
151,099
I have two tables that are joined together. A has many B Normally you would do: select * from a,b where b.a_id = a.id To get all of the records from a that has a record in b. How do I get just the records in a that does not have anything in b?
select * from a where id not in (select a_id from b) Or like some other people on this thread says: select a.* from aleft outer join b on a.id = b.a_idwhere b.a_id is null
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/151099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ] }
151,124
Which one should I use? catch (_com_error e) or catch (_com_error& e)
The second. Here is my attempt at quoting Sutter "Throw by value, catch by reference" Learn to catch properly: Throw exceptions by value (not pointer) and catch them by reference (usually to const ). This is the combination that meshes best with exception semantics. When rethrowing the same exception, prefer just throw; to throw e; . Here's the full Item 73. Throw by value, catch by reference. The reason to avoid catching exceptions by value is that it implicitly makes a copy of the exception. If the exception is of a subclass, then information about it will be lost. try { throw MyException ("error") } catch (Exception e) { /* Implies: Exception e (MyException ("error")) */ /* e is an instance of Exception, but not MyException */} Catching by reference avoids this issue by not copying the exception. try { throw MyException ("error") } catch (Exception& e) { /* Implies: Exception &e = MyException ("error"); */ /* e is an instance of MyException */}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ] }
151,195
I have a bunch of tasks in a MySQL database, and one of the fields is "deadline date". Not every task has to have to a deadline date. I'd like to use SQL to sort the tasks by deadline date, but put the ones without a deadline date in the back of the result set. As it is now, the null dates show up first, then the rest are sorted by deadline date earliest to latest. Any ideas on how to do this with SQL alone? (I can do it with PHP if needed, but an SQL-only solution would be great.) Thanks!
Here's a solution using only standard SQL, not ISNULL(). That function is not standard SQL, and may not work on other brands of RDBMS. SELECT * FROM myTableWHERE ...ORDER BY CASE WHEN myDate IS NULL THEN 1 ELSE 0 END, myDate;
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
151,199
If I have two dates (ex. '8/18/2008' and '9/26/2008' ), what is the best way to get the number of days between these two dates?
If you have two date objects, you can just subtract them, which computes a timedelta object. from datetime import dated0 = date(2008, 8, 18)d1 = date(2008, 9, 26)delta = d1 - d0print(delta.days) The relevant section of the docs: https://docs.python.org/library/datetime.html . See this answer for another example.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/151199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
151,210
So I just interviewed two people today, and gave them "tests" to see what their skills were like. Both are entry level applicants, one of which is actually still in college. Neither applicant saw anything wrong with the following code. I do, obviously or I wouldn't have picked those examples. Do you think these questions are too harsh for newbie programmers? I guess I should also note neither of them had much experience with C#... but I don't think the issues with these are language dependent. //For the following functions, evaluate the code for quality and discuss. E.g.//E.g. could it be done more efficiently? could it cause bugs? public void Question1(){ int active = 0; CheckBox chkactive = (CheckBox)item.FindControl("chkactive"); if (chkactive.Checked == true) { active = 1; } dmxdevice.Active = Convert.ToBoolean(active);}public void Question2(bool IsPostBack){ if (!IsPostBack) { BindlistviewNotification(); } if (lsvnotificationList.Items.Count == 0) { BindlistviewNotification(); }}//Question 3protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e){ ListViewDataItem item = lsvnotificationList.Items[e.ItemIndex]; string Email = ((TextBox)item.FindControl("txtEmailAddress")).Text; int id = Convert.ToInt32(((HiddenField)item.FindControl("hfID")).Value); ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext(); var compare = from N in db.NotificationLists where N.ID == id select N; if (compare.Count() > 0) { lblmessage.Text = "Record Already Exists"; } else { ESLinq.NotificationList Notice = db.NotificationLists.Where(N => N.ID == id).Single(); Notice.EmailAddress = Email; db.SubmitChanges(); } lsvnotificationList.EditIndex = -1; BindlistviewNotification();}
I don't typically throw code at someone interviewing for a position and say "what's wrong?", mainly because I'm not convinced it really finds me the best candidate. Interviews are sometimes stressful and a bit overwhelming and coders aren't always on their A-game. Regarding the questions, honestly I think that if I didn't know C#, I'd have a hard time with question 3. Question #2 is a bit funky too. Yes, I get what you're going for there but what if the idea was that BindlistviewNotification() was supposed to be called twice? It isn't clear and one could argue there isn't enough info. Question 1 is easy enough to clean up, but I'm not convinced even it proves anything for an entry-level developer without a background in C#. I think I'd rather have something talk me through how they'd attack a problem (in pseudo-code or whatever language they are comfortable with) and assess them from that. Just a personal opinion, though.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145/" ] }
151,231
I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case. How can I accomplish this?
In How to get IP addresses in .NET with a host name by John Spano, it says to add the System.Net namespace, and use the following code: //To get the local IP address string sHostName = Dns.GetHostName (); IPHostEntry ipE = Dns.GetHostByName (sHostName); IPAddress [] IpA = ipE.AddressList; for (int i = 0; i < IpA.Length; i++) { Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ()); }
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ] }
151,238
It seems that I've never got this to work in the past. Currently, I KNOW it doesn't work. But we start up our Java process: -Dcom.sun.management.jmxremote-Dcom.sun.management.jmxremote.port=6002-Dcom.sun.management.jmxremote.authenticate=false-Dcom.sun.management.jmxremote.ssl=false I can telnet to the port, and "something is there" (that is, if I don't start the process, nothing answers, but if I do, it does), but I can not get JConsole to work filling in the IP and port. Seems like it should be so simple, but no errors, no noise, no nothing. Just doesn't work. Anyone know the hot tip for this?
I have a solution for this: If your Java process is running on Linux behind a firewall and you want to start JConsole / Java VisualVM / Java Mission Control on Windows on your local machine to connect it to the JMX Port of your Java process . You need access to your linux machine via SSH login. All Communication will be tunneled over the SSH connection. TIP: This Solution works no matter if there is a firewall or not. Disadvantage: Everytime you restart your java process, you will need to do all steps from 4 - 9 again. 1. You need the putty-suite for your Windows machine from here: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html At least the putty.exe 2. Define one free Port on your linux machine: <jmx-remote-port> Example: jmx-remote-port = 15666 3. Add arguments to java process on the linux machine This must be done exactly like this. If its done like below, it works for linux Machines behind firewalls (It works cause of the -Djava.rmi.server.hostname=localhost argument). -Dcom.sun.management.jmxremote-Dcom.sun.management.jmxremote.port=<jmx-remote-port>-Dcom.sun.management.jmxremote.ssl=false-Dcom.sun.management.jmxremote.authenticate=false-Dcom.sun.management.jmxremote.local.only=false-Djava.rmi.server.hostname=localhost Example: java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=15666 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.local.only=false -Djava.rmi.server.hostname=localhost ch.sushicutta.jmxremote.Main 4. Get Process-Id of your Java Process ps -ef | grep <java-processname>result ---> <process-id> Example: ps -ef | grep ch.sushicutta.jmxremote.Mainresult ---> 24321 5. Find arbitrary Port for RMIServer stubs download The java process opens a new TCP Port on the linux machine, where the RMI Server-Stubs will be available for download. This port also needs to be available via SSH Tunnel to get a connection to the Java Virtual Machine. With netstat -lp this port can be found also the lsof -i gives hints what port has been opened form the java process. NOTE: This port always changes when java process is started. netstat -lp | grep <process-id>tcp 0 0 *:<jmx-remote-port> *:* LISTEN 24321/javatcp 0 0 *:<rmi-server-port> *:* LISTEN 24321/javaresult ---> <rmi-server-port> Example: netstat -lp | grep 24321tcp 0 0 *:15666 *:* LISTEN 24321/javatcp 0 0 *:37123 *:* LISTEN 24321/javaresult ---> 37123 6. Enable two SSH-Tunnels from your Windows machine with putty Source port: <jmx-remote-port>Destination: localhost:<jmx-remote-port>[x] Local [x] Auto Source port: <rmi-server-port>Destination: localhost:<rmi-server-port>[x] Local [x] Auto Example: Source port: 15666Destination: localhost:15666[x] Local [x] Auto Source port: 37123Destination: localhost:37123[x] Local [x] Auto 7. Login to your Linux machine with Putty with this SSH-Tunnel enabled. Leave the putty session open. When you are logged in, Putty will tunnel all TCP-Connections to the linux machine over the SSH port 22. JMX-Port: Windows machine: localhost:15666 >>> SSH >>> linux machine: localhost:15666 RMIServer-Stub-Port: Windows Machine: localhost:37123 >>> SSH >>> linux machine: localhost:37123 8. Start JConsole / Java VisualVM / Java Mission Control to connect to your Java Process using the following URL This works, cause JConsole / Java VisualVM / Java Mission Control thinks you connect to a Port on your local Windows machine. but Putty send all payload to the port 15666 to your linux machine. On the linux machine first the java process gives answer and send back the RMIServer Port. In this example 37123. Then JConsole / Java VisualVM / Java Mission Control thinks it connects to localhost:37123 and putty will send the whole payload forward to the linux machine The java Process answers and the connection is open. [x] Remote Process:service:jmx:rmi:///jndi/rmi://localhost:<jndi-remote-port>/jmxrmi Example: [x] Remote Process:service:jmx:rmi:///jndi/rmi://localhost:15666/jmxrmi 9. ENJOY #8-]
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13663/" ] }
151,291
Is it possible to use system.currency. It says system.currency is inaccessible due to its protection level. what is the alternative of currency.
You have to use Decimal data type.. The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ] }
151,299
I'd like my .exe to have access to a resource string with my svn version. I can type this in by hand, but I'd prefer an automated way to embed this at compile time. Is there any such capability in Visual Studio 2008?
I wanted a similar availability and found $Rev$ to be insufficient because it was only updated for a file if that file's revision was changed (which meant it would have to be edited and committed very time: not something I wanted to do.) Instead, I wanted something that was based on the repository's revision number. For the project I'm working on now, I wrote a Perl script that runs svnversion -n from the top-most directory of my working copy and outputs the most recent revision information to a .h file (I actually compare it to a saved reversion in a non-versioned file in my working copy so that I'm not overwriting current revision information at every compile but whether you chose to do so is up to you.) This .h file (or a number of files if necessary, depending on your approach) is referenced both in my application code and in the resource files to get the information where I'd like it. This script is run as a pre-build step so that everything is up-to-date before the build kicks off and the appropriate files are automatically rebuilt by your build tool.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23071/" ] }
151,338
How can I add an instance variable to a defined class at runtime , and later get and set its value from outside of the class? I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class. A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about.
Ruby provides methods for this, instance_variable_get and instance_variable_set . ( docs ) You can create and assign a new instance variables like this: >> foo = Object.new=> #<Object:0x2aaaaaacc400>>> foo.instance_variable_set(:@bar, "baz")=> "baz">> foo.inspect=> #<Object:0x2aaaaaacc400 @bar=\"baz\">
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
151,350
What are my options? I tried MonoDevelop over a year ago but it was extremely buggy. Is the latest version a stable development environment?
MonoDevelop 2.0 has been released, it now has a decent GUI Debugger, code completion, Intellisense C# 3.0 support (including linq), and a decent GTK# Visual Designer. In short, since the 2.0 release I have started using Mono Develop again and am very happy with it so far. Check out the MonoDevelop website for more info.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ] }
151,362
For posting AJAX forms in a form with many parameters, I am using a solution of creating an iframe , posting the form to it by POST, and then accessing the iframe 's content. specifically, I am accessing the content like this: $("some_iframe_id").get(0).contentWindow.document I tested it and it worked. On some of the pages, I started getting an "Access is denied" error. As far as I know, this shouldn't happen if the iframe is served from the same domain. I'm pretty sure it was working before. Anybody have a clue? If I'm not being clear enough: I'm posting to the same domain . So this is not a cross-domain request. I am testing on IE only. P.S. I can't use simple ajax POST queries (don't ask...)
Solved it by myself! The problem was, that even though the correct response was being sent (verified with Fiddler), it was being sent with an HTTP 500 error code (instead of 200). So it turns out, that if a response is sent with an error code, IE replaces the content of the iframe with an error message loaded from the disk ( res://ieframe.dll/http_500.htm ), and that causes the cross-domain access denied error.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ] }
151,407
Under Linux, my C++ application is using fork() and execv() to launch multiple instances of OpenOffice so as to view some powerpoint slide shows. This part works. Next I want to be able to move the OpenOffice windows to specific locations on the display. I can do that with the XMoveResizeWindow() function but I need to find the Window for each instance. I have the process ID of each instance, how can I find the X11 Window from that ? UPDATE - Thanks to Andy's suggestion, I have pulled this off. I'm posting the code here to share it with the Stack Overflow community. Unfortunately Open Office does not seem to set the _NET_WM_PID property so this doesn't ultimately solve my problem but it does answer the question. // Attempt to identify a window by name or attribute.// by Adam Pierce <[email protected]>#include <X11/Xlib.h>#include <X11/Xatom.h>#include <iostream>#include <list>using namespace std;class WindowsMatchingPid{public: WindowsMatchingPid(Display *display, Window wRoot, unsigned long pid) : _display(display) , _pid(pid) { // Get the PID property atom. _atomPID = XInternAtom(display, "_NET_WM_PID", True); if(_atomPID == None) { cout << "No such atom" << endl; return; } search(wRoot); } const list<Window> &result() const { return _result; }private: unsigned long _pid; Atom _atomPID; Display *_display; list<Window> _result; void search(Window w) { // Get the PID for the current Window. Atom type; int format; unsigned long nItems; unsigned long bytesAfter; unsigned char *propPID = 0; if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, XA_CARDINAL, &type, &format, &nItems, &bytesAfter, &propPID)) { if(propPID != 0) { // If the PID matches, add this window to the result set. if(_pid == *((unsigned long *)propPID)) _result.push_back(w); XFree(propPID); } } // Recurse into child windows. Window wRoot; Window wParent; Window *wChild; unsigned nChildren; if(0 != XQueryTree(_display, w, &wRoot, &wParent, &wChild, &nChildren)) { for(unsigned i = 0; i < nChildren; i++) search(wChild[i]); } }};int main(int argc, char **argv){ if(argc < 2) return 1; int pid = atoi(argv[1]); cout << "Searching for windows associated with PID " << pid << endl;// Start with the root window. Display *display = XOpenDisplay(0); WindowsMatchingPid match(display, XDefaultRootWindow(display), pid);// Print the result. const list<Window> &result = match.result(); for(list<Window>::const_iterator it = result.begin(); it != result.end(); it++) cout << "Window #" << (unsigned long)(*it) << endl; return 0;}
The only way I know to do this is to traverse the tree of windows until you find what you're looking for. Traversing isn't hard (just see what xwininfo -root -tree does by looking at xwininfo.c if you need an example). But how do you identify the window you are looking for? Some applications set a window property called _NET_WM_PID. I believe that OpenOffice is one of the applications that sets that property (as do most Gnome apps), so you're in luck.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ] }
151,413
I've got a siluation where i need to access a SOAP web service with WSE 2.0 security. I've got all the generated c# proxies (which are derived from Microsoft.Web.Services2.WebServicesClientProtocol), i'm applying the certificate but when i call a method i get an error: System.Net.WebException : The request failed with HTTP status 405: Method Not Allowed. at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) I've done some googling and it appears that this is a server configuration issue.However this web service is used many clients without any problem (the web service is provided by a Telecom New Zealand, so it's bound to be configured correctly. I believe it's written in Java) Can anyone shed some light on this issue?
Ok, found what the problem was. I was trying to call a .wsdl url instead of .asmx url.Doh!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10793/" ] }
151,448
Bearing in mind this is for classic asp Which is better, all HTML contained within Response.Write Statements or inserting variables into HTML via <%= %>. Eg Response.Write "<table>" & vbCrlfResponse.Write "<tr>" &vbCrLfResponse.Write "<td class=""someClass"">" & someVariable & "</td>" & vbCrLfResponse.Write "</tr>" & vbCrLfResponse.Write "</table>" & vbCrLf VS <table> <tr> <td class="someClass"><%= someVariable %></td> </tr></table> I am mainly asking from a performance point of view in which will have the least server impact when there multiple variables to insert? If there are no technical differences what are the arguments for one over the other?
First, The most important factor you should be looking at is ease of maintenance. You could buy a server farm with the money and time you would otherwise waste by having to decipher a messy web site to maintain it. In any case, it doesn't matter. At the end of the day, all ASP does is just execute a script! The ASP parser takes the page, and transforms <%= expression %> into direct script calls, and every contiguous block of HTML becomes one giant call to Response.Write . The resulting script is cached and reused unless the page changes on disk, which causes the cached script to be recalculated. Now, too much use of <%= %> leads to the modern version of "spaghetti code": the dreaded "Tag soup". You won't be able to make heads or tails of the logic. On the other hand, too much use of Response.Write means you will never be able to see the page at all until it renders. Use <%= %> when appropriate to get the best of both worlds. My first rule is to pay attention at the proportion of "variable text" to "static text". If you have just a few places with variable text to replace, the <%= %> syntax is very compact and readable. However, as the <%= %> start to accumulate, they obscure more and more of the HTML and at the same time the HTML obscures more and more of your logic. As a general rule, once you start taking about loops, you need to stop and switch to Response.Write`. There aren't many other hard and fast rules. You need to decide for your particular page (or section of the page) which one is more important, or naturally harder to understand, or easier to break: your logic or your HTML? It's usually one or the other (I've seen hundreds of cases of both) If you logic is more critical, you should weight more towards Response.Write ; it will make the logic stand out. If you HTML is more critical, favor <%= %> , which will make the page structure more visible. Sometimes I've had to write both versions and compare them side-by-side to decide which one is more readable; it's a last resort, but do it while the code is fresh in your mind and you will be glad three months later when you have to make changes.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4665/" ] }
151,472
In .NET, what is the difference between String.Empty and "" , and are they interchangable, or is there some underlying reference or Localization issues around equality that String.Empty will ensure are not a problem?
In .NET prior to version 2.0, "" creates an object while string.Empty creates no object ref , which makes string.Empty more efficient. In version 2.0 and later of .NET, all occurrences of "" refer to the same string literal, which means "" is equivalent to .Empty , but still not as fast as .Length == 0 . .Length == 0 is the fastest option, but .Empty makes for slightly cleaner code. See the .NET specification for more information .
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/151472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ] }
151,505
I came from Java, and now I am working more with Ruby. One language feature I am not familiar with is the module . I am wondering what exactly is a module and when do you use one, and why use a module over a class ?
The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions. For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs. You might also use a module when you have shared methods across multiple apps (again, the library model is good here).
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/151505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ] }
151,520
It is unclear to me from the MSDN documentation if I should provide a deep or a shallow clone when implementing ICloneable. What is the preferred option?
Short answer: Yes. Long Answer: Don't use ICloneable. That is because .Clone isn't defined as being a shallow or a deep clone. You should implement your own IClone interface, and describe how the clone should work.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20164/" ] }
151,590
How do you detect if Socket#close() has been called on a socket on the remote side?
The isConnected method won't help, it will return true even if the remote side has closed the socket. Try this: public class MyServer { public static final int PORT = 12345; public static void main(String[] args) throws IOException, InterruptedException { ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT); Socket s = ss.accept(); Thread.sleep(5000); ss.close(); s.close(); }}public class MyClient { public static void main(String[] args) throws IOException, InterruptedException { Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT); System.out.println(" connected: " + s.isConnected()); Thread.sleep(10000); System.out.println(" connected: " + s.isConnected()); }} Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time. The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException (broken pipe) will be thrown) on the associated Input/OutputStreams.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ] }
151,595
I'm looking to try out JRuby and JRuby on Rails. I'm having trouble finding information on what's difference between JRuby on Rails and Ruby on Rails. What's the differences I need to look out for?
JRuby is the Ruby implementation that runs on a JVM whereas Matz's Ruby is a C implementation. Key features to note are: JRuby runs on Java VM's and it's either compiled or interpreted down to Java byte code. JRuby can integrate with Java code. If you have Java class libraries (.jar's), you can reference and use them from within Ruby code with JRuby. In the other direction you can also call JRuby code from within Java. JRuby can also use the JVM and application server capabilities. JRuby is usually hosted within Java application servers such as Sun's GlassFish or even the Tomcat web server. Although you cannot use native Ruby gems with JRuby there are JRuby implementations for most of the popular Ruby libraries. There are other differences which are listed at the JRuby wiki: Differences between JRuby and Ruby (MRI) JRuby On Rails
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/151595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16204/" ] }
151,660
In PHP5, is the __destruct() method guaranteed to be called for each object instance? Can exceptions in the program prevent this from happening?
The destructor will be called when the all references are freed, or when the script terminates. I assume this means when the script terminates properly. I would say that critical exceptions would not guarantee the destructor to be called. The PHP documentation is a little bit thin, but it does say that Exceptions in the destructor will cause issues.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682/" ] }
151,677
I'm looking for a tool that will, in bulk, add a license header to some source files, some of which already have the header. Is there a tool out there that will insert a header, if it is not already present? Edit: I am intentionally not marking an answer to this question, since answers are basically all environment-specific and subjective
#!/bin/bashfor i in *.cc # or whatever other pattern...do if ! grep -q Copyright $i then cat copyright.txt $i >$i.new && mv $i.new $i fidone
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5897/" ] }
151,682
<my:DataGridTemplateColumn CanUserResize="False" Width="150" Header="{Binding MeetingName, Source={StaticResource LocStrings}}" SortMemberPath="MeetingName"> </my:DataGridTemplateColumn> I have the above column in a Silverlight grid control. But it is giving me a XamlParser error because of how I am trying to set the Header property. Has anyone done this before? I want to do this for multiple languages. Also my syntax for the binding to a resouce is correct because I tried it in a lable outside of the grid.
You can't Bind to Header because it's not a FrameworkElement. You can make the text dynamic by modifying the Header Template like this: xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"xmlns:dataprimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"<data:DataGridTemplateColumn> <data:DataGridTemplateColumn.HeaderStyle> <Style TargetType="dataprimitives:DataGridColumnHeader"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <TextBlock Text="{Binding MeetingName, Source={StaticResource LocStrings}}" /> </ControlTemplate> </Setter.Value> </Setter> </Style> </data:DataGridTemplateColumn.HeaderStyle></data:DataGridTemplateColumn>
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23663/" ] }
151,701
Our company runs a web site (oursite.com) with affiliate partners who send us traffic. In some cases, we set up our affiliates with their own subdomain (affiliate.oursite.com), and they display selected content from our site on their site (affiliate.com) using an iframe. Example of a page on their site: <html><head></head><body><iframe src="affiliate.example.com/example_page.html">...content...[google analytics code for affiliate.oursite.com]</iframe>[google analytics code for affiliate.com]</body></html> We would like to have Google Analytics tracking for affiliate.oursite.com. At present, it does not seem that Google is receiving any data from the affiliate when the page is loaded from the iframe. Now, there are security implications in that Javascript doesn't like accessing information about a page in a different domain, and IE doesn't like setting cookies for a different domain. Does anyone have a solution to this? Will we need to CNAME the affiliate.oursite.com to cname.oursite.com, or is there a cleaner solution?
You have to append the Google Analytics tracking code to the end of example_page.html . The content between the <iframe> - </iframe> tag only displays for browsers, which do not support that specific tag. Should you need to merge the results from the subdomains, there's an excellent article on Google's help site: How do I track all of the subdomains for my site in one profile?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15088/" ] }
151,728
I know it is easy to recommend several cross platform libraries. However, are there benefits to treating each platform individually for your product? Yes there will be some base libraries used in all platforms, but UI and some other things would be different on each platform. I have no restriction that the product must be 100% alike on each platform. Mac, Linux, and Windows are the target platforms. Heavy win32 API, MFC is already used for the Windows version. The reason I'm not fully for cross platform libraries is because I feel that the end product will suffer a little in trying to generalize it for all platforms.
I would say that the benefits of individual development for each platform are: - native look and feel - platform knowledge acquired by your developers -... i'm out of ideas Seriously, the cost of developing and maintaining 3 separate copies of your application could be huge if you're not careful. If it's just the GUI code you're worried about then by all means separate out the GUI portion into a per-platform development effort, but you'll regret not keeping the core "business logic" type code common. And given that keeping your GUI from your logic separate is generally considered a good idea, this would force your developers to maintain that separation when the temptation to put 'just a little bit' of business logic into the presentation layer inevitably arises.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
151,746
What is the resolution of the image for the tab bar item? And also, please provide some other useful information regarding that tab item image. Thanks in advance.
The documentation says that the tab bar image is usually 30x30, but I've found that the best size to setup the images is 48x32 pixels. This size still renders and gives you a bit more space. The image is a PNG with transparency, only the mask is used. The UI renders the mask gray when unselected or blue/chrome when selected.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451867/" ] }
151,752
I've created some fairly simple XAML, and it works perfectly (at least in KAXML). The storyboards run perfectly when called from within the XAML, but when I try to access them from outside I get the error: 'buttonGlow' name cannot be found in the name scope of 'System.Windows.Controls.Button'. I am loading the XAML with a stream reader, like this: Button x = (Button)XamlReader.Load(stream); And trying to run the Storyboard with: Storyboard pressedButtonStoryboard = Storyboard)_xamlButton.Template.Resources["ButtonPressed"];pressedButtonStoryboard.Begin(_xamlButton); I think that the problem is that fields I am animating are in the template and that storyboard is accessing the button. Here is the XAML: <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:customControls="clr-namespace:pk_rodoment.SkinningEngine;assembly=pk_rodoment" Width="150" Height="55"> <Button.Resources> <Style TargetType="Button"> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid Background="#00FFFFFF"> <Grid.BitmapEffect> <BitmapEffectGroup> <OuterGlowBitmapEffect x:Name="buttonGlow" GlowColor="#A0FEDF00" GlowSize="0"/> </BitmapEffectGroup> </Grid.BitmapEffect> <Border x:Name="background" Margin="1,1,1,1" CornerRadius="15"> <Border.Background> <SolidColorBrush Color="#FF0062B6"/> </Border.Background> </Border> <ContentPresenter HorizontalAlignment="Center" Margin="{TemplateBinding Control.Padding}" VerticalAlignment="Center" Content="{TemplateBinding ContentControl.Content}" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"/> </Grid> <ControlTemplate.Resources> <Storyboard x:Key="ButtonPressed"> <Storyboard.Children> <DoubleAnimation Duration="0:0:0.4" FillBehavior="HoldEnd" Storyboard.TargetName="buttonGlow" Storyboard.TargetProperty="GlowSize" To="4"/> <ColorAnimation Duration="0:0:0.6" FillBehavior="HoldEnd" Storyboard.TargetName="background" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" To="#FF844800"/> </Storyboard.Children> </Storyboard> <Storyboard x:Key="ButtonReleased"> <Storyboard.Children> <DoubleAnimation Duration="0:0:0.2" FillBehavior="HoldEnd" Storyboard.TargetName="buttonGlow" Storyboard.TargetProperty="GlowSize" To="0"/> <ColorAnimation Duration="0:0:0.2" FillBehavior="Stop" Storyboard.TargetName="background" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" To="#FF0062B6"/> </Storyboard.Children> </Storyboard> </ControlTemplate.Resources> <ControlTemplate.Triggers> <Trigger Property="ButtonBase.IsPressed" Value="True"> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource ButtonPressed}"/> </Trigger.EnterActions> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource ButtonReleased}"/> </Trigger.ExitActions> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Button.Resources> <DockPanel> <TextBlock x:Name="TextContent" FontSize="28" Foreground="White" >Test</TextBlock> </DockPanel></Button> Any suggestions from anyone who understands WPF and XAML a lot better than me? Here is the error stacktrace: at System.Windows.Media.Animation.Storyboard.ResolveTargetName(String targetName, INameScope nameScope, DependencyObject element)at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)at System.Windows.Media.Animation.Storyboard.BeginCommon(DependencyObject containingObject, INameScope nameScope, HandoffBehavior handoffBehavior, Boolean isControllable, Int64 layer)at System.Windows.Media.Animation.Storyboard.Begin(FrameworkElement containingObject)at pk_rodoment.SkinningEngine.ButtonControlWPF._button_MouseDown(Object sender, MouseButtonEventArgs e)at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)at System.Windows.Input.InputManager.ProcessStagingArea()at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)at System.Windows.Threading.Dispatcher.Run()at System.Windows.Application.RunDispatcher(Object ignore)at System.Windows.Application.RunInternal(Window window)at System.Windows.Application.Run(Window window)at System.Windows.Application.Run()at ControlTestbed.App.Main() in C:\svnprojects\rodomont\ControlsTestbed\obj\Debug\App.g.cs:line 0at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()at System.Threading.ThreadHelper.ThreadStart_Context(Object state)at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)at System.Threading.ThreadHelper.ThreadStart()
Finally found it. When you call Begin on storyboards that reference elements in the ControlTemplate, you must pass in the control template as well. Changing: pressedButtonStoryboard.Begin(_xamlButton); To: pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template); Fixed everything.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ] }
151,777
I've been working on the Android SDK platform, and it is a little unclear how to save an application's state. So given this minor re-tooling of the 'Hello, Android' example: package com.android.hello;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extends Activity { private TextView mTextView = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTextView = new TextView(this); if (savedInstanceState == null) { mTextView.setText("Welcome to HelloAndroid!"); } else { mTextView.setText("Welcome back."); } setContentView(mTextView); }} I thought it would be enough for the simplest case, but it always responds with the first message, no matter how I navigate away from the app. I'm sure the solution is as simple as overriding onPause or something like that, but I've been poking away in the documentation for 30 minutes or so and haven't found anything obvious.
You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this: @Overridepublic void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. savedInstanceState.putBoolean("MyBoolean", true); savedInstanceState.putDouble("myDouble", 1.9); savedInstanceState.putInt("MyInt", 1); savedInstanceState.putString("MyString", "Welcome back to Android"); // etc.} The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate() and also onRestoreInstanceState() where you would then extract the values from activity like this: @Overridepublic void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean"); double myDouble = savedInstanceState.getDouble("myDouble"); int myInt = savedInstanceState.getInt("MyInt"); String myString = savedInstanceState.getString("MyString");} Or from a fragment. @Overridepublic void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean"); double myDouble = savedInstanceState.getDouble("myDouble"); int myInt = savedInstanceState.getInt("MyInt"); String myString = savedInstanceState.getString("MyString");} You would usually use this technique to store instance values for your application (selections, unsaved text, etc.).
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/151777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ] }
151,804
I want to watch a folder tree on a network server for changes. The files all have a specific extension. There are about 200 folders in the tree and about 1200 files with the extension I am watching. I can't write a service to run on the server (off-limits!) so the solution has to be local to the client. Timeliness is not particularly important. I can live with a minute or more delay in notifications. I am watching for Create, Delete, Rename and Changes. Would using the .NET System.IO.fileSystemWatcher create much of a load on the server? How about 10 separate watchers to cut down the number of folders/files being watched? (down to 200 from 700 folders, 1200 from 5500 files in total) More network traffic instead of less? My thoughts are a reshuffle on the server to put the watched files under 1 tree. I may not always have this option hence the team of watchers. I suppose the other solution is a periodic check if the FSW creates an undue load on the server, or if it doesn't work for a whole bunch of SysAdmin type reasons. Is there a better way to do this?
From a server load point of view, using the IO.FileSystemWatcher for remote change notifications in the scenario you describe is probably the most efficient method possible. It uses the FindFirstChangeNotification and ReadDirectoryChangesW Win32 API functions internally, which in turn communicate with the network redirector in an optimized way (assuming standard Windows networking: if a third-party redirector is used, and it doesn't support the required functionality, things won't work at all). The .NET wrapper also uses async I/O and everything, further assuring maximum efficiency. The only problem with this solution is that it's not very reliable. Other than having to deal with network connections going away temporarily (which isn't too much of a problem, since IO.FileSystemWatcher will fire an error event in this case which you can handle), the underlying mechanism has certain fundamental limitations. From the MSDN documentation for the Win32 API functions: ReadDirectoryChangesW fails with ERROR_INVALID_PARAMETER when the buffer length is greater than 64 KB and the application is monitoring a directory over the network. This is due to a packet size limitation with the underlying file sharing protocols Notifications may not be returned when calling FindFirstChangeNotification for a remote file system In other words: under high load (when you would need a large buffer) or, worse, under random unspecified circumstances, you may not get the notifications you expect. This is even an issue with local file system watchers, but it's much more of a problem over the network. Another question here on SO details the inherent reliability problems with the API in a bit more detail. When using file system watchers, your application should be able to deal with these limitations. For example: If the files you're looking for have sequence numbers, store the last sequence number you got notified about, so you can look for 'gaps' on future notifications and process the files for which you didn't get notified; On receiving a notification, always do a full directory scan. This may sound really bad, but since the scan is event-driven, it's still much more efficient than dumb polling. Also, as long as you keep the total number of files in a single directory, as well as the number of directories to scan, under a thousand or so, the impact of this operation on performance should be pretty minimal anyway. Setting up multiple listeners is something you should avoid as much as possible: if anything, this will make things even less reliable... Anyway, if you absolutely have to use file system watchers, things can work OK as long as you're aware of the limitations, and don't expect 1:1 notification for every file modified/created. So, if you have other options (essentially, having the process writing the files notify you in a non-file system based way: any regular RPC method will be an improvement...), those are definitely worth looking into from a reliability point of view.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492/" ] }
151,841
I'd like to document what high-level (i.e. C++ not inline assembler ) functions or macros are available for Compare And Swap (CAS) atomic primitives... E.g., WIN32 on x86 has a family of functions _InterlockedCompareExchange in the <_intrin.h> header.
I'll let others list the various platform-specific APIs, but for future reference in C++09 you'll get the atomic_compare_exchange() operation in the new "Atomic operations library".
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ] }
151,846
This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants. Why make them waste time and energy resizing my window to match all the others they have? I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.
Using hints from WindowMover article and Nattee Niparnan's blog post I managed to create this: import win32conimport win32guidef isRealWindow(hWnd): '''Return True iff given window is a real Windows application window.''' if not win32gui.IsWindowVisible(hWnd): return False if win32gui.GetParent(hWnd) != 0: return False hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0 lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE) if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner) or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)): if win32gui.GetWindowText(hWnd): return True return Falsedef getWindowSizes(): ''' Return a list of tuples (handler, (width, height)) for each real window. ''' def callback(hWnd, windows): if not isRealWindow(hWnd): return rect = win32gui.GetWindowRect(hWnd) windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1]))) windows = [] win32gui.EnumWindows(callback, windows) return windowsfor win in getWindowSizes(): print win You need the Win32 Extensions for Python module for this to work. EDIT: I discovered that GetWindowRect gives more correct results than GetClientRect . Source has been updated.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3176/" ] }
151,850
In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write: if (var1 = var2) { ...} instead of: var1 = var2;if (var1) { ...} ?
It's more useful for loops than if statements. while(var = GetNext()){ ...do something with 'var' } Which would otherwise have to be written var = GetNext();while(var){ ...do something var = GetNext();}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/151850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ] }
151,917
What is the best way to free resources (in this case unlock the ReadWriteLock) when leaving the scope ? How to cover all possible ways (return, break, exceptions etc)?
A try/finally block is the closest thing that you can get to this behaviour: Lock l = new Lock();l.lock(); // Call the lock before calling try.try { // Do some processing. // All code must go in here including break, return etc. return something;} finally { l.unlock();}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18174/" ] }
151,919
Visual Studio includes support for __forceinline. The Microsoft Visual Studio 2005 documentation states: The __forceinline keyword overrides the cost/benefit analysis and relies on the judgment of the programmer instead. This raises the question: When is the compiler's cost/benefit analysis wrong? And, how am I supposed to know that it's wrong? In what scenario is it assumed that I know better than my compiler on this issue?
You know better than the compiler only when your profiling data tells you so.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22244/" ] }
151,936
I have some code where I'm returning an array of objects. Here's a simplified example: string[] GetTheStuff() { List<string> s = null; if( somePredicate() ) { s = new List<string>(); // imagine we load some data or something } return (s == null) ? new string[0] : s.ToArray();} The question is, how expensive is the new string[0] ? Should I just return null and make the caller accept null as a valid way of indicating "nothing was found"? NB: This is being called in a loop which gets run hundreds and hundreds of times, so it's one of the few cases where I think this kind of optimiziation is not actually 'premature'. PS: And even if it was premature, I'd still like to know how it works :-) Update: Initially when I asked if it used any space, I was thinking of things from the 'C/C++' point of view, kind of like how in C, writing char a[5]; will allocate 5 bytes of space on the stack, and char b[0]; will allocate 0 bytes. I realise this is not a good fit for the .NET world, but I was curious if this was something that the compiler or CLR would detect and optimize out, as a non-resizeable array of size zero really shouldn't (as far as I can see?) require any storage space.
Even if it's being called "hundreds and hundreds" of times, I'd say it's a premature optimization. If the result is clearer as an empty array, use that. Now for the actual answer: yes, an empty array takes some memory. It has the normal object overhead (8 bytes on x86, I believe) and 4 bytes for the count. I don't know whether there's anything beyond that, but it's not entirely free. (It is incredibly cheap though...) Fortunately, there's an optimization you can make without compromising the API itself: have a "constant" of an empty array. I've made another small change to make the code clearer, if you'll permit... private static readonly string[] EmptyStringArray = new string[0];string[] GetTheStuff() { if( somePredicate() ) { List<string> s = new List<string>(); // imagine we load some data or something return s.ToArray(); } else { return EmptyStringArray; }} If you find yourself needing this frequently, you could even create a generic class with a static member to return an empty array of the right type. The way .NET generics work makes this trivial: public static class Arrays<T> { public static readonly Empty = new T[0];} (You could wrap it in a property, of course.) Then just use: Arrays<string>.Empty; EDIT: I've just remembered Eric Lippert's post on arrays . Are you sure that an array is the most appropriate type to return?
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ] }
151,945
Emacs puts backup files named foo~ everywhere and I don't like having to remember to delete them. Also, if I edit a file that has a hard link somewhere else in the file system, the hard link points to the backup when I'm done editing, and that's confusing and awful. How can I either eliminate these backup files, or have them go somewhere other than the same directory?
If you've ever been saved by an Emacs backup file, youprobably want more of them, not less of them. It is annoyingthat they go in the same directory as the file you're editing,but that is easy to change. You can make all backup files gointo a directory by putting something like the following in your .emacs . (setq backup-directory-alist `(("." . "~/.saves"))) There are a number of arcane details associated with how Emacsmight create your backup files. Should it rename the originaland write out the edited buffer? What if the original is linked?In general, the safest but slowest bet is to always make backupsby copying. (setq backup-by-copying t) If that's too slow for some reason you might also have a look at backup-by-copying-when-linked . Since your backups are all in their own place now, you might wantmore of them, rather than less of them. Have a look at the Emacsdocumentation for these variables (with C-h v ). (setq delete-old-versions t kept-new-versions 6 kept-old-versions 2 version-control t) Finally, if you absolutely must have no backup files: (setq make-backup-files nil) It makes me sick to think of it though.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/151945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11138/" ] }
151,952
The Project's Web section (under project properties in VS2008) has a list of debuggers: ASP.NET, Native Code, SQL Server. What is Native Code?
Native code is machine code executed directly by the CPU. This is in contrast to .NET bytecode, which is interpreted by the .NET virtual machine. A nice MSDN hit: Debugging Native Code
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ] }
151,963
Is it possible to get the route/virtual url associated with a controller action or on a view? I saw that Preview 4 added LinkBuilder.BuildUrlFromExpression helper, but it's not very useful if you want to use it on the master, since the controller type can be different. Any thoughts are appreciated.
You can get that data from ViewContext.RouteData. Below are some examples for how to access (and use) that information: /// These are added to my viewmasterpage, viewpage, and viewusercontrol base classes: public bool IsController(string controller){ if (ViewContext.RouteData.Values["controller"] != null) { return ViewContext.RouteData.Values["controller"].ToString().Equals(controller, StringComparison.OrdinalIgnoreCase); } return false;}public bool IsAction(string action){ if (ViewContext.RouteData.Values["action"] != null) { return ViewContext.RouteData.Values["action"].ToString().Equals(action, StringComparison.OrdinalIgnoreCase); } return false;}public bool IsAction(string action, string controller){ return IsController(controller) && IsAction(action);} /// Some extension methods that I added to the UrlHelper class. public static class UrlHelperExtensions{ /// <summary> /// Determines if the current view equals the specified action /// </summary> /// <typeparam name="TController">The type of the controller.</typeparam> /// <param name="helper">Url Helper</param> /// <param name="action">The action to check.</param> /// <returns> /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>. /// </returns> public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller { MethodCallExpression call = action.Body as MethodCallExpression; if (call == null) { throw new ArgumentException("Expression must be a method call", "action"); } return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) && typeof(TController) == helper.ViewContext.Controller.GetType()); } /// <summary> /// Determines if the current view equals the specified action /// </summary> /// <param name="helper">Url Helper</param> /// <param name="actionName">Name of the action.</param> /// <returns> /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>. /// </returns> public static bool IsAction(this UrlHelper helper, string actionName) { if (String.IsNullOrEmpty(actionName)) { throw new ArgumentException("Please specify the name of the action", "actionName"); } string controllerName = helper.ViewContext.RouteData.GetRequiredString("controller"); return IsAction(helper, actionName, controllerName); } /// <summary> /// Determines if the current view equals the specified action /// </summary> /// <param name="helper">Url Helper</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <returns> /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>. /// </returns> public static bool IsAction(this UrlHelper helper, string actionName, string controllerName) { if (String.IsNullOrEmpty(actionName)) { throw new ArgumentException("Please specify the name of the action", "actionName"); } if (String.IsNullOrEmpty(controllerName)) { throw new ArgumentException("Please specify the name of the controller", "controllerName"); } if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)) { controllerName = controllerName + "Controller"; } bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase); return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Determines if the current request is on the specified controller /// </summary> /// <param name="helper">The helper.</param> /// <param name="controllerName">Name of the controller.</param> /// <returns> /// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>. /// </returns> public static bool IsController(this UrlHelper helper, string controllerName) { if (String.IsNullOrEmpty(controllerName)) { throw new ArgumentException("Please specify the name of the controller", "controllerName"); } if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)) { controllerName = controllerName + "Controller"; } return helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Determines if the current request is on the specified controller /// </summary> /// <typeparam name="TController">The type of the controller.</typeparam> /// <param name="helper">The helper.</param> /// <returns> /// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>. /// </returns> public static bool IsController<TController>(this UrlHelper helper) where TController : Controller { return (typeof(TController) == helper.ViewContext.Controller.GetType()); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3085/" ] }
151,966
I want to use remote debugging.The program that I want to debug runs on machine b.Visual Studio runs on machine a. On machine b I have a folder with the following files: msvcr72.dll msvsmon.exe NatDbgDE.dll NatDbgDEUI.dll NatDbgEE.dll NatDbgEEUI.dll If you think some files are missing, could you also describe where they are usually located? In the next step I started the msvsmon.exe and my program on machine b. On machine a, I started Visual Studio 2008 and my solution in which the program was written. Then I choose "Debug - Attach to Process". I chose "Remote Transport (Native Only with no authentication)". I used the correct IP as a qualifier and took the right process (program.exe). After a while the following message occurred in a popup-window: Unhandled exception at 0x7c812a7b in program.exe: 0xE0434F4D: 0xe0434f4d I can continue or break; When continuing, the exception occurs again and again and again. So I pressed break and the following message occurred: No symbols are loaded for any call stack frame. The source code cannot be displayed.
Make sure you copy the .PDB file that is generated with your assembly into the same folder on the remote machine. This will allow the debugger to pickup the debug symbols.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/151966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23681/" ] }
151,969
In PHP 5, what is the difference between using self and $this ? When is each appropriate?
Short Answer Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members. Full Answer Here is an example of correct usage of $this and self for non-static and static member variables: <?phpclass X { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo $this->non_static_member . ' ' . self::$static_member; }}new X();?> Here is an example of incorrect usage of $this and self for non-static and static member variables: <?phpclass X { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo self::$non_static_member . ' ' . $this->static_member; }}new X();?> Here is an example of polymorphism with $this for member functions: <?phpclass X { function foo() { echo 'X::foo()'; } function bar() { $this->foo(); }}class Y extends X { function foo() { echo 'Y::foo()'; }}$x = new Y();$x->bar();?> Here is an example of suppressing polymorphic behaviour by using self for member functions: <?phpclass X { function foo() { echo 'X::foo()'; } function bar() { self::foo(); }}class Y extends X { function foo() { echo 'Y::foo()'; }}$x = new Y();$x->bar();?> The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X , it thus calls X::foo() . If the object is of type Y , it calls Y::foo() . But with self::foo(), X::foo() is always called. From http://www.phpbuilder.com/board/showthread.php?t=10354489 : By http://board.phpbuilder.com/member.php?145249-laserlight
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/151969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682/" ] }
151,974
What are all the C++ blogs that you follow? Please add one url for one posting.
Sutter's Mill
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/151974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ] }
151,979
Have a look at this very simple example WPF program: <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <GroupBox> <GroupBox.Header> <CheckBox Content="Click Here"/> </GroupBox.Header> </GroupBox></Window> So I have a GroupBox whose header is a CheckBox. We've all done something like this - typically you bind the content of the GroupBox in such a way that it's disabled when the CheckBox is unchecked. However, when I run this application and click on the CheckBox, I've found that sometimes my mouse clicks are swallowed and the CheckBox's status doesn't change. If I'm right, it's when I click on the exact row of pixels that the GroupBox's top border sits on. Can someone duplicate this? Why would this occur, and is there a way around it? Edit: Setting the GroupBox's BorderThickness to 0 solves the problem, but obviously it removes the border, so it doesn't look like a GroupBox anymore.
It appears to be a subtle bug in the control template for the GroupBox. I found by editing the default template for the GroupBox and moving the Border named 'Header' to the last item in the control templates Grid element, the issue resolves itself. The reason is that the one of the other Border elements with a TemplateBinding of BorderBrush was further down in the visual tree and was capturing the mouse click, that's why setting the BorderBrush to null allowed the CheckBox to correctly receive the mouse click. Below is resulting style for the GroupBox. It is nearly identical to the default template for the control, except for the Border element named 'Header', which is now the last child of the Grid, rather than the second. <BorderGapMaskConverter x:Key="BorderGapMaskConverter"/><Style x:Key="GroupBoxStyle1" TargetType="{x:Type GroupBox}"> <Setter Property="BorderBrush" Value="#D5DFE5"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupBox}"> <Grid SnapsToDevicePixels="true"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="6"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="6"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="6"/> </Grid.ColumnDefinitions> <Border Grid.Column="0" Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4"/> <ContentPresenter Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="2"/> <Border Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3" BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4"> <Border.OpacityMask> <MultiBinding Converter="{StaticResource BorderGapMaskConverter}" ConverterParameter="7"> <Binding Path="ActualWidth" ElementName="Header"/> <Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}"/> <Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"/> </MultiBinding> </Border.OpacityMask> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3"> <Border BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2"/> </Border> </Border> <Border x:Name="Header" Grid.Column="1" Grid.Row="0" Grid.RowSpan="2" Padding="3,1,3,0"> <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" ContentSource="Header" RecognizesAccessKey="True"/> </Border> </Grid> </ControlTemplate> </Setter.Value> </Setter></Style>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/151979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ] }
152,003
I need to scan uploaded files for viruses on a Linux server, but I'm not sure how to go about it. What are my options, if any? I'm also interested in how the scanners perform when multiple users send multiple files at the same time.
I would have a look at Clam AntiVirus . It provides a clamscan program that can scan a given file and return a pass/fail indication. It's free and automatically updates its database regularly. As for integrating such a product into your file upload process, that would be specific to whatever file upload process you actually use.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21716/" ] }
152,005
What is currying? How can currying be done in C++? Please Explain binders in STL container?
In short, currying takes a function f(x, y) and given a fixed Y , gives a new function g(x) where g(x) == f(x, Y) This new function may be called in situations where only one argument is supplied, and passes the call on to the original f function with the fixed Y argument. The binders in the STL allow you to do this for C++ functions. For example: #include <functional>#include <iostream>#include <vector>using namespace std;// declare a binary function objectclass adder: public binary_function<int, int, int> {public: int operator()(int x, int y) const { return x + y; }};int main(){ // initialise some sample data vector<int> a, b; a.push_back(1); a.push_back(2); a.push_back(3); // here we declare a function object f and try it out adder f; cout << "f(2, 3) = " << f(2, 3) << endl; // transform() expects a function with one argument, so we use // bind2nd to make a new function based on f, that takes one // argument and adds 5 to it transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5)); // output b to see what we got cout << "b = [" << endl; for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) { cout << " " << *i << endl; } cout << "]" << endl; return 0;}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ] }
152,006
I've got a php script. Most of the time the script returns html, which is working fine, but on one occasion (parameter ?Format=XML) the script returns XML instead of HTML. Is there any way to change the returned mime type of the php output on the fly from text/html to text/xml or application/xml?
header('Content-type: application/xml'); More information available at the PHP documentation for header()
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/152006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ] }
152,019
.Net 3.5 doesn't support tuples. Too bad, But not sure whether the future version of .net will support tuples or not?
I've just read this article from the MSDN Magazine: Building Tuple Here are excerpts: The upcoming 4.0 release of Microsoft .NET Framework introduces a new type called System.Tuple. System.Tuple is a fixed-size collection of heterogeneously typed data. Like an array, a tuple has a fixed size that can't be changed once it has been created. Unlike an array, each element in a tuple may be a different type, and a tuple is able to guarantee strong typing for each element. There is already one example of a tuple floating around the Microsoft .NET Framework, in the System.Collections.Generic namespace: KeyValuePair. While KeyValuePair can be thought of as the same as Tuple, since they are both types that hold two things, KeyValuePair feels different from Tuple because it evokes a relationship between the two values it stores (and with good reason, as it supports the Dictionary class). Furthermore, tuples can be arbitrarily sized, whereas KeyValuePair holds only two things: a key and a value. While some languages like F# have special syntax for tuples, you can use the new common tuple type from any language. Revisiting the first example, we can see that while useful, tuples can be overly verbose in languages without syntax for a tuple: class Program { static void Main(string[] args) { Tuple<string, int> t = new Tuple<string, int>("Hello", 4); PrintStringAndInt(t.Item1, t.Item2); } static void PrintStringAndInt(string s, int i) { Console.WriteLine("{0} {1}", s, i); }} Using the var keyword from C# 3.0, we can remove the type signature on the tuple variable, which allows for somewhat more readable code. var t = new Tuple<string, int>("Hello", 4); We've also added some factory methods to a static Tuple class which makes it easier to build tuples in a language that supports type inference, like C#. var t = Tuple.Create("Hello", 4);
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/152019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ] }
152,028
I want to be able to compare an image taken from a webcam to an image stored on my computer. The library doesn't need to be one hundred percent accurate as it won't be used in anything mission critical (e.g. police investigation), I just want something OK I can work with. I have tried a demonstration project for Image Recognition from CodeProject , and it only works with small images / doesn't work at all when I compare an exact same image 120x90 pixels (this is not classified as OK :P ). Has there been any success with image recognition before? If so, would you be able to provide a link to a library I could use in either C# or VB.NET?
You could try this: http://code.google.com/p/aforge/ It includes a comparison analysis that will give you a score. There are many other great imaging features of all types included as well. // The class also can be used to get similarity level between two image of the same size, which can be useful to get information about how different/similar are images:// Create template matching algorithm's instance// Use zero similarity to make sure algorithm will provide anythingExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0);// Compare two imagesTemplateMatch[] matchings = tm.ProcessImage( image1, image2 );// Check similarity levelif (matchings[0].Similarity > 0.95){ // Do something with quite similar images}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/152028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ] }
152,077
I agree, that programming against interfaces is a good practice. In most cases in Java "interface" in this sense means the language construct interface, so that you write an interface and an implementation class and that you use the interface instead of the implementation class most of the time. I wonder if this is a good practice for writing domain models as well. So, for example if you've got a domain class Customer and each customer may have a list of Orders, would you generally also write interfaces ICustomer and IOrder. And also would Customer have a list of IOrders instead of Orders? Or would you use interfaces in the domain model, only if it is really driven by the domain, e.g. you've got at least two different types of Orders? In other words, would you use interfaces because of only technical needs in the domain model, or only when it is really appropriate with respect to the actual domain?
Writing interfaces "just because" strikes me as a waste of time and energy, not to mention a violation of the KISS-principle. I write them when they are actually useful in representing common behavior of related classes, not just as a fancy header file.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722/" ] }
152,084
I'm interested in actual examples of using fixed point combinators (such as the y-combinator in C++. Have you ever used a fixed point combinator with egg or bind in real live code? I found this example in egg a little dense: void egg_example(){ using bll::_1; using bll::_2; int r = fix2( bll::ret<int>( // \(f,a) -> a == 0 ? 1 : a * f(a-1) bll::if_then_else_return( _2 == 0, 1, _2 * lazy(_1)(_2 - 1) ) ) ) (5); BOOST_CHECK(r == 5*4*3*2*1);} Can you explain how this all works? Is there a nice simple example perhaps using bind with perhaps fewer dependancies than this one?
Here is the same code converted into boost::bind notice the y-combinator and its application site in the main function. I hope this helps. #include <boost/function.hpp>#include <boost/bind.hpp>#include <iostream>// Y-combinator compatible factorialint fact(boost::function<int(int)> f,int v){ if(v == 0) return 1; else return v * f(v -1);}// Y-combinator for the int typeboost::function<int(int)> y(boost::function<int(boost::function<int(int)>,int)> f){ return boost::bind(f,boost::bind(&y,f),_1);}int main(int argc,char** argv){ boost::function<int(int)> factorial = y(fact); std::cout << factorial(5) << std::endl; return 0;}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ] }
152,101
I want to learn MVC "architecture pattern" but I don't want to jump into a framework like Rails or Django just yet. I want to understand the concept first and write some simple code in my currently familiar environment, which happens to be PHP/HTML/CSS/MySQL. I don't necessarily need a tutorial that is based on PHP, as I do understand a lot of different languages. And I don't want to have to install any frameworks or APIs or libraries. I just want to learn how to think in MVC and apply it to my projects. Any suggestions?
Almost every framework does MVC differently, so you might end up getting even more confused. The general principles of MVC are very simple: "Model is state; view reacts to model; controller reacts to view; controller changes model". The model, view and controller are concepts - they are whatever you feel them to be. Classes, bunches of classes, instances of classes with XML configuration files, you name it. I actually think that about covers the basic principles. Without a framework, you'd not get much further. What matters is how a particular framework defines model, view and controller and their interactions.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23701/" ] }
152,120
I'm trying to understand the concepts behind DDD, but I find it hard to understand just by reading books as they tend to discuss the topic in a rather abstract way. I would like to see some good implementations of DDD in code, preferably in C#. Are there any good examples of projects practicing DDD in the open source world?
Eric Evans and a Swedish consulting company have released a sample application based on the shipping example that Eric uses throughout the book. It's in Java, but the concepts are well documented on the project page. http://dddsample.sourceforge.net/ However, be warned that DDD is more about the journey than the destination. Understand that the sample code you are looking took many forms before it became what you see now. You did not see the awkward models that were used initially and you're missing the steps taken to refactor the model based on insight gained along the way. While the building blocks are important in DDD, Eric belives they are over-emphasized, so take all samples with a grain of salt.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4422/" ] }
152,188
I have read in some of the ClickOnce posts that ClickOnce does not allow you to create a desktop icon for you application. Is there any way around this?
In Visual Studio 2005, ClickOnce does not have the ability to create a desktop icon, but it is now available in Visual Studio 2008 SP1. In Visual Studio 2005, you can use the following code to create a desktop icon for you when the application starts. I have used this code over several projects for a couple of months now without any problem. I must say that all my applications have been deployed over an intranet in a controlled environment. Also, the icon is not removed when the application is uninstalled. This code creates a shortcut to the shortcut on the start menu that ClickOnce creates. private void CreateDesktopIcon(){ ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment; if (ad.IsFirstRun) { Assembly assembly = Assembly.GetEntryAssembly(); string company = string.Empty; string description = string.Empty; if (Attribute.IsDefined(assembly, typeof(AssemblyCompanyAttribute))) { AssemblyCompanyAttribute ascompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute( assembly, typeof(AssemblyCompanyAttribute)); company = ascompany.Company; } if (Attribute.IsDefined(assembly, typeof(AssemblyDescriptionAttribute))) { AssemblyDescriptionAttribute asdescription = (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute( assembly, typeof(AssemblyDescriptionAttribute)); description = asdescription.Description; } if (!string.IsNullOrEmpty(company)) { string desktopPath = string.Empty; desktopPath = string.Concat( Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "\\", description, ".appref-ms"); string shortcutName = string.Empty; shortcutName = string.Concat( Environment.GetFolderPath(Environment.SpecialFolder.Programs), "\\", company, "\\", description, ".appref-ms"); System.IO.File.Copy(shortcutName, desktopPath, true); } } }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18826/" ] }
152,248
We have a website running on Apache, access to which has a number of static pages protected via HTTP Basic authentication. I've written a new part of the site with Django using Django's built in support for user management. The problem I have is that users have to log in once via the HTTP Basic authentication and then again using a Django login form. This both clumsy and very confusing for users. I was wondering if anyone had found a way to make Django log a user in using the HTTP Basic authentication information. I not expecting to pass a password to Django, but rather if a user dave has been authenticated by Apache then they should be automatically logged into Django as dave too. (One option would be to make Apache and Django share a user store to ensure common usernames and passwords but this would still involve two login prompts which is what I'm trying to avoid.)
This has been added to the Django 1.3 release. See more current documentation for this here: http://docs.djangoproject.com/en/dev/howto/auth-remote-user/
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3171/" ] }
152,259
Say if I had a table of books in a MySQL database and I wanted to search the 'title' field for keywords (input by the user in a search field); what's the best way of doing this in PHP? Is the MySQL LIKE command the most efficient way to search?
Yes, the most efficient way usually is searching in the database. To do that you have three alternatives: LIKE, ILIKE to match exact substrings RLIKE to match POSIX regexes FULLTEXT indexes to match another three different kinds of search aimed at natural language processing So it depends on what will you be actually searching for to decide what would the best be. For book titles I'd offer a LIKE search for exact substring match, useful when people know the book they're looking for and also a FULLTEXT search to help find titles similar to a word or phrase. I'd give them different names on the interface of course, probably something like exact for the substring search and similar for the fulltext search. An example about fulltext: http://www.onlamp.com/pub/a/onlamp/2003/06/26/fulltext.html
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ] }
152,261
I have a Delphi DLL with a function defined as: function SubmitJobStringList(joblist: tStringList; var jobno: Integer): Integer; I am calling this from C#. How do I declare the first parameter as a tStringList does not exist in C#. I currently have the declaration as: [DllImport("opt7bja.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]public static extern int SubmitJobStringList(string[] tStringList, ref int jobno); But when I call it I get a memory access violation exception. Anyone know how to pass to a tStringList correctly from C#?
You'll most likely not have any luck with this. The TStringList is more than just an array, it's a full-blown class, and the exact implementation details may differ from what is possible with .NET. Take a look at the Delphi VCL source code (that is, if you have it) and try to find out if you can rebuild the class in C#, and pass it with the help of your best friend, the Interop Marshaller. Note that even the Delphi string type is different from the .NET string type, and passing it without telling the marshaller what he should do, he will pass it as a char-array, most likely. Other than that, I would suggest changing the Delphi DLL. It's never a good thing to expose anything Delphi-specific in a DLL that is to be used by non-Delphi clients. Make the parameter an array of PChar and you should be fine.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3585/" ] }
152,288
I've been pulling my hear out over this problem for a few hours yesterday: I've a database on MySQL 4.1.22 server with encoding set to "UTF-8 Unicode (utf8)" (as reported by phpMyAdmin). Tables in this database have default charset set to latin2 . But, the web application (CMS Made Simple written in PHP) using it displays pages in utf8 ... However screwed up this may be, it actually works. The web app displays characters correctly (mostly Czech and Polish are used). I run: "mysqldump -u xxx -p -h yyy dbname > dump.sql". This gives me an SQL script which: looks perfect in any editor (like Notepad+) when displaying in UTF-8 - all characters display properly all tables in the script have default charset set to latin2 it has "/*!40101 SET NAMES latin2 */;" line at the beginning (among other settings) Now, I want to export this database to another server running on MySQL 5.0.67, also with server encoding set to "UTF-8 Unicode (utf8)". I copied the whole CMS Made Simple installation over, copied the dump.sql script and ran "mysql -h ddd -u zzz -p dbname < dump.sql". After that, all the characters are scrambled when displaying CMSMS web pages. I tried setting: SET character_set_client = utf8; SET character_set_connection = latin2; And all combinations (just to be safe, even if it doesn't make any sense to me): latin2/utf8, latin2/latin2, utf8/utf8, etc. - doesn't help. All characters still scrambled, however sometimes in a different way :). I also tried replacing all latin2 settings with utf8 in the script (set names and default charsets for tables). Nothing. Are there any MySQL experts here who could explain in just a few words (I'm sure it's simple after all) how this whole encoding stuff really works? I read 9.1.4. Connection Character Sets and Collations but found nothing helpful there. Thanks,Matt
Did you try adding the --default-character-set=name option, like this: mysql --default-character-set=utf8 -h ddd -u zzz -p dbname < dump.sql I had that problem before and it worked after using that option. Hope it helps!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23723/" ] }
152,313
When should you use XML attributes and when should you use XML elements? e.g. <customData> <records> <record name="foo" description="bar" /> </records></customData> or <customData> <records> <record> <name>foo</name> <description>bar</description> </record> </records></customData>
There is an article titled " Principles of XML design: When to use elements versus attributes " on IBM's website. Though there doesn't appear to be many hard and fast rules, there are some good guidelines mentioned in the posting. For instance, one of the recommendations is to use elements when your data must not be normalized for white space as XML processors can normalize data within an attribute thereby modifying the raw text. I find myself referring to this article from time to time as I develop various XML structures. Hopefully this will be helpful to others as well. edit - From the site: Principle of core content If you consider the information in question to be part of the essential material that is being expressed or communicated in the XML, put it in an element. For human-readable documents this generally means the core content that is being communicated to the reader. For machine-oriented records formats this generally means the data that comes directly from the problem domain. If you consider the information to be peripheral or incidental to the main communication, or purely intended to help applications process the main communication, use attributes. This avoids cluttering up the core content with auxiliary material. For machine-oriented records formats, this generally means application-specific notations on the main data from the problem-domain. As an example, I have seen many XML formats, usually home-grown in businesses, where document titles were placed in an attribute. I think a title is such a fundamental part of the communication of a document that it should always be in element content. On the other hand, I have often seen cases where internal product identifiers were thrown as elements into descriptive records of the product. In some of these cases, attributes were more appropriate because the specific internal product code would not be of primary interest to most readers or processors of the document, especially when the ID was of a very long or inscrutable format. You might have heard the principle data goes in elements, metadata in attributes. The above two paragraphs really express the same principle, but in more deliberate and less fuzzy language. Principle of structured information If the information is expressed in a structured form, especially if the structure may be extensible, use elements. On the other hand: If the information is expressed as an atomic token, use attributes. Elements are the extensible engine for expressing structure in XML. Almost all XML processing tools are designed around this fact, and if you break down structured information properly into elements, you'll find that your processing tools complement your design, and that you thereby gain productivity and maintainability. Attributes are designed for expressing simple properties of the information represented in an element. If you work against the basic architecture of XML by shoehorning structured information into attributes you may gain some specious terseness and convenience, but you will probably pay in maintenance costs. Dates are a good example: A date has fixed structure and generally acts as a single token, so it makes sense as an attribute (preferably expressed in ISO-8601). Representing personal names, on the other hand, is a case where I've seen this principle surprise designers. I see names in attributes a lot, but I have always argued that personal names should be in element content. A personal name has surprisingly variable structure (in some cultures you can cause confusion or offense by omitting honorifics or assuming an order of parts of names). A personal name is also rarely an atomic token. As an example, sometimes you may want to search or sort by a forename and sometimes by a surname. I should point out that it is just as problematic to shoehorn a full name into the content of a single element as it is to put it in an attribute.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23726/" ] }
152,318
Can anyone recommend any good resources for learning C++ Templates? Many thanks.
I've found cplusplus.com to be helpful on numerous occasions. Looks like they've got a pretty good intro to templates. If its an actual book you're looking for, Effective C++ is a classic with a great section on templates.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16177/" ] }
152,319
I'm looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other sort algorithm other than bubble or merge would suffice. Please note that this is to work with MS Project 2003, so should avoid any of the Excel native functions and anything .net related.
Take a look here : Edit: The referenced source (allexperts.com) has since closed, but here are the relevant author comments: There are many algorithms available on the web for sorting. The most versatile and usually the quickest is the Quicksort algorithm . Below is a function for it. Call it simply by passing an array of values (string or numeric; it doesn't matter) with the Lower Array Boundary (usually 0 ) and the Upper Array Boundary (i.e. UBound(myArray) .) Example : Call QuickSort(myArray, 0, UBound(myArray)) When it's done, myArray will be sorted and you can do what you want with it. (Source: archive.org ) Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long) Dim pivot As Variant Dim tmpSwap As Variant Dim tmpLow As Long Dim tmpHi As Long tmpLow = inLow tmpHi = inHi pivot = vArray((inLow + inHi) \ 2) While (tmpLow <= tmpHi) While (vArray(tmpLow) < pivot And tmpLow < inHi) tmpLow = tmpLow + 1 Wend While (pivot < vArray(tmpHi) And tmpHi > inLow) tmpHi = tmpHi - 1 Wend If (tmpLow <= tmpHi) Then tmpSwap = vArray(tmpLow) vArray(tmpLow) = vArray(tmpHi) vArray(tmpHi) = tmpSwap tmpLow = tmpLow + 1 tmpHi = tmpHi - 1 End If Wend If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHiEnd Sub Note that this only works with single-dimensional (aka "normal"?) arrays. (There's a working multi-dimensional array QuickSort here .)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/152319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4134/" ] }
152,323
I would like to send mail from a script on a Windows Server 2003 Standard Edition. I think the server setup is pretty much out of the box. The mail server is an Exchange one, and when you're on the internal network you can use plain old SMTP. I have done it from my machine with Perl, but unfortunately Perl is not available on the server. Is there an easy way of doing this from a .bat-file or any other way that doesn't require installing some additional software? Edit: Thanks for the quick replies. The "blat" thingie would probably work fine but with wscript I don't have to use a separate binary. I didn't see PhiLho's post the first time I edited and selected an answer. No need for me to duplicate the code here. Just save the script to a file, say sendmail.vbs, and then call it from the command prompt like so: wscript sendmail.vbs
It is possible with Wscript, using CDO: Dim objMailSet objMail = CreateObject("CDO.Message")objMail.From = "Me <[email protected]>"objMail.To = "You <[email protected]>"objMail.Subject = "That's a mail"objMail.Textbody = "Hello World"objMail.AddAttachment "C:\someFile.ext"---8<----- You don't need this part if you have an active Outlook [Express] account -----' Use an SMTP serverobjMail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2' Name or IP of Remote SMTP ServerobjMail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _ "smtp.server.com"' Server port (typically 25)objMail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25objMail.Configuration.Fields.Update----- End of SMTP usage ----->8---objMail.SendSet objMail=NothingWscript.Quit Update: found more info there: VBScript To Send Email Using CDO By default it seems it uses Outlook [Express], so it didn't worked on my computer but you can use a given SMTP server, which worked fine for me.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5264/" ] }
152,328
What is better? A: server:1080/repo/projectA/trunk/... branches/branch1 branches/branch2 branches/branch3 tags/tag1/... tags/tag2/...server:1080/repo/projectB/trunk/... branches/branch1 branches/branch2 branches/branch3 tags/tag1/... tags/tag2/... B: server:1080/repo/trunk/projectA/... branches/projectA/branch1 branches/projectA/branch2 branches/projectA/branch3 tags/projectA/tag1/... tags/projectA/tag2/...server:1080/repo/trunk/projectB/trunk/... branches/projectB/branch1 branches/projectB/branch2 branches/projectB/branch3 tags/projectB/tag1/... tags/projectB/tag2/... What repository structure do you use and WHY?
The Repository Administration chapter of the SVN book includes a section on Planning Your Repository Organization outlining different strategies and their implication, particularly the implications of the repository layout on branching and merging .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8986/" ] }
152,338
How to unit test WCF services? Any 3rd Party tools available?
As aku says, if you're testing service methods (ie code behaviour) then you can unit test that directly and bypass the WCF infrastructure. Of course, if your code depends on WCF context classes (like OperationContext) then I suggest introducing wrappers much like ASP.NET MVC does for HttpContext. For testing connectivity, it will depend on the type of endpoints you have configured. In some cases you can just self-host your WCF service inside the unit test (like you would with a WCF Windows Service) and test that. However, you may need to spin up the ASP.NET Development Web Server or even IIS if you want to test WCF behaviour specific to those hosting environments (ie SSL, authentication methods). This gets tricky and can start making demands on the configuration of everyone's development machine and the build servers but is doable.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11039/" ] }
152,342
I fill a collection one single time when my J2EE webapp starts.Then, several thread may access it at same time but only to read it. I know using a synchronized collection is mandatory for parallels write but do I still need it for parallels read ?
Normally no because you are not changing the internal state of the collection in this case. When you iterate over the collection a new instance of the iterator is created and the state of the iteration is per iterator instance. Aside note: Remember that by keeping a read-only collection you are only preventing modifications to the collection itself. Each collection element is still changeable. class Test { public Test(final int a, final int b) { this.a = a; this.b = b; } public int a; public int b;}public class Main { public static void main(String[] args) throws Exception { List<Test> values = new ArrayList<Test>(2); values.add(new Test(1, 2)); values.add(new Test(3, 4)); List<Test> readOnly = Collections.unmodifiableList(values); for (Test t : readOnly) { t.a = 5; } for (Test t : values) { System.out.println(t.a); } }} This outputs: 55 Important considerations from @WMR answser. It depends on if the threads that are reading your collection are started before or after you're filling it. If they're started before you fill it, you have no guarantees (without synchronizing), that these threads will ever see the updated values. The reason for this is the Java Memory Model, if you wanna know more read the section "Visibility" at this link: http://gee.cs.oswego.edu/dl/cpj/jmm.html And even if the threads are started after you fill your collection, you might have to synchronize because your collection implementation could change its internal state even on read operations (thanks Michael Bar-Sinai , I didn't know such collections existed). Another very interesting read on the topic of concurrency which covers topics like publishing of objects, visibility, etc. in much more detail is Brian Goetz's book Java Concurrency in Practice .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ] }
152,387
C++ was the first programming language I really got into, but the majority of my work on it was academic or for game programming. Most of the programming jobs where I live require Java or .NET programmers and I have a fairly good idea of what technologies they require aside from the basic language. For example, a Java programmer might be required to know EJB, Servlets, Hibernate, Spring, and other technologies, libraries, and frameworks. I'm not sure about C++, however. In real life situations, for general business programming, what are C++ programmers required to know beyond the language features? Stuff like Win32 API, certain libraries, frameworks, technologies, tools, etc. Edit: I was thinking of the standard library as well when I said basic language, sorry if it was wrong or not clear. I was wondering if there are any more specific domain requirements similar to all the technologies Java or .NET programmers might be required to learn as apposed to what C++ programmers need to know in general. I do agree that the standard library and Boost are essential, but is there anything beyond that or is it different for every company/project/domain?
As for every language, I believe there are three interconnected levels of knowledge : Master your language. Every programmer should (do what it takes to) master the syntax. Good references to achieve this are : The C++ Programming Language by Bjarne Stroustrup. Effective C++ series by Scott Meyers. Know your libraries extensively. STL is definitely a must as it has been included in the C++ Standard Library , so knowing it is very close to point 1 : you have to master it. Knowing boost can be very interesting, as a multi-platform and generic library. Know the libraries you are supposed to work with, whether it is Win32 API , OCCI , XPCOM or UNO (just a few examples here). No need to know a database library if you develop purely graphic components... Develop your knowledge of patterns. Cannot avoid Design Patterns: Elements of Reusable Object-Oriented Software here... So, my answer to your updated question would be : know your language, know your platform, know your domain. I think there is enough work by itself here, especially in C++. It's an evergoing work that should never be overlooked.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23153/" ] }
152,436
I have been working as a native C++ programmer for last few years. Now we are starting a new project from the scratch. So what is your thoughts on shifting to C++\CLI at the cost of losing platform independent code. Are there are any special advantages that one can gain by shifting to C++\CLI?
I would recommend the following, based on my experience with C++, C# and .NET: If you want to go the .NET way, use C#. If you do not want .NET, use traditional C++. If you have to bridge traditional C++ with .NET code, use C++/CLI. Works both with .NET calling C++ classes and C++ calling .NET classes. I see no sense in just going to C++/CLI if you don't need it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21045/" ] }
152,447
When I backup or restore a database using MS SQL Server Management Studio, I get a visual indication of how far the process has progressed, and thus how much longer I still need to wait for it to finish. If I kick off the backup or restore with a script, is there a way to monitor the progress, or do I just sit back and wait for it to finish (hoping that nothing has gone wrong?) Edited: My need is specifically to be able to monitor the backup or restore progress completely separate from the session where the backup or restore was initiated.
I found this sample script here that seems to be working pretty well: SELECT r.session_id,r.command,CONVERT(NUMERIC(6,2),r.percent_complete)AS [Percent Complete],CONVERT(VARCHAR(20),DATEADD(ms,r.estimated_completion_time,GetDate()),20) AS [ETA Completion Time],CONVERT(NUMERIC(10,2),r.total_elapsed_time/1000.0/60.0) AS [Elapsed Min],CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0) AS [ETA Min],CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0/60.0) AS [ETA Hours],CONVERT(VARCHAR(1000),(SELECT SUBSTRING(text,r.statement_start_offset/2,CASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END)FROM sys.dm_exec_sql_text(sql_handle))) AS [SQL]FROM sys.dm_exec_requests r WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/152447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18826/" ] }
152,457
This was a question raised by one of the software engineers in my organisation. I'm interested in the broadest definition.
Summary A TCP socket is an endpoint instance defined by an IP address and a port in the context of either a particular TCP connection or the listening state. A port is a virtualisation identifier defining a service endpoint (as distinct from a service instance endpoint aka session identifier). A TCP socket is not a connection , it is the endpoint of a specific connection. There can be concurrent connections to a service endpoint , because a connection is identified by both its local and remote endpoints, allowing traffic to be routed to a specific service instance. There can only be one listener socket for a given address/port combination . Exposition This was an interesting question that forced me to re-examine a number of things I thought I knew inside out. You'd think a name like "socket" would be self-explanatory: it was obviously chosen to evoke imagery of the endpoint into which you plug a network cable, there being strong functional parallels. Nevertheless, in network parlance the word "socket" carries so much baggage that a careful re-examination is necessary. In the broadest possible sense, a port is a point of ingress or egress. Although not used in a networking context, the French word porte literally means door or gateway , further emphasising the fact that ports are transportation endpoints whether you ship data or big steel containers. For the purpose of this discussion I will limit consideration to the context of TCP-IP networks. The OSI model is all very well but has never been completely implemented, much less widely deployed in high-traffic high-stress conditions. The combination of an IP address and a port is strictly known as an endpoint and is sometimes called a socket. This usage originates with RFC793, the original TCP specification. A TCP connection is defined by two endpoints aka sockets . An endpoint (socket) is defined by the combination of a network address and a port identifier. Note that address/port does not completely identify a socket (more on this later). The purpose of ports is to differentiate multiple endpoints on a given network address. You could say that a port is a virtualised endpoint. This virtualisation makes multiple concurrent connections on a single network interface possible. It is the socket pair (the 4-tupleconsisting of the client IP address,client port number, server IP address,and server port number) that specifiesthe two endpoints that uniquelyidentifies each TCP connection in aninternet. ( TCP-IP Illustrated Volume 1 , W. Richard Stevens) In most C-derived languages, TCP connections are established and manipulated using methods on an instance of a Socket class. Although it is common to operate on a higher level of abstraction, typically an instance of a NetworkStream class, this generally exposes a reference to a socket object. To the coder this socket object appears to represent the connection because the connection is created and manipulated using methods of the socket object. In C#, to establish a TCP connection (to an existing listener) first you create a TcpClient . If you don't specify an endpoint to the TcpClient constructor it uses defaults - one way or another the local endpoint is defined. Then you invoke the Connect method on the instance you've created. This method requires a parameter describing the other endpoint. All this is a bit confusing and leads you to believe that a socket is a connection, which is bollocks. I was labouring under this misapprehension until Richard Dorman asked the question. Having done a lot of reading and thinking, I'm now convinced that it would make a lot more sense to have a class TcpConnection with a constructor that takes two arguments, LocalEndpoint and RemoteEndpoint . You could probably support a single argument RemoteEndpoint when defaults are acceptable for the local endpoint. This is ambiguous on multihomed computers, but the ambiguity can be resolved using the routing table by selecting the interface with the shortest route to the remote endpoint. Clarity would be enhanced in other respects, too. A socket is not identified by the combination of IP address and port: [...]TCP demultiplexes incoming segments using all four values that comprise the local and foreign addresses: destination IP address, destination port number, source IP address, and source port number. TCP cannot determine which process gets an incoming segment by looking at the destination port only. Also, the only one of the [various] endpoints at [a given port number] that will receive incoming connection requests is the one in the listen state. (p255, TCP-IP Illustrated Volume 1 , W. Richard Stevens) As you can see, it is not just possible but quite likely for a network service to have numerous sockets with the same address/port, but only one listener socket on a particular address/port combination. Typical library implementations present a socket class, an instance of which is used to create and manage a connection. This is extremely unfortunate, since it causes confusion and has lead to widespread conflation of the two concepts. Hagrawal doesn't believe me (see comments) so here's a real sample. I connected a web browser to http://dilbert.com and then ran netstat -an -p tcp . The last six lines of the output contain two examples of the fact that address and port are not enough to uniquely identify a socket. There are two distinct connections between 192.168.1.3 (my workstation) and 54.252.94.236:80 (the remote HTTP server) TCP 192.168.1.3:63240 54.252.94.236:80 SYN_SENT TCP 192.168.1.3:63241 54.252.94.236:80 SYN_SENT TCP 192.168.1.3:63242 207.38.110.62:80 SYN_SENT TCP 192.168.1.3:63243 207.38.110.62:80 SYN_SENT TCP 192.168.1.3:64161 65.54.225.168:443 ESTABLISHED Since a socket is the endpoint of a connection, there are two sockets with the address/port combination 207.38.110.62:80 and two more with the address/port combination 54.252.94.236:80 . I think Hagrawal's misunderstanding arises from my very careful use of the word "identifies". I mean "completely, unambiguously and uniquely identifies". In the above sample there are two endpoints with the address/port combination 54.252.94.236:80 . If all you have is address and port, you don't have enough information to tell these sockets apart. It's not enough information to identify a socket. Addendum Paragraph two of section 2.7 of RFC793 says A connection is fully specified by the pair of sockets at the ends. Alocal socket may participate in many connections to different foreignsockets. This definition of socket is not helpful from a programming perspective because it is not the same as a socket object , which is the endpoint of a particular connection. To a programmer, and most of this question's audience are programmers, this is a vital functional difference. @plugwash makes a salient observation. The fundamental problem is that the TCP RFC definition of socket is in conflict with the defintion of socket used by all major operating systems and libraries. By definition the RFC is correct. When a library misuses terminology, this does not supersede the RFC. Instead, it imposes a burden of responsibility on users of that library to understand both interpretations and to be careful with words and context. Where RFCs do not agree, the most recent and most directly applicable RFC takes precedence. References TCP-IP Illustrated Volume 1 The Protocols , W. Richard Stevens, 1994 Addison Wesley RFC793 , Information Sciences Institute, University of Southern California for DARPA RFC147 , The Definition of a Socket, Joel M. Winett, Lincoln Laboratory
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/152457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199234/" ] }
152,483
Is there a way to print all methods of an object in JavaScript?
Sure: function getMethods(obj) { var result = []; for (var id in obj) { try { if (typeof(obj[id]) == "function") { result.push(id + ": " + obj[id].toString()); } } catch (err) { result.push(id + ": inaccessible"); } } return result;} Using it: alert(getMethods(document).join("\n"));
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/152483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21132/" ] }
152,506
Saw this question here : What Great .NET Developers Ought To Know (More .NET Interview Questions)
It will show processes that have loaded modules (usaully .DLL files) hosting the .NET runtime. The same technique can be used to search for other DLLs that have been loaded. On a related note, Process Explorer is a Microsoft task manager replacement that will show .NET processes highlighted. I cannot recommend it enough. It is well worth investigating along with the rest of the Sysinternals Suite .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621/" ] }
152,514
I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter). Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would be a shell script, since a shell should be available on any Linux box. There were some valid arguments about details of the file renaming. I think files with the same lowercase names should be overwritten; it's the user's problem. When checked out on a case-ignoring file system, it would overwrite the first one with the latter, too. I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code). The script would be needed to run a build on a Linux system, so I think changes to CVS or Subversion version control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate.
A concise version using the "rename" command: find my_root_dir -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \; This avoids problems with directories being renamed before files and trying to move files into non-existing directories (e.g. "A/A" into "a/a" ). Or, a more verbose version without using "rename" . for SRC in `find my_root_dir -depth`do DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'` if [ "${SRC}" != "${DST}" ] then [ ! -e "${DST}" ] && mv -T "${SRC}" "${DST}" || echo "${SRC} was not renamed" fidone P.S. The latter allows more flexibility with the move command (for example, "svn mv" ).
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/152514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23740/" ] }
152,555
I've always used a *.h file for my class definitions, but after reading some boost library code, I realised they all use *.hpp . I've always had an aversion to that file extension, I think mainly because I'm not used to it. What are the advantages and disadvantages of using *.hpp over *.h ?
Here are a couple of reasons for having different naming of C vs C++ headers: Automatic code formatting, you might have different guidelines for formatting C and C++ code. If the headers are separated by extension you can set your editor to apply the appropriate formatting automatically Naming, I've been on projects where there were libraries written in C and then wrappers had been implemented in C++. Since the headers usually had similar names, i.e. Feature.h vs Feature.hpp, they were easy to tell apart. Inclusion, maybe your project has more appropriate versions available written in C++ but you are using the C version (see above point). If headers are named after the language they are implemented in you can easily spot all the C-headers and check for C++ versions. Remember, C is not C++ and it can be very dangerous to mix and match unless you know what you are doing. Naming your sources appropriately helps you tell the languages apart.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/152555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ] }
152,580
How do I check if an object is of a given type, or if it inherits from a given type? How do I check if the object o is of type str ? Beginners often wrongly expect the string to already be "a number" - either expecting Python 3.x input to convert type, or expecting that a string like '1' is also simultaneously an integer. This is the wrong canonical for those questions. Please carefully read the question and then use How do I check if a string represents a number (float or int)? , How can I read inputs as numbers? and/or Asking the user for input until they give a valid response as appropriate.
Use isinstance to check if o is an instance of str or any subclass of str : if isinstance(o, str): To check if the type of o is exactly str , excluding subclasses of str : if type(o) is str: Another alternative to the above: if issubclass(type(o), str): See Built-in Functions in the Python Library Reference for relevant information. Checking for strings in Python 2 For Python 2, this is a better way to check if o is a string: if isinstance(o, basestring): because this will also catch Unicode strings. unicode is not a subclass of str ; whereas, both str and unicode are subclasses of basestring . In Python 3, basestring no longer exists since there's a strict separation of strings ( str ) and binary data ( bytes ). Alternatively, isinstance accepts a tuple of classes. This will return True if o is an instance of any subclass of any of (str, unicode) : if isinstance(o, (str, unicode)):
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/152580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14102/" ] }
152,585
What is the simplest way to identify and separate GET and POST parameters from a controller in Ruby on Rails, which will be equivalent to $_GET and $_POST variables in PHP?
You can use the request.get? and request.post? methods to distinguish between HTTP Gets and Posts. See http://api.rubyonrails.org/classes/ActionDispatch/Request.html
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18768/" ] }
152,613
I have a specialized list that holds items of type IThing : public class ThingList : IList<IThing>{...}public interface IThing{ Decimal Weight { get; set; } Decimal Velocity { get; set; } Decimal Distance { get; set; } Decimal Age { get; set; } Decimal AnotherValue { get; set; } [...even more properties and methods...]} Sometimes I need to know the maximum or minimum of a certain property of all the things in the list. Because of "Tell don't ask" we let the List figure it out: public class ThingList : IList<IThing>{ public Decimal GetMaximumWeight() { Decimal result = 0; foreach (IThing thing in this) { result = Math.Max(result, thing.Weight); } return result; }} Thats very nice. But sometimes I need the minimum weight, sometimes the maximum velocity and so on. I don't want a GetMaximum*()/GetMinimum*() pair for every single property. One solution would be reflection. Something like (hold your nose, strong code smell!): Decimal GetMaximum(String propertyName);Decimal GetMinimum(String propertyName); Are there any better, less smelly ways to accomplish this? Thanks,Eric Edit: @Matt: .Net 2.0 Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005). Maybe we should move to .Net 3.5 and Visual Studio 2008 sometime soon. Thanks, guys. Conclusion: There are diffent ways that are far better than reflection. Depending on runtime and C# version. Have a look at Jon Skeets answer for the differences. All answers are are very helpful. I will go for Sklivvz suggestion (anonymous methods). There are several code snippets from other people (Konrad Rudolph, Matt Hamilton and Coincoin) which implement Sklivvz idea. I can only "accept" one answer, unfortunately. Thank you very much. You can all feel "accepted", altough only Sklivvz gets the credits ;-)
(Edited to reflect .NET 2.0 answer, and LINQBridge in VS2005...) There are three situations here - although the OP only has .NET 2.0, other people facing the same problem may not... 1) Using .NET 3.5 and C# 3.0: use LINQ to Objects like this: decimal maxWeight = list.Max(thing => thing.Weight);decimal minWeight = list.Min(thing => thing.Weight); 2) Using .NET 2.0 and C# 3.0: use LINQBridge and the same code 3) Using .NET 2.0 and C# 2.0: use LINQBridge and anonymous methods: decimal maxWeight = Enumerable.Max(list, delegate(IThing thing) { return thing.Weight; });decimal minWeight = Enumerable.Min(list, delegate(IThing thing) { return thing.Weight; }); (I don't have a C# 2.0 compiler to hand to test the above - if it complains about an ambiguous conversion, cast the delegate to Func<IThing,decimal>.) LINQBridge will work with VS2005, but you don't get extension methods, lambda expressions, query expressions etc. Clearly migrating to C# 3 is a nicer option, but I'd prefer using LINQBridge to implementing the same functionality myself. All of these suggestions involve walking the list twice if you need to get both the max and min. If you've got a situation where you're loading from disk lazily or something like that, and you want to calculate several aggregates in one go, you might want to look at my "Push LINQ" code in MiscUtil . (That works with .NET 2.0 as well.)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8976/" ] }
152,643
For an std::map<std::string, std::string> variables , I'd like to do this: BOOST_CHECK_EQUAL(variables["a"], "b"); The only problem is, in this context variables is const , so operator[] won't work :( Now, there are several workarounds to this; casting away the const , using variables.count("a") ? variables.find("a")->second : std::string() or even making a function wrapping that. None of these seem to me to be as nice as operator[] . What should I do? Is there a standard way of doing this (beautifully)? Edit: Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.
template <typename K, typename V>V get(std::map<K, V> const& map, K const& key){ std::map<K, V>::const_iterator iter(map.find(key)); return iter != map.end() ? iter->second : V();} Improved implementation based on comments: template <typename T>typename T::mapped_type get(T const& map, typename T::key_type const& key){ typename T::const_iterator iter(map.find(key)); return iter != map.end() ? iter->second : typename T::mapped_type();}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2971/" ] }
152,664
I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this?
the ItemTemplateSelector will work but I think it is easier to create multiple DataTemplate s in your resource section and then just giving each one a DataType . This will automatically then use this DataTemplate if the items generator detects the matching data type? <DataTemplate DataType={x:Type local:ObjectA}> ...</DataTemplate> Also make sure that you have no x:Key set for the DataTemplate . Read more about this approach here
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ] }
152,691
Is Eclipse the best IDE for Java? If not, is there something better? I want to know and possibly try it out. Thanks.
Let me just start out by saying that Eclipse is a fantastic IDE for Java and many other languages. Its plugin architecture and its extensibility are hard to rival and the fact that it's free is a huge plus for smaller teams or tight budgets. A few things that I hate about Eclipse. The documentation is really lacking. I don't know who writes the stuff, but if it's not just flatly missing, it's incomplete. If it's not incomplete, then it's just flat out wrong. I have wasted many precious hours trying to use a given feature in Eclipse by walking through its documentation only to discover that it was all trash to begin with. Despite the size of the project, I have found the community to be very lacking and/or confusing enough to be hard to participate in. I have tried several times to get help on a particular subject or plugin only to be sent to 3 or 4 different newsgroups who all point to the other newsgroup or just plain don't respond. This can be very frustrating, as much smaller open source products that I use are really good about answering questions I have. Perhaps it's simply a function of the size of the community. If you need functionality beyond the bundled functionality of one of their distros (for instance, the Eclipse for Java EE Developers distro which bundles things like the WTP), I have found the installation process for extra plugins excruciatingly painful . I don't know why they can't make that process simpler (or maybe I'm just spoiled on my Mac at home and don't know how bad it really is out in the 'real' world) but if I'm not just unsuccessful, oftentimes it's a process of multiple hours to get a new plugin installed. This was supposedly one of their goals in 3.4 (to make installation of new projects simpler); if they succeeded, I can't tell. Documentation in the form of books and actual tutorials is sorely lacking. I want a master walkthrough for something as dense and feature-rich as Eclipse; something that says, 'hey, did you know about this feature and how it can really make you more productive?'. As far as I've found, nothing like that exists. If you want to figure out Eclipse, you've got one option, sit down and play with it (literally play with it, not just see a feature and go and read the documentation for it, because that probably doesn't exist or is wrong). Despite these things, Eclipse really is a great IDE. Its refactoring tooling works tremendously well. The handling of Javadoc works perfectly. All of features we've come to expect of an IDE are their (code completion, templates, integration with various SCMSs, integration with build systems). Its code formatting and cleanup tools are very powerful. I find its build system to work well and intuitively. I think these are the things upon which its reputation is really built. I don't have enough experience with other IDEs or with other distros of Eclipse (I've seen RAD at work quite a few times; I can't believe anyone would pay what they're charging for that) to comment on them, but I've been quite happy with Eclipse for the most part. One tip I have heard from multiple places is that if you want Eclipse without a lot of the hassle that can come with its straight install, go with a for-pay distro of it. My Eclipse is a highly recommended version that I've seen all over the net that is really very affordable (last I heard, $50 for the distro plus a year of free upgrades). If you have the budget and need the added functionality, I'd go with something like that. Anyway, I've tried to be as detailed as I can. I hope this helps and good luck on your search! :)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
152,699
In Python, you can do this: import webbrowserwebbrowser.open_new("http://example.com/") It will open the passed in url in the default browser Is there a ruby equivalent?
Cross-platform solution: First, install the Launchy gem: $ gem install launchy Then, you can run this: require 'launchy'Launchy.open("http://stackoverflow.com")
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/152699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147/" ] }
152,708
I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using find piped with xargs grep : find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN' But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns.
So I discovered pcregrep which stands for Perl Compatible Regular Expressions GREP . the -M option makes it possible to search for patterns that span line boundaries. For example, you need to find files where the ' _name ' variable is followed on the next line by the ' _description ' variable: find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description' Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/152708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22035/" ] }
152,712
I like the simplistic look and design of some of the Microsoft blogs. Alas, I can't join the Microsoft dev party and create my own development blog on the blogs.msdn.com page because I don't work at Microsoft, and I already have my own wordpress blog. I was looking to have my blog styled to one of the default looking themes shown here: http://blogs.msdn.com/jmeier/default.aspx Could Microsoft take legal action against me if I used a stylesheet from their page? If I made my page 'based' off their stylesheet, e.g. written from the ground up, would that be copyright infringement?
Could Microsoft take legal action against me if I used a stylesheet from their page? Absolutely, since you infringed their copyright. On the other hand, it's debatable whether the stylesheet alone constitues a sufficient threshold of originality to justify legal actions 1 . At the least, taking without asking is often considered rude. ;-) 1) No. It certainly doesn't . A sophisticated design however will.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ] }
152,714
I am relatively new to matchers. I am toying around with hamcrest in combination with JUnit and I kinda like it. Is there a way, to state that one of multiple choices is correct? Something like assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest The method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java? (I am open to hamcrest-alternatives)
assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3))) From Hamcrest tutorial : anyOf - matches if any matchers match, short circuits (like Java ||) See also Javadoc . Moreover, you could write your own Matcher, which is quite easy to do.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/152714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870/" ] }
152,729
If you use Image.Save Method to save an image to a EMF/WMF, you get an exception ( http://msdn.microsoft.com/en-us/library/ktx83wah.aspx ) Is there another way to save the image to an EMF/WMF?Are there any encoders available?
Image is an abstract class: what you want to do depends on whether you are dealing with a Metafile or a Bitmap . Creating an image with GDI+ and saving it as an EMF is simple with Metafile . Per Mike's post : var path = @"c:\foo.emf"var g = CreateGraphics(); // get a graphics object from your form, or wherevervar img = new Metafile(path, g.GetHdc()); // file is created herevar ig = Graphics.FromImage(img);// call drawing methods on ig, causing writes to the fileig.Dispose(); img.Dispose(); g.ReleaseHdc(); g.Dispose(); This is what you want to do most of the time, since that is what EMF is for: saving vector images in the form of GDI+ drawing commands. You can save a Bitmap to an EMF file by using the above method and calling ig.DrawImage(your_bitmap) , but be aware that this does not magically covert your raster data into a vector image.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12192/" ] }
152,774
What's the best way to trim a DateTime object to a specific precision? For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this? private static DateTime TrimDateToMinute(DateTime date){ return new DateTime( date.Year, date.Month, date.Day, date.Hour, date.Minute, 0);} What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day.
static class Program{ //using extension method: static DateTime Trim(this DateTime date, long roundTicks) { return new DateTime(date.Ticks - date.Ticks % roundTicks, date.Kind); } //sample usage: static void Main(string[] args) { Console.WriteLine(DateTime.Now); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerDay)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerHour)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMillisecond)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMinute)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerSecond)); Console.ReadLine(); }}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/152774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21807/" ] }
152,834
I need to know the default port settings for the following services SQL Server SQL Browser SQL Reporting services SQL Analysis services I need to know the port settings for these services for different versions of SQL Server (2000,2005,2008) Also let me know whether the default port setting will change based on sql server versions.
The default SQL Server port is 1433 but only if it's a default install. Named instances get a random port number. The browser service runs on port UDP 1434. Reporting services is a web service - so it's port 80, or 443 if it's SSL enabled. Analysis services is 2382 but only if it's a default install. Named instances get a random port number.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/152834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ] }
152,837
How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database. I'm not sure if it makes a difference, but I'm using Oracle 9i.
I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far. Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name. SET DEFINE OFF will stop sqlplus interpreting & this way. But what if you need to use sqlplus variables and literal & characters? You need SET DEFINE ON to make variables work And SET ESCAPE ON to escape uses of &. e.g. set define onset escape ondefine myvar=/forthselect 'back\\ \& &myvar' as swing from dual; Produces: old 1: select 'back\\ \& &myvar' from dualnew 1: select 'back\ & /forth' from dualSWING--------------back\ & /forth If you want to use a different escape character: set define onset escape '#'define myvar=/forthselect 'back\ #& &myvar' as swing from dual; When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first: set escape offset escape '#'
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/152837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466/" ] }
152,866
For simplicity, I generally split a lot of my configuration (i.e. the contents of app.config and web.config) out into separate .config files, and then reference them from the main config file using the 'configSource' attribute. For example: <appSettings configSource="appSettings.config"/> and then placing all of the key/value pairs in that appSettings.config file instead of having this in-line in the main config file: <appSettings> <add key="FirstKey" value="FirstValue"/> <add key="SecondKey" value="SecondValue"/> ...</appSettings> This typically works great with the application itself, but I run into problems when attempting to write unit tests that, for whatever reason, need to get at some value from a configuration section that is stored in one of these external files. (I understand that most of these would likley be considered "integration tests", as they are relying on the Configuration system, and I do have "pure unit tests" as well, but those are the not the problem. I'm really looking to test that these configuration values are retrieved correctly and impact behavior in the correct way). Due to how MSTest compiles and copies the output to obfuscated-looking folders that are different from every test run (rather than to the 'bin' folder like you might think), it never seems to be able to find those external files while the tests are executing. I've tried messing around with post build actions to make this work but with no luck. Is there a way to have these external files copied over into the correct output folder at run time?
Found it: If you edit the test run configuration (by double clicking the .testrunconfig file that gets put into the 'Solution Items' solution folder when you add a new unit test), you get a test run configuration dialog. There's a section there called 'Deployment' where you can specifiy files or whole folders from anywhere in the solution that can be copied out with the compiled assemblies at run time to the correct folder. In this way, I can now actually just define most of my configuration in one set of external .config files and have them automatically copied out at the run of each test.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1680/" ] }
152,871
When you think about it, doesn't the REST paradigm of being resource-oriented boil down to being object-oriented (with constrained functionality, leveraging HTTP as much as possible)? I'm not necessarily saying it's a bad thing, but rather that if they are essentially the same very similar then it becomes much easier to understand REST and the implications that such an architecture entails. Update: Here are more specific details: REST resources are equivalent to public classes. Private classes/resources are simply not exposed. Resource state is equivalent to class public methods or fields. Private methods/fields/state is simply not exposed (this doesn't mean it's not there). While it is certainly true that REST does not retain client-specific state across requests, it does retain resource state across all clients. Resources have state, the same way classes have state. REST resources are are globally uniquely identified by a URI in the same way that server objects are globally uniquely identified by their database address, table name and primary key. Granted there isn't (yet) a URI to represent this, but you can easily construct one.
REST is similar to OO in that they both model the world as entities that accept messages (i.e., methods) but beyond that they're different. Object orientation emphasizes encapsulation of state and opacity , using as many different methods necessary to operate on the state. REST is about transfer of (representation of) state and transparency . The number of methods used in REST is constrained and uniform across all resources. The closest to that in OOP is the ToString() method which is very roughly equivalent to an HTTP GET. Object orientation is stateful --you refer to an object and can call methods on it while maintaining state within a session where the object is still in scope. REST is stateless --everything you want to do with a resource is specified in a single message and all you ever need to know regarding that message is sent back in a single response. In object-orientation, there is no concept of universal object identity --objects either get identity from their memory address at any particular moment, a framework-specific UUID, or from a database key. In REST all resources are identified with a URI and don't need to be instantiated or disposed--they always exist in the cloud unless the server responds with a 404 Not Found or 410 Gone , in whch case you know there's no resource with that URI. REST has guarantees of safety (e.g., a GET message won't change state) and idempotence (e.g., a PUT request sent multiple times has same effect as just one time). Although some guidelines for particular object-oriented technologies have something to say about how certain constructs affect state, there really isn't anything about object orientation that says anything about safety and idempotence.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/152871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14731/" ] }
152,887
This has been bugging me for a long time -- how do I properly resolve a merge conflict within the SVN properties set on a directory? Say for instance there are two developers working on a project where svn:ignore is set on some directory. If both developers make changes to this property, when the second one updates, they will see a merge conflict. Unlike file merge conflicts, a single file is generated in the directory called "dir_conflicts.prej", which the second developer must read and manually correct. Usually, what I end up doing is reverting all my changes to the local copy, then re-setting these properties manually with the info in dir_conflicts.prej. However, this is rather cumbersome when dealing with a big list of URLs in an svn:externals property, as many of our projects use. There has got to be a better way to do this -- does anybody know how?
Just a quick update after some additional research -- it is not possible to easily merge SVN properties. My originally described method (revert, merge data from .prej files, propset, re-commit) appears to be the best way to deal with this type of problem.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14302/" ] }
152,889
So I feel I pretty well understand the application layer, and everything below (and including) the transport layer. The session and presentation layers, though, I don't fully understand. I've read the simplistic descriptions in Wikipedia, but it doesn't have an example of why separating out those layers is useful. So: What is the session layer? What does it do, and under what circumstances is it better to have a session layer than simply talk to the transport with your app? What is the presentation layer? (same questions as above) -Adam
The session layer is meant to store states between two connections, like what we use cookies for when working with web programming. The presentation layer is meant to convert between different formats. This was simpler when the only format that was worried about was character encoding, ie ASCII and EBCDIC. When you consider all of the different formats that we have today(Quicktime, Flash, Pdf) centralizing this layer is out of the question. TCP/IP doesn't make any allocation to these layers, since they are really out of the scope of a networking protocol. It's up to the applications that take advantage of the stack to implement these.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ] }
152,938
By and large, modal interfaces suck big rocks. On the other hand, I can't think of a better way to handle File Open... , or Print... and this, I think, is because they are occasional actions, infrequent and momentous, and they are atomic in nature; you either finish specifying all your print options and go through with it, or you cancel the whole show. Let's put together a little style-guide. Suggest any use-cases in which a dialog is the preferred presentation and why it is preferred. Can the dialog be non-modal? If it is, how do you mark transactional boundaries, since Cancel ceases to have a clear meaning. Do you use an Apply button, for example?
IMO, modal interfaces should only be used when you HAVE to deal with whatever the dialog is doing or asking before the application can continue. Any other time, if you're using a dialog, it should be non-modal.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1715673/" ] }
152,968
Do you know an easy and straight-forward method/sub/module which allows me to convert a number (say 1234567.89) to an easily readable form - something like 1.23M? Right now I can do this by making several comparisons, but I'm not happy with my method: if($bytes > 1000000000){ $bytes = ( sprintf( "%0.2f", $bytes/1000000000 )). " Gb/s"; }elsif ($bytes > 1000000){ $bytes = ( sprintf( "%0.2f", $bytes/1000000 )). " Mb/s"; }elsif ($bytes > 1000){ $bytes = ( sprintf( "%0.2f", $bytes/1000 )). " Kb/s"; }else{ $bytes = sprintf( "%0.2f", $bytes ). "b/s";} Thank you for your help!
The Number::Bytes::Human module should be able to help you out. An example of how to use it can be found in its synopsis: use Number::Bytes::Human qw(format_bytes); $size = format_bytes(0); # '0' $size = format_bytes(2*1024); # '2.0K' $size = format_bytes(1_234_890, bs => 1000); # '1.3M' $size = format_bytes(1E9, bs => 1000); # '1.0G' # the OO way $human = Number::Bytes::Human->new(bs => 1000, si => 1); $size = $human->format(1E7); # '10MB' $human->set_options(zero => '-'); $size = $human->format(0); # '-'
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/152968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23780/" ] }
152,975
I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area. Is something like this possible with jQuery? $("#menuscontainer").clickOutsideThisElement(function() { // Hide the menus});
Note: Using stopPropagation is something that should be avoided as it breaks normal event flow in the DOM. See this CSS Tricks article for more information. Consider using this method instead. Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body. $(window).click(function() { //Hide the menus if visible});$('#menucontainer').click(function(event){ event.stopPropagation();});
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/152975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ] }
153,039
I am all about using ASP.NET MVC, but one of the areas that I hope gets improved on is Client-Side Validation. I know the most recent version (Preview 5) has a lot of new features for Validation, but they all seem to be after the page has been posted. I have seen an interesting article by Steve Sanderson ... using Live Validation, Castle.Components.Validator.dll, and a Validator framework he made. I have used it in my project, but I am hoping something like it will get integrated into the official ASP.NET MVC release. I definitely think the business rules should reside either on the model or in the controller rather than in the View. Have any of you used a similar approach? Are you aware of something like this being added to the official ASP.NET MVC release?
"Obviously you'll still need to validate your input on the server side for the small percentage of users who disable javascript." Just an update to this comment. Server-side validation has nothing to do with users that run with JavaScript disabled. Instead, it is needed for security reasons, and to do complex validation that can't be done on the client. A form should always have server-side validation. Client-side validation is only there as a convenience. A malicious user could easily post data to your form bypassing any client-side validation that you have in place. Never trust input data!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4481/" ] }