Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.
You will probably find your application is bandwidth limited not CPU or I/O limited. As such, add as many as you like until performance begins to degrade. You may come up against other limits depending on your network setup. Like if you're behind an ADSL router, there will be a limit on the number of concurrent NAT sessions, which may impact making too many HTTP requests at once. Make too many and your provider may treat you as being infected by a virus or the like. There's also the issue of how many requests the server you're crawling can handle and how much of a load you want to put on it. I wrote a crawler once that used just one thread. It took about a day to process all the information I wanted at about one page every two seconds. I could've done it faster but I figured this was less of a burden for the server. So really theres no hard and fast answer. Assuming a 1-5 megabit connection I'd say you could easily have up to 20-30 threads without any problems.
I would use one thread and [twisted](http://twistedmatrix.com/) with either a deferred semaphore or a task cooperator if you already have an easy way to feed an arbitrarily long list of URLs in. It's extremely unlikely you'll be able to make a multi-threaded crawler that's faster or smaller than a twisted-based crawler.
For my app, how many threads would be optimal?
[ "", "python", "multithreading", "" ]
maybe using the latest technologies, in 3.5 SP1, is there a way to short this? ``` // Bruno: add the empty row with column names // -- select [CRM5].[USERGROUP].[UserGroup_id], [CRM5].[USERGROUP].[name] AS [name] if (col.ToLower().Contains("] as [")) { // [CRM5].[USERGROUP].[name] AS [name] splitColumn.Clear(); // clear the list splitColumn.AddRange(col.Trim().Split(' ')); emptyRow.Append(String.Format(" '' AS {0},", splitColumn[splitColumn.Count - 1])); } else { // [CRM5].[USERGROUP].[UserGroup_id] splitColumn.Clear(); // clear the list splitColumn.AddRange(col.Trim().Split('.')); emptyRow.Append(String.Format(" '' AS {0},", splitColumn[splitColumn.Count - 1])); ``` } In other words, is there a way to retrieve the last element of a String when split? maybe ``` col.Trim().Split('.').Find(x => x.LastItem); ``` > col is a String > > splitColumn is a List < String >
Assuming that you've imported System.Linq: ``` var lastOrNull = "".Split(' ').LastOrDefault(); ``` To elaborating the above code snippet... this do the trick: ``` col = (col ?? "").Split(new char[] { ' ' }, int.MaxValue, StringSplitOptions.RemoveEmptyEntries) .LastOrDefault(); if (col != null) { emptyRow.Append(String.Format(" '' AS {0},", col); } ``` Trim() is unnecessary if you specify StringSplitOptions.RemoveEmptyEntries. The above code will not throw if the string is null or empty.
Try this: ``` string last = col.Split('.').Last(); ```
Improve code on Getting last split secction
[ "", "c#", "" ]
I'm writing an XNA game where I do per-pixel collision checks. The loop which checks this does so by shifting an int and bitwise ORing and is generally difficult to read and understand. I would like to add private methods such as `private bool IsTransparent(int pixelColorValue)` to make the loop more readable, but I don't want the overhead of method calls since this is very performance sensitive code. Is there a way to force the compiler to inline this call or will I do I just hope that the compiler will do this optimization? If there isn't a way to force this, is there a way to check if the method was inlined, short of reading the disassembly? Will the method show up in reflection if it was inlined and no other callers exist? **Edit:** I can't force it, so can I detect it?
No you can't. Even more, the one who decides on inlining isn't VS compiler that takes you code and converts it into IL, but JIT compiler that takes IL and converts it to machine code. This is because only the JIT compiler knows enough about the processor architecture to decide if putting a method inline is appropriate as it’s a tradeoff between instruction pipelining and cache size. So even looking in .NET Reflector will not help you.
> "You can check > System.Reflection.MethodBase.GetCurrentMethod().Name. > If the method is inlined, it will > return the name of the caller > instead." --[Joel Coehoorn](https://stackoverflow.com/users/3043/joel-coehoorn)
Can I check if the C# compiler inlined a method call?
[ "", "c#", "optimization", "inline", "compilation", "" ]
I was wondering if there's an easy way with javascript (including JQuery, which we're using on the site) to put descriptive text in a text input until the user clicks it to type in their own text. For instance I'd like to put the word 'Search' in a text input (preferrably in a lighter color than real input) until the user clicks the input, when it disappears and allows them to type in their search terms. I don't want to actually have the word 'Search' be the value of the text input though, because it is somewhat important that the user can search for the word search. I was thinking of absolute positioning a <p> element with the word search over the input and hiding it when it (or the input) is clicked. What do you think? is this horribly misguided?
I recently bumped into the [jQuery Form Example plugin](http://mucur.name/system/jquery_example/) that does just what you want. The github page for the project is [here](http://github.com/mudge/jquery_example/tree/master). With that plugin, you can display a placeholder value that will vanish on click with just this: `$('input#search').example('Search');`
You can set the initial value of the search input to "Search" and then add an onClick listener to remove it. `$("input.search-term").one("click", function() { $(this).removeAttr("value"); });` It won't impact the user's ability to search for "search." This is a much cleaner approach than trying to finagle a `<p>` or `<label>` element over the input. **EDIT:** You are all absolutely right - removing the value on each click is poor UX. That's what I get for answering quickly. :) Updated to only remove the initial value.
Text Input with descriptive text
[ "", "javascript", "jquery", "html", "usability", "textinput", "" ]
I have a directory full of files, some which have an ampersand in their names. I would like to rename all the files with ampersands and replace each ampersand with a plus (+). I am working with around 10k files. What would be the best method to do this?
``` import glob, os for filename in glob.glob(os.path.join(yourPath, "*&*")): os.rename(filename, filename.replace('&','+')) ```
If you have subdirectories: ``` import os for dirpath, dirs, files in os.walk(your_path): for filename in files: if '&' in filename: os.rename( os.path.join(dirpath, filename), os.path.join(dirpath, filename.replace('&', '+')) ) ```
Rename files, Python/Jython
[ "", "python", "file", "jython", "rename", "" ]
I've read that although SQL is meant to be standardised, it is implemented different etc with different databases. I have only ever used MySQL for databases. What I would like to know is what other databases share the same syntax? I am using PDO now, and I would like to set a flag to allow the user to specify which database they would like to use. I would be interested in knowing which are the 'safe' databases that will handle most (if not all) my general MySQL queries. Mainly SELECT, INSERT, UPDATE, DROP, DELETE. Thanks
There are several revisions of a such called `ANSI SQL`. All major database engines (that is `Oracle`, `MS SQL`, `PostgreSQL` and `MySQL`) should (should) in theory support `SQL-92`. This includes everything you've mentioned: `SELECT`, `INSERT`, `UPDATE`, `DROP`, `DELETE`, as long as you don't use complex clauses with them. In practice: 1. Not all databases support the full set of `SQL-92`. Writing cross-platform `SQL` even in `SQL-92` requires lots of testing. 2. Platform independency in `SQL` ends when you insert your `1001st` row and need to optimize you queries. If you browse a little over `StackOverflow` questions tagged `SQL`, you will see that most of them say "*help me to optimize this query*", and most answers say "*use this platform dependent hack*"
You will find that some database store datatypes differently, for example, mysql stores Booleans as 1 and 0 and postgres stores them as 't' and 'f'. As long as your database classes are aware of the need to convert data, you should be fine, probably 96.3482% of everyday CRUD will work pretty well across the board. Even if you create database classes that directly call PDO, you can later on add some logic for data translation or query modification. You could use the database abstraction layer [ADOdb](http://adodb.sourceforge.net/). (its got what plants crave) I'd suggest making sure that your customers actually give a crap about which database they need to run before you spend a lot of time developing functionality you may not need.
What databases used with PHP share the same (or most) of the SQL syntax?
[ "", "php", "mysql", "pdo", "" ]
Is there a way to detect the name of the server running a PHP script from the command line? There are numerous ways to do this for PHP accessed via HTTP. But there does not appear to be a way to do this for CLI. For example: ``` $_SERVER['SERVER_NAME'] ``` is not available from the command line.
``` echo php_uname("n"); ``` see <http://php.net/manual/en/function.php-uname.php>
``` <?php echo gethostname(); // may output e.g,: sandie ``` See <http://php.net/manual/en/function.gethostname.php> gethostname() is a convenience function which does the same as `php_uname('n')` and was added as of PHP 5.3
PHP Server Name from Command Line
[ "", "php", "command-line", "command-line-interface", "" ]
I have created a .net web part and deployed it on the sharepoint site. When I preview it, the sharepoint throws up an error saying "An error occured when previewing the Web Part" The code in the web part is as follows ``` Dim myweb As Microsoft.SharePoint.SPWeb = Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(Context) 'Dim mylist As Microsoft.SharePoint.SPList = myweb.Lists(System.Configuration.ConfigurationSettings.AppSettings("BedList").ToString()) Dim mylist As Microsoft.SharePoint.SPList = myweb.Lists("{80F6F320-E1F5-42EB-A2FB-895EAE00F589}") Dim items As Microsoft.SharePoint.SPListItemCollection = mylist.Items For Each item As Microsoft.SharePoint.SPListItem In items returnString = returnString + "<br/>" + item("Status").ToString() + " For " + item("Title").ToString + "<br/>" Next ``` Does anyone know why this would not work. I can not get hold of the execption thrown. any help would be greatful
First you should make your exceptions visible by changing the following in the web.config CallStack = true ``` <SafeMode MaxControls="200" CallStack="true" DirectFileDependencies="10" TotalFileDependencies="50" AllowPageLevelTrace="false"> ``` CustomErrors = Off ``` <customErrors mode="Off" /> ``` Then you will see the real exception You can also try obtain the current web using the following code: ``` Dim myweb As Microsoft.SharePoint.SPWeb = SPContext.Current.Web ``` Other problem could be related with wrong listId ou ListName when you try to obtain the list. Hope it helps
Also look for <compilation..> tag and set it to <compilation debug="true"..>
Sharepoint errors
[ "", "c#", "vb.net", "sharepoint", "moss", "" ]
So I have this annoying issue with Visual Studio (when working with C#), I've been digging around in the C# formatting options, general VS options and on google and MSDN but can't really find a fix for this - I'm assuming there's just a checkbox somewhere and I've just overlooked it. Here it is: I like to format my code like this: ``` Type var2 = new Type(); Type someVar = new Type(); ``` But visual studio insists on formatting it like this, whenever the automatic format feature is applied: ``` Type var2 = new Type(); Type someVar = new Type(); ``` Where do I turn this annoying feature **off**?
In the Formatting Options, In the Spacing section: there is an option called **'Ignore spaces in declaration statements'**. Check that option, and VS.NET will not re-format the declarations that you make. So, this should work: ``` int i = 5; int melp = 4; ``` But, when you do this, VS.NET will still reformat your code: ``` int i; int melp; i = 5; melp = 4; ``` will become: ``` int i; int melp; i = 5; melp = 4; ``` So, it is really only in declaration statements that VS.NET will ignore the extra spacing you provide.
Tools|Options|C#|Formatting I. Ignore spaces in declaration statements <<-- check this AND II. Set spacing for operators Insert space... Ignore spaces ... <<-- check this
How do I turn off Visual Studio's formatting options?
[ "", "c#", ".net", "asp.net", "visual-studio", "visual-studio-2008", "" ]
I need to retrieve rows from a table (i.e: 'orders') ordered by a column (lets say 'user') randomly. That is, I need all orders from the same user to remain together (one after the other) and users to be ordered randomly.
I'm going to assume you have a second table called "users" that has all the users in it. If not, you could still do this by adding another SELECT DISTINCT subquery on orders, but that would be much messier: ``` SELECT orders.* FROM orders INNER JOIN (SELECT userid, RAND() as random FROM users) tmp ON orders.userid = tmp.userid ORDER BY tmp.random, tmp.userid ``` You'll want to order by the random number AND the user id so if two user ids get the same random number their orders won't be all jumbled together.
How random does it have to be? I can think of a few possible answers. If the "random" sequence should be repeatable, you can sort by a hash of the user ID, using MD5 or a custom one you create yourself e.g. ORDER BY MD5(), secondary\_sort\_column.
MySQL - How do I order the results randomly inside a column?
[ "", "sql", "mysql", "" ]
I'm looping through the Session keys and adding entries and their values to a Hashtable, which I'm then serializing. The problem I'm having is there is an object on the Session that is not serializable, and it shouldn't be serialized anyway. I'm looking around, and plenty of built-in types don't implement the ISerializable attribute, so testing for that doesn't work: ``` if (val is ISerializable) { ... } ``` So, how do I test for this? Does this make sense?
There is only one guaranteed way to determine if an object is serializable. Serialize it and see if the operation succeeds. I know that seems a bit overkill but there are just so many different ways that serialization can be broken. There are two items in Metadata you can check to see if a type claims serializability (ISerializable and [Serializable]) but this is just a claim. It can and is broken in so many different ways. The problem is that in the .Net world the act of declaring the ability to be serialized and actually serializing are 2 separate distinct actions. It's perfectly possible (and legal) to do one but not the other. Take this for example ``` [Serializable] public class Foo { public Object Field1; } ``` This class claims to be serializable and may very well be. It all depends on the value actually stored in Field1. No amount of metadata inspection on the type will every tell you whether it can actually be serialized. All you can do is try and see if it suceeds.
You can use the IsSerializable property of the Type class. ``` if(val.GetType().IsSerializable) ```
How do I tell if a class can be serialized?
[ "", "c#", "serialization", "" ]
I'm writing a Windows Service application which listens for connections and performs certain tasks as instructed from a different application running on another computer on the network. One of the tasks ensures no user is currently logged on, locks the workstation, delete some files, and then restarts the system. I considered using [this solution](https://stackoverflow.com/questions/132620/how-do-you-retrieve-a-list-of-logged-in-connected-users-in-c) to look through the list of running processes and check the user names, determining if no user is logged on by matchhing the user names against SYSTEM, NETWORK, etc. I realized I have PostgreSQL running which uses a user account named postgres so that wouldn't work. Checking if explorer.exe is running also wouldn't work because explorer sometmes crashes, or I sometimes end the process myself and restart it. What would be a good way of determining that NO user is logged on to a workstation using C#?
Use [`WTSGetActiveConsoleSessionId()`](http://msdn.microsoft.com/en-us/library/aa383835%28VS.85%29.aspx) to determine whether anybody is logged on locally. Use [`WTSEnumerateSessions()`](http://msdn.microsoft.com/en-us/library/aa383833.aspx) to determine if there is any session at all (including remote terminal services sessions).
Another option, if you don't want to deal with the P/Invokes: use [Cassia](https://github.com/danports/cassia). ``` using Cassia; public static bool IsSomeoneLoggedOn(string server) { foreach (ITerminalServicesSession session in new TerminalServicesManager().GetSessions(server)) { if (!string.IsNullOrEmpty(session.UserName)) { return true; } } return false; } ```
Check if no user is currently logged on to Windows
[ "", "c#", ".net", "windows-services", "" ]
Is there a way to search for the existence of a given WCF service in any of the computer of a local Network? For example, I am looking for the Math/Add2Numbers service and I want to know which machines on the LAN provide it, is there any way to do that?
Here is a super simple discovery example. It does not use a config file, it is all c# code, but you can probably port the concepts to a config file. share this interface between host and client program (copy to each program for now) ``` [ServiceContract] public interface IWcfPingTest { [OperationContract] string Ping(); } ``` put this code in the host program ``` public class WcfPingTest : IWcfPingTest { public const string magicString = "djeut73bch58sb4"; // this is random, just to see if you get the right result public string Ping() {return magicString;} } public void WcfTestHost_Open() { string hostname = System.Environment.MachineName; var baseAddress = new UriBuilder("http", hostname, 7400, "WcfPing"); var h = new ServiceHost(typeof(WcfPingTest), baseAddress.Uri); // enable processing of discovery messages. use UdpDiscoveryEndpoint to enable listening. use EndpointDiscoveryBehavior for fine control. h.Description.Behaviors.Add(new ServiceDiscoveryBehavior()); h.AddServiceEndpoint(new UdpDiscoveryEndpoint()); // enable wsdl, so you can use the service from WcfStorm, or other tools. var smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; h.Description.Behaviors.Add(smb); // create endpoint var binding = new BasicHttpBinding(BasicHttpSecurityMode.None); h.AddServiceEndpoint(typeof(IWcfPingTest) , binding, ""); h.Open(); Console.WriteLine("host open"); } ``` put this code in the client program ``` private IWcfPingTest channel; public Uri WcfTestClient_DiscoverChannel() { var dc = new DiscoveryClient(new UdpDiscoveryEndpoint()); FindCriteria fc = new FindCriteria(typeof(IWcfPingTest)); fc.Duration = TimeSpan.FromSeconds(5); FindResponse fr = dc.Find(fc); foreach(EndpointDiscoveryMetadata edm in fr.Endpoints) { Console.WriteLine("uri found = " + edm.Address.Uri.ToString()); } // here is the really nasty part // i am just returning the first channel, but it may not work. // you have to do some logic to decide which uri to use from the discovered uris // for example, you may discover "127.0.0.1", but that one is obviously useless. // also, catch exceptions when no endpoints are found and try again. return fr.Endpoints[0].Address.Uri; } public void WcfTestClient_SetupChannel() { var binding = new BasicHttpBinding(BasicHttpSecurityMode.None); var factory = new ChannelFactory<IWcfPingTest>(binding); var uri = WcfTestClient_DiscoverChannel(); Console.WriteLine("creating channel to " + uri.ToString()); EndpointAddress ea = new EndpointAddress(uri); channel = factory.CreateChannel(ea); Console.WriteLine("channel created"); //Console.WriteLine("pinging host"); //string result = channel.Ping(); //Console.WriteLine("ping result = " + result); } public void WcfTestClient_Ping() { Console.WriteLine("pinging host"); string result = channel.Ping(); Console.WriteLine("ping result = " + result); } ``` on the host, simply call the WcfTestHost\_Open() function, then sleep forever or something. on the client, run these functions. It takes a little while for a host to open, so there are several delays here. ``` System.Threading.Thread.Sleep(8000); this.server.WcfTestClient_SetupChannel(); System.Threading.Thread.Sleep(2000); this.server.WcfTestClient_Ping(); ``` host output should look like ``` host open ``` client output should look like ``` uri found = http://wilkesvmdev:7400/WcfPing creating channel to http://wilkesvmdev:7400/WcfPing channel created pinging host ping result = djeut73bch58sb4 ``` this is seriously the minimum I could come up with for a discovery example. This stuff gets pretty complex fast.
What you need is WS-Discovery, but unfortunately, this is not included as part of the ws-\* extensions in WCF. There are some homegrown implementations of it. Here's a [google search](http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=P7g&q=wcf++ws-discovery&btnG=Search) for that. Otherwise, you can implement an enterprise UDDI or registry solution by a third party vendor (like [IBM](http://www.ibm.com/developerworks/websphere/library/techarticles/0609_mckee/0609_mckee.html) or [Microsoft](http://www.microsoft.com/windowsserver2003/technologies/idm/uddi/default.mspx)).
Search for WCF service in a LAN?
[ "", "c#", ".net", "wcf", "" ]
I have an SPListItemCollection. I basically want to get one of the items (randomly) in the collection and return it. My method has a return type that expects an SPListItemCollection, so I dont mind having an SPListItemCollection that has just the one item in it and returning that. Im not sure how to return an SPListItemCollection with this one item in it how can i do this?
On re-reading, it looks like you want to reduce the SPListItemCollection to a single item, but here's a way to get a SPListItemCollection with a single random item directly from the list: ``` private SPListItemCollection GetRandomItem(SPList list) { Random random = new Random(); int index = random.Next(0, list.ItemCount - 1); SPQuery query = new SPQuery(); query.Query = string.Format("<Where><Eq><FieldRef Name=\"ID\" /><Value Type=\"Integer\">{0}</Value></Eq></Where>", index); return list.GetItems(query); } ```
I think you have to add the item to the collection you want to return, then you have to call update() ``` SPListItemCollection collListItemsDest; //collection to return SPListItem oListDest = collListItemsDest.Add(); //add item to collection oListDest["Field1_Name"] = "RANDOM"; //random item you retrieved oListDest.Update(); ``` Then you can return collListItemsDest [MSDN - SPListItemCollection add()](http://msdn.microsoft.com/en-us/library/ms470423.aspx#) But really, you should think about returning just the item, not the collection. There is no point to return a collection if you always know its only going to have one item
return an SPListItemCollection with one random item
[ "", "c#", "sharepoint", "" ]
Can any one explain the difference between factory and strategy patterns? For me both are looking same other than an extra factory class (which create an object of product in factory patterns)
A factory pattern is a creational pattern. A strategy pattern is an operational pattern. Put another way, a factory pattern is used to create objects of a specific type. A strategy pattern is use to perform an operation (or set of operations) in a particular manner. In the classic example, a factory might create different types of Animals: Dog, Cat, Tiger, while a strategy pattern would perform particular actions, for example, Move; using Run, Walk, or Lope strategies. In fact the two can be used together. For example, you may have a factory that creates your business objects. It may use different strategies based on the persistence medium. If your data is stored locally in XML it would use one strategy. If the data were remote in a different database, it would use another.
The strategy pattern allows you to polymorphically change behavior of a class. The factory pattern allows you to encapsulate object creation. Gary makes a great point. If you are using the principle of coding to abstractions rather than "concretions" then a lot of the patterns start looking like variations on a theme.
What is the difference between Factory and Strategy patterns?
[ "", "java", "design-patterns", "factory-pattern", "strategy-pattern", "abstract-factory", "" ]
Which do you think is better as a programmer, and as a end user, and why?
Applets are *usually* slow, horrible, inappropriate in a browser, can't be printed, make everything else feel slow... I just hate when I go somewhere and an applet starts loading. Applets are a big failure and are fortunately dying slowly. Web Start is nice for applications that are made to be desktop applications and solves the deployment issue (centralized deployment). Applications are downloaded to be executed in a JVM outside the browser. They can be linked to the desktop, started offline... Last but not least, **you** choose to use a Web Start application or not. Applets : 0 - Web Start : **1** EDIT: I made the first sentence a little bit less generic. There are successful implementation of applets, no doubts about it. I just have a negative global perception because I've seen more wrong applets or usages than good ones.
From my experience, customers don't want their programs to be running inside a browser. But, from Java6 update 10, applets can be running outside of the browser in a separate process. This appealing feature might fill the gap between the applet and JWS.
Which do you prefer: Java Web Start, or Java Applets?
[ "", "java", "applet", "java-web-start", "" ]
Yet again I have some questions regarding polygon algorithms. I'll try to explain my problem: I am using a subset of a third party library called Geometric Tools(GT) to perform boolean operations on my polygons. To accomplish this I have to convert my internal polygon format to the format GT uses. Our internal polygon format consists of a vertex array, while the GT polygon consists of an indexed vertex array where each edge is represented by a pair of indices. Example of a square for clarification: Internal format: ``` vertices[0] = Vertex2D(1,0) -> start vertices[1] = Vertex2D(1,1) vertices[2] = Vertex2D(0,1) vertices[3] = Vertex2D(0,0) vertices[4] = Vertex2D(1,0) -> end ``` External format: ``` vertices[0] = Vertex2D(1,0) vertices[1] = Vertex2D(1,1) vertices[2] = Vertex2D(0,1) vertices[3] = Vertex2D(0,0) edges[0] = std::pair<int,int>(0,1) edges[1] = std::pair<int,int>(1,2) edges[2] = std::pair<int,int>(2,3) edges[3] = std::pair<int,int>(3,0) //There is also a BSP tree of the polygon which I don't care to depict here. ``` Now, I wrote an algorithm that works in most cases, but crashes and burns when two edges share the same starting vertex. Let me start by explaining how my current algorithm works. Make a std::map where the key is an integer representing the vertex index. The value represents where in the edge array there is an edge with the key-index as starting index. Mockup example: ``` std::vector< std::pair< int, int > > edge_array; edge_array.push_back( std::pair< int, int >( 0, 1 ) ); edge_array.push_back( std::pair< int, int >( 2, 3 ) ); edge_array.push_back( std::pair< int, int >( 1, 2 ) ); edge_array.push_back( std::pair< int, int >( 3, 0 ) ); std::map< int, int > edge_starts; for ( int i = 0 ; i < edge_array.size(); ++i ) { edge_starts[ edge_array[i].first ] = i; } ``` To jump from correct edge to correct edge i can now just do the following inside a while loop: ``` while ( current_placed_index = first_index_in_polygon ) { int index_to_next_edge_to_be_traversed = edge_starts[ current_edge.second ]; } ``` Inside this loop there is done some optimization, and vertex indices are added to an array. Each time a polygon is closed i find the first untraversed edge and start making another polygon. I keep on doing this until there are no more untraversed edges in the GTPolygon. So each GTPolygon can result in several Polygon(internal) objects. The flaw in this algorithm is evident when there are two edges sharing the same vertex as a starting vertex. Example: ``` <1,2> <1,3> <1,5> ``` When traversing my edges, how will i know which of these edges belongs to the polygon I am currently traversing? I could try traversing the edges BACKWARDS when such a duplicate situation occurs. The problem then would be the possibility of the traversation going back and forth infinitely if another duplicate is found while reversing. My question is, how can I solve this? Is it solvable at all? Can I use the BSP tree to solve this in some way? The amount of corner cases is a bit daunting. Any help is greatly appreciated as 5 months of work depends on this working. **Edit:** To clarify: I want to convert from the indexed representation of a polygon that Geometry Tools works with to our internal polygon format, which is just a series of connected vertices in a list.
You are effectively trying to find all [cycles](http://en.wikipedia.org/wiki/Cycle_(graph_theory)) in an [undirected](http://www.brpreiss.com/books/opus4/html/page529.html) [graph](http://en.wikipedia.org/wiki/Graph_(mathematics)) where each cycle represents the edges of a unique polygon. [This paper](http://www.me.utexas.edu/~bard/IP/Handouts/cycles.pdf) proposes a [depth-first search (DFS)](http://en.wikipedia.org/wiki/Depth-first_search) solution.
Haha, ok guys. It seems like all the hubub has been for nothing. I found that Geometry Tools has it's own class to deal with problems like these. Example found [here](http://www.geometrictools.com/SampleFoundation/MinimalCycleBasis/MinimalCycleBasis.html).
Converting indexed polygons to unindexed ones. Several problems have cropped up
[ "", "c++", "algorithm", "geometry", "polygon", "" ]
I'm working on .NET windows application that should do a simple searching function. The application searches for some cards by their serial numbers on a SQLServer database, those serial numbers are imported in a text file and I simply open a StreamReader on the file and start reading lines-as each line contains only one serial. After retrieving the data, I then display them all on a DataGridView. Those serials on the file are not in a certain order (i.e. i can't do `Select * from table where serial between( min and max)`); they're totally not related. So without further ado, here's what I've done: ``` DataTable table = new DataTable() StreamReader stream= new StreamReader(fileName); while (!stream.EndOfStream) { string serial = stream.ReadLine(); SqlDataReader reader= GetCardBySerial(serial); table.Load(reader); reader.Close(); } public SqlDataReader GetCardBySerial(string serialNo) { SqlConnection cnn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("Cards_GetCardBySerial", cnn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@serialNo", SqlDbType.NVarChar).Value = serialNo; cnn.Open(); return cmd.ExecuteReader(CommandBehavior.CloseConnection); } ``` Though this works, but it's very slow to me. What should be done instead to make the search faster?
I would think that the quickest way would be to bulk insert the serials into a table on SQL Server. Then do your search on ALL the serials with a single SQL statement by joining the search table into the Cards table on Serial number.
It looks like you're opening a new connection for each query. You would be best off to create a single connection then reuse it for each query. ``` DataTable table = new DataTable() SqlConnection cnn = new SqlConnection(connectionString); StreamReader stream = new StreamReader(fileName); while (!stream.EndOfStream) { string serial = stream.ReadLine(); SqlDataReader reader = GetCardBySerial(serial, cnn); table.Load(reader); reader.Close(); } cnn.Close(); public SqlDataReader GetCardBySerial(string serialNo, SqlConnection cnn) { SqlCommand cmd = new SqlCommand("Cards_GetCardBySerial", cnn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@serialNo", SqlDbType.NVarChar).Value = serialNo; return cmd.ExecuteReader(); } ```
Select elements from a SQL Server based on a list on a text file faster
[ "", "c#", "sql-server", "" ]
A well known problem with Java Applets in webpages is that browsers ignore the z-index of the applet tag vs. other components in the page. No matter how you position and z-index elements in the page, applets will draw themselves on top of everything. There is a workaround, known as the iframe shim, as described here: <http://www.oratransplant.nl/2007/10/26/using-iframe-shim-to-partly-cover-a-java-applet/>. However, this workaround does not work in Safari 3 or 4 in Windows (assuming the same for Mac). Does anyone know a way to make it work in Safari? Does anyone have ideas about how to pressure Sun to fix the underlying problem so we can avoid clumsy shims? Here is a bug report on the issue, <https://bugs.java.com/bugdatabase/view_bug?bug_id=6646289>, notice that it has been open for a year, however other bug reports go back many many years. This is so frustrating, don't Sun understand that this is the very sort of thing that has marginalized Java as a way of doing cool stuff in the browser? I love you Java, but you are not helping your situation...
Actually problem is not related to z-index at all. It's caused by "windowed" drawing model of Netscape Plugin API (NPAPI). You can't do anything about it (except the shim). Plugin author has to [rewrite it using windowless API](https://developer.mozilla.org/en/Gecko_Plugin_API_Reference:Plug-in_Basics#Windowed%20and%20Windowless%20Plug-ins).
There is a tricky solution for the problem. It's not necessary to have the code inside an `iframe`. We can have a dummy `iframe` just as a layer above the applet. And then an absolute div with the text can easily placed above that `iframe`. working example ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Applet z index issue</title> <style> .applet {width:400px; margin:0 auto; text-align:center; border:1px solid #000; left:40%; position:absolute } .iframe {width:400px; background:#fff; position:absolute; border:1px solid #f00; position:absolute; left:45%; top:20px; z-index:9; height:201px;} .message { width:250px; border:1px solid #000; background:#fff; height:150px; color:#fff; text-align:center; z-index:99; background:#555; float:left; position:absolute; left:45%; top:20px} </style> </head> <body> <div class="message">Message</div> <div class="iframe"><iframe style="width:500px; height:205px; background:none; border:none"> </iframe></div> <div class="applet"> <applet code="Bubbles.class" width="400" height="350"> Java applet that draws animated bubbles. </applet> </div> </body> </html> ```
Java Applet z-index on Safari and beyond
[ "", "java", "html", "applet", "overlay", "z-index", "" ]
I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. For example: ``` "This is a Test" -> "thisisatest" "A235th@#$&( er Ra{}|?>ndom" -> "atherrandom" ``` I have a simple function to do this: ``` import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) ``` But I cannot help thinking there is a more efficient, or more elegant, way. Thanks! --- **Edit:** Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.
Another solution (not that pythonic, but very fast) is to use string.translate - though note that this will not work for unicode. It's also worth noting that you can speed up [Dana's code](https://stackoverflow.com/questions/638893/what-is-the-most-efficient-way-in-python-to-convert-a-string-to-all-lowercase-str/638920#638920) by moving the characters into a set (which looks up by hash, rather than performing a linear search each time). Here are the timings I get for various of the solutions given: ``` import string, re, timeit # Precomputed values (for str_join_set and translate) letter_set = frozenset(string.ascii_lowercase + string.ascii_uppercase) tab = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase * 2) deletions = ''.join(ch for ch in map(chr,range(256)) if ch not in letter_set) s="A235th@#$&( er Ra{}|?>ndom" # From unwind's filter approach def test_filter(s): return filter(lambda x: x in string.ascii_lowercase, s.lower()) # using set instead (and contains) def test_filter_set(s): return filter(letter_set.__contains__, s).lower() # Tomalak's solution def test_regex(s): return re.sub('[^a-z]', '', s.lower()) # Dana's def test_str_join(s): return ''.join(c for c in s.lower() if c in string.ascii_lowercase) # Modified to use a set. def test_str_join_set(s): return ''.join(c for c in s.lower() if c in letter_set) # Translate approach. def test_translate(s): return string.translate(s, tab, deletions) for test in sorted(globals()): if test.startswith("test_"): assert globals()[test](s)=='atherrandom' print "%30s : %s" % (test, timeit.Timer("f(s)", "from __main__ import %s as f, s" % test).timeit(200000)) ``` This gives me: ``` test_filter : 2.57138351271 test_filter_set : 0.981806765698 test_regex : 3.10069885233 test_str_join : 2.87172979743 test_str_join_set : 2.43197956381 test_translate : 0.335367566218 ``` [Edit] Updated with filter solutions as well. (Note that using `set.__contains__` makes a big difference here, as it avoids making an extra function call for the lambda.
``` >>> filter(str.isalpha, "This is a Test").lower() 'thisisatest' >>> filter(str.isalpha, "A235th@#$&( er Ra{}|?>ndom").lower() 'atherrandom' ```
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
[ "", "python", "string", "" ]
I have a number of user controls. The user controls can be used on different pages. The behavior of the user controls are different based on what page they are used on. How can I set a parameter on the host page that ALL user controls have access to?
Your description "The behavior of the user controls are different based on what page they are used on" indicates a design flaw. The Control Model in ASP.NET is designed around [encapsulation](http://en.wikipedia.org/wiki/Encapsulation_(computer_science)) and [OOP](http://en.wikipedia.org/wiki/Object-oriented_programming), which means a control should be agnostic regarding its surrounding context. You should rethink your design with that in mind. That having been said, it is entirely possible (**warning - bad practice**) to set a public property on your page that the controls can read: ``` class MyPage : Page { public string MyProperty; } class MyUserControl : UserControl { void Page_Load(object sender, EventArgs e) { ((MyPage)this.Page).MyProperty //casts Page as the specific page } } ```
I agree with Rex, I am suspicious of the requirement. That said, I find it cleaner to put it on the HttpContext.Current.Items collection. The page would set the value preferably on its OnInit, using a nice class wrapping around it, to get the info. If you want you can have the wrapper actually read the current Url, or check the type of the page (which is the usually the current Handler HttpContext.Current.Handler / don't recall if ajax affects that), which can get you a solution that doesn't needs the page to set anything at all.
Host Page - User control communication ASP.NET
[ "", "c#", "asp.net", "user-controls", "" ]
I'm trying to send a COM object over a MSMQ message in C++. This is my object : ``` class ATL_NO_VTABLE CAnalisis : public CComObjectRootEx, public CComCoClass, public ISupportErrorInfo, public IDispatchImpl, public IPersistStreamInit { private: typedef struct { DOUBLE size; float color; float light; BSTR imgName; BSTR uname; } Image; Image img; STDMETHOD(Load)(IStream *pStm); STDMETHOD(Save)(IStream *pStm, BOOL fClearDirty); ``` Everything goes fine and I can get the whole object but the BSTR types. Floats and integers are properly sent and received. But the BSTR types dont work. I'm trying to send strings and can't find the way. I did try with VARIANT instead and the result was wrong too. Somehow, it looks like the strings are not serialized. These are some of the get and set functions for my ATL component: This one works fine: ``` STDMETHODIMP CAnalisis::getLight(FLOAT* light) { *light=img.light; return S_OK; } STDMETHODIMP CAnalisis::setLight(FLOAT light) { img.light=light; return S_OK; } ``` This one doesn't : ``` STDMETHODIMP CAnalisis::getImgName(BSTR* imgName) { *imgName = img.imgName; return S_OK; } STDMETHODIMP CAnalisis::setImgName(BSTR imgName) { img.imgName=imgName; return S_OK; } ``` and this is the way I create the MSMQ message and fill the values in my producer : ``` // For these ActiveX components we need only smart interface pointer IMSMQQueueInfosPtr pQueueInfos; IMSMQQueueInfoPtr pQueueInfo; IMSMQQueuePtr pQueue; IUnknownPtr pIUnknown; // Instanciate the follwing ActiveX components IMSMQQueryPtr pQuery(__uuidof(MSMQQuery)); IMSMQMessagePtr pMessage(__uuidof(MSMQMessage)); IAnalisisPtr pAnalisis(__uuidof(Analisis)); WCHAR * imagen; imagen = L"imagen1.jpg"; pAnalisis->setImgName(imagen); (...) pAnalisis->setFruitSize(20.00); (...) pQueueInfo = new IMSMQQueueInfoPtr( __uuidof(MSMQQueueInfo) ); pQueueInfo->PathName = "MYCOMPUTER\\private$\\myprivatequeue"; pQueue = pQueueInfo->Open(MQ_SEND_ACCESS, MQ_DENY_NONE); pMessage->Body = static_cast(pAnalisis); pMessage->Send(pQueue); ``` here is the serialization code ``` STDMETHODIMP CAnalisis::Load( IStream *pStm ) { ULONG cb; HRESULT hr; if (NULL==pStm) return ResultFromScode(E_POINTER); // Read an object from the stream. // hr=pStm->Read(&img, sizeof(Image), &cb); if (FAILED(hr)) return hr; if (sizeof(Image) != cb) return E_FAIL; return NOERROR; } STDMETHODIMP CAnalisis::Save( IStream *pStm, BOOL bClearDirty ) { ULONG cb; HRESULT hr; if (NULL==pStm) return ResultFromScode(E_POINTER); // Write an object into the stream. hr=pStm->Write(&img, (ULONG)sizeof(Image), &cb); if (FAILED(hr) || sizeof(Image)!=cb) return ResultFromScode(STG_E_WRITEFAULT); return NOERROR; } ``` If I get the BSTR value in the producer (before serialization), `pAnalisis-getImgName()`, it works fine. In contrast, when I try to get it in the consumer, after reading the message from the queue, it doesn't return anything. The other values, such as the size, are returned with no trouble. does anyone know how to send a BSTR value inside a COM object through MSMQ ? I've tried to find some similar examples but totally in vain. the thing is that i'm getting either an very weird value with weird characters or an Hexadecimal value, depending on how I extract the value .. the thing is that I do never get the right value. and I was wondering, however... are we sure it is possible to send a BSTR value ? if i'm not wrong, it is a pointer to a string... I'm running two different processes (i.e. producer and consumer), so they use different memory blocks, and they are meant to be run on different machines so... I was trying to send this info as a VARIANT type.. but also got lost. However, this seems a bit less far-fetched than sending a BSTR. ANY IDEAS ON THIS?
The problem is that the serialization of Image class treats it as a contiguous block of memory. Since BSTR is really a pointer only the pointer value is serialized and the BSTR payload is lost. Instead you should write all fields except BSTRs as binary and process BSTRs separately. For example, you can write BSTR length as integer first, then its payload. When reading you will read length first, call SysAllocStringLen() to allocate a buffer, then read the payload. Leave serialization of simple fields as it is (the IPersistStreamInit::Save() ): ``` pStm->Write(&(img.color), (ULONG)sizeof(float), &cb); ``` For BSTRs do this: ``` int length = SysStringLen( img.uname ); pStm->Write(&length, (ULONG)sizeof(int), &cb); if( length > 0 ) { pStm->Write( img.uname, (ULONG)(length * sizeof(WCHAR) ), &cb); } ``` Similar for reading (the IPersistStreamInit::Load()): ``` int length; pStm->Read(&length, (ULONG)sizeof(int), &cb); if( length > 0 ) { img.uname = SysAllocStringLen( 0, length ); pStm->Read( img.uname, (ULONG)( length * sizeof( WCHAR) ), &cb); } else { img.uname = 0; } ``` Note that this code writes/reads string length and then writes/reads the payload that consists of Unicode characters. Unicode characters occupy more than one bytes each - hence the multiplication in IStream Read/Write methods call.
If you simply pass a WCHAR -- the length information is lost. The BSTR is malformed and this is probably causing you all the grief. You need to use `SysAllocString` to use it across components. See [MSDN](http://msdn.microsoft.com/en-us/library/ms221069.aspx) -- the **Remarks** section. Try: ``` BSTR imagen = SysAllocString(L"imagen1.jpg"); ```
send a COM object with a BSTR value type in a MSMQ message
[ "", "c++", "com", "msmq", "send", "bstr", "" ]
How do I allow the STL implementation to pick up my custom types? On MSVC, there is a class `std::tr1::hash`, which I can partially specialize by using ``` namespace std { namespace tr1 { template <> struct hash<MyType> { ... }; } } ``` but is this the recommended way? Moreover, does this work with GCC's implementation as well? For `boost::hash`, it's enough to provide a free function `size_t hash_value (const MyType&)`, is there something similar for the TR1 implementation?
Yes, this will also work for GCC. I'm using it in a bigger project and it works without problems. You could also provide your own custom hashing class for the TR1 containers, but it is specified that std::tr1::hash<> is the default hashing class. Specializing it for custom types seems like the natural way to extend the standard hashing functionality.
I was trying to work out the exact syntax for doing this with the unordered associative containers (also using GCC, as the OP was asking) and hit this question. Unfortunately it didn't go down to the level of detail I wanted. By looking through the gcc headers at how they have implemented the standard hash functions I got it working. In view of the dearth of examples (at least at time of writing) on the web I thought this would be as good a place as any to post my own example (which I can confirm works with GCC): ``` namespace std { namespace tr1 { template <> struct hash<MyType> : public unary_function<MyType, size_t> { size_t operator()(const MyType& v) const { return /* my hash algorithm */; } }; }} ``` (notice there *are* two namespaces here - that's just my convention for collapsing nested namespaces)
How to extend std::tr1::hash for custom types?
[ "", "c++", "tr1", "" ]
I am attempting to create a fixed step loop in my program, but for some reason I just can't seem to get it to work properly. Basically what I need is a loop that does: ``` while(!over) { Update(elapsedtime); Draw(elapsedtime); } ``` or something similar, with a . I've tried using Thread.Sleep but I'm not so sure it gave me a real fixed step loop, and when I tried to implement the solution on [this](http://gafferongames.com/game-physics/fix-your-timestep/) website I had problems due to the fact that I couldn't see a way to save the state of the objects affected by the loop. This forced me to exclude that part, which led to slowdown when there were many objects in the loop. How can I get a fixed step loop without constantly having to save the state of every object in the loop?
If you are working on a game engine, a Timer will probably not work well. Timers do not have enough accuracy to handle a fixed step loop and keep it regular. You'll need to implement this using a high precision timer. In this case, you'll want to use [the Stopwatch class.](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) This will allow you to have enough precision to track your elapsedTime accurately. You'll just need to keep track of how frequently you want to update (in Ticks), then use a stopwatch to measure the time it takes for each of your updates. After that, you can potentially use a Sleep() call to block, but realize that sleep will only have a precision of 14-15 ms on most systems, even if you only sleep for 0 or 1 ms. This may slow down your loop too much, so you may need to implement a spin lock or similar (while (waiting) { do something }). Sleep() is nice because it saves CPU if you can, the spin lock will eat CPU cycles while you're waiting, but gives you more precision.
Are you asking for a loop which will run basically every n ticks? This sounds like a [Timer](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx). There are a couple of timer's in the BCL. A [timer for servers](http://msdn.microsoft.com/en-us/library/system.timers.aspx) or one [for Window Forms](http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx). You can use them along these lines. The following is psuedo code and meant to show generally how this is done. In other words it probably won't compile if you just copy and paste. ``` public class RepeatingTask { public MyObjectState _objectState; public RepeatingTask(Timespan interval) { Timer timer=new Timer(Timer_Tick); //This assumes we pass a delegate. Each timer is different. Refer to MSDN for proper usage timer.Interval=interval; timer.Start(); } private DateTime _lastFire; private void Timer_Tick() { DateTime curTime=DateTime.Now(); DateTime timeSinceLastFire = curTime-lastFireTime; _lastFire=DateTime.Now(); //Store when we last fired... accumulatedtime+=timeSinceLastFire while(accumulatedtime>=physicsInterval) { Update(physicsInterval); accumulated-=physicInterval; } } } ``` You can also use a closure to wrap up your state of the method which the timer is defined in. # Edit I read the article and I understand the issue; however, you could still use a timer, but you need to as he indicates set your function up to call the engines for each interval you set your physics engine to. Are you using WPF they have some events I believe which get fired at steady rates for doign animations. # Edit I updated my code sample to show you my interpretation but basically what you do is define an interval for your physics engine, and then what you need to do on each pass through your "Loop / Timer whatever" is determine how much real time passed since the last iteration. You then store that delta in an Accumalator, which you will use to count down until you've called your physics engine for all the intervals that you missed since you last called. What I struggle with is if using a timer here is better, then having a dedidicated thread sleeping, or some other implementation.
How to implement a fixed-step loop?
[ "", "c#", "loops", "fixed", "" ]
I am writing a python platform for the simulation of distributed sensor swarms. The idea being that the end user can write a custom Node consisting of the SensorNode behaviour (communication, logging, etc) as well as implementing a number of different sensors. The example below briefly demonstrates the concept. ``` #prewritten class Sensor(object): def __init__(self): print "Hello from Sensor" #... #prewritten class PositionSensor(Sensor): def __init__(self): print "Hello from Position" Sensor.__init__(self) #... #prewritten class BearingSensor(Sensor): def __init__(self): print "Hello from Bearing" Sensor.__init__(self) #... #prewritten class SensorNode(object): def __init__(self): print "Hello from SensorNode" #... #USER WRITTEN class MySensorNode(SensorNode,BearingSensor,PositionSensor): def CustomMethod(self): LogData={'Position':position(), 'Bearing':bearing()} #position() from PositionSensor, bearing() from BearingSensor Log(LogData) #Log() from SensorNode ``` ## NEW EDIT: Firstly an overview of what I am trying to achieve: I am writing a simulator to simulate swarm intelligence algorithms with particular focus on mobile sensor networks. These networks consist of many small robots communicating individual sensor data to build a complex sensory map of the environment. The underlying goal of this project is to develop a simulation platform that provides abstracted interfaces to sensors such that the same user-implemented functionality can be directly ported to a robotic swarm running embedded linux. As robotic implementation is the goal, I need to design such that the software node behaves the same, and only has access to information that an physical node would have. As part of the simulation engine, I will be providing a set of classes modelling different types of sensors and different types of sensor node. I wish to abstract all this complexity away from the user such that all the user must do is define which sensors are present on the node, and what type of sensor node (mobile, fixed position) is being implemented. My initial thinking was that every sensor would provide a read() method which would return the relevant values, however having read the responses to the question, I see that perhaps more descriptive method names would be beneficial (.distance(), .position(), .bearing(), etc). I initially wanted use separate classes for the sensors (with common ancestors) so that a more technical user can easily extend one of the existing classes to create a new sensor if they wish. For example: ``` Sensor | DistanceSensor(designed for 360 degree scan range) | | | IR Sensor Ultrasonic SickLaser (narrow) (wider) (very wide) ``` The reason I was initially thinking of Multiple Inheritance (although it semi-breaks the IS-A relationship of inheritance) was due to the underlying principle behind the simulation system. Let me explain: The user-implemented MySensorNode should not have direct access to its position within the environment (akin to a robot, the access is indirect through a sensor interface), similarly, the sensors should not know where they are. However, this lack of direct knowledge poses a problem, as the return values of the sensors are all dependent on their position and orientation within the environment (which needs to be simulated to return the correct values). SensorNode, as a class implemented within the simulation libraries, is responsible for drawing the MySensorNode within the pygame environment - thus, it is the only class that should have direct access to the position and orientation of the sensor node within the environment. SensorNode is also responsible for translation and rotation within the environment, however this translation and rotation is a side effect of motor actuation. What I mean by this is that robots cannot directly alter their position within the world, all they can do is provide power to motors, and movement within the world is a side-effect of the motors interaction with the environment. I need to model this accurately within the simulation. So, to move, the user-implemented functionality may use: ``` motors(50,50) ``` This call will, as a side-effect, alter the position of the node within the world. If SensorNode was implemented using composition, SensorNode.motors(...) would not be able to directly alter instance variables (such as position), nor would MySensorNode.draw() be resolved to SensorNode.draw(), so SensorNode imo should be implemented using inheritance. In terms of the sensors, the benefit of composition for a problem like this is obvious, MySensorNode is composed of a number of sensors - enough said. However the problem as I see it is that the Sensors need access to their position and orientation within the world, and if you use composition you will end up with a call like: ``` >>> PosSensor.position((123,456)) (123,456) ``` Then again - thinking, you could pass self to the sensor upon initialisation, eg: ``` PosSensor = PositionSensor(self) ``` then later ``` PosSensor.position() ``` however this PosSensor.position() would then need to access information local to the instance (passed as self during **init**()), so why call PosSensor at all when you can access the information locally? Also passing your instance to an object you are composed of just seems not quite right, crossing the boundaries of encapsulation and information hiding (even though python doesn't do much to support the idea of information hiding). If the solution was implemented using multiple inheritance, these problems would disappear: ``` class MySensorNode(SensorNode,PositionSensor,BearingSensor): def Think(): while bearing()>0: # bearing() is provided by BearingSensor and in the simulator # will simply access local variables provided by SensorNode # to return the bearing. In robotic implementation, the # bearing() method will instead access C routines to read # the actual bearing from a compass sensor motors(100,-100) # spin on the spot, will as a side-effect alter the return # value of bearing() (Ox,Oy)=position() #provided by PositionSensor while True: (Cx,Cy)=position() if Cx>=Ox+100: break else: motors(100,100) #full speed ahead!will alter the return value of position() ``` --- Hopefully this edit has clarified some things, if you have any questions I'm more than happy to try and clarify them ## OLD THINGS: When an object of type MySensorNode is constructed, all constructors from the superclasses need to be called. I do not want to complicate the user with having to write a custom constructor for MySensorNode which calls the constructor from each superclass. Ideally, what I would like to happen is: ``` mSN = MySensorNode() # at this point, the __init__() method is searched for # and SensorNode.__init__() is called given the order # of inheritance in MySensorNode.__mro__ # Somehow, I would also like to call all the other constructors # that were not executed (ie BearingSensor and PositionSensor) ``` Any insight or general comments would be appreciated, Cheers :) OLD EDIT: Doing something like: ``` #prewritten class SensorNode(object): def __init__(self): print "Hello from SensorNode" for clss in type(self).__mro__: if clss!=SensorNode and clss!=type(self): clss.__init__(self) ``` This works, as self is an instance of MySensorNode. However this solution is messy. ---
The sensor architecture can be solved by using composition if you want to stick to your original map-of-data design. You seem to be new to Python so I'll try to keep idioms to a minimum. ``` class IRSensor: def read(self): return {'ir_amplitude': 12} class UltrasonicSensor: def read(self): return {'ultrasonic_amplitude': 63} class SickLaserSensor: def read(self): return {'laser_amplitude': 55} class CompositeSensor: """Wrap multiple component sensors, coalesce the results, and return the composite readout. """ component_sensors = [] def __init__(self, component_sensors=None): component_sensors = component_sensors or self.component_sensors self.sensors = [cls() for cls in component_sensors] def read(self): measurements = {} for sensor in self.sensors: measurements.update(sensor.read()) return measurements class MyCompositeSensor(CompositeSensor): component_sensors = [UltrasonicSensor, IRSensor] composite_sensor = MyCompositeSensor() measurement_map = composite_sensor.read() assert measurement_map['ultrasonic_amplitude'] == 63 assert measurement_map['ir_amplitude'] == 12 ``` The architectural problem you're describing with the actuators is solved by using mixins and **proxying** (via `__getattr__`) rather than inheritance. (Proxying can be a nice alternative to inheritance because objects to proxy to can be bound/unbound at runtime. Also, you don't have to worry about handling all initialization in a single constructor using this technique.) ``` class MovementActuator: def __init__(self, x=0, y=0): self.x, self.y = (x, y) def move(self, x, y): print 'Moving to', x, y self.x, self.y = (x, y) def get_position(self): return (self.x, self.y) class CommunicationActuator: def communicate(self): return 'Hey you out there!' class CompositeActuator: component_actuators = [] def __init__(self, component_actuators=None): component_actuators = component_actuators \ or self.component_actuators self.actuators = [cls() for cls in component_actuators] def __getattr__(self, attr_name): """Look for value in component sensors.""" for actuator in self.actuators: if hasattr(actuator, attr_name): return getattr(actuator, attr_name) raise AttributeError(attr_name) class MyCompositeActuator(CompositeActuator): component_actuators = [MovementActuator, CommunicationActuator] composite_actuator = MyCompositeActuator() assert composite_actuator.get_position() == (0, 0) assert composite_actuator.communicate() == 'Hey you out there!' ``` And finally, you can throw it all together with a simple node declaration: ``` from sensors import * from actuators import * class AbstractNode: sensors = [] # Set of classes. actuators = [] # Set of classes. def __init__(self): self.composite_sensor = CompositeSensor(self.sensors) self.composite_actuator = CompositeActuator(self.actuators) class MyNode(AbstractNode): sensors = [UltrasonicSensor, SickLaserSensor] actuators = [MovementActuator, CommunicationActuator] def think(self): measurement_map = self.composite_sensor.read() while self.composite_actuator.get_position()[1] >= 0: self.composite_actuator.move(100, -100) my_node = MyNode() my_node.think() ``` That should give you an idea of the alternatives to the rigid type system. Note that you don't have to rely on the type hierarchy at all -- just implement to a (potentially implicit) common interface. # LESS OLD: After reading the question more carefully, I see that what you have is a classic example of [diamond inheritance](http://en.wikipedia.org/wiki/Diamond_problem), which is the [evil that makes people flee](http://code.activestate.com/recipes/146462/) towards single inheritance. You probably don't want this to begin with, since class hierarchy means squat in Python. What you want to do is make a `SensorInterface` (minimum requirements for a sensor) and have a bunch of "mixin" classes that have totally independent functionality that can be invoked through methods of various names. In your sensor framework you shouldn't say things like `isinstance(sensor, PositionSensor)` -- you should say things like "can this sensor geo-locate?" in the following form: ``` def get_position(sensor): try: return sensor.geolocate() except AttributeError: return None ``` This is the heart of duck-typing philosophy and [EAFP](http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Exceptions) (Easier to Ask for Forgiveness than Permission), both of which the Python language embraces. You should probably describe what methods these sensors will actually implement so we can describe how you can use mixin classes for your plugin architecture. # OLD: If they write the code in a module that gets put in a plugin package or what have you, you can magically instrument the classes for them when you import their plugin modules. Something along the lines of this snippet (untested): ``` import inspect import types from sensors import Sensor def is_class(obj): return type(obj) in (types.ClassType, types.TypeType) def instrumented_init(self, *args, **kwargs): Sensor.__init__(self, *args, **kwargs) for module in plugin_modules: # Get this from somewhere... classes = inspect.getmembers(module, predicate=is_class) for name, cls in classes: if hasattr(cls, '__init__'): # User specified own init, may be deriving from something else. continue if cls.__bases__ != tuple([Sensor]): continue # Class doesn't singly inherit from sensor. cls.__init__ = instrumented_init ``` You can [find the modules within a package](https://stackoverflow.com/questions/487971/is-there-a-standard-way-to-list-names-of-python-modules-in-a-package) with another function.
`super` calls the next class in the mro-list. This works even if you leave out the `__init__` form some class. ``` class A(object): def __init__(self): super(A,self).__init__() print "Hello from A!" class B(A): def __init__(self): super(B,self).__init__() print "Hello from B!" class C(A): def __init__(self): super(C,self).__init__() print "Hello from C!" class D(B,C): def __init__(self): super(D,self).__init__() print "Hello from D!" class E(B,C): pass ``` Example: ``` >>> x = D() Hello from A! Hello from C! Hello from B! Hello from D! >>> y = E() Hello from A! Hello from C! Hello from B! >>> ``` **Edit:** Rewrote the answer. (again)
Discussion of multiple inheritance vs Composition for a project (+other things)
[ "", "python", "constructor", "oop", "multiple-inheritance", "" ]
Does anyone know an easy way in Python to convert a string with HTML entity codes (e.g. `&lt;` `&amp;`) to a normal string (e.g. < &)? `cgi.escape()` will escape strings (poorly), but there is no `unescape()`.
[HTMLParser](https://docs.python.org/2.7/library/htmlparser.html) has the functionality in the standard library. It is, unfortunately, undocumented: (Python2 [Docs](https://docs.python.org/2.7/library/htmlparser.html)) ``` >>> import HTMLParser >>> h= HTMLParser.HTMLParser() >>> h.unescape('alpha &lt; &beta;') u'alpha < \u03b2' ``` (Python 3 [Docs](https://docs.python.org/3/library/html.parser.html)) ``` >>> import html.parser >>> h = html.parser.HTMLParser() >>> h.unescape('alpha &lt; &beta;') 'alpha < \u03b2' ``` [htmlentitydefs](http://docs.python.org/library/htmllib.html#module-htmlentitydefs) is documented, but requires you to do a lot of the work yourself. If you only need the XML predefined entities (lt, gt, amp, quot, apos), you could use minidom to parse them. If you only need the predefined entities and no numeric character references, you could even just use a plain old string replace for speed.
I forgot to tag it at first, but I'm using BeautifulSoup. Digging around in the documentation, I found: ``` soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) ``` does it exactly as I was hoping.
HTML Entity Codes to Text
[ "", "python", "html", "beautifulsoup", "" ]
I've finally managed to create a Netbeans project out of an old standalone (not Web-) Java application which consisted only out of single .java sources. Now I have basically two questions regarding Netbeans Subversion interaction and application deployment: 1. Do you check in all the Netbeans project files into the repository, normally? 2. If I build the project using Netbeans (or ant) I get a .jar file and some additional jar libraries. In order for the app to run properly on the server, some additional config files and directories (log/ for example) are needed. The application itself is a J2SE application (no frameworks) which runs from the command line on a Linux platform. How would you deploy and install such an application? It would also be nice if I could see what version of app is currently installed (maybe by appending the version number to the installed app path). Thanks for any tips.
1. No, not usually. Anything specific to NetBeans (or Eclipse, IntteliJ, etc), I don't check in; try to make it build from the command line with your ant script and produce exactly what you want. The build.xml is something that can be used for other IDEs, or in use with Anthill or CruiseControl for automated builds/continuous integration, so that should be checked in. Check in what is needed to produce/create your artifacts. 2. You don't specify what type of server, or what exact type of application. Some apps are deployed via JNLP/WebStart to be downloaded by multiple users, and have different rules than something deployed standalone for one user on a server to run with no GUI as a monitoring application. I cannot help you more with that unless you can give some more details about your application, the server environment, etc. Regarding the config files, how do you access those? Are they static and never going to change (something you can load using a ResourceBundle)? ? You can add them to the jar file to look them up in the ResourceBundle, but it all depends on what you are doing there. If they have to be outside the jar file for modification without recompiling, have them copied with an installer script. As for directories, must they already exist? Or does the application check for their existence, and create them if necessary? If the app can create them if absent, you have no need to create them. If they need to be there, you could make it part of the install script to create those folders before the jar files are installed. Version number could be as simple as adding an about box somewhere in the app, and looking up the version string in a config/properties file. It has to be maintained, but at least you would be able to access something that would let you know you have deployed build 9876.5.4.321 (or whatever version numbering scheme you use).
Ideally, you should not tie down your application sources and config to a particular IDE. Questionwise, * I suggest you do not. Keep you repository structure independent of the IDE * You might have to change your application so that it's structure is very generic and can be edited in any IDE. Is this a web app? A standalone Java app? If you clarify these, it would be easier to answer your query.
Deploy java (command line) app using Netbeans / ant
[ "", "java", "deployment", "netbeans", "ant", "" ]
From an input text I need to call a function to capture the onkeydown event and I need to pass a parameter to that event, for example: ``` <input type="text" onkeydown="TextOnKeyDown('myPrefix');" />... ``` Then in that function I need to know what key was pressed. I use ``` function TextOnKeyDown(prefix) { var key = event.keyCode; ... } ``` This works like a charm in IE, but not in Firefox. I've read that for firefox you have to pass an argument to the handler and then use it to get the key, something similar to: ``` <input type="text" onkeydown="detectKey(event)"/> ... function detectKey(e){ var key = (document.all) ? e.keyCode : e.which; ... } ``` But I cannot get to pass my parameter and the needed event parameter for firefox. Any suggestions?
None of the proposed solutions worked as what I needed was to add **my own parameter** apart from the necessary "event" parameter for Firefox to get the keyCode. Anyway the helped, thanks guys. I put the final solution for future readers: In the end I just had to add the "event" parameter to the caller: ``` <input type="text" onkeydown="TextOnKeyDown('myPrefix', event);" /> ``` and the handler: ``` function TextOnKeyDown(prefix, evt) { var key = (evt.which) ? evt.which : evt.keyCode; ... } ``` Somehow it didn't work before, I don't know why.
I wrote this yesterday, works in both FF and IE => ``` //execute this during initialization document.onkeydown = function(event) { var holder; //IE uses this if(window.event) { holder = window.event.keyCode; } //FF uses this else { holder = event.which; } keyz(holder); } function keyz(key) { if(key === /*desired code*/) { /*execute stuff*/ } } ``` you will want to replace document.onkeydown with [your input].onkeydown
Firefox onkeydown detect pressed key
[ "", "javascript", "html", "firefox", "" ]
I'm having a look at this MVVM stuff and I'm facing a problem. The situation is pretty simple. I have the following code in my index.xaml page ``` <Grid> <ItemsControl ItemsSource="{Binding}"> <ItemsControl.ItemTemplate> <DataTemplate> <view:MovieView ></view:MovieView> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> ``` and in my index.xaml.cs ... InitializeComponent(); base.DataContext = new MovieViewModel(ent.Movies.ToList()); .... and here is my MoveViewModel ``` public class MovieViewModel { readonly List<Movies> _m; public ICommand TestCommand { get; set; } public MovieViewModel(List<Movies> m) { this.TestCommand = new TestCommand(this); _m = m; } public List<Movies> lm { get { return _m; } } } ``` finally here is my control xaml MovieView ``` <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"></ColumnDefinition> <ColumnDefinition Width="Auto"></ColumnDefinition> </Grid.ColumnDefinitions> <Label VerticalAlignment="Center" Grid.Row="0" Grid.Column="0">Title :</Label><TextBlock VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" Text="{Binding Title}"></TextBlock> <Label VerticalAlignment="Center" Grid.Row="1" Grid.Column="0">Director :</Label><TextBlock VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" Text="{Binding Director}"></TextBlock> <Button Grid.Row="2" Height="20" Command="{Binding Path=TestCommand}" Content="Edit" Margin="0,4,5,4" VerticalAlignment="Stretch" FontSize="10"/> </Grid> ``` So the problem I have is that if I set ItemsSource at Binding it doesn't make anything if I set ItemsSource="{Binding lm}" it populates my itemsControl but the Command (Command="{Binding Path=TestCommand}" ) doesn't not work. Of course it doesn't not work because TestCommand doesn't not belong to my entity object Movies. So finally my question is, what do I need to pass to the ItemsControl to make it working? Thx in advance
Got it working here is the thing ``` <ItemsControl DataContext="{Binding}" ItemsSource="{Binding lm}"> Command="{Binding Path=DataContext.TestCommand, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" ``` so the RelativeSource was the thing I've missed. if somebody has a good explaination of this, I would be definitely happy.
As soon as your items are rendered, each item gets set to the DataContext of the specific row it represents, so you are no longer able to reference to your first DataContext.. Also, due to the fact that you are in a DataTemplate, your bindings will start working when there is need for that Template.. so in that case you need to look up your parent control through a RelativeSource binding... Hope that explains some things..
ICommand in MVVM WPF
[ "", "c#", "wpf", "mvvm", "" ]
I am using an array with titles. Each titles index corresponds to an id in a database which contains html for that given title. Lets say I have a string which contains one of the titles. ``` title = "why-birds-fly"; titles[] // an array which contains all the titles ``` To use the string "title" to get the corresponding id I could do: ``` for (i = 0; i < titles.length-1; i++) { if (titles[i] == title) return i+1; } ``` Another method I could use is to create an associative array together with the titles array which is the exact opposite of titles. That is, it uses the string as an index and returns the number. ``` titles_id {blah:0,why-birds-fly:1,blah2:2} ``` I could then access the ID by: ``` return titles_id[title]+1; ``` What would be most effective considering CPU, Memory, etc? Also, please let me know if my logic is all wrong. Thanks Willem
The linear search approach has a [complexity](http://en.wikipedia.org/wiki/Big_O_notation) of O(n), and I think the worst case for the associative array approach is probably O(log n), (the *best* case maybe O(1) if the JS engine is using hashes and getting no collisions). It will depend on how a JS engine typically implements [associative arrays/objects](http://en.wikipedia.org/wiki/Associative_array#Data_structures_for_associative_arrays), but you can be sure it will beat O(n). So, the second approach will be faster, but will of course use more memory. This is a very typical [trade off](http://en.wikipedia.org/wiki/Time-space_tradeoff), gaining more speed, but using more memory, and only you can decide whether you want to make that trade.
It is also important to consider the number of key value pairs you will need to store. If its less than ~50 (depending on implementation) then doing a linear search will be as efficient as doing a hash table lookup, because of the cost of calculating the hash value and resolving collisions. An exception is the Google chrome v8 JavaScript engine keeps a sort of cached version of all objects that allow it to perform a direct lookup of a property on an object, therefore the use of the Object class as a hash table may be faster, though I'm not sure if the cost of creating this cached version will outweigh the benefit for smaller lists.
Effective ways of finding an element in a Javascript array
[ "", "javascript", "search", "complexity-theory", "big-o", "associative-array", "" ]
i want to know how to generate a url in a servlet. I have a login servlet, and every time that add a user i want to gen. a url for each user profile. Can anyone help me please?
I think the solution of kgiannakakis is very good. I just want to add some details, because reading the comment of Agusti-N I have the suspect that may be he is missing something. Let's say that you have the **UsersServlet** described by kgiannakakis, a jsp called **showUserProfile.jsp** and an **userBean** that has all the properties of the user's profile needed to be shown in the jsp. When a new user registers to your application, you need to do nothing more than you already do now. Just register a new user in the db, and **forget the login servlet**. Now suppose that I registered to your app with my username **alexmeia**. When someone digit the url *yourApp/Users/alexmeia* the **UsersServlet is called**. This servlet gets the username alexmeia from the request url, checks in the DB if this username exists and if exist **load all the properties of this user in the userBean**. After that, forward to **showUserProfile.jsp**, which shows the user profile reading it from the userBean. Obviously, if the user alexmeia is not in the Db, you can redirect to a generic userNotFound.jsp, or go to home page and show a message and so on... This works for all the registered users in the same way. You don't need to really create a real new url for every new user.
The easiest way is to declare a servlet mapping like the following: ``` <servlet-mapping> <servlet-name>UsersSelvlet</servlet-name> <url-pattern>/Users/*</url-pattern> </servlet-mapping> ``` Now, whenever you get a request for MyApp/Users/UserId you read the request path, get the userId and check if the user exists. If not you return 'Not found'. Otherwise you return the user's page. This is a quick and dirty implementation of a RESTful service.
How to create a URL in a servlet?
[ "", "java", "servlets", "jakarta-ee", "" ]
let's say that you want to select all rows from one table that have a corresponding row in another one (the data in the other table is not important, only the presence of a corresponding row is important). From what I know about DB2, this kinda query is better performing when written as a correlated query with a EXISTS clause rather than a INNER JOIN. Is that the same for SQL Server? Or doesn't it make any difference whatsoever?
I just ran a test query and the two statements ended up with the exact same execution plan. Of course, for just about any performance question I would recommend running the test on your own environment; With SQL server Management Studio this is easy (or SQL Query Analyzer if your running 2000). Just type both statements into a query window, select Query|Include Actual Query Plan. Then run the query. Go to the results tab and you can easily see what the plans are and which one had a higher cost.
Odd: it's normally more natural for me to write these as a correlated query first, at which point I have to then go back and re-factor to use a join because in my experience the sql server optimizer is more likely to get that right. But don't take me too seriously. For all I have 26K rep here and one of only 2 current sql topic-specific badges, I'm actually pretty junior in terms of sql knowledge (It's all about the volume! ;) ); certainly I'm no DBA. In practice, you will of course need to profile each method to gauge it's actual performance. I would *expect* the optimizer to recognize what you're asking for and handle either query in the optimal way, but you never know until you check.
Correlated query vs inner join performance in SQL Server
[ "", "sql", "sql-server", "" ]
What is the best way to find the user's home directory in Java? The difficulty is that the solution should be cross-platform; it should work on Windows 2000, XP, Vista, OS X, Linux, and other Unix variants. I am looking for a snippet of code that can accomplish this for all platforms, and a way to detect the platform. Per Java bug [4787931](https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4787931), system property `user.home` does not work correctly on Windows XP, so using this system property is not an acceptable solution as it is not cross-platform.
The bug you reference (bug 4787391) has been fixed in Java 8. Even if you are using an older version of Java, the `System.getProperty("user.home")` approach is probably still the best. The `user.home` approach seems to work in a very large number of cases. A 100% bulletproof solution on Windows is hard, because Windows has a shifting concept of what the home directory means. If `user.home` isn't good enough for you I would suggest choosing a definition of `home directory` for windows and using it, getting the appropriate environment variable with `System.getenv(String)`.
Actually with Java 8 the right way is to use: ``` System.getProperty("user.home"); ``` The bug [JDK-6519127](http://bugs.java.com/view_bug.do?bug_id=6519127) has been fixed and the "Incompatibilities between JDK 8 and JDK 7" section of the [release notes](http://www.oracle.com/technetwork/java/javase/8-compatibility-guide-2156366.html) states: > Area: Core Libs / java.lang > > Synopsis > > The steps used to determine the user's home directory on Windows have changed to follow the Microsoft recommended approach. This change > might be observable on older editions of Windows or where registry > settings or environment variables are set to other directories. Nature > of Incompatibility > > ``` > behavioral RFE > > 6519127 > ``` Despite the question being old I leave this for future reference.
What is the best way to find the user's home directory in Java?
[ "", "java", "cross-platform", "home-directory", "" ]
Imagine you have two buttons on the win form. What do you think should be the behavior when user presses the "button 1" with the below code? Should it display all 5 message box in one go, or one by one - MessageBox.Show statement is inside a lock statement? ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } private static readonly object lockobject = new object(); private void button1_Click(object sender, EventArgs e) { var action = new Action(function); for(int i = 0; i< 5; i++) { action.BeginInvoke(null, null); } } private void function() { if (button2.InvokeRequired) { var func = new Action(function); button2.Invoke(func); } else { lock (lockobject) { MessageBox.Show("Testing"); } } } } ``` Now if we replace MessageBox.Show with any other statment, it would execute the statement only one at a time, the other threads would wait, one at a time.
Since your lock statement is executed when InvokeRequired is false, the locks will all run on the same (main) thread. Therefore the locks will not block. ~~If you want the MessageBox to block, use ShowDialog instead.~~
1. lock only blocks if another thread owns the lock, locking on the same object from the same thread multiple times is allowed - otherwise it would be an instant deadlock, after all it would have been blocking the current thread while waiting for the current thread. 2. Control.BeginInvoke doesn't execute code in a different thread, it will always execute the code in the thread pumping messages for the control, it does so by posting a message to the control's input queue and then executing the code when the message arrives. because of 2 your code isn't multi-threaded at all, everything executes in the same thread - and this brings us back to 1, when you don't have multiple threads lock does nothing.
Is this is a bug in .net Monitor/lock statement or does MessageBox.Show behaves differently?
[ "", "c#", ".net", "locking", "monitor", "" ]
i have little problem with if ``` { string nom; string ou; nom = "1"; if (nom == "1") { nom +=1; ou = nom; } Console.Write(ou); } ``` but i cant print ou value i dont know why
Another option is to set ou in an else: ``` if (nom == "1") { nom +=1; ou = nom; } else { ou = "blank value"; } ```
Try something like this ``` { string nom; string ou = String.Empty; nom = "1"; if (nom == "1") { nom +=1; ou = nom; } Console.Write(ou); } ```
Why does this string initialization in an if statement prevent me from printing?
[ "", "c#", "syntax", "language-design", "if-statement", "" ]
What is an [AppDomain](http://en.wikipedia.org/wiki/Application_Domain)? What are the benefits of AppDomains or why Microsoft brought the concept of AppDomains, what was the problem without AppDomains? Please elaborate.
An `AppDomain` provides a layer of isolation within a process. Everything you usually think of as "per program" (static variables etc) is actually per-AppDomain. This is useful for: * plugins (you can unload an `AppDomain`, but not an assembly *within* an `AppDomain`) * security (you can run a set of code with specific trust levels) * isolation (you can run different versions of assemblies etc) The pain is you need to use remoting etc. [See MSDN](http://msdn.microsoft.com/en-us/library/cxk374d9.aspx) for lots more info. To be honest, it isn't something you need to mess with very often.
An App-domain implements the concept of a contiguous virtual memory space that holds the code and the in-memory resources that can be directly accesses or referenced. Separate AppDomains do not share memory space and, consequently, one AppDomain cannot directly reference contents in another. In particular, data must be passed between AppDomains through a copy-by-value process. In particular, reference objects, which rely on pointers and therefore memory addresses, must first be serialized from the source and then deserialization into the destination AppDomain. Previously on Windows systems, memory boundaries were implemented by processes; however, constructing processes is resource intensive. They also serve a dual purpose as thread boundaries. App-domains, on the other hand, are concerned only with memory boundary or address space. Threads can 'flow' across AppDomains (that is, a procedure can invoke an entry point in another AppDomain and wait for it to return. The thread is said to 'continue' execution within the other AppDomain). One significant benefit of this architecture is that communication patterns between App-domains remain substantially unchanged whether the AppDomains are in the same process, different processes, or on a different machines all together: namely the process of serialization and deserialization (marshaling) of parameter data. Note 1: the meaning of a thread crossing an AppDomain is that of a blocking or synchronous method call into another AppDomain (versus a non-blocking or asynchronous call which would spawn another thread to continue execution in the target AppDomain and continue in it's current AppDomain without awaiting response). Note 2: there is such a thing as Thread Local Storage. However, a better name would have been App-Domain Thread Local Storage since threads leave their data behind as they cross App-Domains but pick them back up when they return: <http://msdn.microsoft.com/en-us/library/6sby1byh.aspx> Note3: A .Net Runtime is a Windows Process application with an associated heap. It may host one or more AppDomains in that heap. However, the AppDomains are design to be oblivious of each other and to communicate with each other via marshaling. It is conceivable that an optimization can be performed that bypasses marshaling between communicating AppDomains sharing the same .Net Runtime and therefore the same Windows Process heap.
What is AppDomain?
[ "", "c#", ".net", "appdomain", "" ]
I have an application that contains Menu and sub menus. I have attached Appliocation Commands to some of the sub menu items such as Cut, Copy and Paste. I also have some other menu items that do not have application commands. How could I add a custom command binding to those sub menu items? I have gone through [this](http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx) article but unable to attach event to my sub menu items.
I use a static class that I place after the Window1 class (or whatever the window class happens to be named) where I create instances of the RoutedUICommand class: ``` public static class Command { public static readonly RoutedUICommand DoSomething = new RoutedUICommand("Do something", "DoSomething", typeof(Window1)); public static readonly RoutedUICommand SomeOtherAction = new RoutedUICommand("Some other action", "SomeOtherAction", typeof(Window1)); public static readonly RoutedUICommand MoreDeeds = new RoutedUICommand("More deeds", "MoreDeeeds", typeof(Window1)); } ``` Add a namespace in the window markup, using the namespace that the Window1 class is in: ``` xmlns:w="clr-namespace:NameSpaceOfTheApplication" ``` Now I can create bindings for the commands just as for the application commands: ``` <Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Open" Executed="CommandBinding_Open" /> <CommandBinding Command="ApplicationCommands.Paste" Executed="CommandBinding_Paste" /> <CommandBinding Command="w:Command.DoSomething" Executed="CommandBinding_DoSomething" /> <CommandBinding Command="w:Command.SomeOtherAction" Executed="CommandBinding_SomeOtherAction" /> <CommandBinding Command="w:Command.MoreDeeds" Executed="CommandBinding_MoreDeeds" /> </Window.CommandBindings> ``` And use the bindings in a menu for example: ``` <MenuItem Name="Menu_DoSomething" Header="Do Something" Command="w:Command.DoSomething" /> ```
Instead of defining them in a static class, you might as well declare the commands directly in XAML. Example (adapted from Guffas nice example): ``` <Window.Resources> <RoutedUICommand x:Key="DoSomethingCommand" Text="Do Something" /> <RoutedUICommand x:Key="DoSomethingElseCommand" Text="Do Something Else" /> </Window.Resources> <Window.CommandBindings> <CommandBinding Command="{StaticResource DoSomethingCommand}" Executed="CommandBinding_DoSomething" /> <CommandBinding Command="{StaticResource DoSomethingElseCommand}" Executed="CommandBinding_DoSomethingElse" /> </Window.CommandBindings> ... <MenuItem Name="Menu_DoSomething" Header="Do Something" Command="{StaticResource DoSomethingCommand}" /> ```
How do I add a custom routed command in WPF?
[ "", "c#", "wpf", "" ]
I am looking to provide some convenience through reflection to programmers who will be using my code. To achieve my desired result I would like to get the class object for classes that extend my code. Even though they can't override the static method I wish to access the information from, it would be currently helpful. I may end up simply refactoring the design a bit to avoid this situation, but wanted to toss this question out to the community. The only way to achieve this that I am aware of is to take the current thread, navigate the stack trace, and extract the class name, then convert that into an actual instance of the class. Any other suggestions? Side note: the above approach is also the only way that I'm aware of getting the calling method.
When in the static method, what is the guarantee that some (any) class that has been extended from yours is on the stack? If you think about this a little, I suspect you will realize what you are looking for does not exist. /EDIT 1/ I think what you need is ``` abstract class B { <T extends B> B create(Class<T> clazz) { .... } ``` Hmmm. What if `create` is `protected` method? Then you could be pretty sure the caller is a `B`, you can even require that, throwing `UnsupportedOperation` or `IllegalState` if the caller is not assignable to `B`. You can use `Thread.currentThread().getStackTrace()`
Walking the stack is not necessarily safe to do unfortunately: From the JDK 6 Javadoc for getStackTrace: > Some virtual machines may, under some > circumstances, omit one or more stack > frames from the stack trace. In the > extreme case, a virtual machine that > has no stack trace information > concerning this throwable is permitted > to return a zero-length array from > this method. Generally speaking, the > array returned by this method will > contain one element for every frame > that would be printed by > printStackTrace. You could, perhaps, use the debugger api to do it. I believe that the debug stuff is able to use HotSpot at full speed (I could be wrong) so you would not see a massive speed hit for doing it. You might start by looking at: <http://java.sun.com/javase/6/docs/technotes/guides/jpda/trace.html> Also, building on Unanswereds answer... ``` class Base { // instance method helper public final int foo() { return (foo(this.getClass())); } // the real helper, with access to the class private static int foo(final Class clazz) { return (0); } } class Child extends Base { public void bar() { final int x; x = foo(); } } ```
getClass() and static methods: What is the best practice?
[ "", "java", "reflection", "static", "" ]
I have a SIP application that needs to send UDP packets to set up the SIP calls. SIP has a timeout mechanism to cope with delivery failures. An additional thing I would like to be able to do is detect whether a UDP socket is closed in order having to wait the 32s retransmit interval SIP uses. The cases I am referring to are when an attempt to send to a UDP socket results in an ICMP Destination Unreachable packet being generated by the remote host. If I attempt to send a UDP packet to a host that's up but that the port is not listening I can see the ICMP message arriving back with a packet tracer but the question is how do I get access to that from my C# code? I'm playing around with raw sockets but as yet have not been able to get the ICMP packets to be received by my program. The sample below never receives a packet even though ICMP messages are arriving on my PC. ``` Socket icmpListener = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); icmpListener.Bind(new IPEndPoint(IPAddress.Any, 0)); byte[] buffer = new byte[4096]; EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); int bytesRead = icmpListener.ReceiveFrom(buffer, ref remoteEndPoint); logger.Debug("ICMPListener received " + bytesRead + " from " + remoteEndPoint.ToString()); ``` Below is a wireshark trace showing the ICMP responses coming into my PC from an attempt to send a UDP packet from 10.0.0.100 (my PC) to 10.0.0.138 (my router) on a port I know it's not listening on. My problem is how to make use of those ICMP packets to realise the UDP send has failed rather than just waiting for the application to timeout after an arbitrary period? ![ICMP responses to UDP send](https://i.stack.imgur.com/lmb4J.png)
Nearly 3 years later and I stumbled across <http://www.codeproject.com/Articles/17031/A-Network-Sniffer-in-C> which gave me enough of a hint to help me find a solution to receiving ICMP packets on Windows 7 (don't know about Vista, which the original question was about but I suspect this solution would work). The two key points are that the socket has to be bound to a single specific IP address rather than IPAddress.Any and the IOControl call which sets the SIO\_RCVALL flag. ``` Socket icmpListener = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); icmpListener.Bind(new IPEndPoint(IPAddress.Parse("10.1.1.2"), 0)); icmpListener.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 }); byte[] buffer = new byte[4096]; EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); int bytesRead = icmpListener.ReceiveFrom(buffer, ref remoteEndPoint); Console.WriteLine("ICMPListener received " + bytesRead + " from " + remoteEndPoint); Console.ReadLine(); ``` I also had to set a firewall rule to allow ICMP Port Unreachable packets to be received. ``` netsh advfirewall firewall add rule name="All ICMP v4" dir=in action=allow protocol=icmpv4:any,any ```
**UPDATE: I think I'm going crazy.... That piece of code that you posted is also working for me...** The following piece of code works fine for me(xp sp3): ``` using System; using System.Net; using System.Net.Sockets; namespace icmp_capture { class Program { static void Main(string[] args) { IPEndPoint ipMyEndPoint = new IPEndPoint(IPAddress.Any, 0); EndPoint myEndPoint = (ipMyEndPoint); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); socket.Bind(myEndPoint); while (true) { /* //SEND SOME BS (you will get a nice infinite loop if you uncomment this) var udpClient = new UdpClient("192.168.2.199", 666); //**host must exist if it's in the same subnet (if not routed)** Byte[] messagebyte = Encoding.Default.GetBytes("hi".ToCharArray()); int s = udpClient.Send(messagebyte, messagebyte.Length); */ Byte[] ReceiveBuffer = new Byte[256]; var nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref myEndPoint); if (ReceiveBuffer[20] == 3)// ICMP type = Delivery failed { Console.WriteLine("Delivery failed"); Console.WriteLine("Returned by: " + myEndPoint.ToString()); Console.WriteLine("Destination: " + ReceiveBuffer[44] + "." + ReceiveBuffer[45] + "." + ReceiveBuffer[46] + "." + ReceiveBuffer[47]); Console.WriteLine("---------------"); } else { Console.WriteLine("Some (not delivery failed) ICMP packet ignored"); } } } } } ```
Listen for ICMP packets in C#
[ "", "c#", "icmp", "" ]
I am looking to write a javascript function that will fire when a user submits a form, however I do not have edit access to the submit button so that I can add the onsubmit function. I am able to add a `<script>` tag, so if I can detect the submit, then I can execute my code. Anyone know how to do this?
You can locate the submit button through the DOM (`getElementByID()` or `document.formname` come to mind) and then set the submit button's `onsubmit` value to a function of your choice.
> however I do not have programmatic > access to the submit button so that I > can add the onsubmit function How is that possible? If you're executing JavaScript on page, you have access to the entire DOM.
Is there a way to fire a javascript function on submit without onsubmit()
[ "", "javascript", "detect", "onsubmit", "" ]
I have a .NET2.0 C# web-app. It has a variable number of large, init-expensive objects which are shared across multiple requests but not sessioned to any given user. I therefore need to persist them in a lookup structure. These objects need to be created as required and are not required for the lifespan of the app, merely the lifespan of their usage. Plus a bit. The memory leaking way to do this is a simple dictionary, the memory safe way to do this is a weakreference backed dictionary, but the problem I'm having is that the GC is just too damned fast. Realistically this may not be a problem because the traffic to the objects should be such that they'll stay alive without being forced to regenerate too much, but ideally I'd like them to scale down too. Is there some kind of middle-ground solution I'm not thinking of which will keep the objects safely hidden from the GC for a period of time X, but also allow them to be collected at the end of that time, preferably where that time counter gets reset every time they're used in a way similar to session tokens?
I'm not sure why the [HttpRuntime cache](http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx) would not work here. Items inserted into the cache will be "renewed" every time they are touched, thus keeping them alive until they are no longer needed; and after that they will continue to stay in cache until they expire (sliding or rolling time) or they are forced out due to memory pressure. They can also be forced out at an explicitly-set, absolute time regardless of usage: * **Absolute time**: items are forced out after the system clock passes a certain DateTime * **Sliding (rolling) time**: every time an item is touched, its countdown to death is reset. The duration of the countdown is the sliding time (for example, 5 minutes). Example usage: ``` //adds itemObject to cache under name "UniqueItemKey" //set to expire 5 minutes after last touched HttpRuntime.Cache.Add("UniqueItemKey", itemObject, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), CacheItemPriority.Normal, null); ```
Why don't you use the Cache object from the framework and set a sliding expiration on it. Say 10 minutes. If it is used at least once every 10 minutes it will stay in cache, if the 10 minutes elapses it will expire and GC will remove it. An example: (I believe this is the full syntax ``` Cache.Add("myKey", MyLargeObject, null, DateTime.Now.AddMinutes(10), Cache.SlidingExpiration, CacheItemPriority.High) ```
large object cache
[ "", "c#", "collections", "caching", ".net-2.0", "garbage-collection", "" ]
I am working on querying the address book via J2ME and returning a custom Hashtable which I will call *pimList*. The keys in *pimList* {firstname, lastname} maps to an object (we'll call this object *ContactInfo*) holding (key, value) pairs e.g. work1 -> 44232454545, home1 -> 44876887787 Next I take *firstName* and add it into a tree. The nodes of the tree contains the characters from the *firstName*. e.g. "Tom" would create a tree with nodes: ``` "T"->"o"->"m"-> ContactInfo{ "work1" -> "44232454545", "home1" -> "44876887787" } ``` So the child of the last character *m* points to the same object instance in *pimList*. As I understand it, the purpose of WeakReferences is to that its pointer is weak and the object it points to can be easily GC'ed. In a memory constraint device like mobile phones, I would like to ensure I don't leak or waste memory. Thus, is it appropriate for me to make: 1. *pimList*'s values to be a WeakReference 2. The child of node "m" to point to WeakReference ?
I am not sure if the WeakMap is the right thing here. If you do not hold strong references anywhere in your application, the data in the map will disappear nearly immediately, because nobody is referencing it. A weak map is a nice thing, if you want to find things again, that are still in use elsewhere and you only want to have one instance of it. But I might not get your data setup right... to be honest.
It should work. You will need to handle the case where you are using the returned Hashtable and the items are collected however... which might mean you want to rethink the whole thing. If the Hashtable is short lived then there likely isn't a need for the weak references. You can remove the items out of the Hashtable when you are done with them if you want them to be possibly cleaned up while the rest of the Hashtable is stll being used.
Is this scenario suitable for WeakReferences?
[ "", "java", "memory-management", "java-me", "memory-leaks", "mobile", "" ]
I don't understand why this compiles. f() and g() are visible from the inner classes, despite being private. Are they treated special specially because they are inner classes? If A and B are not static classes, it's still the same. ``` class NotPrivate { private static class A { private void f() { new B().g(); } } private static class B { private void g() { new A().f(); } } } ```
(Edit: expanded on the answer to answer some of the comments) The compiler takes the inner classes and turns them into top-level classes. Since private methods are only available to the inner class the compiler has to add new "synthetic" methods that have package level access so that the top-level classes have access to it. Something like this (the $ ones are added by the compiler): ``` class A { private void f() { final B b; b = new B(); // call changed by the compiler b.$g(); } // method generated by the compiler - visible by classes in the same package void $f() { f(); } } class B { private void g() { final A a; a = new A(); // call changed by the compiler a.$f(); } // method generated by the compiler - visible by classes in the same package void $g() { g(); } } ``` Non-static classes are the same, but they have the addition of a reference to the outer class so that the methods can be called on it. The reason Java does it this way is that they did not want to require VM changes to support inner classes, so all of the changes had to be at the compiler level. The compiler takes the inner class and turns it into a top level class (thus, at the VM level there is no such thing as an inner class). The compiler then also has to generate the new "forwarding" methods. They are made at the package level (not public) to ensure that only classes in the same package can access them. The compiler also updated the method calls to the private methods to the generated "forwarding" methods. You can avoid having the compiler generate the method my declaring the methods as "package" (the absence of public, private, and protected). The downside to that is that any class in the package can call the methods. Edit: Yes, you can call the generated (synthetic) method, but DON'T DO THIS!: ``` import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class Main { public static void main(final String[] argv) throws Exception { final Class<?> clazz; clazz = Class.forName("NotPrivate$A"); for(final Method method : clazz.getDeclaredMethods()) { if(method.isSynthetic()) { final Constructor constructor; final Object instance; constructor = clazz.getDeclaredConstructor(new Class[0]); constructor.setAccessible(true); instance = constructor.newInstance(); method.setAccessible(true); method.invoke(null, instance); } } } } ```
I think [this quote](http://www.onjava.com/pub/a/onjava/excerpt/HardcoreJava_chap06/index.html) sums it up nicely: *...inner classes can access all members of the declaring class, even private members. In fact, the inner class itself is said to be a member of the class; therefore, following the rules of object-oriented engineering, it should have access to all members of the class.* And following from that, since both inner classes are really just part of the containing class, they should be able to access each others private members as well.
Why do inner classes make private methods accessible?
[ "", "java", "inner-classes", "" ]
I want to hide panel2 on a split container and have panel1 utilize the space. I was hoping setting Panel2Collapsed would do the trick, but no luck. Ideas?
This worked for me on a similar situation: ``` splitContainer1.Panel2Collapsed = true; splitContainer1.Panel2.Hide(); ``` I wanted the second panel to not be visible at all in some cases, so I implemented it this way.
Setting `Panel2Collapsed` property to `true` in the form designer and programatically both work as you want them to (i.e. Panel1 then occupies all of the space)... so there must be something else going on.
How can I hide a panel that is on a SplitContainer?
[ "", "c#", ".net", "winforms", "" ]
I want to find the highest AutoIncremented value from a field. (its not being fetched after an insert where I can use `@@SCOPE_IDENTITY` etc) Which of these two queries would run faster or gives better performance. `Id` is the primary key and `autoincrement` field for `Table1`. And this is for Sql Server 2005. ``` SELECT MAX(Id) FROM Table1 SELECT TOP 1 Id FROM Table1 ORDER BY Id DESC ``` **[Edit]** Yes in this case `Id` is the field on which I have defined the clustered index. If the index is `ID DESC` then what.. And yes it would be nice to know how the performance would be affected if 1. Id is a clustered index + primary key. 2. Id is a clustered index and not primary key. 3. Id is a non clustered index ASC + primary key. 4. Id is a non clustered index ASC and not primary key. 5. Id is a non clustered index DESC + primary key. 6. Id is a non clustered index DESC and not primary key. 7. Id is just `AutoIncrement` Hope its not a tall order!
In theory, they will use same plans and run almost same time. In practice, ``` SELECT TOP 1 Id FROM Table1 ORDER BY Id DESC ``` will more probably use a `PRIMARY KEY INDEX`. Also, this one is more extendable if you will decide to select some else column along with `id`. An actual plan on `MAX()` says: ``` SELECT <- AGGREGATE <- TOP <- CLUSTERED INDEX SCAN ``` , while plan for `TOP 1` says: ``` SELECT <- TOP <- CLUSTERED INDEX SCAN ``` , i. e. `aggregate` is omitted. Aggregate actually won't do anything here, as there is but one row. *P. S.* As `@Mehrdad Afshari` and `@John Sansom` noted, on a non-indexed field `MAX` is slightly faster (of course not `20` times as optimizer says): ``` -- 18,874,368 rows SET LANGUAGE ENGLISH SET STATISTICS TIME ON SET STATISTICS IO ON PRINT 'MAX' SELECT MAX(id) FROM master PRINT 'TOP 1' SELECT TOP 1 id FROM master ORDER BY id DESC PRINT 'MAX' SELECT MAX(id) FROM master PRINT 'TOP 1' SELECT TOP 1 id FROM master ORDER BY id DESC PRINT 'MAX' SELECT MAX(id) FROM master PRINT 'TOP 1' SELECT TOP 1 id FROM master ORDER BY id DESC PRINT 'MAX' SELECT MAX(id) FROM master PRINT 'TOP 1' SELECT TOP 1 id FROM master ORDER BY id DESC PRINT 'MAX' SELECT MAX(id) FROM master PRINT 'TOP 1' SELECT TOP 1 id FROM master ORDER BY id DESC Changed language setting to us_english. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. MAX SQL Server Execution Times: CPU time = 0 ms, elapsed time = 20 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 447, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 5452 ms, elapsed time = 2766 ms. TOP 1 SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 2, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 6813 ms, elapsed time = 3449 ms. MAX SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 44, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 5359 ms, elapsed time = 2714 ms. TOP 1 SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 6766 ms, elapsed time = 3379 ms. MAX SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 5406 ms, elapsed time = 2726 ms. TOP 1 SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 6780 ms, elapsed time = 3415 ms. MAX SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 85, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 5392 ms, elapsed time = 2709 ms. TOP 1 SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 10, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 6766 ms, elapsed time = 3387 ms. MAX SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 5374 ms, elapsed time = 2708 ms. TOP 1 SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. (строк обработано: 1) Table 'master'. Scan count 3, logical reads 32655, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 6797 ms, elapsed time = 3494 ms. ```
Nobody mentioned IDENT\_CURRENT('Table1') - blows them all away - of course it only works on identity columns, but that *was* the question...
For autoincrement fields: MAX(ID) vs TOP 1 ID ORDER BY ID DESC
[ "", "sql", "sql-server", "sql-server-2005", "query-optimization", "" ]
I need to write a .NET library for printing checks. Nothing fancy: you pass in the data, out comes the printed check. What's the best way to do this? Constraints: The format of the check.
A lot of people are using report generators for this. It's a bit overkill, but crystal reports will certainly do the job. Other than that, this is a basic question about formatting printed output. Is that your intention? --- Check out the printdocument class and you can do this yourself: <http://msdn.microsoft.com/en-us/magazine/cc188767.aspx> --- If you're printing checks remotely (ie, you need to provide a check on the website that the user can print out) then using PDF is the easiest and most certain way to accomplish that, but be careful of the security implications. -Adam
Wow... that takes me back! In the old days printers where dot matrix and cheques where a continous feed. I suppose nowadays cheques are preprinted single sheets and are printed with lasers/inkjets. Back then we'd just write plain ascii to the printer and send printer specific control/escape sequences for any specific formatting needs (picking the font size, line spacing, and page sizes). Now I would like try generating a PDF and then submitting that file for printing. It out to be possible to do this with a plain text file too... though that's getting pretty close to old school. The report generator suggestion by Adam is pretty good idea too. Generally with cheque printing it is a lot of trial and error to get the formatting right. Printing on plain paper and holding it and a preprinted cheque up to the window is an easy way to check positioning without burning through tons of cheques. One thing to note though is whether or not there is a requirement to track the control numbers preprinted on the cheques (aka cheque number). Auditors sometimes require this and it is also a reasonable guard against fraud (accounting for every preprinted cheque is not a terrible idea). To do this you need to handle reprinting, and markng individual cheques/cheque runs as "spoiled". You also need a manual process to collect and store spoiled cheques (for the auditors). On whole it's a giant pain to get this right and can take more time than you might imagine.
How do I print a check?
[ "", "c#", ".net", "printing", "" ]
I need to replace all iframe tags, stored as nvarchar in my database. I can find the entries using the following sql-question: ``` SELECT * FROM databasename..VersionedFields WHERE Value LIKE '%<iframe%' ``` Say I want to replace the following code segment: ``` code before iframe <iframe src="yadayada"> </iframe> code after iframe ``` With this: ``` code before iframe <a>iframe src="yadayada"</a> code after iframe ```
I think 2 update calls should do ``` update VersionedFields set Value = replace(value,'<iframe','<a><iframe') update VersionedFields set Value = replace(value,'> </iframe>','</a>') ```
You can do it with an UPDATE statement setting the value with a REPLACE ``` UPDATE Table SET Column = Replace(Column, 'find value', 'replacement value') WHERE xxx ``` You will want to be extremely careful when doing this! I highly recommend doing a backup first.
Search and replace part of string in database
[ "", "sql", "sql-server", "t-sql", "" ]
I want to swap to tables in the best possible manner. I have an IpToCountry table, and I create a new one on a weekly basis according to an external CSV file which I import. The fastest way I've found to make the switch was doing the following: ``` sp_rename IpToCountry IpToCountryOld go sp_rename IpToCountryNew IpToCountry go ``` The problem with this is that the table might still be accessed in between. How do I approach this problem in SQL? In considered using sp\_getapplock and sp\_releaseapplock, but I want to keep the read from the table function as quick as possible.
Assuming that you're unable to update/insert into the existing table, why don't you wrap all access to the table using a [view](http://msdn.microsoft.com/en-us/library/ms187956.aspx)? For example, you might initially store your data in a table called *IpToCountry20090303*, and your view would be something like this: ``` CREATE VIEW IpToCountry AS SELECT * FROM IpToCountry20090303 ``` When the new data comes in, you can create and populate the *IpToCountry20090310* table. Once the table is populated just update your view: ``` ALTER VIEW IpToCountry AS SELECT * FROM IpToCountry20090310 ``` The switch will be completely atomic, without requiring any explicit locking or transactions. Once the view has been updated, you can simply drop the old table (or keep it if you prefer).
I've had problems getting partitioning functions to work at scale. CREATE and DROP PARTITION are blocking operations, and you have little control over the blocking, and if it can't get a lock it will fail with a severity level 16 and kill your connection -- which you can't trap and retry without reestablishing the connection. But it might work just fine for you. Also, MSS Enterprise Edition is required, you can't use SE -- might be too much for some smaller or more cost-concerned shops. I've also found the view redef to block at high-scale (= transaction volume + sheer volume of constantly-inserted data, in my case) on sys tables and objects, so those operations can deadlock on things like reindexing and DTCCs -- and in one case, specifically with a user in SSMS (of all things) trying to browse views in the Object Explorer (somebody needs to tell those guys about READPAST). Again, your mileage may vary. In contrast, the sp\_rename works well for me at scale: it gives you control over the locking and the scope of it. To solve the blocking issue prior to the swap, try it as shown below. At face value this would seem to have the same scale issue at high volume... but I haven't seen it in practice. So, works for me... but again, everybody's needs and experiences are different. ``` DECLARE @dummylock bit BEGIN TRANSACTION BEGIN TRY -- necessary to obtain exclusive lock on the table prior to swapping SELECT @dummylock = 1 WHERE EXISTS (SELECT 1 FROM A WITH (TABLOCKX)) -- may or may not be necessary in your case SELECT @dummylock = 1 WHERE EXISTS (SELECT 1 FROM B WITH (TABLOCKX)) exec sp_rename 'A', 'TEMP' exec sp_rename 'B', 'A' exec sp_rename 'TEMP', 'B' COMMIT TRANSACTION END TRY BEGIN CATCH -- other error handling here if needed ROLLBACK TRANSACTION END CATCH ```
Swapping ms-sql tables
[ "", "sql", "swap", "" ]
So, i have the following script to use the google maps API, its all fine, but i need to create a map that has more than one Marker (the balloon shaped icon pointing to something) and i need each of those markers to point on a different area of the map (i.e. different coordinates), how can i do it? ``` <script type="text/javascript"> function load() { var map = new GMap2(document.getElementById("map")); var marker = new GMarker(new GLatLng(<%=coordinates%>)); var html="<img src='simplemap_logo.jpg' width='20' height='20'/> " + "<%=maptitle%><br/>" + "<%=text%>"; map.setCenter(new GLatLng(<%=coordinates%>), <%=zoom%>) map.setMapType(G_HYBRID_MAP); map.addOverlay(marker); map.addControl(new GLargeMapControl()); map.addControl(new GScaleControl()); map.addControl(new GMapTypeControl()); marker.openInfoWindowHtml(html); } //]]> </script> ``` One more question, if i pass the Script text as a variable, lets say something like: ``` <script type="text/javascript"> <%=ScriptText%> </script> ``` and my <%=ScriptText%> will be a string which i will build and assign its value to a Friend or Public variable called ScriptText, will it still run and work properly? (i am doing this to make my script dynamic and different based on how i build it as a STRING, due to my illiteracy in javascripting ;P)
obeattie and gregers are both right. In general, you need to store the marker parameters in some kind of array which you will later use at-least twice: 1. when adding the overlay to the map 2. when adding it to a GLatLngBounds object to calculate the center point and zoom level The array or markers would look like an array of objects, something like: ``` var latlng1 = [ new GLatLng( 48.1234, -120.1234 ), new GLatLng( 48.5678, -120.5678 ), new GLatLng( 48.9101, -120.9112 ), new GLatLng( 48.1121, -120.1314 ), new GLatLng( 48.3145, -120.1516 ), new GLatLng( 48.1617, -120.1718 ), new GLatLng( 48.1819, -120.1920 ), new GLatLng( 48.2021, -120.2122 ) ]; ``` The code for adding markers would look something similar to: ``` // assume that map1 is an instance of a GMap2 object // #0 -- google maps api requires us to call setCenter first before calling any other operation on the map map1.setCenter( new GLatLng( 0, 0 ), 0 ); // #1 -- add markers for ( var i = 0; i < latlng1.length; i++ ) { var marker = new GMarker( latlng1[ i ] ); map1.addOverlay( marker ); } // #2a -- calculate center var latlngbounds = new GLatLngBounds( ); for ( var i = 0; i < latlng1.length; i++ ) { latlngbounds.extend( latlng1[ i ] ); } // #2b -- set center using the calculated values map1.setCenter( latlngbounds.getCenter( ), map1.getBoundsZoomLevel( latlngbounds ) ); ``` As for your question about using server side script inside client side javascript, yes you can mix them together. Judging by your description, i think this is what you need to do: ``` <script type="text/javascript"> var latlng1 = new Array( ); </script> <script type="text/javascript"> <% do until rs.eof %> latlng1.push( new GLatLng( parseFloat( '<%= rs( "Lat" ) %>' ), parseFloat( '<%= rs( "Lng" ) %>' ) ) ); <% rs.movenext loop %> </script> ``` I've posted an article at: <http://salman-w.blogspot.com/2009/03/zoom-to-fit-all-markers-polylines-or.html>
You'll need to create a new [`GMarker`](http://code.google.com/apis/maps/documentation/reference.html#GMarker) for each place you want to mark on the map. There is quite good documentation available [here](http://code.google.com/apis/maps/documentation/overlays.html#Markers) for `GMarker`s. To create a `GMarker`, you'll see from the documentation that you first need to create a `GLatLng` representing the location you want to drop the marker. You haven't mentioned wanting any content in a balloon, so I'm assuming it's just the marker you're after. In your case, the code would probably look something like this: ``` var markerCoords = [ new GLatLng(<latitude>, <longitude>), new GLatLng(<latitude>, <longitude>), [...] ]; for (coord in markerCoords){ map.addOverlay(new GMarker(coord)); }; ``` I'm sure you can probably tell exactly what's going on here, but just in case, I create an array of `GLatLng` objects (this can be of any length [within bounds haha]), and then iterate over it, adding markers to the map for each `GLatLng` defined in the array. If you are planning on creating a lot of markers, you'll probably find it useful to use the [Marker Manager](http://code.google.com/apis/maps/documentation/overlays.html#Marker_Manager), which will speed up rendering a lot of markers simultaneously (by not rendering off-screen markers and condensing on-screen ones if there are a lot in one region of the screen).
How to use google maps API with multiple markers on the same map
[ "", "javascript", "asp.net", "google-maps", "google-maps-api-2", "" ]
I am not quite clear if auto\_ptr will help me in this case: ``` class A { A(const B& member) : _member(B) {}; ... const B& _member; }; A generateA() { auto_ptr<B> smart(new B()); A myA(*smart); return myA; } ``` Will the `myA._member` reference be valid when `smart` leaves its enclosing scope? If auto\_ptr isn't the answer here, what is? EDIT: I see where I confused everyone; I have to return myA outside the scope, which is why I care about \_member being valid after smart exits the scope.
It won't help you. \_member will become a dangling handle. This is because `auto_ptr` guarantees destruction at end of scope: no more, and *no less*. There are 2 possible answers. * You can make \_member's type `boost::shared_ptr<const B>`. * Alternatively, if class B is **small**, **copyable**, **monomorphic**, and object identity **doesn't need to be preserved**, you can make \_member a value, and store a copy of the argument there. This is by far the simplest option but obviously it is quite limiting. **In response to your edit:** That is indeed the case that I was talking about. By returning myA by value, a copy is created, and the copy's \_member refers to the already destructed local. As described, both `shared_ptr` and value semantics solve this.
The `auto_ptr` class is a wrapper over normal pointers. They take care of de-allocation when the stack is unwound (the destructor of `auto_ptr` gets called which in turn frees your contained object). Note well, that your `A` object is also created on the stack. When the scope ends, both A and the auto\_ptr will be deallocated. Beyond this point trying to access the `A` object will give you a compile-time error. Assuming the `A` object was created somewhere outside the block, then you have a real problem. Since, the `A` object stores a **reference** to the `B` object, outside the block-scope, this reference becomes invalid. Note also that with C++0x, `auto_ptr` has been deprecated. Use a `unique_ptr` instead. Do take a look at the [General Purpose Smart Pointers](http://en.wikipedia.org/wiki/C%2B%2B0x#General-purpose_smart_pointers) that are coming your way in C++0x.
Will auto_ptr protect against this?
[ "", "c++", "auto-ptr", "" ]
## Start with these simple classes... Let's say I have a simple set of classes like this: ``` class Bus { Driver busDriver = new Driver(); } class Driver { Shoe[] shoes = { new Shoe(), new Shoe() }; } class Shoe { Shoelace lace = new Shoelace(); } class Shoelace { bool tied = false; } ``` A `Bus` has a `Driver`, the `Driver` has two `Shoe`s, each `Shoe` has a `Shoelace`. All very silly. ## Add an IDisposable object to Shoelace Later I decide that some operation on the `Shoelace` could be multi-threaded, so I add an `EventWaitHandle` for the threads to communicate with. So `Shoelace` now looks like this: ``` class Shoelace { private AutoResetEvent waitHandle = new AutoResetEvent(false); bool tied = false; // ... other stuff .. } ``` ## Implement IDisposable on Shoelace But now [Microsoft's FxCop](https://en.wikipedia.org/wiki/FxCop) will complain: *"Implement IDisposable on 'Shoelace' because it creates members of the following IDisposable types: 'EventWaitHandle'."* Okay, I implement `IDisposable` on `Shoelace` and my neat little class becomes this horrible mess: ``` class Shoelace : IDisposable { private AutoResetEvent waitHandle = new AutoResetEvent(false); bool tied = false; private bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Shoelace() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (waitHandle != null) { waitHandle.Close(); waitHandle = null; } } // No unmanaged resources to release otherwise they'd go here. } disposed = true; } } ``` Or (as pointed out by commenters) since `Shoelace` itself has no unmanaged resources, I might use the simpler dispose implementation without needing the `Dispose(bool)` and Destructor: ``` class Shoelace : IDisposable { private AutoResetEvent waitHandle = new AutoResetEvent(false); bool tied = false; public void Dispose() { if (waitHandle != null) { waitHandle.Close(); waitHandle = null; } GC.SuppressFinalize(this); } } ``` ## Watch in horror as IDisposable spreads Right that's that fixed. But now FxCop will complain that `Shoe` creates a `Shoelace`, so `Shoe` must be `IDisposable` too. And `Driver` creates `Shoe` so `Driver` must be `IDisposable`. And `Bus` creates `Driver` so `Bus` must be `IDisposable` and so on. Suddenly my small change to `Shoelace` is causing me a lot of work and my boss is wondering why I need to checkout `Bus` to make a change to `Shoelace`. ## The Question How do you prevent this spread of `IDisposable`, but still ensure that your unmanaged objects are properly disposed?
You can't really "prevent" IDisposable from spreading. Some classes need to be disposed, like `AutoResetEvent`, and the most efficient way is to do it in the `Dispose()` method to avoid the overhead of finalizers. But this method must be called somehow, so exactly as in your example the classes that encapsulate or contain IDisposable have to dispose these, so they have to be disposable as well, etc. The only way to avoid it is to: * avoid using IDisposable classes where possible, lock or wait for events in single places, keep expensive resources in single place, etc * create them only when you need them and dispose them just after (the `using` pattern) In some cases IDisposable can be ignored because it supports an optional case. For example, WaitHandle implements IDisposable to support a named Mutex. If a name is not being used, the Dispose method does nothing. MemoryStream is another example, it uses no system resources and its Dispose implementation also does nothing. Careful thinking about whether an unmanaged resource is being used or not can be instructional. So can examining the available sources for the .net libraries or using a decompiler.
In terms of correctness, you can't prevent the spread of IDisposable through an object relationship if a parent object creates and essentially owns a child object which must now be disposable. FxCop is correct in this situation and the parent must be IDisposable. What you can do is avoid adding an IDisposable to a leaf class in your object hierarchy. This is not always an easy task but it's an interesting exercise. From a logical perspective, there is no reason that a ShoeLace needs to be disposable. Instead of adding a WaitHandle here, is it also possible to add an association between a ShoeLace and a WaitHandle at the point it's used. The simplest way is through an Dictionary instance. If you can move the WaitHandle into a loose association via a map at the point the WaitHandle is actually used then you can break this chain.
How do you prevent IDisposable from spreading to all your classes?
[ "", "c#", ".net", "garbage-collection", "dispose", "idisposable", "" ]
I'm compiling and linking a cpp file against a pre-compiled library, and I'm getting an "undefined reference" error. Firstly, this is the command (the library in question is quicknet3, the program I'm compiling is trapper): `g++ -w -g -I. -g -O3 -pipe -Wall -I/home/install/x86_64/include/quicknet3 -L/home/install/x86_64/lib -lquicknet3 -lintvec -lfltvec -o trapper trapper.cpp CMyException.cpp` Here's the undefined reference error: `/tmp/ccFuVczF.o: In function 'main': trapper.cpp:1731: undefined reference to 'QN_InFtrLabStream_PFile::QN_InFtrLabStream_PFile(int, char const*, _IO_FILE*, int)'` The call in trapper.cpp (line 1731) is: `IN_PFILE = new QN_InFtrLabStream_PFile(0, "", fp, 1);` where `fp` is a `FILE *`, assigned as the result of an `fopen` call beforehand. The constructor being called is defined in the relevant header file (QN\_Pfile.h), as follows: `class QN_InFtrLabStream_PFile : public QN_InFtrLabStream { public: QN_InFtrLabStream_PFile(int a_debug, const char* a_dbgname, FILE* a_file, int a_indexed); (... other declarations ...) }` The definition of the constructor is indeed given in QN\_Pfile.cc: `QN_InFtrLabStream_PFile::QN_InFtrLabStream_PFile(int a_debug,const char* a_dbgname, FILE* a_file, int a_indexed) : log(a_debug, "QN_InFtrLabStream_PFile", a_dbgname),file(a_file),indexed(a_indexed),buffer(NULL),sentind(NULL) { (... the usual constructor stuff :P ...) }` I compiled the quicknet3 library myself, without error, and installed it to /home/install/x86\_64/lib/libquicknet3.a So, I can't understand why the call from trapper.cpp is unable to find the reference to this constructor definition. The g++ arguments of `-L/home/install/x86_64/lib -lquicknet3` should do the trick, right? Any ideas? Thanks, Roy
A quick workaround is to add /home/install/x86\_64/lib/libquicknet3.a to g++ commandline. I you want to investigate further, if g++ is picking another copy of libquicknet3, you can pass -v to g++ so it will output its searching paths.
I notice that you're mixing `FILE*` and `_IO_FILE*`. I'm not familiar with the latter, are you sure they're one and the same?
g++ undefined reference to constructor
[ "", "c++", "constructor", "linker", "g++", "undefined-reference", "" ]
I'm sure this has been asked before, but as I can't seem to find a good answer, here I am, asking... again. :) Is there any way, using only a mixture of HTML, JavaScript/AJAX, and PHP, to report the actual progress of a file upload? In reply to anyone suggesting SWFUpload or similar: I know all about it. Been down that road. I'm looking for a 100% pure solution (and yes, I know I probably won't get it).
If you're able to add PECL packages into your PHP, there is the [uploadprogress](http://pecl.php.net/package/uploadprogress) package. The simplest way would be to just use swfupload, though.
Monitoring your file uploads with PHP/Javascript requires the PECL extension: > [uploadprogress](http://pecl.php.net/package/uploadprogress) A good example of the code needed to display the progress to your users is: > [Uber Uploader](http://uber-uploader.sourceforge.net/) If I'm not mistaken it uses JQuery to communicate with PHP. You could also write it yourself, It's not that complex. Add a hidden element as the *first* element of upload form, named `UPLOAD_IDENTIFIER`. Poll a PHP script that calls `uploadprogress_get_info( UPLOAD_IDENTIFIER )` It return an array containing the following: ``` time_start - The time that the upload began (unix timestamp), time_last - The time that the progress info was last updated, speed_average - Average speed in bytes per second, speed_last - Last measured speed in bytes per second, bytes_uploaded - Number of bytes uploaded so far, bytes_total - The value of the Content-Length header sent by the browser, files_uploaded - Number of files uploaded so far, est_sec - Estimated number of seconds remaining. ``` Let PHP return the info to Javascript and you should have plenty of information. Depending on the audience, you will likely not use all the info available.
Upload progress using pure PHP/AJAX?
[ "", "php", "ajax", "upload", "" ]
Basically I am using the C++ API of an app, but there is no reference for its python access. One variable is passed by ref, like so: ``` GetPoint ( Point &p, Object obj ) ``` so how can I translate to Python? Is there a pass by ref symbol?
There is no pass by reference symbol in Python. Just modify the passed in point, your modifications will be visible from the calling function. ``` >>> def change(obj): ... obj.x = 10 ... >>> class Point(object): x,y = 0,0 ... >>> p = Point() >>> p.x 0 >>> change(p) >>> p.x 10 ``` ... > So I should pass it like: GetPoint (p, obj)? Yes, though [Iraimbilanja](https://stackoverflow.com/questions/578635/how-to-pass-values-by-ref-in-python/578651#578651) has a good point. The bindings may have changed the call to return the point rather than use an out parameter.
It's likely that your Python bindings have turned that signature into: ``` Point GetPoint(Object obj) ``` or even: ``` Point Object::GetPoint() ``` So look into the bindings' documentation or sources.
How to pass values by ref in Python?
[ "", "python", "variables", "pass-by-reference", "" ]
Consider the following snippet: ``` struct Foo { static const T value = 123; //Where T is some POD-type }; const T Foo::value; //Is this required? ``` In this case, does the standard require us to explicitly declare **value** in a translation unit? It seems I have conflicting information; boost and things like numeric\_limits from the STL seem to do this sort of thing just like in my snippet. OTOH, I remember reading somewhere (albeit a long long time ago) that you're still required to provide a declaration in a translation unit. If this is the case, what about template specialization? Will each specialization require a declaration? I'd appreciate your comments as to what the "right way" is.
You have to provide a *definition* in a translation unit too, in case you *use* the value variable. That means, if for example you read its value. The important thing is that the compiler is not required to give a warning or error if you violate that rule. The Standard says "no diagnostic required" for a violation. In the next C++ Standard version, the rule changed. A variable is *not* used when it is used as a constant expression. Simply reading *value* above where the variable is initialized directly in the class means that still no definition is required then. See the definition of `use` in section `3.2 One Definition Rule` of the Standard and requirement for a definition for static data-members in `9.4.2, paragraph 4 and 5` (in the C++98 Standard. Appears in paragraph 3 and 4 in the n2800 draft of the next Standard). **Correction:** The rule already changed for c++03: If the variable appears where a integral constant expression is required, no definition is needed (quoting from an unofficial revisions list for the 2003 update), see resolution for [this language defect report](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#48): > An expression is potentially evaluated unless it appears where an integral constant expression is required (see 5.19), is the operand of the sizeof operator (5.3.3), or is the operand of the typeid operator and the expression does not designate an lvalue of polymorphic class type (5.2.8)... Note that even then, many uses are in cases where an integral constant is not *required*. Cases where one is, is in array dimensions or in template metaprogramming. So strictly speaking (see [this report](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#454)), only the c++1x solution provides really guarantee that in obvious cases also like `"s == string::npos"` where an integral constant is not *required* the definition of the static member is not needed, because the next Standard has a different, better wording of 3.2. This is however quite theoretical stuff, since most (all?) compiler don't moan anyway. Thanks for the guy in the comment section for telling me.
To add on to what litb said, from my copy of n2798: > **9.4.2** > > [...] > > 2 The declaration of a static data member in its class definition is not a definition and > may be of an incomplete type other than cv-qualified void. The definition for a static > data member shall appear in a namespace scope enclosing the member’s class definition. In > the definition at namespace scope, the name of the static data member shall be qualified > by its class name using the :: operator.
Static Constant Class Members
[ "", "c++", "" ]
I'm working on win 32 multithreading with c++. Scenario: I have a function used by multiple threads. This function as a critical sections (or any kind of construct that can lock a resource). In the critical section an exception is thrown. At this point I need to take care of unlocking the resource in the exception catch block. Is there any other way that this can be done? I mean, let's say that I don't want to have to remember to release the lock in the catch block, is there any common way to handle this problem to avoid this error prone scenario?
The idea is to encapsulate the act of acquiring and releasing the critical section in an object such that constructing the object acquires the CS and destroying the object releases it. ``` struct CSHolder { explicit CSHolder(CRITICAL_SECTION& cs): lock(cs) { ::EnterCriticalSection(&lock); } ~CSHolder() { ::LeaveCriticalSection(&lock); } CRITICAL_SECTION& lock; }; CRITICAL_SECTION gLock; void foo() { CSHolder lockIt(gLock); // lock is held until lockIt is destroyed } ``` The concept is called [RAII](http://en.wikipedia.org/wiki/RAII) - Resource Acquisition is Initialization. It is a very common idiom in modern C++.
If you're using an existing framework, you likely already have an RAII container class that can do this for you. If you're using MFC, take a look at `CSingleLock`, if you're using boost look at [`scoped_lock`](http://www.boost.org/doc/libs/1_36_0/doc/html/boost/interprocess/scoped_lock.html). It's a shame that everyone seems to have to (or think they have to) roll their own.
How to catch an exception thrown in a critical section?
[ "", "c++", "multithreading", "winapi", "exception", "" ]
I have some existing code that I've used to write out an image to a bitmap file. One of the lines of code looks like this: ``` bfh.bfType='MB'; ``` I think I probably copied that from somewhere. One of the other devs says to me "that doesn't look right, isn't it supposed to be 'BM'?" Anyway it does seem to work ok, but on code review it gets refactored to this: ``` bfh.bfType=*(WORD*)"BM"; ``` A google search indicates that most of the time, the first line seems to be used, while some of the time people will do this: ``` bfh.bfType=0x4D42; ``` So what is the difference? How can they all give the correct result? What does the multi-byte character constant mean anyway? Are they the same really?
All three are (probably) equivalent, but for different reasons. ``` bfh.bfType=0x4D42; ``` This is the simplest to understand, it just loads bfType with a number that happens to represent ASCII 'M' in bits 8-15 and ASCII 'B' in bits 0-7. If you write this to a stream in little-endian format, then the stream will contain 'B', 'M'. ``` bfh.bfType='MB'; ``` This is essentially equivalent to the first statement -- it's just a different way of expressing an integer constant. It probably depends on the compiler exactly what it does with it, but it will probably generate a value according to the endian-ness of the machine you compile on. If you compile and execute on a machine of the same endian-ness, then when you write the value out on the stream you should get 'B', 'M'. ``` bfh.bfType=*(WORD*)"BM"; ``` Here, the "BM" causes the compiler to create a block of data that looks like 'B', 'M', '\0' and get a char\* pointing to it. This is then cast to WORD\* so that when it's dereferenced it will read the memory as a WORD. Hence it reads the 'B', 'M' into bfType in whatever endian-ness the machine has. Writing it out using the same endian-ness will obviously put 'B', 'M' on your stream. So long as you only use bfType to write out to the stream this is the most portable version. However, if you're doing any comparisons/etc with bfType then it's probably best to pick an endian-ness for it and convert as necessary when reading or writing the value.
I did not find the API, but according to <http://cboard.cprogramming.com/showthread.php?t=24453>, the bfType is a bitmapheader. A value of BM would most likely mean "bitmap". 0x4D42 is a hexadecimal value (0x4D for M and 0x42 for B). In the [little endian](http://en.wikipedia.org/wiki/Endianness) way of writing (least significate byte first), that would be the same as "BM" (not "MB"). If it also works with "MB" then probably some default value is taken.
Multibyte character constants and bitmap file header type constants
[ "", "c++", "windows", "" ]
I'm maintaing an older Java code base (jvm 1.4) that seems to use cloning as an alternative to object instantiation, I'm guessing as a performance optimization. Here's a contrived example: ``` public class Foo { private SomeObject obj; // SomeObject implements Cloneable public Foo() { obj = new SomeObject(); obj.setField1("abc"); // these fields will have the same value every time obj.setField2("def"); } public void doStuff() { SomeObject newObj = obj.clone(); // clone it instead of using a factory method // do stuff with newObj } } ``` The usual caveats about premature optimization notwithstanding, was this actually a recommended idiom at some point?
One reason to invoke `clone()` instead of the copy constructor or a factory method is that none of the other options may be available. Implementing `clone()` to perform a shallow object copy (deep copy is more involved) is trivial compared to implementing a copy constructor or a factory method to perform the same operation. To implement `clone()`, a class need simply implement the `Cloneable` interface and override method `clone()` with one that invokes `super.clone()` which usually invokes `Object.clone()`. `Object.clone()` copies every property of the original object into the corresponding property of the duplicate, thus creating a shallow copy. Though implementing `clone()` is straightforward, it is still easy to forget to implement `Cloneable`. Consequently, a potential risk of using `clone()` to duplicate an object is that if the class of that object does neglect to implement `Cloneable` and `clone()` invokes `Object.clone()` either directly or indirectly, it will throw `CloneNotSupportedException`. See this [code example](https://stackoverflow.com/questions/1138769/why-is-the-clone-method-protected-in-java-lang-object/1255990#1255990) and a previous [discussion](https://stackoverflow.com/questions/1138769/why-is-the-clone-method-protected-in-java-lang-object) on the [poor design](https://stackoverflow.com/questions/1138769/why-is-the-clone-method-protected-in-java-lang-object/1138790#1138790) of the `Cloneable` interface.
Presumably they wanted a copy. Perhaps they want to pass it to another function, and can't be sure that that function won't change it. It's a way of making sure that the method doStuff() is const with respect to the state of the Foo object it's called on.
Does cloning provide a performance improvement over constructors/factory methods?
[ "", "java", "optimization", "clone", "cloneable", "" ]
Is is possible to detect if a Python script was started from the command prompt or by a user "double clicking" a .py file in the file explorer on Windows?
Here is an example of how to obtain the parent process id and name of the current running script. As suggested by [Tomalak](https://stackoverflow.com/users/18771/tomalak) this can be used to detect if the script was started from the command prompt or by double clicking in explorer. ``` import win32pdh import os def getPIDInfo(): """ Return a dictionary with keys the PID of all running processes. The values are dictionaries with the following key-value pairs: - name: <Name of the process PID> - parent_id: <PID of this process parent> """ # get the names and occurences of all running process names items, instances = win32pdh.EnumObjectItems(None, None, 'Process', win32pdh.PERF_DETAIL_WIZARD) instance_dict = {} for instance in instances: instance_dict[instance] = instance_dict.get(instance, 0) + 1 # define the info to obtain counter_items = ['ID Process', 'Creating Process ID'] # output dict pid_dict = {} # loop over each program (multiple instances might be running) for instance, max_instances in instance_dict.items(): for inum in xrange(max_instances): # define the counters for the query hq = win32pdh.OpenQuery() hcs = {} for item in counter_items: path = win32pdh.MakeCounterPath((None,'Process',instance, None,inum,item)) hcs[item] = win32pdh.AddCounter(hq,path) win32pdh.CollectQueryData(hq) # store the values in a temporary dict hc_dict = {} for item, hc in hcs.items(): type,val=win32pdh.GetFormattedCounterValue(hc,win32pdh.PDH_FMT_LONG) hc_dict[item] = val win32pdh.RemoveCounter(hc) win32pdh.CloseQuery(hq) # obtain the pid and ppid of the current instance # and store it in the output dict pid, ppid = (hc_dict[item] for item in counter_items) pid_dict[pid] = {'name': instance, 'parent_id': ppid} return pid_dict def getParentInfo(pid): """ Returns a PID, Name tuple of the parent process for the argument pid process. """ pid_info = getPIDInfo() ppid = pid_info[pid]['parent_id'] return ppid, pid_info[ppid]['name'] if __name__ == "__main__": """ Print the current PID and information of the parent process. """ pid = os.getpid() ppid, ppname = getParentInfo(pid) print "This PID: %s. Parent PID: %s, Parent process name: %s" % (pid, ppid, ppname) dummy = raw_input() ``` When run from the command prompt this outputs: > This PID: 148. Parent PID: 4660, Parent process name: cmd When started by double clicking in explorer this outputs: > This PID: 1896. Parent PID: 3788, Parent process name: explorer
If running from the command line there is an extra environment variable 'PROMPT' defined. This script will pause if clicked from the explorer and not pause if run from the command line: ``` import os print 'Hello, world!' if not 'PROMPT' in os.environ: raw_input() ``` Tested on Windows 7 with Python 2.7
Detect script start up from command prompt or "double click" on Windows
[ "", "python", "windows", "" ]
There is guy here swearing that JAXB is the greatest thing since sliced bread. I am curious to see what Stack Overflow users think the use case is for JAXB and what makes it a good or a bad solution for that case.
I'm a big fan of JAXB for manipulating XML. Basically, it provides a solution to this problem (I'm assuming familiarity with XML, Java data structures, and XML Schemas): Working with XML is difficult. One needs a way to take an XML file - which is basically a text file - and convert it into some sort of data structure, which your program can then manipulate. JAXB will take an XML Schema that you write and create a set of classes that correspond to that schema. The JAXB utilities will create the hierarchy of data structures for manipulating that XML. JAXB can then be used to read an XML file, and then create instances of the generated classes - laden with the data from your XML. JAXB also does the reverse: takes java classes, and generates the corresponding XML. I like JAXB because it is easy to use, and comes with Java 1.6 (if you are using 1.5, you can download the JAXB .jars.) The way it creates the class hierarchy is intuitive, and in my experience, does a decent job abstracting away the "XML" so that I can focus on "data". So to answer your question: I would expect that, for small XML files, JAXB might be overkill. It requires you to create and maintain an XML schema, and to use "standard textbook methods" of utilizing Java classes for data structures. (Main classes, small inner-classes to represent "nodes", and a huge hierarchy of them.) So, JAXB is probably not that great for a simple linear list of "preferences" for an application. But if you have a rather complex XML schema, and lots of data contained within it, then JAXB is fantastic. In my project, I was converting large amounts of data between binary (which was consumed by a C program) and XML (so that humans could consume and modify that data). The resulting XML Schema was nontrivial (many levels of hierarchy, some fields could be repeated, others could not) so JAXB was helpful in being able to manipulate that.
Here's a reason not to use it: performance suffers. There is a good deal of overhead when marshaling and unmarshaling. You might also want to consider another API for XML-Object binding -- such as JiBX: <http://jibx.sourceforge.net/>
What is JAXB and why would I use it?
[ "", "java", "jaxb", "" ]
Hi im thinking about developing a sort of File Transfer program and was wondering if i want as good encryption that i can get what should i use? ill be developing this with c# so i got access to the .net lib :P having a certificate with me on my usb to access the server is no problem if that would increase the security!
The simplest built in way with the .NET Framework is probably to use the [SslStream](https://web.archive.org/web/20170906055838/https://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx) class which is built in. Example of usage [here](https://web.archive.org/web/20200220153113/http://geekswithblogs.net:80/luskan/archive/2007/10/01/115758.aspx).
Look into tunneling your connection through [SSL](http://en.wikipedia.org/wiki/Transport_Layer_Security). It does all the hard work for you.
Good, secure encryption
[ "", "c#", ".net", "security", "file-transfer", "" ]
I'm trying to create coloumns of text for a C# app that will be running on MSN Messenger. I'm having trouple getting everything to line up. Here's an example of the output that I want: ``` 1) Pizza Hut 123 Fake St. 2) Domino's Pizza 123 Fake St. 3) The Cheesecake Cafe 123 Fake St. 4) Capital Pizza & Steakhouse 123 Fake St. 5) Funky Pickle Pizza 123 Fake St. 6) Boston Pizza 123 Fake St. 7) Rose Bowl Rouge Lounge 123 Fake St. 8) Royal Pizza 123 Fake St. 9) A Columbus Pizza & Donair Inc 123 Fake St. ``` But because it is a variable width font it is displaying like this: ``` 1) Pizza Hut 123 Fake St. 2) Domino's Pizza 123 Fake St. 3) The Cheesecake Cafe 123 Fake St. 4) Capital Pizza & Steakhouse 123 Fake St. 5) Funky Pickle Pizza 123 Fake St. 6) Boston Pizza 123 Fake St. 7) Rose Bowl Rouge Lounge 123 Fake St. 8) Royal Pizza 123 Fake St. 9) A Columbus Pizza & Donair Inc 123 Fake St. ``` I have tried using the C# string.PadRight() function as well as creating my own function that add padding using spaces and tabs. Both work fine with fixed width fonts but break with variable width fonts. Is there any way to determine the width of a string in a given font? Or does anyone have any other suggestions?
Just use the [TextRenderer](http://msdn.microsoft.com/en-us/library/system.windows.forms.textrenderer.aspx) class. The simplest case : ``` Size size = TextRenderer.MeasureText("Hello world", someFont); ``` If you don't have access to System.Windows.Fonts [Graphics.MeasureString](http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx) remains, it have some limitations but should do the work : ``` Bitmap bmp = new Bitmap(1,1); Graphics graphics = Graphics.FromImage(bmp); SizeF size = graphics.MeasureString("Hello world", someFont); ``` But be aware that if the font of your text and the spaces MUST be the same there will be cases where you can't align the text perfectly. I don't know what MSN Messenger is able to do in your case but except if you have access to at least a subset of HTML you won't have a perfect output. You should also be aware that if you do measurements on a local computer and send to another without the correct font installed your columns won't look like columns anymore so your are limited to the basic subset of fonts presents on all computers. If multiple operating system support is also a requirement you will have some big problems as the Arial font on Mac and PCs doesn't look (and measure) exactly the same.
It looks like you are trying to render this all in ASCII in a single text field. Yes? If that's the case, that's pretty tricky. It looks like you have a fixed number of tabs after each one right now, and that would be the issue. You could instead do spaces -- which I suspect you are doing with padright (not very familiar with that specific function). The key thing, though, is that with pure ASCII like that, shown in a variable width font, you will never get it to line up perfectly in a second column. You can get it close if you are diligent, but that's it -- if you have one row with a lot of capital W's, and another with a lot of lowercase i's, you'll have big width differences no matter what you do. If you're rendering in GDI, the best approach is to make one call to DrawText per column. You can make one big string out of each column if you want, and call MeasureString on the first column to determine how much space you need to move over for the second column. Or if this is an interface where you can do html, tables or divs would work great. Depends on the specifics of your environment. You could also do something like having two auto-height-set labels in a FlowLayout panel if this was WinForms, etc. There are a lot of options for making this work, but just not pure ascii with a variable width font. EDIT: Also, I saw you asked about how to get a Graphics class instance in a web service. You can do something like this: ``` private static Bitmap bitmap = new Bitmap( 1, 1 ); private static Graphics graphics = null; public static Graphics GetGeneralGraphics() { if ( graphics == null ) graphics = Graphics.FromImage( bitmap ); return graphics; } ``` You probably want to make those local variables (that you properly dispose when finished with) in a web services context.
Creating columns of text with a variable width font
[ "", "c#", "text-formatting", "windows-live-messenger", "" ]
Given the following Xml fragment: ``` <root> <sheetData> <row r="1" /> <row r="2" /> <row r="3" /> <row r="4" /> <row r="5" /> <row r="6" /> <row r="7" /> </sheetData> </root> ``` Which can be created with the following code: ``` XElement testElement = new XElement("root", new XElement("sheetData", new XElement("row", new XAttribute("r", 1)), new XElement("row", new XAttribute("r", 2)), new XElement("row", new XAttribute("r", 3)), new XElement("row", new XAttribute("r", 4)), new XElement("row", new XAttribute("r", 5)), new XElement("row", new XAttribute("r", 6)), new XElement("row", new XAttribute("r", 7)))); ``` Is this the best way to find the row where the r attribute is 2? This works, but I am repeating the Where clause in the select statement, and I am wondering if there is a better way and more efficent method. ``` int rowNumber = 2; XElement rowElement = testElement .Descendants("sheetData") .Where<XElement>(item => item.Descendants("row") .Where<XElement>(i => i.Attribute("r").Value == rowNumber.ToString()) .FirstOrDefault<XElement>() != null) .Select<XElement, XElement>(item => item.Descendants("row") .Where<XElement>(i => i.Attribute("r").Value == rowNumber.ToString()) .FirstOrDefault<XElement>()) .FirstOrDefault<XElement>(); ``` In general what is the best way to determine if Linq to Xml query optimized?
The best way is: ``` var row = testElement .XPathSelectElements("sheetData/row[@r='2']") .FirstOrDefault(); ``` A pure LINQ query that doesn't repeat the `Where` call: ``` var row = testElement .Descendants("sheetData") .Descendants("row") .Where(x => x.Attribute("r").Value == "2") .FirstOrDefault(); ```
``` //if sheetData appears multiple times XElement rowElement = testElement .Descendants("sheetData") .SelectMany(s=>s.Descendats("row)) .Where(i=>i.Attribute("r").Value == rowNumber.ToString()); //if sheetData appears once XElement rowElement = testElement .Element("sheetData") .Descendants("row)) .Where(i=>i.Attribute("r").Value == rowNumber.ToString()); ```
How do I optimize a Linq to Xml query againist attributes?
[ "", "c#", "optimization", ".net-3.5", "linq-to-xml", "" ]
I’m using the .NET entity framework and I’ve got one entity containing a varbinary. Is there an easy way to get the size of the varbinary in the codebehind, efter it’s been retrieved from the database? I’m thinking there might be some way to get the size directly from the entity, something like entity.Context.Size – or do one need to handle it differently?
A `varbinary` translates to a `byte[]` field in Entity Framework, which means you can check the **Length** property of the array: ``` int fieldSize = entity.MyVarBinaryField.Length; ``` As mentioned by [tster](https://stackoverflow.com/a/5409481/137471): In a LINQ to Entities query, you can call the [DataLength](http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.datalength.aspx) method of the [SqlFunctions](http://msdn.microsoft.com/en-us/library/dd466188.aspx) class, which will translate into a [DATALENGTH](http://msdn.microsoft.com/en-us/library/ms173486.aspx) function call in the generated SQL statement. This only works with SQL Server and Entity Framework 4 or later: ``` int? fieldSize = repository.Entity .Select(e => SqlFunctions.DataLength(e.MyVarBinaryField)).Single(); ```
I know this question is old, but EF now supports this by using `SqlFunctions.DataLength()`
Entity framework and VARBINARY
[ "", "c#", "asp.net", "sql-server-2005", "entity-framework", "" ]
How do i do this in wpf VB.NET ``` Private Sub FrmSettings_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing e.Cancel = (e.CloseReason = Forms.CloseReason.UserClosing) Me.Hide() End Sub ``` c# ``` private void FrmSettings_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e) { e.Cancel = (e.CloseReason == Forms.CloseReason.UserClosing); this.Hide(); } ``` as wpf's Close event just gives me e.Cancel and no closereason :(
There is not an equivalent in the default implementation of WPF. You can use a windows hook to get the reason though. The following post details how to do this: <http://social.msdn.microsoft.com/forums/en-US/wpf/thread/549a4bbb-e77b-4c5a-b724-07996774c60a/>
I would like to thank Bob King for his hint and make an addition to his code as C# WPF. It works for me. My application is a tray icon by type. In a WPF XAML form code behind: ``` protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); Application.Current.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose; } private bool m_isExplicitClose = false;// Indicate if it is an explicit form close request from the user. protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { base.OnClosing(e); if (m_isExplicitClose == false)//NOT a user close request? ... then hide { e.Cancel = true; this.Hide(); } } private void OnTaskBarMenuItemExitClick(object sender, RoutedEventArgs e) { m_isExplicitClose = true;//Set this to unclock the Minimize on close this.Close(); } ```
WPF Hide on Close?
[ "", "c#", "wpf", "vb.net", "" ]
From MSDN: > While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called. For example, you cannot retrieve output parameters until after you call Close. a) Why couldn’t you use SqlConnection for anything else? After all, when `ExecuteQuery()` returns SqlDataReader object, the data from DB has already been retrieved and populated SqlDatareader object. Thus I don’t see how or why SqlConnection should still be serving SqlDataReader object?! b) More importantly, for what reason would it be bad idea to retrieve output parameters before you call `Close()` on SqlDataReader? c) When above quote mentions that no other operations can be performed on SqlConnection, what operations does it have in mind? Just those that would require to connect to remote sql server, or we can’t use any members of SqlConnection instance?
a) When `ExecuteReader` returns, the data has not all been retrieved and populated in the reader, it may still be streaming back from the database. That's the whole point of the `SqlDataReader` because it's more efficient to do this than to load it all up front. b) You can't retrieve output parameters until after the reader has finished because of the way the Tabular Data Stream (TDS) protocol is structured. The output parameters are not physically sent down the stream until after the result set data. c) It means none of the operations except `Close` are documented as being guaranteed to work. Whether they actually do work or not is irrelevant because that is an implementation detail rather than a contract, and programming against implementation details is a recipe for disaster. Why do you want to re-use the connection anyway? The connections that `SqlConnection` uses are pooled behind the scenes, so when you dispose one it doesn't really get rid of all the resources, it just returns the connection to the pool. This means you can use the connection for the shortest time possible, ideally within a `using` block, and not have to worry about this type of thing. Just create a new connection whenever you need one, and don't bother trying to re-use them as it's already happening behind the scenes.
Uhm... you can in SQL Server 2005. Please read this page: <http://msdn.microsoft.com/en-us/library/ms345109.aspx>
Why can’t I use a SqlConnection instance until the SqlDataReader is closed?
[ "", "c#", ".net", "asp.net", "ado.net", "" ]
I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality. The simplest way I can think to do this is by writing the data to a buffer file from the application, and then read the same file using the monitor application. The writer application is C++, and the reader is currently Python on Win32 XP. Are there libraries to do this? Has anyone seen examples of this? I don't want to have to use a database as I don't want to link to a database library in the applcation. I.e. don't have space and may not be supported on the embedded platform. Another way to do this is over a network connection, but I figure files are the simplest solution.
Most systems has several solutions for what you want to do, such as pipes and unix sockets. These are intended for this, unlike regular files. There are however programs that does this on regular files, and I think the clearest example of this is the unix-utility tail, which can "follow" a file. Take a look at <http://msdn.microsoft.com/en-us/library/aa365590(VS.85).aspx> Python has a good wrapper library for win32, so anything you see there can probably be access from python.
You can use memory-mapped files, standard Python module called mmap.
Can I use a single file as a buffer? I.e. write to and read from at same time
[ "", "python", "file-io", "" ]
I have seen a few sites that have a thumbnail and when you click it, it enlarges the image in a modal like popup. Can anyone tell me how this is done? Thanks!
It is done with [lightbox](http://www.lokeshdhakar.com/projects/lightbox2/). There are several other scripts that do this, for example a [jquery plugin](http://leandrovieira.com/projects/jquery/lightbox/).
[Jquery](http://jquery.com/) is an easy way to implement a modal popup. It is usually done using one of the many plugins. * [piroBox](http://www.pirolab.it/pirobox/) * [FancyBox](http://fancy.klade.lv/) * [prettyPhoto](http://www.no-margin-for-errors.com/projects/prettyPhoto-jquery-lightbox-clone/) * [nyroModal](http://nyromodal.nyrodev.com/) * [thickbox](http://jquery.com/demo/thickbox/) The list goes on and on. You can view the top 23 [here](http://www.blogrammierer.de/jquery-die-23-besten-bildergalerie-plugins/)
modal image popups
[ "", "javascript", "image", "modal-dialog", "" ]
Can anyone list the steps needed to programatically install an application on Windows. Aside from copying the files where they need to be, what are the additional steps needed so that your app will be a first-class citizen in Windows (i.e. show up in the programs list, uninstall list...etc.) I tried to google this, but had no luck. BTW: This is for an unmanaged c++ application (developed in Qt), so I'd rather not involve the .net framework if I don't have to.
I think the theme to the answers you'll see here is that you should **use an installation program** and that **you should not write the installer yourself**. Use one of the many installer-makers, such as Inno Setup, InstallSheild, or anything else someone recommends. If you try to write the installer yourself, you'll probably do it wrong. This isn't a slight against you personally. It's just that there are a lot of little details that an installer should consider, and a lot of things that can go wrong, and if you want to write the installer yourself, you're just going to have to get all those things right. That means lots of research and lots of testing on your part. Save yourself the trouble. Besides copying files, installation tasks vary quite a bit depending on what your program needs. Maybe you need to put an icon on the Start menu; an installer tool should have a way to make that happen very easily, automatically filling in the install location that the customer chose earlier in the installation, and maybe even choosing the right local language for the shortcut's label. You might need to create registry entries, such as for file associations or licensing. Your installer tool should already have an easy way to specify what keys and values to create or modify. You might need to register a COM server. That's a common enough action that your installer tool probably has a way of specifying that as part of the post-file-copy operation. If there are some actions that your chosen installer tool doesn't already provide for, the tool will probably offer a way to add custom actions, perhaps through a scripting language, or perhaps through linking external code from a DLL you would write that gets included with your installer. Custom actions might include downloading an update from a specific Web site, sending e-mail, or taking an inventory of what other products from your company are already installed. A couple of final things that an installer tool should provide are ways to **apply upgrades** to an existing installation, and a way to **uninstall** the program, undoing all those installation tasks (deleting files, restoring backups, unregistering COM servers, etc.).
I highly recommend [NSIS](http://nsis.sourceforge.net/). Open Source, very active development, and it's hard to match/beat its extensibility. To add your program to the Add/Remove Programs (or Programs and Features) list, add the following reg keys: ``` [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\PROGRAM_NAME] "DisplayName"="PROGRAM_NAME" "Publisher"="COMPANY_NAME" "UninstallString"="PATH_TO_UNINSTALL_PROGRAM" "DisplayIcon"="PATH_TO_ICON_FILE" "DisplayVersion"="VERSION" "InstallLocation"="PATH_TO_INSTALLATION_LOCATION" ```
how-to: programmatic install on windows?
[ "", "c++", "windows", "installation", "" ]
Is there an Open Source java alternative to GraphViz? I'm aware of the existence of Grappa which basically wraps the Graph interface to GraphViz as an JavaAPI. However the layouting is still done by the GraphViz binaries. I'm looking for a pure-java, open source library providing the same functions and layouting algorithms as GraphViz.
You can have a look at [JUNG (Java Universal Network/Graph Framework)](http://jung.sourceforge.net/) which has visualization and analytics functions. It's open source.
Interestingly, the Eclipse project has an SWT/JFace component/framework capable of displaying and generating (import/export) Graphviz's 'DOT' format, in pure Java: [ZEST (home page & download links)](http://wiki.eclipse.org/Zest) See <http://wiki.eclipse.org/Graphviz_DOT_as_a_DSL_for_Zest> for usage examples. Although ZEST is touted as an Eclipse plugin, it does seem that the DOT-manipulation API's can be used standalone and external to an Eclipse installation. To clarify, the DOT functionality is a part of the [ZEST 2](http://wiki.eclipse.org/Zest) functionality, which itself is a sub-component of the [GEF4](http://wiki.eclipse.org/GEF/GEF4) project. Cheers Rich **Update (May 2017)** <https://github.com/nidi3/graphviz-java>
Pure Java reimplementation of GraphViz?
[ "", "java", "drawing", "graphviz", "graph-visualization", "" ]
Today I ran into a problem with the php function `strpos()` because it returned FALSE even if the correct result was obviously 0. This was because one parameter was encoded in UTF-8, but the other (origin is a HTTP GET parameter) obviously not. Now I have noticed that using the `mb_strpos` function solved my problem. My question is now: Is it wisely to use the PHP multibyte string functions generally to avoid theses problems in future? Should I avoid the traditional `strpos`, `strlen`, `ereg`, etc., etc. functions at all? Notice: I don't want to set `mbstring.func_overload` global in php.ini, because this leads to other problems when using the PEAR library. I am using PHP4.
It depends on the character encoding you are using. In single-byte character encodings, or UTF-8 (where a single byte inside a character can never be mistaken for another character), then as long as the string you are searching in and the string you are using to search are in the same encoding then you can continue to use the regular string search functions. If you are using a multi-byte encoding other than UTF-8, which does not prevent single bytes within a character from appearing like other characters, then it is never safe to do a string search using the regular string search functions. You may find false positives. This is because PHP's string comparison in functions such as strpos is per-byte, and with the exception of UTF-8 which is specifically designed to prevent this problem, multi-byte encodings suffer the problem that any subsequent byte in a character made up of more than one byte may match part of a different character. If the string you are searching *in* and the string you are searching for are of different character encodings, then conversion will always be necessary. Otherwise you'll find that for any string that would be represented differently in the other encoding, it will always return false. You should do such conversion on input: decide on a character encoding your app will use, and be consistent within the application. Any time you receive input in a different encoding, convert on the way in.
There have been some problems with the mb\_ \* functions in PHP versions prior to 5.2. So if your code is going on multiple platforms with different versions of PHP, strange behavior can occur. Furthermore the mb\_ strpos function is rather slow, it has to skip the number of characters specified by the offset parameter to get the real byte position used internally. In loops depending on the strpos/mb\_strpos functionality this can become a major bottleneck.
PHP Multibyte String Functions
[ "", "php", "utf-8", "multibyte", "" ]
I would like to be able to iterate through the values of a struct in C# (.Net 2.0). This is to be done at runtime, with no knowledge of the possible values in the struct. I was thinking along the lines of either using Reflection to add the struct values to a list, or converting the struct to a data structure that implements the IEnumerable interface. Can anyone provide any pointers? Thanks in advance for your help. Regards, Andy.
What exactly do you mean - the various fields within a struct? Or properties perhaps? If so, `Type.GetFields()` or `Type.GetProperties()` is the way to go. Are you absolutely sure you need to use a struct, by the way? That's rarely the best design decision in C#, particularly if the struct contains multiple values. EDIT: Yes, it seems that structs are being used for legacy reasons. One thing I didn't mention before: if the struct's fields aren't public, you'll need to specify appropriate BindingFlags (e.g. `BindingFlags.Instance | BindingFlags.NonPublic`).
At the simplest level, assuming that you want to iterate over the properties: ``` PropertyInfo[] properties = myStructInstance.GetType().GetProperties(); foreach (var property in properties) { Console.WriteLine(property.GetValue(myStructInstance, null).ToString()); } ```
Iterate Through a Struct?
[ "", "c#", ".net", "" ]
The following HTML form successfully utilizes jQuery's form validation, displaying "This field is required" to the right of the form field if left blank, and "Please enter at least 2 characters" if fewer than 2 characters were entered. However, instead of the validation metadata being specified using the class and minlength attributes on the "cname" form input field, I'd like to use jQuery's "rules" API instead, where the rules are specified in the body of the validate function. Thanks in advance: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="/lib/js/jquery.js"></script> <script src="/lib/js/jquery.validate.js"></script> <script> $(document).ready(function(){$("#commentForm").validate( /* rules/messages here */ );} ); </script> </head> <body> <form id="commentForm" method="get" action=""> <fieldset> <legend>A simple comment form with submit validation and default messages</legend> <p> <label for="cname">Name</label> <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" /> </p> <p> <input class="submit" type="submit" value="Submit"/> </p> </fieldset> </form> </body> </html> ```
The examples contained in [this blog post](http://web.archive.org/web/20120108075037/http://www.raymondcamden.com/index.cfm/2009/2/10/An-Introduction-to-jQuery-and-Form-Validation-2) do the trick.
``` rules: { cname: { required: true, minlength: 2 } }, messages: { cname: { required: "<li>Please enter a name.</li>", minlength: "<li>Your name is not long enough.</li>" } } ```
Simplest jQuery validation rules example
[ "", "javascript", "jquery", "validation", "declarative", "" ]
I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below? ``` if 13 in intList: i = intList.index(13) ``` In the case of dictionaries, there's a `get` function which will ascertain membership and perform look-up with the same search. Is there something similar for lists?
You answered it yourself, with the `index()` method. That will throw an exception if the index is not found, so just catch that: ``` def getIndexOrMinusOne(a, x): try: return a.index(x) except ValueError: return -1 ```
It looks like you'll just have to catch the exception... ``` try: i = intList.index(13) except ValueError: i = some_default_value ```
Do Python lists have an equivalent to dict.get?
[ "", "python", "list", "" ]
I have `SalesMan` class which is inherited from `User` class and also implements `ISalesMan` interface. ``` public class SalesMan : User, ISalesMan { ... } ``` I need to convert `User` objects into `SalesMan` objects. I understand that direct casting from `User` type of objects into `SalesMan` type is not possible. How should I do the converting? I'm thinking two different ways: 1. Creating constructor for `SalesMan` class that takes `User` parameter and initializes a new `SalesMan` object based on the given `User`. 2. Creating new method for the `SalesMan` class that takes `User` as a parameter and returns a new `SalesMan` object based on the given `User` parameter. ...or is there an even smarter way to solve this kind of problem?
The constructor described in Option 1 is what I would expect to find if I were poking around an unfamiliar API. They can be boring beasts to write though, and you may forget to update them when adding new fields to the User class. So (if performance considerations allow), consider writing an "intelligent" constructor using reflection, [along the lines of this example](http://www.johnsadventures.com/archives/2006/07/an_intelligent_copy_constructor_in_c_usi/). On the issue of constructors versus factory methods, the [Framework Design Guidelines](http://www.amazon.co.uk/Framework-Design-Guidelines-Conventions-Development/dp/0321545613) offers the following advice: > * DO prefer constructors to factories, because they are > generally more usable, consistent, > and convenient then specialized > construction mechanisms. > * CONSIDER using a factory if you need more control than can be > provided by constructors over the > creation of the instances. > * DO use a factory where a developer might not know which type to > construct, such as when coding > against a base type or interface. > * CONSIDER using a factory if having a named method is the only way to > make the operation > self-explanatory.
Option 1 is the tidiest and most intuitive.
Inheritance and converting objects
[ "", "c#", "oop", "" ]
On my website I use PHP sessions. Session information is stored in files in my ./session path. After a few months I discovered that these session files are never deleted, by now there are 145.000 of them in this directory. How should these be cleaned up? Do I have to do it programmatically, or is ther a setting I can use somewhere that would have this cleanup happen automatically? **EDIT** forgot to mention: This site runs at a provider, so I don't have access to a command line. I do have ftp-access, but the session files belong to another user (the one the webserver proces runs I guess) From the first answers I got I think it's not just a setting on the server or PHP, so I guess I'll have to implement something for it in PHP, and call that periodically from a browser (maybe from a cron job running on my own machine at home)
To handle session properly, take a look at <http://php.net/manual/en/session.configuration.php>. There you'll find these variables: * session.gc\_probability * session.gc\_divisor * session.gc\_maxlifetime These control the garbage collector (GC) probability of running with each page request. You could set those with [ini\_set()](http://php.net/manual/en/function.ini-set.php) at the beginning of your script or .htaccess file so you get certainty to some extent they will get deleted sometime.
Debian/Ubuntu handles this with a cronjob defined in /etc/cron.d/php5 ``` # /etc/cron.d/php5: crontab fragment for php5 # This purges session files older than X, where X is defined in seconds # as the largest value of session.gc_maxlifetime from all your php.ini # files, or 24 minutes if not defined. See /usr/lib/php5/maxlifetime # Look for and purge old sessions every 30 minutes 09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm ``` The maxlifetime script simply returns the number of minutes a session should be kept alive by checking php.ini, it looks like this ``` #!/bin/sh -e max=1440 for ini in /etc/php5/*/php.ini; do cur=$(sed -n -e 's/^[[:space:]]*session.gc_maxlifetime[[:space:]]*=[[:space:]]*\([0-9]\+\).*$/\1/p' $ini 2>/dev/null || true); [ -z "$cur" ] && cur=0 [ "$cur" -gt "$max" ] && max=$cur done echo $(($max/60)) exit 0 ```
cleanup php session files
[ "", "php", "session", "" ]
I'm writing some code that will need to speak to a web service over HTTP(s). In the past I've used the curl library. Recently, I noticed that I can simply use fopen() to access a remote URL and it seems far simpler. Curl seems to be much more configurable, having a plethora of options. Beyond that configurability, does it matter which method is used? If so, which is better and why?
`fopen()` will only open remote URLs if `allow_fopen_url` is enabled in `php.ini`. However in versions prior to 5.2.0, this was exceedingly dangerous because the `include` function would also download **and parse** PHP code from remote sites. A naive coder could easily be caught out with code like: ``` <?php $page = $_GET['page']; include($page); ?> ``` at which point an attacker just has to ask for `http://example.com/script.php?page=http://example.net/my_exploit_script` to execute their own code on the system and introduce an exploit. Unfortunately the default value for `allow_fopen_url` is 'on'. Fortunately, since 5.2.0 there's a separate setting (which *should* default to 'off') called `allow_url_include` which prevents `include` from downloading remote code. Personally, if you've got the option to use Curl, use that rather than `fopen`.
As Alnitak said, using CURL does not depend on the PHP settings. I've done some speed tests ``` file_get_contents ``` with my ``` function file_get_contents_curl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); curl_close($ch); return $data; } ``` Result: ``` 0.263456821442 0.0626730918884 ``` CURL is 4 times faster :)
What are the important differences between using fopen($url) and curl in PHP?
[ "", "php", "web-services", "http", "curl", "" ]
I use .net 2.0 (C#) I have a Person class, and i pupulate List< Person> p from the database. i know for a fact that my list has duplicates, but when i try to [remove the duplicates](https://stackoverflow.com/questions/47752/remove-duplicates-from-a-listt-in-c/48275#48275) they don't get removed. Does my Person class need to implement any interfaces for List< T>.Contains(T) to work properly? Any other ideas? Thank you.
Your Person class should implement [IEquatable](http://msdn.microsoft.com/en-us/library/ms131187(VS.80).aspx)
You should override **Equals** and **GetHashCode** method.
How do i make sure that List<T>.Contains(T) works with my custom class?
[ "", "c#", ".net-2.0", "" ]
How can I get the id of a html control just by specifying the coordinates of a triggered event (like `onmousedown`, `onmouseup`, `onclick`, etc..). the coordinates can be got by: `e.clientX` , `e.clientY` where e is the event object. The idea is to get the id of control on which a click event is done without having any `onClick` event in that control's definition. This will dispense the need of specifying the `onClick` event for multiple controls.
I do not believe that this is possible, but fortunately (if I understand your requirements correctly) you do not need to: If you want to get the HTML element where a user clicked, without specifying a click event handler on each element, simply specify a click handler on a top level element (one that contains all the other interesting elements - maybe even "document"), and then look at the MouseEvent's target property - it will specify the HTML element that received the click initially and not the element where you specified the onclick event handler (this can be gotten to simply by using the "this" keyword). If you have firebug, try this out in your firebug console right here on StackOverflow: ``` document.getElementById('question').onclick = function(e) { var target = window.event?window.event.srcElement:e.target; alert("Got click: " + target); } ``` Then click anywhere on your question text to get an alert with the correct HTML element :-) .
This is a very good question, lets suppose the function we are looking for is something like this: ``` document.elementFromPoint = function(x,y) { return element; }; ``` This obscure function is actually implemented in Firefox 3.0 using the gecko layout engine. <https://developer.mozilla.org/en/DOM/document.elementFromPoint> It doesn't work anywhere else though. You could build this function yourself though: ``` document.elementFromPoint = function(x,y) { // Scan through every single HTML element var allElements = document.getElementsByTagName("*"); for( var i = 0, l = allElements.length; i < l; i++ ) { // If the element contains the coordinate then we found an element: if( getShape(allElements[i]).containsCoord(x,y) ) { return allElements[i]; } } return document.body; }; ``` That would be very slow, however, it could potentially work! If you were looking for something like this to make your HTML code faster then find something else instead... Basically what that does is it goes through every single HTML element there is in the document and tries to find one which contains the coordinate. We can get the shape of an HTML element by using element.offsetTop and element.offsetWidth. I might find myself using something like this someday. This could be useful if you want to make something universal across the entire document. Like a tooltip system that works anywhere, or a system that launches context menus at any left click. It would be preferable to find some way to cache the results of getShape on the HTML element...
Retrieving html control by specifying coordinates
[ "", "javascript", "dom-events", "" ]
Consider i have an assembly(class library dll) which i have loaded using the following code, ``` Assembly a = Assembly.LoadFrom(@"C:\Documents and Settings\E454935\My Documents\Visual Studio 2005\Projects\nunit_dll_hutt\for_hutt_proj\bin\Debug\asdf.dll"); ``` and i need to get the type of the Assembly. In order to get the **type** i need the namespace of the assembly. ``` Type t = asm.GetType("NAMESPACE.CLASSNAME",false,true); ``` how can i get the Namespace in the above line.?! as inorder to get the **Namespace**, i need to get the type..? ``` Type.Namespace; ``` i.e i need to get the Namespace of the assembly which can be used to get its Type. Thanks in advance
Use ``` Assembly.GetTypes(); ``` This will get you a collection of all types and then you can get the Namespace property for each of them. Then I guess you can simply check that all the types have same Namespace value and use this value. Otherwise add some other logic to detect what namespace to consider primary.
An assembly can contain multiple namespaces. I think what you really want to ask is how to get a type from an assembly without specifying the namespace. I don't know if there is a better way, but you can try looking for the specific type like this (add - using linq;): ``` myassembly.GetTypes().SingleOrDefault(t => t.Name == "ClassName") ``` This will effectively throw if there is more than 1 class with that name under different namespaces (because the Single method ensures there is only 1). For a list of the namespaces for that class you can: ``` Assembly.Load("ClassName").GetTypes().Select(t => t.Namespace).Distinct(); ```
How to get Namespace of an Assembly?
[ "", "c#", ".net", "assemblies", "namespaces", "" ]
After reading the "Modern PHP workflow" article in the [November 2008 edition of php|architect magazine](http://phparch.com/magazine/index/86) which discussed unit testing ([phpUnit](http://www.phpunit.de/)), build tools ([Phing](http://phing.info/trac/)) and continuous integration ([Xinc](http://code.google.com/p/xinc/)), I'm inspired the learn more about some of the tooling available for PHP, especially Phing. In the past I've often handled deployment to a production server by running the live site as a subversion working copy and simply running an "svn update" on the production box to deploy the latest version of the code. Do you use build tools for PHP code? What advantages you you believe they offer over deploying direct from subversion? What should I look out for, or what gotchas might I face?
I have used both Phing and Ant and prefer the latter much more. I initially went with Phing due to it being written in PHP but to be honest it isn't as mature as Ant. In the end, having a mature buildsystem with a large community is worth more. Things done with Ant/Phing: 1. From a base checkout loalize to a specific language, ensure dependencies are there (other libs, directories, etc) 2. if you have them, compile templates, etc 3. Bring target database up to the required version, depending on the checked out code version 4. run unit tests, etc
A large issue that I see with Phing is that it creates a needless layer of indirection. PHP is a scripting language, and therefore could be run directly. Phing's use of XML configuration is a poor fit for the language: it does provide a more readable declarative configuration, but at the cost of sacrificing any of the flexibility of the language. With Ant (the inspiration for that route) it makes sense since Java did not have that flexibility as it is less dynamic and requires compilation. Unfortunately I haven't seen many good alternatives in the PHP space, and unlike other languages build tools are not as essential or a part of the culture so the evolution of another well supported option may not happen any time soon. I'd therefore stick to options that are closer to what PHP *could* do from cultures that more aggressively support build tools. I normally use [Gradle](http://www.gradle.org/). [Rake](http://rake.rubyforge.org/) also does a great job depending on with which language you want to cheat (and there may be other similar options). You should also weigh things like Webdriver support if you're into that type of thing. Otherwise creating a lightweight solution using PHP and/or BASH should cover everything while maintaining transparency
PHP build/integration tools: Do you use them?
[ "", "php", "build", "continuous-integration", "phing", "xinc", "" ]
I have the following table: ``` CREATE TABLE [dbo].[EntityAttributeRelship]( [IdNmb] [int] IDENTITY(1,1) NOT NULL, [EntityIdNmb] [int] NOT NULL, [AttributeIdNmb] [int] NOT NULL, [IsActive] [bit] NOT NULL CONSTRAINT [DF_EntityAttributeRelship_IsActive] DEFAULT ((0)), CONSTRAINT [PK_EntityAttributeRelship] PRIMARY KEY CLUSTERED ([IdNmb] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] ``` A portion of the data in the table looks like something this: ``` IdNmb EntityIdNmb AttributeIdNmb IsActive 1 22 7 0 2 22 8 0 3 22 9 0 4 22 10 1 ``` I want to add a constraint to make sure that no one adds or updates a record to have IsActive = 1, if there is already a record for the EntityIdNmb where IsActive = 1. How do I do this?
If you are using SQLServer you can create a clustered indexed view. ``` CREATE VIEW dbo.VIEW_EntityAttributeRelship WITH SCHEMABINDING AS SELECT EntityIdNmb FROM dbo.EntityAttributeRelship WHERE IsActive = 1 GO CREATE UNIQUE CLUSTERED INDEX UIX_VIEW_ENTITYATTRIBUTERELSHIP ON dbo.VIEW_EntityAttributeRelship (EntityIdNmb) ``` This ensures there's only one EntityIdNmb in your table with IsActive = 1.
Sounds like you need to implement a trigger (assuming your db product supports it). If you only want one active and one inactive entry, a unique index will work. Otherwise, you'll need to write some sort of custom constraint or a trigger (probably 2 - one for inserts, one for updates) that makes sure that you don't have 2 records with the same id where both are active.
How do I create a table constraint to prevent duplicate values across two columns?
[ "", "sql", "constraints", "alter-table", "" ]
I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories. The problem is I'm not replacing in place. I'm opening files, passing the contents into memory, and then overwriting the file, like so: ``` file = open('path/to/file','r') in_string = file.read() file.close() # ... #Processing logic # ... file = open('path/to/file','w') file.write(out_string) file.close() ``` Besides the obvious performance/memory concerns, which are legitimate, but not so much a problem for my use, there's another drawback to this method. SVN freaks out. I can do some copy and paste workarounds after the fact to fix the checksum error that svn throws on a commit, but it makes the utility pointless. Is there a better way to do this? I'm guessing that if I were editing the file in place there wouldn't be any sort of problem. How do I go about that?
I suspect the problem is that you are in fact editing wrong files. Subversion should never raise any errors about check sums when you are just modifying your tracked files -- independently of *how* you are modifying them. Maybe you are accidentally editing files in the `.svn` directory? In `.svn/text-base`, Subversion stores copies of your files using the same name plus the extension `.svn-base`, make sure that you are not editing those!
What do you mean by "SVN freaks out"? Anyway, the way vi/emacs/etc works is as follows: ``` f = open("/path/to/.file.tmp", "w") f.write(out_string) f.close() os.rename("/path/to/.file.tmp", "/path/to/file") ``` (ok, there's actually an "fsync" in there... But I don't know off hand how to do that in Python) The reason it does that copy is to ensure that, if the system dies half way through writing the new file, the old one is still there... And the 'rename' operation is defined as being atomic, so it will either work (you get 100% of the new file) or not work (you get 100% of the old file) -- you'll never be left with a half-file.
File editing in python
[ "", "python", "svn", "" ]
I have the following snippet of Javascript, which is just attaching an onclick to a button and then updating the text of an em tag underneath it. I'm slowly trying to educate myself and work with jQuery more as I've found to like the syntax a lot more and for some tasks, it's more of a pleasure to work with. Some of the best examples I've found have come from Stackoverflow, so I come once again, to see how this could refactored and improved with jQuery; any thoughts? ``` $$('em.green').each(function(em) { em.up('button').onclick = function() { em.update('Saving...') }; }); ``` Thanks!
Here is a line by line translation from your prototype code. Not a lot different: ``` $('em.green').each(function(i, em) { $(em).closest('button').click(function() { $(em).html('Saving...') }) }); ``` IMO the prototype version looks just as nice if not nicer (without `$` sprinkled everywhere).
Try this, little bit shorter: ``` $('button').click(function(i, button) { $(button).closest('em.green').html('Saving...'); }); ``` Saves you from having to loop through every EM and then bind the onclick. Might also help to add a class to the button so you're not binding to every button on the page, just in case there are others.
Can this snippet of Javascript be simplified more with jQuery?
[ "", "javascript", "jquery", "refactoring", "prototypejs", "" ]
I am considering the possibility of designing an application that would allow people to develop C++ code graphically. I was amazed when I discovered Scratch (see [site](http://scratch.mit.edu/) and [tutorial videos](http://info.scratch.mit.edu/Support/Videos)). I believe most of C++ can be represented graphically, with the exceptions of preprocessor instructions and possibly function pointers. What C++ features do you think could be (or not be) represented by graphical items? What would be the pros and cons of such an application ? How much simpler would it be than "plain" C++? **RECAP and MORE:** *Pros:* * intuitive * simple for small applications * helps avoid typos *Cons:* * may become unreadable for large (medium?) - sized applications * manual coding is faster for experienced programmers * C++ is too complicated a language for such an approach Considering that we -at my work- already have quite a bit of existing C++ code, I am not looking for a completely new way of programming. I am considering an alternate way of programming that is fully compatible with legacy code. Some kind of "viral language" that people would use for new code and, hopefully, would eventually use to replace existing code as well (where it could be useful). **How do you feel towards this viral approach?** When it comes to manual vs graphical programming, I tend to agree with your answers. This is why, ideally, I'll find a way to let the user always choose between typing and graphical programming. A line-by-line parser (+partial interpreter) might be able to convert typed code into graphical design. It *is* possible. Let's all cross our fingers. **Are there caveats to providing both typing and graphical programming capabilities that I should think about and analyze carefully?** I have already worked on template classes (and more generally type-level C++) and their graphical representation. See [there](http://www.freeimagehosting.net/image.php?c8e4dc91ae.png) for an example of graphical representation of template classes. Boxes represent classes or class templates. First top node is the class itself, the next ones (if any) are typedef instructions inside the class. Bottom nodes are template arguments. Edges, of course, connect classes to template arguments for instantiations. I already have a prototype for working on such type-level diagrams. **If you feel this way of representing template classes is plain wrong, don't hesitate to say so and why!**
**Writing code** is the easiest part of a developers day. I don't think we need more help with that. Reading, understanding, maintaining, comparing, annotating, documenting, and validating is where - despite a gargantuan amount of tools and frameworks - we still are lacking. --- To dissect your pros: **Intuitive** and **simple for small applications** - replace that with "misleading". It makes it look simple, but it isn't: As long as it is simple, VB.NET is simpler. When it gets complicated, visual design would get in the way. **Help avoid typos** - that's what a good style, consistency and last not least intellisense are for. The things you need anyway when things aren't simple anymore. --- **Wrong level** You are thinking on the wrong level: C++ statements are not reusable, robust components, they are more like a big bag of gears that need to be put together *correctly*. C++ with it's complexity and exceptions (to rules) isn't even particulary suited. If you want to make things easy, you need reusable components at a much higher level. Even if you have these, plugging them together is not simple. Despite years of struggle, and many attempts in many environments, this sometimes works and often fails. --- **Viral** - You are correct IMO about that requriement: allow incremental adoption. This is closely related to switching smoothly between source code and visual representation, which in turn probably means you must be able to generate the visual representation from modified source code. --- **IDE Support** - here's where most language-centered approaches go astray. A modern IDE is more than just a text editor and a compiler. What about debugging your graph - with breakpoints, data inspection etc? Will profilers, leak detectors etc. highlight nodes in your graph? Will source control give me a Visual Diff of yesterday's graph vs. today's? --- Maybe you are on to something, despite all my "no"s: a better way to *visualize* code, a way to put different filters on it so that I see just what I need to see.
Much as I like Scratch, it is still *much* quicker for an experienced programmer to write code using a text editor than it is to drag blocks around, This has been proved time and again with any number of graphical programming environments.
Write C++ in a graphical scratch-like way?
[ "", "c++", "graphical-programming", "" ]
I'm kind of new to JavaScript and jQuery and now I'm facing a problem: I need to post some data to PHP and one bit of the data needs to be the background color hex of div X. jQuery has the css("background-color") function and with it I can get RGB value of the background into a JavaScript variable. The CSS function seems to return a string like this rgb(0, 70, 255). I couldn't find any way to get hex of the background-color (even though it's set as hex in CSS). So it seems like I need to convert it. I found a function for converting RGB to hex, but it needs to be called with three different variables, r, g and b. So I would need to parse the string rgb(x,xx,xxx) into var r=x; var g=xx; var b=xxx; somehow. I tried to google parsing strings with JavaScript, but I didn't really understand the regular expressions thing. Is there a way to get the background-color of div as hex, or can the string be converted into 3 different variables?
try this out: ``` var rgbString = "rgb(0, 70, 255)"; // get this in whatever way. var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); // parts now should be ["rgb(0, 70, 255", "0", "70", "255"] delete (parts[0]); for (var i = 1; i <= 3; ++i) { parts[i] = parseInt(parts[i]).toString(16); if (parts[i].length == 1) parts[i] = '0' + parts[i]; } var hexString ='#'+parts.join('').toUpperCase(); // "#0070FF" ``` In response to the question in the comments below: > I'm trying to modify the regex to handle both rgb and rgba depending which one I get. Any hints? Thanks. I'm not exactly sure if it makes sense in the context of this question (since you can't represent an rgba color in hex), but I guess there could be other uses. Anyway, you could change the regex to be like this: ``` /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0\.\d+))?\)$/ ``` Example output: ``` var d = document.createElement('div'); d.style.backgroundColor = 'rgba( 255, 60, 50, 0)'; /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0\.\d+))?\)$/.exec(d.style.backgroundColor); // ["rgba(255, 60, 50, 0.33)", "255", "60", "50", "0.33"] ```
If you have jQuery available, this is the super-compact version that I just came up with. ``` var RGBtoHEX = function(color) { return "#"+$.map(color.match(/\b(\d+)\b/g),function(digit){ return ('0' + parseInt(digit).toString(16)).slice(-2) }).join(''); }; ```
Background-color hex to JavaScript variable
[ "", "javascript", "jquery", "hex", "rgb", "background-color", "" ]
I understand pointers and the rare need to use them in C# code. My question is: what is the reasoning behind having to explicitly state "unsafe" in a block of code. Additionally, why must a compiler option be changed to allow "unsafe" code? **Bottom Line:** What in the CLR (or language specs) makes it so we can't just use pointers whenever we want (much like C and C++) without having to type "unsafe" and change the compiler option? *For clarification: I know what "unsafe" and "safe" code is. It's just a question of why must we do all the extra work (ok, not THAT much extra) just to be able to use these features.*
There's an interview with C# Creator Anders Hejlsberg that touches on the subject [here](http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/hejlsberg_0800.html). Basically, exactly what @Marc Gravell said: typesafety first, unsafety by explicit declaration. So to answer your question: nothing in the CLR prevents it; it's a language idiom designed to allow you to work with safety gloves when dealing with types. If you want to take the gloves off, it's your choice, but you have to make the active choice to take the gloves off. **Edit:** > *For clarification: I know what > "unsafe" and "safe" code is. It's just > a question of why must we do all the > extra work (ok, not THAT much extra) > just to be able to use these features.* As mentioned in the interview I linked, it was an explicit design decision. C# is essentially an evolution of Java and in Java, you don't have pointers at all. But the designers wanted to allow pointers; however because C# would typically be bringing in Java developers, they felt it would be best if the **default** behavior be similar to Java, i.e. no pointers, while still allowing the use of pointers by explicit declaration. So the "extra work" is deliberate to force you to think about what you are doing before you do it. By being explicit, it forces you to at least consider: "Why am I doing this? Do I **really** need a pointer when a reference type will suffice?"
It is largely about being verifiable. By stating `unsafe`, the gloves are off - the system can no longer guarantee that your code won't run amok. In most cases it is highly desirable to stay in the safe zone. This gets more noticeable with partial trust (addins etc), but is still valuable in regular code.
C#: Benefit of explicitly stating "unsafe" / compiler option
[ "", "c#", "pointers", "unsafe", "compiler-options", "" ]
I'm having some serious problems with the PHP Data Object functions. I'm trying to loop through a sizeable result set (~60k rows, ~1gig) using a buffered query to avoid fetching the whole set. No matter what I do, the script just hangs on the PDO::query() - it seems the query is running unbuffered (why else would the change in result set size 'fix' the issue?). Here is my code to reproduce the problem: ``` <?php $Database = new PDO( 'mysql:host=localhost;port=3306;dbname=mydatabase', 'root', '', array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true ) ); $rQuery = $Database->query('SELECT id FROM mytable'); // This is never reached because the result set is too large echo 'Made it through.'; foreach($rQuery as $aRow) { print_r($aRow); } ?> ``` If I limit the query with some reasonable number, it works fine: ``` $rQuery = $Database->query('SELECT id FROM mytable LIMIT 10'); ``` I have tried playing with PDO::MYSQL\_ATTR\_MAX\_BUFFER\_SIZE and using the PDO::prepare() and PDO::execute() as well (though there are no parameters in the above query), both to no avail. Any help would be appreciated.
If I understand this right, buffered queries involve telling PHP that you want to wait for the entire result set before you begin processing. Prior to PDO, this was the default and you had to call [`mysql_unbuffered_query`](http://us.php.net/manual/en/function.mysql-unbuffered-query.php) if you wanted to deal with results immediately. Why this isn't explained on the PDO MySQL driver page, I don't know.
You could try to split it up into chunks that aren't big enough to cause problems: ``` <?php $id = 0; $rQuery = $Database->query('SELECT id FROM mytable ORDER BY id ASC LIMIT 100'); do { stuff($rQuery); $id += 100; } while ( $rQuery = $Database->query( 'SELECT id FROM mytable ORDER BY id ASC LIMIT 100 OFFSET '.$id ) ); ?> ``` ...you get the idea, anyway.
PHP PDO Buffered query problem
[ "", "php", "mysql", "pdo", "" ]
I have a timer on a windows form (C# 3.0, .net 3.5 SP1, VS2008 SP1, Vista) that seems to work even after it is stoppped. The code is: ``` using System; using System.Windows.Forms; namespace TestTimer { public partial class Form1 : Form { public Form1() { InitializeComponent(); StartTimer(); } private DateTime deadline; private void StartTimer() { deadline = DateTime.Now.AddSeconds(4); timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { int secondsRemaining = (deadline - DateTime.Now).Seconds; if (secondsRemaining <= 0) { timer1.Stop(); timer1.Enabled = false; MessageBox.Show("too slow..."); } else { label1.Text = "Remaining: " + secondsRemaining.ToString() + (secondsRemaining > 1 ? " seconds" : " second"); } } } } ``` Even after the timer1.Stop() is called, I keep reeciving MessageBoxes on the screen. When I press esc, it stops. Howevere, I've expected that only one message box appears... What else should I do? adding timer1.Enabled = false does not change the behavior. Thanks
I could be wrong, but is MessageBox.Show() a blocking operation (that waits for you to dismiss the dialog)? If so, just move the Show() call to after the Stop/Enabled lines?
A couple of factors may be at work here. The modal MessageBox.Show() could prevent the timer stop from taking effect until it is dismissed (as Brian pointed out). The timer1\_Tick could be executing on a background thread. UI calls such as MessageBox.Show() and background threads to not mix. Both issues can be solved by using BeginInvoke to call a method that shows the message box.
Timer cannot be stopped in C#
[ "", "c#", ".net", "winforms", "timer", "" ]
Essentially its a pacman clone game I'm working on. I have an Enemy class, and 4 instances of this class created which all represent 4 ghosts of the game. All ghosts start up in random areas of the screen and then they have to work their way towards the pacman character. As the player controls the pacman, moving it around, they should follow it and take the nearest possible way towards him. There is no maze/obstacles (yet) so the entire map (400x400 pixels) is open ground to them. For the player and each Ghost, i can retrieve the X, Y, image width and height attributes. Also, i already have a collision detection algorithm, so not worried about that, just about the ghosts finding their way to pacman.
For a good pathfinding algorithm, using [A\*](http://en.wikipedia.org/wiki/A*_search_algorithm) would probably be a good idea, however, for a simple game that doesn't require sophisticated, efficient, nor effective path searching, simply having the characters move toward a target by finding out the direction of the target should be sufficient. For example, the decision to make the character move, in pseudocode: ``` if (target is to the left of me): move(left); else move(right); if (target is above me): move(up); else move(down); ``` Yes, the character is not going to make the most efficient movement, but it will get closer and closer to the target on each iteration of the game loop. It's also my guess that an arcade game from the early 80's probably wouldn't be using sophisticated pathfinding algorithms.
If you just have a grid of pixels - an "big field" on which pacman and ghost can move about freely - then the shortest path is easy - a straight line between the ghost and the pacman. But "shortest path" invariably means we're trying to solve a graph-theory problem. (I'm assuming knowledge of graphs, some graph theory, adj. matrices, etc!) In the case above, consider each pixel to be a node on a graph. Each node is connected to its neighbors by an edge, and each edge has equal "weight" (moving to the node on "above" is no slower than moving to the node "below"). So you have this: ("\*" = node, "-, /, \, |" = edge) ``` *-*-* |\|/| *-*-* ... (etc) |/|\| *-*-* ``` If Pacman is in the center, it can move to any other node very easily. Something more closer to reality might be this: ``` *-*-* | | | *-*-* ... (etc) | | | *-*-* ``` Now, pacman cannot move diagonally. To go from the center to the bottom-right requires 2 "hops" rather than one. To continue the progression: ``` *-*-*-* | | | | | | | | | | | | *-*-*-* | | | | *-*-*-* ``` Now, to go from a node in the middle to a node at the top, you need 3 hops. However, to move toward the bottom only takes 1 hop. It would be easy to translate any game-board setup into a graph. Each "intersection" is a node. The path between two intersections is an edge, and the length of that path is the weight of that edge. Enter A\*. By constructing a graph (use an adjency matrix or a list of nodes), you can use the A\* algorithm to find the shortest path. Other algorithms include Dijkstra's. And many others! But first you need to frame your problem in terms of a graph, and then toy with how you'd go from node A (pacman) to node B (ghost). Hope that helps!
Path finding in a Java 2d Game?
[ "", "java", "algorithm", "pseudocode", "path-finding", "" ]
It doesn't seem like there is an obvious to implement databinding using jQuery or any other javascript framwork. I'm wondering if anyone has implemented databinding using jQuery in the same vein as WPF databinding, or even your standard databinding scenario (fill a table with the results of this resource).
This seems to fit the bill: <http://knockoutjs.com/>
Looks like Microsoft has this in the works for .NET 4.0 as part of the ASP.NET AJAX 4.0 functionality. There is a community technology preview for this on [codeplex](http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24645) that is compatible with .NET 3.5. Looks very slick and WPF-life - allowing developers to leverage all that Silverlight/WPF knowledge about databinding and generalizing that to client side javascript databinding.
What is the best way to implement data binding with a web application?
[ "", "javascript", "html", "data-binding", "" ]
What are your methods of linking data spread over multiple databases architectures (think MySQL vs PostgreSQL etc), into a single application? Would you create giant hashtables/arrays to match content against one another? Are there other, more effective and less memory-consuming options for doing this? If you were to use data both from a MySQL & PostgreSQL source, with no way of converting one DB to the other (application constraints, lack of time, lack of knowledge, ... ), how would you go about it?
At least in the case of MySQL, you can use data from multiple databases in a single query anyway, provided the databases are hosted by the same MySQL Server instance. You can distinguish tables from different databases by qualifying the table with a schema name: ``` CREATE TABLE test.foo (id SERIAL PRIMARY KEY) TYPE=InnoDB; CREATE DATABASE test2; CREATE TABLE test2.bar (foo_id BIGINT UNSIGNED, FOREIGN KEY (foo_id) REFERENCES test.foo(id)) TYPE=InnoDB; SELECT * FROM test.foo f JOIN test2.bar b ON (f.id = b.foo_id); ``` In PostgreSQL, you can also qualify table references with a schema name. I'm not sure if you can create foreign key constraints across databases, though.
SQL Relay or another sql proxy. <http://sqlrelay.sourceforge.net/>
Linking multi-database information
[ "", "php", "mysql", "database", "database-connection", "" ]
this is a "hard" question. I've found nothing interesting over the web. I'm developing a Memory Management module for my company. We develop games for next-gen consoles (Xbox 360, PS3 and PC... we consider PC a console!). We'll need in future, for our next games, to handle texture streaming for large game worlds that cannot be loaded all in main console memory (not talking about PC for now). We are going to stream at the beginning hi-res mipmaps of textures (that is about 70% of the size of world data). Maybe in the future we'll have to stream also geometry, smaller mipmaps, audio, etc. I'm developing a Memory Manager for that issue, focused on X360 (because over PS3 we can use host memory and the associated, auto-defragmenting GMM allocator). The problem I'm facing is the following: We have decided to reserve a specific Memory Area for texture streaming (for example 64 Megabytes) and we want to handle all allocations and deallocations in that area. We have allocated the area at the beginning of the application and the area is Physically guaranteed to be contiguous (not just virtually, cause we need to store textures there). I've implemented an auto defragmenting allocator, using handles instead of pointers. Time is not an issue, the problem is memory fragmentation. In game we continuously load and unload streaming targets, so we'd like to use the maximum amount of our buffer (64 Megabytes). With this allocator we can use all of the allocated space but the defragmentation routine works in an unaccettable time (sometimes 60 milliseconds, more than a frames!) while the algorithm is not too bad... there are just too meny unevitable memcpy! I'm looking for a solution to solve this issue. I'd like to find at least a good paper, or a post-mortem, or someone who have faced the same problem of mine. Now I'm choosing between two strategies: 1) move the defragmentation routine on a dedicated thread (good for X360 with 6 hw threads, bad for PS3 with just a hw thread... and don't tell me to use SPU's!) with all multithreading problems of locking regions, of accessing a region who is being moved,... 2) find an "incremental" solution to defragmentation problem: we can give each frame a time budget (for example up to 1 millisecond) for defragmentation and the Memory Manager will do what it can do in the budget each frame. Can someone tell me his experience about?
I did a lot of study recently regarding memory management and this is the most informative and helpful article I found on the net. <http://www.ibm.com/developerworks/linux/library/l-memory/> Based on that paper the best and fastest result you will get is to divide your 64 MB into equal sized chunks. The size of chunks will depend on your object size. And allocate or deallocate a full chunk at a time. It's 1. Faster than incremental garbage collection. 2. Simpler. 3. And solves that "too much fragmantation" problem by some amount. Read it, you will find excellent information on every possible solution there is and merits and demerits for each.
Why not use multiple memory areas for the streamed textures and pool by texture size? Insomniac has a paper about their texture streaming implementation on PS3. I suppose it could be helpful: [link](http://www.insomniacgames.com/tech/articles/1107/texture_streaming.php). For general allocation strategies to minimize fragmentation, maybe [Doug Lea](http://g.oswego.edu/dl/html/malloc.html) can help. But from my reading of your question, it sounds like you're overthinking it and I highly recommend a pooled approach. (Also running a defragment pass on write-combined memory doesn't sound particularly safe or fun.)
C++ Memory Management for Texture Streaming in Videogames
[ "", "c++", "memory-management", "defragmentation", "" ]
I want to create a floor plan map of an interior space that has clickable regions. My first thought was to investigate GeoDjango since its *the* mapping app for Django. But considering the dependencies, the learning curve and overall complexity, I'm concerned that I may be trying to swat a fly with a bazooka. Should I use GeoDjango for this, or should I just store integer lists in a database field? **EDIT:** The floor plan would be fairly simple; a collection of walls and workstations with the ability to define regions for how much space the workstation occupies, thus allowing offices to be defined as well as open plan layouts.
I'd say that using GeoDjango for this purpose is definitely overkill. It could be implemented simply with an image map, or Canvas/SVG or Flash for extra pretty-points :)
IMHO using GeoDjango for a floor plan isn't a bad idea. But if your data does not change much and the amount of data (rooms, areas, workstation, ...) isn't very large, then you might not need a database and a full GeoDjango stack. A simpler solution would be using [OpenLayers](http://www.openlayers.org) directly with an image of the a (maybe scanned) floor plan as background layer. OpenLayers lets you also define region and points (markers) which handle "mouse over" or click events. An example of using OpenLayers for a floor plan is [Office Plans via Open Layers](http://www.laudontech.com/openlayers/openlayersv1.php5).
Should I use GeoDjango for mapping a floor plan?
[ "", "python", "django", "mapping", "geodjango", "" ]
My JS code includes some images that are empty at the beginning (without src attribute specified at all + display:none). When added to sites with CSS1 compatibility I see broken image icon where the image should be even though **the images are supposed not to be displayed** (display:none). Any idea how I can hide the broken image icons? Notes: I don't want to load empty images. I tried width and height= 1px or 0px . didn't work. specifying src="" also gives empty image icons. Edit: I found the solution: add style="display:none" to the img definition (Not in CSS)
Have you tried wrapping the images inside a div and hiding the div instead?
The solution is quite simple: add style="display:none" to the img definition (Not in CSS)
How to hide img elements that do not have src attribute, until the attribute is added?
[ "", "javascript", "image", "src", "" ]
I have a 2D array of doubles in Java which is basically a table of values and I want to find out how many rows it has... It is declared elsewhere (and allocated) like this: ``` double[][] table; ``` then passed to a function... ``` private void doSomething(double[][] table) { } ``` In my function I want to know the length of each dimension without having to pass them around as arguments. I can do this for the number of columns but don't know how to do it for the rows... ``` int cols = table[0].length; int rows = ?; ``` How do I do that? Can I just say... ``` int rows = table.length; ``` Why would that not give rows x cols?
In Java a 2D array is nothing more than an array of arrays. This means that you can easily get the number of rows like this: ``` int rows = array.length; ``` This also means that each row in such an array *can* have a different amount of elements (i.e. each row can have a varying number of columns). ``` int columnsInFirstRow = array[0].length; ``` This will only give you the number of columns in the first row, but the second row could have more or less columns than that. You could specify that your method only takes rectangular arrays and *assume* that each row has the same number of columns than the first one. But in that case I'd wrap the 2D-array in some Matrix class (that you might have to write). This kind of array is called a [Jagged Array](http://xahlee.info/java-a-day/arrays2.html).
Look [at this example](http://leepoint.net/notes-java/data/arrays/arrays-2D-2.html). They use .length there to get the row count, [].length to get the column count. It's because the array consists of "row" pointers and these could lead anywhere, so you have to use .length for each column to get the sizes of these arrays, too.
Java native array lengths
[ "", "java", "arrays", "" ]
I'm looking at the source code for a server using SocketAsyncEventArgs, and I'm trying to figure out how this wouldn't cause a stack overflow: So this code is called to allow the socket to accept an incoming connection (scroll down to the bottom to see what I mean): ``` /// <summary> /// Begins an operation to accept a connection request from the client. /// </summary> /// <param name="acceptEventArg">The context object to use when issuing /// the accept operation on the server's listening socket.</param> private void StartAccept(SocketAsyncEventArgs acceptEventArg) { if (acceptEventArg == null) { acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted); } else { // Socket must be cleared since the context object is being reused. acceptEventArg.AcceptSocket = null; } this.semaphoreAcceptedClients.WaitOne(); Boolean willRaiseEvent = this.listenSocket.AcceptAsync(acceptEventArg); if (!willRaiseEvent) { this.ProcessAccept(acceptEventArg); } } ``` Then this code gets called once a connection is actually accepted (see last line): ``` /// <summary> /// Process the accept for the socket listener. /// </summary> /// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param> private void ProcessAccept(SocketAsyncEventArgs e) { if (e.BytesTransferred > 0) { Interlocked.Increment(ref this.numConnectedSockets); Console.WriteLine("Client connection accepted. There are {0} clients connected to the server", this.numConnectedSockets); } // Get the socket for the accepted client connection and put it into the // ReadEventArg object user token. SocketAsyncEventArgs readEventArgs = this.readWritePool.Pop(); readEventArgs.UserToken = e.AcceptSocket; // As soon as the client is connected, post a receive to the connection. Boolean willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs); if (!willRaiseEvent) { this.ProcessReceive(readEventArgs); } // Accept the next connection request. this.StartAccept(e); // <==== tail end recursive? } ``` Look at the last line. It calls the top function again. How does this not overflow the stack by ping-ponging back and forth between these 2 functions? It seems to be tail end recursion, but this isn't Haskell so I don't see how this would work. It was my understanding that these weren't fired in threads but where just executed one at a time by the cpu.
If the AsyncAccept (or any AsyncXXX operation for that matter) cannot be satisfied immediately, then it will return true, indicating that the operation will complete asynchronously. When this happens, the callback-event will ultimately fire on a thread-pool thread. Even if it marshal's back to a UI thread (because it was initiated there), it will do so via a post. AsyncAccept is *highly* likely to return true, because unless there are socket connections truly pending (see backlog in [Listen](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.listen.aspx)), you are waiting for a client to connect. Hence, StartAccept() will simply exit without calling ProcessAccept, and ProcessAccept when (and if) it fires, will probably be on a different thread.
Look at the code: ``` if (!willRaiseEvent) { this.ProcessAccept(acceptEventArg); } ``` Although I don't yet understand the whole mechanism, willRaiseEvent == true will clearly end the recursion, so I guess this happens so it's not endless recursion.
How does this not cause a stack overflow?
[ "", "c#", "" ]
I have a ComboBox in WPF whose ItemsSource is set to a list programmatically. How would I go about clearing the selection in an event handler? I've tried: ``` comboBox.SelectedIndex = -1; comboBox.SelectedItem = null; comboBox.SelectedValue = null; comboBox.SelectedValue = ""; ``` None of them have any effect.
`comboBox.SelectedIndex = -1;` works for me. Are you doing anything else in your event handler? Are you using databinding?
``` comboBox.SelectedIndex = -1; ``` Is the way to go. I don't know why it doesn't work for you; perhaps an event handler for `SelectedIndexChanged` changes the value?
Programmatically Clear Selection in WPF ComboBox
[ "", "c#", "wpf", "" ]
In a c# threading app, if I were to lock an object, let us say a queue, and if an exception occurs, will the object stay locked? Here is the pseudo-code: ``` int ii; lock(MyQueue) { MyClass LclClass = (MyClass)MyQueue.Dequeue(); try { ii = int.parse(LclClass.SomeString); } catch { MessageBox.Show("Error parsing string"); } } ``` As I understand it, code after the catch doesn't execute - but I have been wondering if the lock will be freed.
First; have you considered TryParse? ``` in li; if(int.TryParse(LclClass.SomeString, out li)) { // li is now assigned } else { // input string is dodgy } ``` The lock will be released for 2 reasons; first, `lock` is essentially: ``` Monitor.Enter(lockObj); try { // ... } finally { Monitor.Exit(lockObj); } ``` Second; you catch and don't re-throw the inner exception, so the `lock` never actually sees an exception. Of course, you are holding the lock for the duration of a MessageBox, which might be a problem. So it will be released in all but the most fatal catastrophic unrecoverable exceptions.
I note that no one has mentioned in their answers to this old question that *releasing a lock upon an exception is an incredibly dangerous thing to do.* Yes, lock statements in C# have "finally" semantics; when control exits the lock normally or abnormally, the lock is released. You're all talking about this like it is a good thing, but it is a bad thing! The right thing to do if you have a locked region that throws an unhandled exception is to *terminate the diseased process immediately before it destroys more user data*, not *free the lock and keep on going*. Look at it this way: suppose you have a bathroom with a lock on the door and a line of people waiting outside. A bomb in the bathroom goes off, killing the person in there. Your question is "in that situation will the lock be automatically unlocked so the next person can get into the bathroom?" Yes, it will. **That is not a good thing.** A bomb just went off in there and killed someone! The plumbing is probably destroyed, the house is no longer structurally sound, and *there might be another bomb in there*. The right thing to do is *get everyone out as quickly as possible and demolish the entire house.* I mean, think it through: if you locked a region of code in order to read from a data structure without it being mutated on another thread, and something in that data structure threw an exception, *odds are good that it is because the data structure is corrupt*. User data is now messed up; you don't want to *try to save user data* at this point because you are then saving *corrupt* data. Just terminate the process. If you locked a region of code in order to perform a mutation without another thread reading the state at the same time, and the mutation throws, then **if the data was not corrupt before, it sure is now**. Which is exactly the scenario that the lock is supposed to *protect against*. Now code that is waiting to read that state will *immediately* be given access to corrupt state, and probably itself crash. Again, the right thing to do is to terminate the process. No matter how you slice it, an exception inside a lock is *bad news*. The right question to ask is not "will my lock be cleaned up in the event of an exception?" The right question to ask is "how do I ensure that there is never an exception inside a lock? And if there is, then how do I structure my program so that mutations are rolled back to previous good states?"
Does a locked object stay locked if an exception occurs inside it?
[ "", "c#", ".net", "multithreading", "exception", "locking", "" ]
I am using Stackdumps with Win32, to write all return adresses into my logfile. I match these with a mapfile later on (see my article [Post Mortem Debugging][1]). **EDIT:: Problem solved - see my own answer below.** With Windows x64 i do not find a reliable way to write only the return adresses into the logfile. I tried several ways: **Trial 1: Pointer Arithmetic:** ``` CONTEXT Context; RtlCaptureContext(&Context); char *eNextBP = (char *)Context.Rdi; for(ULONG Frame = 0; eNextBP ; Frame++) { char *pBP = eNextBP; eNextBP = *(char **)pBP; // Next BP in Stack fprintf(LogFile, "*** %2d called from %016LX (pBP at %016LX)\n", Frame, (ULONG64)*(char **)(pBP + 8), (ULONG64)pBP); } ``` This works fine in the debug version - but it crashes in the release version. The value of Context.Rdi has no usable value there. I did check for differences in the compiler settings (visual Studio 2005). I have not found anything suspicious. **Trial 2: Using StackWalk64** ``` RtlCaptureContext(&Context); STACKFRAME64 stk; memset(&stk, 0, sizeof(stk)); stk.AddrPC.Offset = Context.Rip; stk.AddrPC.Mode = AddrModeFlat; stk.AddrStack.Offset = Context.Rsp; stk.AddrStack.Mode = AddrModeFlat; stk.AddrFrame.Offset = Context.Rbp; stk.AddrFrame.Mode = AddrModeFlat; for(ULONG Frame = 0; ; Frame++) { BOOL result = StackWalk64( IMAGE_FILE_MACHINE_AMD64, // __in DWORD MachineType, GetCurrentProcess(), // __in HANDLE hProcess, GetCurrentThread(), // __in HANDLE hThread, &stk, // __inout LP STACKFRAME64 StackFrame, &Context, // __inout PVOID ContextRecord, NULL, // __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, SymFunctionTableAccess64, // __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, SymGetModuleBase64, // __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, NULL // __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress ); fprintf(gApplSetup.TraceFile, "*** %2d called from %016LX STACK %016LX FRAME %016LX\n", Frame, (ULONG64)stk.AddrPC.Offset, (ULONG64)stk.AddrStack.Offset, (ULONG64)stk.AddrFrame.Offset); if(! result) break; } ``` This does not only dump the return addresses, but the WHOLE STACK. I receive about 1000 lines in my log file using this approach. I can use this, but i have to search trough the lines and some data of the stacks happens to be a valid code address. **Trial 3: Using Backtrace** ``` static USHORT (WINAPI *s_pfnCaptureStackBackTrace)(ULONG, ULONG, PVOID*, PULONG) = 0; if (s_pfnCaptureStackBackTrace == 0) { const HMODULE hNtDll = ::GetModuleHandle("ntdll.dll"); reinterpret_cast<void*&>(s_pfnCaptureStackBackTrace) = ::GetProcAddress(hNtDll, "RtlCaptureStackBackTrace"); } PVOID myFrames[128]; s_pfnCaptureStackBackTrace(0, 128, myFrames, NULL); for(int ndx = 0; ndx < 128; ndx++) fprintf(gApplSetup.TraceFile, "*** BackTrace %3d %016LX\n", ndx, (ULONG64)myFrames[ndx]); ``` Results in no usable information. Has anyone implemented such a stack walk in x64 that does only write out the return adresses in the stack? Ive seen the approaches [StackTrace64][2], [StackWalker][3] and other ones. They either do not compile or they are much too much comlicated. It basically is a simple task! **Sample StackDump64.cpp** ``` #include <Windows.h> #include <DbgHelp.h> #include <Winbase.h> #include <stdio.h> void WriteStackDump() { FILE *myFile = fopen("StackDump64.log", "w+t"); CONTEXT Context; memset(&Context, 0, sizeof(Context)); RtlCaptureContext(&Context); RtlCaptureContext(&Context); STACKFRAME64 stk; memset(&stk, 0, sizeof(stk)); stk.AddrPC.Offset = Context.Rip; stk.AddrPC.Mode = AddrModeFlat; stk.AddrStack.Offset = Context.Rsp; stk.AddrStack.Mode = AddrModeFlat; stk.AddrFrame.Offset = Context.Rbp; stk.AddrFrame.Mode = AddrModeFlat; for(ULONG Frame = 0; ; Frame++) { BOOL result = StackWalk64( IMAGE_FILE_MACHINE_AMD64, // __in DWORD MachineType, GetCurrentProcess(), // __in HANDLE hProcess, GetCurrentThread(), // __in HANDLE hThread, &stk, // __inout LP STACKFRAME64 StackFrame, &Context, // __inout PVOID ContextRecord, NULL, // __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, SymFunctionTableAccess64, // __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, SymGetModuleBase64, // __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, NULL // __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress ); fprintf(myFile, "*** %2d called from %016I64LX STACK %016I64LX AddrReturn %016I64LX\n", Frame, stk.AddrPC.Offset, stk.AddrStack.Offset, stk.AddrReturn.Offset); if(! result) break; } fclose(myFile); } void funcC() { WriteStackDump(); } void funcB() { funcC(); } void funcA() { funcB(); } int main(int argc, char *argv[]) { funcA(); } ``` Running this sample results in the follwing log file content: ``` *** 0 called from 000000014000109E STACK 000000000012F780 AddrReturn 0000000140005798 *** 1 called from 000000001033D160 STACK 000000000012F788 AddrReturn 00000001400057B0 *** 2 called from 00000001400057B0 STACK 000000000012F790 AddrReturn 0000000000000001 *** 3 called from 0000000000000002 STACK 000000000012F798 AddrReturn 00000001400057B0 *** 4 called from 0000000000000002 STACK 000000000012F7A0 AddrReturn 000000000012F7F0 *** 5 called from 000000000012F7F0 STACK 000000000012F7A8 AddrReturn 0000000000000000 *** 6 called from 0000000000000000 STACK 000000000012F7B0 AddrReturn 000007FF7250CF40 *** 7 called from 000007FF7250CF40 STACK 000000000012F7B8 AddrReturn 000007FF7250D390 *** 8 called from 000007FF7250D390 STACK 000000000012F7C0 AddrReturn 000007FF725B6950 *** 9 called from 000007FF725B6950 STACK 000000000012F7C8 AddrReturn CCCCCCCCCCCCCCCC *** 10 called from CCCCCCCCCCCCCCCC STACK 000000000012F7D0 AddrReturn 000000001033D160 *** 11 called from 000000001033D160 STACK 000000000012F7D8 AddrReturn CCCCCCCCCCCCCCCC *** 12 called from CCCCCCCCCCCCCCCC STACK 000000000012F7E0 AddrReturn CCCCCCCCCCCCCCCC *** 13 called from CCCCCCCCCCCCCCCC STACK 000000000012F7E8 AddrReturn CCCCCCCCCCCCCCCC *** 14 called from CCCCCCCCCCCCCCCC STACK 000000000012F7F0 AddrReturn 0000000000000000 *** 15 called from 0000000000000000 STACK 000000000012F7F8 AddrReturn 0000000000000000 *** 16 called from 0000000000000000 STACK 000000000012F800 AddrReturn 0000000000000000 *** 17 called from 0000000000000000 STACK 000000000012F808 AddrReturn 0000000000000000 *** 18 called from 0000000000000000 STACK 000000000012F810 AddrReturn 0000000000000000 *** 19 called from 0000000000000000 STACK 000000000012F818 AddrReturn 0000000000000000 *** 20 called from 0000000000000000 STACK 000000000012F820 AddrReturn 00001F800010000F *** 21 called from 00001F800010000F STACK 000000000012F828 AddrReturn 0053002B002B0033 *** 22 called from 0053002B002B0033 STACK 000000000012F830 AddrReturn 00000206002B002B *** 23 called from 00000206002B002B STACK 000000000012F838 AddrReturn 0000000000000000 *** 24 called from 0000000000000000 STACK 000000000012F840 AddrReturn 0000000000000000 *** 25 called from 0000000000000000 STACK 000000000012F848 AddrReturn 0000000000000000 *** 26 called from 0000000000000000 STACK 000000000012F850 AddrReturn 0000000000000000 *** 27 called from 0000000000000000 STACK 000000000012F858 AddrReturn 0000000000000000 *** 28 called from 0000000000000000 STACK 000000000012F860 AddrReturn 0000000000000000 *** 29 called from 0000000000000000 STACK 000000000012F868 AddrReturn 0000000000000246 *** 30 called from 0000000000000246 STACK 000000000012F870 AddrReturn 000000000012F7F0 *** 31 called from 000000000012F7F0 STACK 000000000012F878 AddrReturn 0000000000000000 *** 32 called from 0000000000000000 STACK 000000000012F880 AddrReturn 0000000000000000 *** 33 called from 0000000000000000 STACK 000000000012F888 AddrReturn 000000000012F888 *** 34 called from 000000000012F888 STACK 000000000012F890 AddrReturn 0000000000000000 *** 35 called from 0000000000000000 STACK 000000000012F898 AddrReturn 0000000000000000 *** 36 called from 0000000000000000 STACK 000000000012F8A0 AddrReturn 000000000012FE10 *** 37 called from 000000000012FE10 STACK 000000000012F8A8 AddrReturn 0000000000000000 *** 38 called from 0000000000000000 STACK 000000000012F8B0 AddrReturn 0000000000000000 *** 39 called from 0000000000000000 STACK 000000000012F8B8 AddrReturn 0000000000000000 *** 40 called from 0000000000000000 STACK 000000000012F8C0 AddrReturn 0000000000000246 *** 41 called from 0000000000000246 STACK 000000000012F8C8 AddrReturn 0000000000000000 *** 42 called from 0000000000000000 STACK 000000000012F8D0 AddrReturn 0000000000000000 *** 43 called from 0000000000000000 STACK 000000000012F8D8 AddrReturn 0000000000000000 *** 44 called from 0000000000000000 STACK 000000000012F8E0 AddrReturn 0000000000000000 *** 45 called from 0000000000000000 STACK 000000000012F8E8 AddrReturn 0000000000000000 *** 46 called from 0000000000000000 STACK 000000000012F8F0 AddrReturn 000000000000027F *** 47 called from 000000000000027F STACK 000000000012F8F8 AddrReturn 0000000000000000 *** 48 called from 0000000000000000 STACK 000000000012F900 AddrReturn 0000000000000000 *** 49 called from 0000000000000000 STACK 000000000012F908 AddrReturn 0000FFFF00001F80 *** 50 called from 0000FFFF00001F80 STACK 000000000012F910 AddrReturn 0000000000000000 *** 51 called from 0000000000000000 STACK 000000000012F918 AddrReturn 0000000000000000 *** 52 called from 0000000000000000 STACK 000000000012F920 AddrReturn 0000000000000000 *** 53 called from 0000000000000000 STACK 000000000012F928 AddrReturn 0000000000000000 *** 54 called from 0000000000000000 STACK 000000000012F930 AddrReturn 0000000000000000 *** 55 called from 0000000000000000 STACK 000000000012F938 AddrReturn 0000000000000000 *** 56 called from 0000000000000000 STACK 000000000012F940 AddrReturn 0000000000000000 *** 57 called from 0000000000000000 STACK 000000000012F948 AddrReturn 0000000000000000 *** 58 called from 0000000000000000 STACK 000000000012F950 AddrReturn 0000000000000000 *** 59 called from 0000000000000000 STACK 000000000012F958 AddrReturn 0000000000000000 *** 60 called from 0000000000000000 STACK 000000000012F960 AddrReturn 0000000000000000 *** 61 called from 0000000000000000 STACK 000000000012F968 AddrReturn 0000000000000000 *** 62 called from 0000000000000000 STACK 000000000012F970 AddrReturn 0000000000000000 *** 63 called from 0000000000000000 STACK 000000000012F978 AddrReturn 0000000000000000 *** 64 called from 0000000000000000 STACK 000000000012F980 AddrReturn 0000000000000000 *** 65 called from 0000000000000000 STACK 000000000012F988 AddrReturn 0000000000000000 *** 66 called from 0000000000000000 STACK 000000000012F990 AddrReturn 0000000000000000 *** 67 called from 0000000000000000 STACK 000000000012F998 AddrReturn 0000000000000000 *** 68 called from 0000000000000000 STACK 000000000012F9A0 AddrReturn 0000000000000000 *** 69 called from 0000000000000000 STACK 000000000012F9A8 AddrReturn 0000000000000000 *** 70 called from 0000000000000000 STACK 000000000012F9B0 AddrReturn 0000000000000000 *** 71 called from 0000000000000000 STACK 000000000012F9B8 AddrReturn 0000000000000000 *** 72 called from 0000000000000000 STACK 000000000012F9C0 AddrReturn 0000000000000000 *** 73 called from 0000000000000000 STACK 000000000012F9C8 AddrReturn 0000000000000000 *** 74 called from 0000000000000000 STACK 000000000012F9D0 AddrReturn 0000000000000000 *** 75 called from 0000000000000000 STACK 000000000012F9D8 AddrReturn 0000000000000000 *** 76 called from 0000000000000000 STACK 000000000012F9E0 AddrReturn 0000000000000000 *** 77 called from 0000000000000000 STACK 000000000012F9E8 AddrReturn 0000000000000000 *** 78 called from 0000000000000000 STACK 000000000012F9F0 AddrReturn 0000000000000000 *** 79 called from 0000000000000000 STACK 000000000012F9F8 AddrReturn 0000000000000000 *** 80 called from 0000000000000000 STACK 000000000012FA00 AddrReturn 0000000000000000 *** 81 called from 0000000000000000 STACK 000000000012FA08 AddrReturn 0000000000000000 *** 82 called from 0000000000000000 STACK 000000000012FA10 AddrReturn 0000000000000000 *** 83 called from 0000000000000000 STACK 000000000012FA18 AddrReturn 0000000000000000 *** 84 called from 0000000000000000 STACK 000000000012FA20 AddrReturn 0000000000000000 *** 85 called from 0000000000000000 STACK 000000000012FA28 AddrReturn 0000000000000000 *** 86 called from 0000000000000000 STACK 000000000012FA30 AddrReturn 0000000000000000 *** 87 called from 0000000000000000 STACK 000000000012FA38 AddrReturn 0000000000000000 *** 88 called from 0000000000000000 STACK 000000000012FA40 AddrReturn 0000000000000000 *** 89 called from 0000000000000000 STACK 000000000012FA48 AddrReturn 0000000000000000 *** 90 called from 0000000000000000 STACK 000000000012FA50 AddrReturn 0000000000000000 *** 91 called from 0000000000000000 STACK 000000000012FA58 AddrReturn 0000000000000000 *** 92 called from 0000000000000000 STACK 000000000012FA60 AddrReturn 0000000000000000 *** 93 called from 0000000000000000 STACK 000000000012FA68 AddrReturn 0000000000000000 *** 94 called from 0000000000000000 STACK 000000000012FA70 AddrReturn 0000000000000000 *** 95 called from 0000000000000000 STACK 000000000012FA78 AddrReturn 0000000000000000 *** 96 called from 0000000000000000 STACK 000000000012FA80 AddrReturn 0000000000000000 *** 97 called from 0000000000000000 STACK 000000000012FA88 AddrReturn 0000000000000000 *** 98 called from 0000000000000000 STACK 000000000012FA90 AddrReturn 0000000000000000 *** 99 called from 0000000000000000 STACK 000000000012FA98 AddrReturn 0000000000000000 *** 100 called from 0000000000000000 STACK 000000000012FAA0 AddrReturn 0000000000000000 *** 101 called from 0000000000000000 STACK 000000000012FAA8 AddrReturn 0000000000000000 *** 102 called from 0000000000000000 STACK 000000000012FAB0 AddrReturn 0000000000000000 *** 103 called from 0000000000000000 STACK 000000000012FAB8 AddrReturn 0000000000000000 *** 104 called from 0000000000000000 STACK 000000000012FAC0 AddrReturn 0000000000000000 *** 105 called from 0000000000000000 STACK 000000000012FAC8 AddrReturn 0000000000000000 *** 106 called from 0000000000000000 STACK 000000000012FAD0 AddrReturn 0000000000000000 *** 107 called from 0000000000000000 STACK 000000000012FAD8 AddrReturn 0000000000000000 *** 108 called from 0000000000000000 STACK 000000000012FAE0 AddrReturn 0000000000000000 *** 109 called from 0000000000000000 STACK 000000000012FAE8 AddrReturn 0000000000000000 *** 110 called from 0000000000000000 STACK 000000000012FAF0 AddrReturn 0000000000000000 *** 111 called from 0000000000000000 STACK 000000000012FAF8 AddrReturn 0000000000000000 *** 112 called from 0000000000000000 STACK 000000000012FB00 AddrReturn 0000000000000000 *** 113 called from 0000000000000000 STACK 000000000012FB08 AddrReturn 0000000000000000 *** 114 called from 0000000000000000 STACK 000000000012FB10 AddrReturn 0000000000000000 *** 115 called from 0000000000000000 STACK 000000000012FB18 AddrReturn 0000000000000000 *** 116 called from 0000000000000000 STACK 000000000012FB20 AddrReturn 0000000000000000 *** 117 called from 0000000000000000 STACK 000000000012FB28 AddrReturn 0000000000000000 *** 118 called from 0000000000000000 STACK 000000000012FB30 AddrReturn 0000000000000000 *** 119 called from 0000000000000000 STACK 000000000012FB38 AddrReturn 0000000000000000 *** 120 called from 0000000000000000 STACK 000000000012FB40 AddrReturn 0000000000000000 *** 121 called from 0000000000000000 STACK 000000000012FB48 AddrReturn 0000000000000000 *** 122 called from 0000000000000000 STACK 000000000012FB50 AddrReturn 0000000000000000 *** 123 called from 0000000000000000 STACK 000000000012FB58 AddrReturn 0000000000000000 *** 124 called from 0000000000000000 STACK 000000000012FB60 AddrReturn 0000000000000000 *** 125 called from 0000000000000000 STACK 000000000012FB68 AddrReturn 0000000000000000 *** 126 called from 0000000000000000 STACK 000000000012FB70 AddrReturn 0000000000000000 *** 127 called from 0000000000000000 STACK 000000000012FB78 AddrReturn 0000000000000000 *** 128 called from 0000000000000000 STACK 000000000012FB80 AddrReturn 0000000000000000 *** 129 called from 0000000000000000 STACK 000000000012FB88 AddrReturn 0000000000000000 *** 130 called from 0000000000000000 STACK 000000000012FB90 AddrReturn 0000000000000000 *** 131 called from 0000000000000000 STACK 000000000012FB98 AddrReturn 0000000000000000 *** 132 called from 0000000000000000 STACK 000000000012FBA0 AddrReturn 0000000000000000 *** 133 called from 0000000000000000 STACK 000000000012FBA8 AddrReturn 0000000000000000 *** 134 called from 0000000000000000 STACK 000000000012FBB0 AddrReturn 0000000000000000 *** 135 called from 0000000000000000 STACK 000000000012FBB8 AddrReturn 0000000000000000 *** 136 called from 0000000000000000 STACK 000000000012FBC0 AddrReturn 0000000000000000 *** 137 called from 0000000000000000 STACK 000000000012FBC8 AddrReturn 0000000000000000 *** 138 called from 0000000000000000 STACK 000000000012FBD0 AddrReturn 0000000000000000 *** 139 called from 0000000000000000 STACK 000000000012FBD8 AddrReturn 0000000000000000 *** 140 called from 0000000000000000 STACK 000000000012FBE0 AddrReturn 0000000000000000 *** 141 called from 0000000000000000 STACK 000000000012FBE8 AddrReturn 0000000000000000 *** 142 called from 0000000000000000 STACK 000000000012FBF0 AddrReturn 0000000000000000 *** 143 called from 0000000000000000 STACK 000000000012FBF8 AddrReturn 0000000000000000 *** 144 called from 0000000000000000 STACK 000000000012FC00 AddrReturn 0000000000000000 *** 145 called from 0000000000000000 STACK 000000000012FC08 AddrReturn 0000000000000000 *** 146 called from 0000000000000000 STACK 000000000012FC10 AddrReturn 0000000000000000 *** 147 called from 0000000000000000 STACK 000000000012FC18 AddrReturn 0000000000000000 *** 148 called from 0000000000000000 STACK 000000000012FC20 AddrReturn 0000000000000000 *** 149 called from 0000000000000000 STACK 000000000012FC28 AddrReturn 0000000000000000 *** 150 called from 0000000000000000 STACK 000000000012FC30 AddrReturn 0000000000000000 *** 151 called from 0000000000000000 STACK 000000000012FC38 AddrReturn 0000000000000000 *** 152 called from 0000000000000000 STACK 000000000012FC40 AddrReturn 0000000000000000 *** 153 called from 0000000000000000 STACK 000000000012FC48 AddrReturn 0000000000000000 *** 154 called from 0000000000000000 STACK 000000000012FC50 AddrReturn 0000000000000000 *** 155 called from 0000000000000000 STACK 000000000012FC58 AddrReturn 0000000000000000 *** 156 called from 0000000000000000 STACK 000000000012FC60 AddrReturn 0000000000000000 *** 157 called from 0000000000000000 STACK 000000000012FC68 AddrReturn 0000000000000000 *** 158 called from 0000000000000000 STACK 000000000012FC70 AddrReturn 0000000000000000 *** 159 called from 0000000000000000 STACK 000000000012FC78 AddrReturn 0000000000000000 *** 160 called from 0000000000000000 STACK 000000000012FC80 AddrReturn 0000000000000000 *** 161 called from 0000000000000000 STACK 000000000012FC88 AddrReturn 0000000000000000 *** 162 called from 0000000000000000 STACK 000000000012FC90 AddrReturn 0000000000000000 *** 163 called from 0000000000000000 STACK 000000000012FC98 AddrReturn 0000000000000000 *** 164 called from 0000000000000000 STACK 000000000012FCA0 AddrReturn 0000000000000000 *** 165 called from 0000000000000000 STACK 000000000012FCA8 AddrReturn 0000000000000000 *** 166 called from 0000000000000000 STACK 000000000012FCB0 AddrReturn 0000000000000000 *** 167 called from 0000000000000000 STACK 000000000012FCB8 AddrReturn 0000000000000000 *** 168 called from 0000000000000000 STACK 000000000012FCC0 AddrReturn CCCCCCCCCCCCCCCC *** 169 called from CCCCCCCCCCCCCCCC STACK 000000000012FCC8 AddrReturn CCCCCCCCCCCCCCCC *** 170 called from CCCCCCCCCCCCCCCC STACK 000000000012FCD0 AddrReturn CCCCCCCCCCCCCCCC *** 171 called from CCCCCCCCCCCCCCCC STACK 000000000012FCD8 AddrReturn CCCCCCCCCCCCCCCC *** 172 called from CCCCCCCCCCCCCCCC STACK 000000000012FCE0 AddrReturn CCCCCCCCCCCCCCCC *** 173 called from CCCCCCCCCCCCCCCC STACK 000000000012FCE8 AddrReturn 0000000300000000 *** 174 called from 0000000300000000 STACK 000000000012FCF0 AddrReturn 0000000300000000 *** 175 called from 0000000300000000 STACK 000000000012FCF8 AddrReturn 0000000300000000 *** 176 called from 0000000300000000 STACK 000000000012FD00 AddrReturn 000000000012FCF0 *** 177 called from 000000000012FCF8 STACK 000000000012FD08 AddrReturn 0000000300000000 *** 178 called from 0000000300000000 STACK 000000000012FD10 AddrReturn 000000000012FD10 *** 179 called from 000000000012FD18 STACK 000000000012FD18 AddrReturn 0000000300000000 *** 180 called from 0000000300000000 STACK 000000000012FD20 AddrReturn 0000000000000000 *** 181 called from 0000000000000000 STACK 000000000012FD28 AddrReturn 0000000000000000 *** 182 called from 0000000000000000 STACK 000000000012FD30 AddrReturn 0000000000000000 *** 183 called from 0000000000000000 STACK 000000000012FD38 AddrReturn 0000000000000000 *** 184 called from 0000000000000000 STACK 000000000012FD40 AddrReturn 0000000000000000 *** 185 called from 0000000100000000 STACK 000000000012FD48 AddrReturn 0000000100000000 *** 186 called from 0000000000000000 STACK 000000000012FD50 AddrReturn 0000000000000000 *** 187 called from 0000000000000000 STACK 000000000012FD58 AddrReturn 0000000100000000 *** 188 called from 0000000100000000 STACK 000000000012FD60 AddrReturn 0000000000000000 *** 189 called from 0000000000000000 STACK 000000000012FD68 AddrReturn 0000000000000000 *** 190 called from 0000000000000000 STACK 000000000012FD70 AddrReturn 0000000000000000 *** 191 called from 0000000000000000 STACK 000000000012FD78 AddrReturn 0000000000000000 *** 192 called from 0000000000000000 STACK 000000000012FD80 AddrReturn 0000000000000000 *** 193 called from 0000000000000000 STACK 000000000012FD88 AddrReturn 0000000000000000 *** 194 called from 0000000000000000 STACK 000000000012FD90 AddrReturn 0000000000000000 *** 195 called from 0000000000000000 STACK 000000000012FD98 AddrReturn 0000000000000000 *** 196 called from 0000000000000000 STACK 000000000012FDA0 AddrReturn 0000000000000000 *** 197 called from 0000000000000000 STACK 000000000012FDA8 AddrReturn 0000000000000000 *** 198 called from 0000000000000000 STACK 000000000012FDB0 AddrReturn 0000000000000000 *** 199 called from 0000000000000000 STACK 000000000012FDB8 AddrReturn 0000000000000000 *** 200 called from 0000000000000000 STACK 000000000012FDC0 AddrReturn 0000000000000000 *** 201 called from 0000000000000000 STACK 000000000012FDC8 AddrReturn 0000000000000000 *** 202 called from 0000000000000000 STACK 000000000012FDD0 AddrReturn 0000000000000000 *** 203 called from 0000000000000000 STACK 000000000012FDD8 AddrReturn 0000000000000000 *** 204 called from 0000000000000000 STACK 000000000012FDE0 AddrReturn 0000000000000000 *** 205 called from 0000000000000000 STACK 000000000012FDE8 AddrReturn CCCCCCCCCCCCCCCC *** 206 called from CCCCCCCCCCCCCCCC STACK 000000000012FDF0 AddrReturn 000000CECCCCCCCC *** 207 called from 000000CFCCCCCCCC STACK 000000000012FDF8 AddrReturn CCCCCCCC00000001 *** 208 called from CCCCCCCC00000001 STACK 000000000012FE00 AddrReturn FFFFFFFFFFFFFFFE *** 209 called from FFFFFFFFFFFFFFFE STACK 000000000012FE08 AddrReturn CCCCCCCCCCCCCCCC *** 210 called from CCCCCCCCCCCCCCCC STACK 000000000012FE10 AddrReturn 000000000012FE40 *** 211 called from 000000000012FE40 STACK 000000000012FE18 AddrReturn 000000014000122F *** 212 called from 000000014000122F STACK 000000000012FE20 AddrReturn CCCCCCCCCCCCCCCC *** 213 called from CCCCCCCCCCCCCCCC STACK 000000000012FE28 AddrReturn CCCCCCCCCCCCCCCC *** 214 called from CCCCCCCCCCCCCCCC STACK 000000000012FE30 AddrReturn CCCCCCCCCCCCCCCC *** 215 called from CCCCCCCCCCCCCCCC STACK 000000000012FE38 AddrReturn CCCCCCCCCCCCCCCC *** 216 called from CCCCCCCCCCCCCCCC STACK 000000000012FE40 AddrReturn 000000000012FE70 *** 217 called from 000000000012FE70 STACK 000000000012FE48 AddrReturn 000000014000125F *** 218 called from 000000014000125F STACK 000000000012FE50 AddrReturn CCCCCCCCCCCCCCCC *** 219 called from CCCCCCCCCCCCCCCC STACK 000000000012FE58 AddrReturn CCCCCCCCCCCCCCCC *** 220 called from CCCCCCCCCCCCCCCC STACK 000000000012FE60 AddrReturn CCCCCCCCCCCCCCCC *** 221 called from CCCCCCCCCCCCCCCC STACK 000000000012FE68 AddrReturn CCCCCCCCCCCCCCCC *** 222 called from CCCCCCCCCCCCCCCC STACK 000000000012FE70 AddrReturn 000000000012FEA0 *** 223 called from 000000000012FEA0 STACK 000000000012FE78 AddrReturn 000000014000128F *** 224 called from 000000014000128F STACK 000000000012FE80 AddrReturn CCCCCCCCCCCCCCCC *** 225 called from CCCCCCCCCCCCCCCC STACK 000000000012FE88 AddrReturn CCCCCCCCCCCCCCCC *** 226 called from CCCCCCCCCCCCCCCC STACK 000000000012FE90 AddrReturn CCCCCCCCCCCCCCCC *** 227 called from CCCCCCCCCCCCCCCC STACK 000000000012FE98 AddrReturn CCCCCCCCCCCCCCCC *** 228 called from CCCCCCCCCCCCCCCC STACK 000000000012FEA0 AddrReturn 000000000012FED0 *** 229 called from 000000000012FED0 STACK 000000000012FEA8 AddrReturn 00000001400012CB *** 230 called from 00000001400012CB STACK 000000000012FEB0 AddrReturn CCCCCCCCCCCCCCCC *** 231 called from CCCCCCCCCCCCCCCC STACK 000000000012FEB8 AddrReturn CCCCCCCCCCCCCCCC *** 232 called from CCCCCCCCCCCCCCCC STACK 000000000012FEC0 AddrReturn CCCCCCCCCCCCCCCC *** 233 called from CCCCCCCCCCCCCCCC STACK 000000000012FEC8 AddrReturn CCCCCCCCCCCCCCCC *** 234 called from CCCCCCCCCCCCCCCC STACK 000000000012FED0 AddrReturn 0000000000000000 *** 235 called from 0000000000000000 STACK 000000000012FED8 AddrReturn 000000014000190C *** 236 called from 000000014000190C STACK 000000000012FEE0 AddrReturn 0000000100000001 *** 237 called from 0000000100000001 STACK 000000000012FEE8 AddrReturn 0000000000454B50 *** 238 called from 0000000000454B50 STACK 000000000012FEF0 AddrReturn 0000000000000000 *** 23 ```
I finally found a reliable way to log the stack frames in x64, using the Windows function `CaptureStackBackTrace()`. As I did not want to update my SDK, I call it via `GetProcAddress(LoadLibrary());` ``` typedef USHORT (WINAPI *CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __out_opt PULONG); CaptureStackBackTraceType func = (CaptureStackBackTraceType)(GetProcAddress(LoadLibrary("kernel32.dll"), "RtlCaptureStackBackTrace")); if(func == NULL) return; // WOE 29.SEP.2010 // Quote from Microsoft Documentation: // ## Windows Server 2003 and Windows XP: // ## The sum of the FramesToSkip and FramesToCapture parameters must be less than 63. const int kMaxCallers = 62; void* callers[kMaxCallers]; int count = (func)(0, kMaxCallers, callers, NULL); for(i = 0; i < count; i++) printf(TraceFile, "*** %d called from %016I64LX\n", i, callers[i]); ```
For vs2008 x64: Based on <https://msdn.microsoft.com/en-us/library/windows/desktop/bb204633%28v=vs.85%29.aspx> and RED SOFT ADAIR: ``` #if defined DEBUG_SAMPLES_MANAGEMENT #include "DbgHelp.h" #include <WinBase.h> #pragma comment(lib, "Dbghelp.lib") void printStack( void* sample_address, std::fstream& out ) { typedef USHORT (WINAPI *CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __out_opt PULONG); CaptureStackBackTraceType func = (CaptureStackBackTraceType)(GetProcAddress(LoadLibrary(L"kernel32.dll"), "RtlCaptureStackBackTrace")); if(func == NULL) return; // WOE 29.SEP.2010 // Quote from Microsoft Documentation: // ## Windows Server 2003 and Windows XP: // ## The sum of the FramesToSkip and FramesToCapture parameters must be less than 63. const int kMaxCallers = 62; void * callers_stack[ kMaxCallers ]; unsigned short frames; SYMBOL_INFO * symbol; HANDLE process; process = GetCurrentProcess(); SymInitialize( process, NULL, TRUE ); frames = (func)( 0, kMaxCallers, callers_stack, NULL ); symbol = ( SYMBOL_INFO * )calloc( sizeof( SYMBOL_INFO ) + 256 * sizeof( char ), 1 ); symbol->MaxNameLen = 255; symbol->SizeOfStruct = sizeof( SYMBOL_INFO ); out << "(" << sample_address << "): " << std::endl; const unsigned short MAX_CALLERS_SHOWN = 6; frames = frames < MAX_CALLERS_SHOWN? frames : MAX_CALLERS_SHOWN; for( unsigned int i = 0; i < frames; i++ ) { SymFromAddr( process, ( DWORD64 )( callers_stack[ i ] ), 0, symbol ); out << "*** " << i << ": " << callers_stack[i] << " " << symbol->Name << " - 0x" << symbol->Address << std::endl; } free( symbol ); } #endif ``` Called here: ``` #if defined DEBUG_SAMPLES_MANAGEMENT if(owner_ != 0) { std::fstream& out = owner_->get_debug_file(); printStack( this, out ); } #endif ```
How to Log Stack Frames with Windows x64
[ "", "c++", "c", "winapi", "64-bit", "callstack", "" ]