Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
This only occurs in Internet Explorer. I have a ListBox which is in an UpdatePanel. The ListBox has around 100 items in it and it shows 15 are visible at a time. They are sorted from 1 to 100. If I scroll to the bottom and select item number 50, item 50 stays selected, but the ListBox jumps back to the top of the List, so it is displaying items 1 thru 15. This only happens in Internet Explorer. If I do this in FireFox, the item selected is still displayed, it just becomes the last visible item in the list meaning item 15. Does anyone know a solution to this and why it is happening? Thanks, XaiSoft
This question appears to have been answered in this post: [Maintain scroll position in listboxes in updatepanels, NOT the page](https://stackoverflow.com/questions/543131/maintain-scroll-position-in-listboxes-in-updatepanels-not-the-page)
Try setting `MaintainScrollPositionOnPostBack="true"` in your Page directive (`<%@ page %>`)
ListBox in an UpdatePanel jumps to the top after selecting an item at the bottom?
[ "", "c#", "asp.net", "updatepanel", "" ]
I have this java swing application that I intend to sell over the internet. At the moment I'm leaning towards deploying the application using java webstart. The product will be licensed for the user to use the program on one computer at a time only. I am concerned about piracy with this model. I would like to install some security features to enforce the license model. The goal is to at least make it difficult for a licensed user to copy the installed product including license key to unlicensed users. Here are the options I am looking at now: 1. Force the user to authenticate to the mother ship with a username/password each time the program is launched. 2. Simply install a license key somewhere (hidden?) on the users PC after they have registered and paid. At runtime, verify that there is a valid license key installed. 3. Use/build a security package that is based on a hardware fingerprint of the users computer. This fingerprint would be computed each time the app is started and compared with the locally installed license key using some sort of hash. This license key would be would only be valid with this hardware fingerprint. One of the issues here is that once this application is installed, there isn't any runtime need for the application to contact the mother ship, other than checking for application updates using java webstart. Everything the app does it does locally and displays the results to the user using swing. So any solution involving a mother ship would basically mean building a server infrastructure for the sole purpose of license verification. I guess what I'm looking for is something java based that is at least somewhat secure, easy to deploy and is not a pain for the user. What security/licensing approach have you used? EDIT: I should add that I am not necessarily looking for a silver bullet to prevent absolutely everyone from defeating security. There will always be someone with enough time on their hands to find ways to get it done. I'm not so concerned with these guys. I'm basically looking to make it difficult for a casual user to simply copy the license key and send to his buddies. Implemented correctly, the solution should convince the casual user that it is simpler to just buy it.
I'd say (2) is your best bet. You've already talked yourself out of (1), and (3) would cause problems if the user, say, bought a new motherboard. (2) won't be much protection against a reasonably computer-savvy user, but it shouldn't cause too many problems either. But in the end, nothing you can do will stop a determined user from pirating your software. > In fact, the most effective anti-piracy software development strategy is the simplest one of all: > > 1. **Have a great freaking product.** > 2. **Charge a fair price for it.** -- [Jeff Atwood](https://blog.codinghorror.com/my-software-is-being-pirated/)
IMO, trying to enforce copy protection on the client side is probably more trouble than it's worth. You will spend countless of hours trying to outsmart your customers (hours that you could instead spend improving your product), but in the end the pirates will always win. You have other options, though: 1. Have an attractive pricing model, and make it *really simple* for people to buy your product. If you have low enough barrier to entry and treat your customer with respect and trust instead of suspicion, you minimize the risk of piracy. 2. Tie your product to some kind of online service. Give away the client, but charge for the service. This is what Blizzard does with World of Warcraft, and that is one of the few games out there that has no piracy problems whatsoever (they have a lot of other problems, but that's another story).
How to prevent piracy for java webstart application
[ "", "java", "security", "deployment", "java-web-start", "" ]
With new features in .NET 3.5 (such as var, Lambda, linq, etc), and more on its way, we can conclude that C# not only statically typed language, but also **Dynamically typed** ? Why or Why not? **Edit#1** As many posters below claim, .net 4.0 will add the dynamical type-ness to the language. Will this slow down the language? With every release csharp takes something from different languages. In so far as .Net1.1, our forefathers didn't intend to even make it functional language.... **Edit#2** I think many of you misunderstood the question; as I am referring to C# language overall, including the upcoming release 4.0. Thus, it is fair to say that the language is dynamically typed...
C# is not dynamically typed - all types are statically inferred in the examples you mentioned. The *next* version of C# will include some dynamic features though for working with COM and truly dynamic languages. [Edit #1] Yes C#'s new dynamic feature will be slower as everything using it will require late-binding. However it will only slow down your application if you use it - it is not a change to the core language itself. C# 4 will be a statically typed language with the capability of working with late-bound types. [Edit #2] No C# 4 will not be a dynamically typed language. C# 4 introduces a new `dynamic` type which will substitute late-binding on type members in lieu of static type checking. Dynamic capabilities will only be available on these dynamic types. C#'s underlying type system has not changed.
No, it is still statically typed, var/lambda/linq all use inferance by the compiler so the type is known at compile time, dynamic/duck typing will come with c# 4.0
C# Dynamically typed language
[ "", "c#", ".net", "programming-languages", "" ]
I am using C#.Net. I have textbox which allow only number, decimal and percentage(%) sign. I have the keycode for all number and decimal, but what is the "%" sign's keycode? How can I check the `keydown` event for %?
Something like this: ``` private void yourControl_KeyDown(object sender, KeyEventArgs e) { if((e.KeyCode == Keys.D5) && e.Shift) { // User pressed '%' ... } } ``` or ``` private void yourControl_KeyDown(object sender, KeyEventArgs e) { switch(e.KeyCode) { //... case Keys.D5: if(e.Shift) { // Handle '%' } else { // Handle '5' } break; // ... } } ``` You want to check that the key being pressed is the 5 key, and that it has been modified by pressing the shift key.
Ascii code for "%" is 37, and in unicode &#37.
What is the Keycode for % sign?
[ "", "c#", ".net", "" ]
As developer, I am often interested in new language feature that can make your life easier. For example, java 5 brought generics and annotations to the language, features that can definitely boost your productivity. However, when I look back at close to a decade working on java platform, I find that the versioning related problems are the biggest culprit of unproductive and needlessly spent effort. Hours and hours of looking for the correct version of the jar, trying to reconcile some versioning conflict, upgrading dependent libraries etc. When I started working in java, things were not that difficult, you’d have a few 3rd party libraries and that’s it. Today, your typical web app might easily use: Spring Framework, Hibernate, Struts, you name it. All of these carry a number of dependant 3rd party libraries. Today, my ear archives will typically include some 40 or more 3rd party libraries. A real jar hell! With annotations, I don’t have to manage config files for Hibernate for example. A nice feature, but I haven’t seen that many problems arising from the fact I keep my descriptors in separate file. With generics, I am spared from writing cast statements, but in my whole programming carrier I can’t remember a single bug that could have been prevented by using type-safe container. Wouldn’t solution to versioning problems have been much more valuable? All these problems have resulted in number of tools like [Maven](http://maven.apache.org/), [ivy](http://ant.apache.org/ivy/), [One Jar](http://one-jar.sourceforge.net/), [Jar Jar Links](http://code.google.com/p/jarjar/) (not kidding!), even appropriately named [Jar Hell](http://incubator.apache.org/depot/version/jar-hell.html) etc. Even if you use some of these tools, you are far from being immune to the problem. I use Maven 2 and it has been a great help. Still, it is a world to itself. Novice programmer can take a while to learn it. Moving your legacy projects to Maven structure is also a pain. It seems that in .Net they have learned the lesson with dll hell and management of .Net assemblies is much simpler. There seems to be plans to solve this problem for java platform and alternatives like OSGI. I think that some basic and platform enforced versioning mechanism is badly needed
Take a peek at OSGi - it deals with versioning and management of bundles (jars) very nicely. ALSO: Eclipse (which is built on top of OSGi) has some relatively new API Tools that can help you compare your API against a previous baseline and determine how to appropriately express the next version number of your bundles. The general eclipse versioning scheme: ``` v.m.n.q ``` where v: high-level version - changes here represent generally breaking changes in the API m: major changes - new functionality, new API n: minor changes - same API, behind-the-scenes changes q: qualifier - useful to mark builds, alpha/beta, etc OSGi specifies version dependencies using ranges. For example ``` Require-Bundle: com.javadude.foo;bundle-version="[1.2.0,2.0.0)" ``` in your MANIFEST.MF specifies that the bundle requires version 1.2.0 or later of bundle com.javadude.foo, up through (but not including) version 2.0.0. You can also specify dependencies at the package level instead.
I've also been using Java for over a decade but I have to say I haven't found many *JAR hell* issues at all (even using all the 3rd-party tools you mention)! I found `Maven` to be a horrible tool, so build everything with `ant`. At our company we have a bespoke dependency-resolution `ant` task based on a simple (small) dependency file for each project, together with defining each project as either an `app` or a `lib` (you should only ever depend on a `lib`; never an `app`). It works just fine. We also have `ant` tasks to modify our eclipse `.classpath` and IDEA `.iml` files to generate dependency graphs for our IDEs.
Is platform enforced versioning mechanism most sorely needed feature of java?
[ "", "java", "dependencies", "versioning", "jar", "" ]
I want to design a 2D game idea with C#/XNA. Between school, project inexperience, limited resources, and other things that may cause me to bail on the project I am going to try to plan it out before I jump in: * What are some key aspects you've noticed in a successful personal project? * How did you (successfully) draw revenue the project (besides asking for donations)? (Note: this is not the main purpose of my project but would be nice!) * How do you plan non-programming aspects like window layouts (UI), flow of game, and look and feel? * How do you bring an abstract idea of a game and making into a real product. What tools do you use in your sketching and planning? * With limited resources (artistic talent and money), how do I create some of the art resources I need (besides stock art)? Or should I not worry about that until I have a finished product? * Finally, how do you break barriers in your code (may it be knowledge, time, or perseverance)?
**What are some key aspects you've noticed in a successful personal project?** I suppose this largely depends on your definition of success. I consider a game project successful if: * It's fun. Enough that I want to play it after I've finished. * I learn something in the process of making it. * I actually complete the project, where complete is defined as having art, audio, and any other assets adequate for the style of game that I'm making. * It works under 'field conditions', rather than simply on my own machine/hardware configuration. In my case, every project that I've considered successful has been one that I've done some serious planning on and committed to seeing through to completion. That's the biggest step for me to get past. A casual project that is the product of a bored weekend usually won't get finished. **How did you (successfully) draw revenue the project (besides asking for donations)? (Note: this is not the main purpose of my project but would be nice!)** Heh. Haven't managed this yet. But then, that hasn't been a concern of mine enough to do the work required to support it. Someone already mentioned the potential revenue from XBLA for XNA projects, which is a very easy avenue to success if your project is the sort of thing that translates well to the console. I've looked into it, but it isn't really appropriate for my projects so far. **How do you plan non-programming aspects like window layouts (UI), flow of game, and look and feel?** Pen. And paper. I draw a lot of screenshots as guides and I'll usually have some kind of artistic theme in mind to go along with the gameplay. Rapid prototypes help here too; everything from making mockups of menus and various screens in a drawing program to making some simple interactive stuff in a throwaway project. Write everything down. I take lots of notes and I've been known to have a laptop with notepad open on it sitting next to my development machine, to save me the trouble of alt-tabbing away from my code to type a quick note on what I'm doing. Some great ideas come out of the process of trying to make other things work and if you don't write it down, it didn't happen. **How do you bring an abstract idea of a game and making into a real product. What tools do you use in your sketching and planning?** Work iteratively as much as possible. I hate to sound cliche, but the whole agile model works really well for games. Start with that core 'fun' idea you have that inspired you to make a game in the first place and get that working in code. Maybe it's a single mechanic that you want to build puzzles/levels around or maybe it's more of a look/feel that you can capture in a single environment/level/whatever. Either way, if you can get a single example of it working right, it becomes a good check on whether the idea is actually viable and will likely give you some ideas of the different ways it can be implemented. That might seem kind of vague, but more specific advice would depend on any number of other factors (your choice of genre, audience, the specific ideas you have in mind, etc.). **With limited resources (artistic talent and money), how do I create some of the art resources I need (besides stock art)? Or should I not worry about that until I have a finished product?** Peter Molyneux of Lionhead has said that he used to prototype all of his games with ascii art. If they were fun with that limited level of graphics, then they were worth continuing. While you might not be able to get that simple with some genres (and an ascii 3d shooter might be novel for it's own sake...), certainly worrying about finished art, audio, or other assets is something that can be saved for much later. In the end, if the game is fun to play, then getting an artist willing to work with you becomes a lot more trivial. I have, on many occasions, used copyrighted assets during my prototyping phase when I just couldn't stand to look at my own art any longer. Just be sure that you have anything like that replaced before you start distributing your project... **Finally, how do you break barriers in your code (may it be knowledge, time, or perseverance)?** Not sure exactly what you're thinking about here, but breaking barriers is what writing code is all about really. You're finding creative solutions to interesting problems. The web is a great resource for general knowledge, but in the end, it's your own time and perseverance that will create something interesting. Best of luck.
> What are some key aspects you've noticed in a successful personal project? 1. Don't worry about how it will turn out 2. Do it for fun 3. Don't plan it 4. Start small, don't think big 5. Actually code instead of procrastinating on so or other similar sites
Personal Project Planning
[ "", "c#", "project-management", "xna", "" ]
Does null inherit from Object as well in C#? Where does the null itself defined?
null is of the "null type", which does inherit from object. See ECMA-334 11.2.7
> Does null inherit from Object as well in C#? Unlike in some other systems, `null` is not defined in terms of a class or an instance. On the contrary, it signifies the *absence* of any instance, and it doesn't have a type. It is implicitly converted to whatever reference type fits the context. The widest conversion (i.e. when no other can be inferred) is to `object`. But still, `null` is not generally of type `object`.
Does null inherit from Object as well in C#?
[ "", "c#", ".net", "" ]
We have a system that uses UniqueIdentifier as the primary key of each of the tables. It has been brought to our attention that this is a bad idea. I have seen similar post on the subject but I am interested in any MS SQL performance and other potential problems I may encounter due to this decision.
There are pros and cons: [This article](http://blog.codinghorror.com/primary-keys-ids-versus-guids/) covers everything. GUID Pros * Unique across every table, every database, every server * Allows easy merging of records from different databases * Allows easy distribution of databases across multiple servers * You can generate IDs anywhere, instead of having to roundtrip to the database * Most replication scenarios require GUID columns anyway GUID Cons * It is a whopping 4 times larger than the traditional 4-byte index value; this can have serious performance and storage implications if you're not careful * Cumbersome to debug (where userid='{BAE7DF4-DDF-3RG-5TY3E3RF456AS10}') * The generated GUIDs should be partially sequential for best performance (eg, newsequentialid() on SQL 2005) and to enable use of clustered indexes
I wrote a post about this last week with some code to show you what happens: [Some Simple Code To Show The Difference Between Newid And Newsequentialid](http://sqlblog.com/blogs/denis_gobo/archive/2009/02/05/11743.aspx) Basically if you use newid() instead of Newsequentialid() you get horrible page splits if your PK is a clustered index (which it will be by default)
Is it a bad idea to use GUIDs as primary keys in MS SQL?
[ "", "sql", "sql-server", "database", "primary-key", "" ]
Is it safe to fork off a Thread to execute an insert using a `JdbcTemplate` in Swing. It's a logging event and as much as possible I don't want it to affect perceived performance.
[This answer](http://forum.spring.io/forum/spring-projects/data/16972-jdbctemplate-thread-safety) from the Spring forum says yes.t=25965 JdbcTemplate is a singleton that won't change state once it's set.
Also note that its thread-safety is [very well explained in the Spring 3.1 reference documentation](http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html#jdbc-JdbcTemplate-idioms): **13.2.1.2 JdbcTemplate best practices** > Instances of the JdbcTemplate class are threadsafe once configured. This is important because it means that you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs (or repositories). The JdbcTemplate is stateful, in that it maintains a reference to a DataSource, but this state is not conversational state.
Spring JdbcTemplate and Threading
[ "", "java", "multithreading", "swing", "jdbc", "spring-jdbc", "" ]
I have several message with properties set. Some of these contain numeric data, although I have made no attempt to declare this explicitly to ActiveMQ while sending the messages. When I try to use arithmetic conditions, ie: <, >, <=, >= and family, I get an error. Is there any way to use arithmetic conditions using selectors via Stomp? I have already searched the web and only got the following hit on google: <http://rubyforge.org/tracker/index.php?func=detail&aid=21378&group_id=1010&atid=3981> This issue seems to be on the table to be fixed with v1.1 of the STOMP protocol: <http://stomp.codehaus.org/Stomp+v1.1+Ideas>
I recommend you try out the ActiveMQ subproject called [Apollo](http://activemq.apache.org/apollo/). It's a focused on having great STOMP support and does support numeric selectors [see the docs](http://activemq.apache.org/apollo/documentation/user-manual.html#Message_Selectors)
currently Stomp treats all properties as Strings, so using arithmetic does not work. As you found out, it is planned to support property types in Stomp 1.1 and then you'll be able to use them like in JMS. Cheers Dejan
How to use Arithmetic conditions and Operators in ActiveMQ/JMS Selectors using the Stomp protocol
[ "", "php", "activemq-classic", "stomp", "" ]
What is a 'public key token' and how is it calculated in assembly strong names?
Regarding your question, "How is it calculated", it's an SHA1 hash. From [dot net blog](http://ashishcodes.blogspot.com/2004/09/public-keys-and-public-key-tokens.html): > Microsoft solves the "public key > bloat" problem by using a hash of the > strongly-named assembly's public key. > These hashes are referred to as public > key tokens, and are the low 8 bytes of > the SHA1 hash of the strongly-named > assembly's public key. SHA1 hashes are > 160 bit (20 byte) hashes, and the top > 12 bytes of the hash are simply > discarded in this algorithm.
You can get the PublicKeyToken from the VS Command Line by typing: ``` sn –T DLLName.dll ```
What is a public key token and how is it calculated in assembly strong names?
[ "", "c#", "publickeytoken", "" ]
I have a PHP function that I'm using to output a standard block of HTML. It currently looks like this: ``` <?php function TestBlockHTML ($replStr) { ?> <html> <body><h1> <?php echo ($replStr) ?> </h1> </html> <?php } ?> ``` I want to return (rather than echo) the HTML inside the function. Is there any way to do this without building up the HTML (above) in a string?
You can use a [heredoc](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc), which supports variable interpolation, making it look fairly neat: ``` function TestBlockHTML ($replStr) { return <<<HTML <html> <body><h1>{$replStr}</h1> </body> </html> HTML; } ``` Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.
Yes, there is: you can capture the `echo`ed text using [`ob_start`](http://php.net/ob_start): ``` <?php function TestBlockHTML($replStr) { ob_start(); ?> <html> <body><h1><?php echo($replStr) ?></h1> </html> <?php return ob_get_clean(); } ?> ```
Is there any way to return HTML in a PHP function? (without building the return value as a string)
[ "", "php", "string", "templating", "" ]
I have a select query which does some text manipulation to essentially reformat a field so that I can look it up in another table: If my first table if I have a field like "J1/2" it looks up the ID of a record in a different table with J1 and J2 in the appropriate fields. This all works well. Now I want to update the original table so I don't have to do lookups using this string manipulation anymore, but my attempts at update queries end with "Operation must use an updateable query" Any ideas? My SELECT statement: ``` SELECT DISTINCT t1.DD, t1.TN, t1.DD & " J" & MID(t1.TN,2,1) AS CalculatedStart, t1.DD & " J" & MID(t1.TN,4,1) AS CalculatedEnd, t2.ID FROM t1 INNER JOIN t2 ON (t1.DD & " J" & MID(t1.TN,2,1)=t2.StartLink) AND (t1.DD & " J" & MID(t1.TN,4,1)=t2.EndLink) WHERE t1.TN Like "J?/?" AND t1.DD Like "M*"; ``` Recall - this works fine and I get the necessary t2.ID out the other end. So I want to do something like: ``` UPDATE t1 SET t2ID = ( SELECT Query1.ID FROM Query1 WHERE t1.DD=Query1.DD AND t1.TN=Query1.TN ) WHERE t1.TN Like "J?/?" AND t1.DD Like "M*"; ``` Only this fails. This is within MS Access itself so I can't imagine an actual permissions problem like most of the "Operation must use an updateable query" problems seem to be. EDIT: Trying to simplify the case that doesn't work. This UPDATE query is fine: ``` UPDATE t1 SET t2ID="Unknown" WHERE TN LIKE "J?/?" AND DD LIKE "M*"; ``` This one fails (Thanks Goedke - this example obviously fails because the subquery returns more than 1 result. I had oversimplified to try to find my problem) ``` UPDATE t1 SET t2ID=(SELECT ID FROM t2) WHERE TN LIKE "J?/?" AND DD LIKE "M*"; ``` So do I just have my subquery syntax wrong in some way? EDIT: This SELECT statement is fine too: ``` SELECT t1.OA, t1.DD, t1.TN, t1.HATRIS, query1.DD, query1.TN, query1.ID FROM t1 INNER JOIN query1 ON t1.DD=query1.DD AND t1.TN=query1.TN ``` Furthermore, using count on the select statement above shows that there is exactly 1 ID being returned per (DD,TN) combination EDIT: The simplest case I've now got to - using various SELECT statements I now have a table with just 2 columns - the primary key of t1 and the value I want to insert into t1. I still can't seem to write ``` UPDATE t1 SET t1.f2 = (SELECT t2.f2 FROM t2 WHERE t2.f1 = t1.f1) ``` where t1's primary key is f1. Even adding WHERE t1.f1 IN (SELECT f1 FROM t2) doesn't help. (Added to eliminate the possibility that the subquery returns 0 results)
A subquery of (SELECT ID FROM t2) can't work unless there is only one record in t2. Which ID are you expecting to be used? The error message that is being reported normally occurs when you have joins and are not including all of the primary keys necessary to update back to tables in a data bound form (for example, your original DISTINCT destroys information about keys, so if it was bound to a form, the form would not be able to save back). The fact you are using DISTINCT there would make me suspicious that the sub query is returning more than one row in your more complex example. This is probably the most common problem with assigning out of a sub query result: under-constraining the where clause. Another problem I have seen with assigning out of a subquery is if the *syntax* of the inner query is incorrect. At least with SQL 2000 and 2005 back ends, the query processor will *silently* fail and return NULL in such cases. (This is, as far as I can tell, a bug: I see no reason why something that will return an error at the top level would be silently permitted in a subquery... but there it is.) EDIT: Just to ensure that neither Paul or I wasn't going crazy, I created the following tables: ``` t1 | ID, FK, Data t2 | ID2, Data2 ``` I did *not* put any constraints except a primary key on ID and ID2. All fields were text, which is different from what I normally use for IDs, but should be irrelevant. t1: ``` ID FK Data Key1 Data1 Key2 Data2 Key3 Data3 ``` t2: ``` ID2 Data2 Key1 DataA Key2 DataB Key3 DataC ``` A query of the form: ``` UPDATE t1 SET t1.FK = (select ID2 from t2 where t2.ID2 = t1.ID); ``` Failed with the same message Paul got. ``` select *, (select ID2 from t2 where t2.ID2 = t1.ID) as foreign from t1, ``` works as expected, so we know the subquery syntax is not to blame. ``` UPDATE t1 SET t1.FK = 'Key1' ``` also works as expected, so we don't have a corrupt or non updateable destination. Note: if I change the database backend from native to SQL 2005, the update works! A bit of googling around, and I find Access MVPs suggesting DLOOKUP to replace a subquery: <http://www.eggheadcafe.com/software/aspnet/31849054/update-with-subquerycomp.aspx> Apparently this is a bug in Access SQL, one that is avoided when using a SQL Express 2000 or higher back end. (The google results for "access update subquery" support this theory). See here for how to use this workaround: <http://www.techonthenet.com/access/functions/domain/dlookup.php>
I have to weigh in with David W. Fenton's comment on the OP. This is highly annoying problem with Jet/ACE. But try either: 1. go to the query properties (click the background of the pane where the tables are displayed) and set 'Unique Records' to 'Yes' 2. Option 1 is the equivalent of adding the somewhat strange looking `DISTINCTROW` keyword to the `SELECT` clause, eg : ``` UPDATE DISTINCTROW tblClient INNER JOIN qryICMSClientCMFinite ON tblClient.ClientID = qryICMSClientCMFinite.ClientID SET tblClient.ClientCMType = "F"; ``` This solves so many problems involving this error message that it is almost ridiculous. That's MS Access in a nutshell - if you don't know the trade-secret workaround for problem x, you can take days trying to find the answer. To know the 10,000 workarounds IS to program Access. Is that enough of a warning for the uninitiated ? Ben
SQL Update woes in MS Access - Operation must use an updateable query
[ "", "sql", "ms-access", "sql-update", "" ]
I need to access the assembly of my project in C#. I can see the GUID in the 'Assembly Information' dialog in under project properties, and at the moment I have just copied it to a const in the code. The GUID will never change, so this is not that bad of a solution, but it would be nice to access it directly. Is there a way to do this?
Try the following code. The value you are looking for is stored on a `GuidAttribute` instance attached to the `Assembly` ``` using System.Runtime.InteropServices; static void Main(string[] args) { var assembly = typeof(Program).Assembly; var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute),true)[0]; var id = attribute.Value; Console.WriteLine(id); } ```
Or, just as easy: ``` string assyGuid = Assembly.GetExecutingAssembly().GetCustomAttribute<GuidAttribute>().Value.ToUpper(); ``` It works for me...
How do I programmatically get the GUID of an application in C# with .NET?
[ "", "c#", ".net", "" ]
I am trying to parse url-encoded strings that are made up of key=value pairs separated by either `&` or `&amp;`. The following will only match the first occurrence, breaking apart the keys and values into separate result elements: ``` var result = mystring.match(/(?:&|&amp;)?([^=]+)=([^&]+)/) ``` The results for the string '1111342=Adam%20Franco&348572=Bob%20Jones' would be: ``` ['1111342', 'Adam%20Franco'] ``` Using the global flag, 'g', will match all occurrences, but only return the fully matched sub-strings, not the separated keys and values: ``` var result = mystring.match(/(?:&|&amp;)?([^=]+)=([^&]+)/g) ``` The results for the string '1111342=Adam%20Franco&348572=Bob%20Jones' would be: ``` ['1111342=Adam%20Franco', '&348572=Bob%20Jones'] ``` While I could split the string on `&` and break apart each key/value pair individually, is there any way using JavaScript's regular expression support to match multiple occurrences of the pattern `/(?:&|&amp;)?([^=]+)=([^&]+)/` similar to PHP's `preg_match_all()` function? I'm aiming for some way to get results with the sub-matches separated like: ``` [['1111342', '348572'], ['Adam%20Franco', 'Bob%20Jones']] ``` or ``` [['1111342', 'Adam%20Franco'], ['348572', 'Bob%20Jones']] ```
Hoisted from the comments > 2020 comment: rather than using regex, we now have [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams), which does all of this for us, so no custom code, let alone regex, are necessary anymore. > > – [Mike 'Pomax' Kamermans](https://stackoverflow.com/users/740553/mike-pomax-kamermans) Browser support is listed here <https://caniuse.com/#feat=urlsearchparams> --- I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually and [`re.exec()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec): ``` function getUrlParams(url) { var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g, match, params = {}, decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));}; if (typeof url == "undefined") url = document.location.href; while (match = re.exec(url)) { params[decode(match[1])] = decode(match[2]); } return params; } var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr"); ``` `result` is an object: ``` { f: "q" geocode: "" hl: "de" ie: "UTF8" iwloc: "addr" ll: "50.116616,8.680573" q: "Frankfurt am Main" sll: "50.106047,8.679886" source: "s_q" spn: "0.35972,0.833588" sspn: "0.370369,0.833588" z: "11" } ``` The regex breaks down as follows: ``` (?: # non-capturing group \?|& # "?" or "&" (?:amp;)? # (allow "&amp;", for wrongly HTML-encoded URLs) ) # end non-capturing group ( # group 1 [^=&#]+ # any character except "=", "&" or "#"; at least once ) # end group 1 - this will be the parameter's name (?: # non-capturing group =? # an "=", optional ( # group 2 [^&#]* # any character except "&" or "#"; any number of times ) # end group 2 - this will be the parameter's value ) # end non-capturing group </pre> ```
You need to use the 'g' switch for a global search ``` var result = mystring.match(/(&|&amp;)?([^=]+)=([^&]+)/g) ```
How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?
[ "", "javascript", "regex", "" ]
I played around with it for a while, but I simply can't figure it out. I made a tank that fires missiles, and when the missiles hit the walls, I want them to bounce off, but I want them to bounce off to the right angle. Right now I haven't got any obstacles, the missiles just bounce off when they get outside the `viewportRectangle` I made. Is the solution I'm looking for quite advanced? Is there a relativly simple way to do it?
I think an easier way to do this is to use the velocity of the missile instead of calculating angles. Say you have a missile that has `xVelocity` and `yVelocity` to represent its movement horizontally and vertically. Those velocities can be positive or negative to represent left, right, up, or down. * If a missile hits a top or bottom border reverse the sign of the `yVelocity`. * If a missile hits a left or right border reverse the sign of the `xVelocity`. This will keep the movement in the opposite axis the same. Borrowing the image from [ChrisF's answer](https://stackoverflow.com/questions/573084/how-to-calculate-bounce-angle/573100#573100), let's say the missile starts out at position I. ![Angle of Reflection](https://upload.wikimedia.org/wikipedia/commons/2/24/Angle_of_Reflection_(PSF).png) With the `xVelocity` and `yVelocity` both being positive (in 2D graphics right and down are typically positive) the missile will travel in the direction indicated. Let's just assign values of ``` xVelocity = 3 yVelocity = 4 ``` When the missile hits the wall at position **C**, its `xVelocity` shouldn't change, but its `yVelocity` should be reversed to -4 so that it travels back in the up direction, but keeps going to the right. The benefit to this method is that you only need to keep track of a missile's `xPosition`, `yPosition`, `xVelocity`, and `yVelocity`. Using just these four components and your game's update rate, the missile will always get redrawn at the correct position. Once you get into more complicated obstacles that are not at straight angles or are moving, it will be a lot easier to work with X and Y velocities than with angles.
You might think that because your walls are aligned with the coordinate axes that it makes sense to write special case code (for a vertical wall, negate the x-coordinate of the velocity; for a horizontal wall, negate the y-coordinate of the velocity). However, once you've got the game working well with vertical and horizontal walls, probably the next thing you'll think is, "what about walls at arbitrary angles?" So it's worth thinking about the general case from the beginning. In the general case, suppose your missile has velocity **v** and hits a wall with surface normal **n**. ![Missile with vector v about to obliquely hit a wall with surface normal n.](https://i.stack.imgur.com/c7WTq.png) Split **v** into components **u** perpendicular to the wall and **w** parallel to it. ![Right-angled triangle with hypotenuse for v, short side u parallel to wall and long side w parallel to wall.](https://i.stack.imgur.com/e6K3L.png) Where: **u** = (**v** · **n** / **n** · **n**) **n** **w** = **v** − **u** Here, **v** · **n** is the [dot product](http://en.wikipedia.org/wiki/Dot_product) of the vectors **v** and **n**. See the link for an explanation of how to compute it. The dot product **n** · **n** evaluates to the square of the length of the normal vector; if you always keep your normals in the form of [unit vectors](http://en.wikipedia.org/wiki/Unit_vector) then **n** · **n** = 1 and you can omit the division. After bouncing, the component of motion parallel to the wall is affected by friction *f*, and the component perpendicular to the wall is affected by elasticity, which can be given in the form of a [coefficient of restitution](http://en.wikipedia.org/wiki/Coefficient_of_restitution) *r*. So the velocity after the collision is **v′** = *f* **w** − *r* **u**. In a perfectly elastic, frictionless collision, **v′** = **w** − **u**; that is, the motion is reflected about the normal at the point of collision, as in the diagram given in Bill's answer. This approach works just the same in three dimensions too. (Obviously this is a very simplified notion of bouncing; it takes no account of angular momentum or deformation. But for many kinds of video games this kind of simplification is perfectly adequate.)
How to calculate bounce angle?
[ "", "c#", "xna", "physics", "" ]
This question applies to Windows Vista! I have an application which normally works without administrative privileges. There is one activity which does need administrative privilege but I don't want to start the application itself with higher privileges when I know most of time user wont even be using that feature. I am thinking about certain method by which I can elevate the privileges of application on some event (such as press of a button). Example: ![](https://i.stack.imgur.com/7wMTs.jpg) If user clicks this button then he is prompted with UAC dialog or consent. How can I do this?
I don't believe that it is possible to elevate the currently running process. It is built into Windows Vista that administrator privileges are given to a process upon startup, as I understand. If you look at various programs that utilise UAC, you should see that they actually launch a separate process each time an administrative action needs to be performed (Task Manager is one, Paint.NET is another, the latter being a .NET application in fact). The typical solution to this problem is to specify command line arguments when launching an elevated process (abatishchev's suggestion is one way to do this), so that the launched process knows only to display a certain dialog box, and then quit after this action has been completed. Thus it should hardly be noticeable to the user that a new process has been launched and then exited, and would rather appear as if a new dialog box within the same app has been opened (especially if you some hackery to make the main window of the elevated process a child of the parent process). If you don't need UI for the elevated access, even better. For a full discussion of UAC on Vista, I recommend you see [this very through article](http://weblogs.asp.net/kennykerr/archive/2006/09/29/Windows-Vista-for-Developers-_1320_-Part-4-_1320_-User-Account-Control.aspx) on the subject (code examples are in C++, but I suspect you'll need to use the WinAPI and P/Invoke to do most of the things in C# anyway). Hopefully you now at least see the right approach to take, though designing a UAC compliant program is far from trivial...
As it was said [there](https://stackoverflow.com/questions/562350/requested-registry-access-is-not-allowed-under-windows-7/562389#562389): ``` Process.StartInfo.UseShellExecute = true; Process.StartInfo.Verb = "runas"; ``` will run the process as admin to do whatever you need with the registry, but return to your app with the normal privileges.
How to elevate privileges only when required?
[ "", "c#", ".net", "windows-vista", "uac", "privileges", "" ]
I've read conflicting opinions as to whether every BeginInvoke() has to be matched by an EndInvoke(). Are there any leaks or other problems associated with NOT calling EndInvoke()?
Delegate.EndInvoke is documented as a *thou shalt call this* (i.e. necessary - else leaks happen) - from [msdn](http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx): > **Important Note** > > No matter which technique you use, > always call EndInvoke to complete your > asynchronous call. Control.EndInvoke is OK to ignore for fire-and-forget methods - from [msdn](http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx): > You can call EndInvoke to retrieve the > return value from the delegate, if > neccesary, but this is not required. However - if you are using `Delegate.BeginInvoke` and don't want the result, consider using `ThreadPool.QueueUserWorkItem` instead - it'll make life a lot easier, and avoid the pain of `IAsyncResult` etc.
EndInvoke is not optional. More info [here](http://www.interact-sw.co.uk/iangblog/2005/05/16/endinvokerequired)
Is EndInvoke() optional, sort-of optional, or definitely not optional?
[ "", "c#", "multithreading", "delegates", "" ]
The table `Arc(x,y)` currently has the following tuples (note there are duplicates): ``` (1,2), (1,2), (2,3), (3,4), (3,4), (4,1), (4,1), (4,1), (4,2) ``` Compute the result of the query: ``` SELECT a1.x, a2.y, COUNT(*) FROM Arc a1, Arc a2 WHERE a1.y = a2.x GROUP BY a1.x, a2.y; ``` What are `a1` and `a2` referring to?
a1 and a2 are just aliases for the Arc table which is being joined to itself. You could also say, ``` Arc As a1, Arc As a2 ``` Is that what you're asking?
It's called a `self join`. You may join a table with itself, as in your task, it will result in: ``` (1, 2) (2, 3) // note the join condition, y from the right is equal to x from the left (1, 2) (2, 3) (2, 3) (3, 4) (2, 3) (3, 4) ... ``` etc. This will of course shrink after `GROUP`'ing. `a1` and `a2` refer to the instances of the table. From which part of the result you want the `x`? Use `a1.x` for the left part, `a2.x` for the right part.
Please help explain this SQL statement
[ "", "sql", "" ]
In Python 2.5, the following code raises a `TypeError`: ``` >>> class X: def a(self): print "a" >>> class Y(X): def a(self): super(Y,self).a() print "b" >>> c = Y() >>> c.a() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in a TypeError: super() argument 1 must be type, not classobj ``` If I replace the `class X` with `class X(object)`, it will work. What's the explanation for this?
The reason is that [`super()`](https://docs.python.org/2/library/functions.html#super) only operates on [new-style classes](https://docs.python.org/2/glossary.html#term-new-style-class), which in the 2.x series means extending from `object`: ``` >>> class X(object): def a(self): print 'a' >>> class Y(X): def a(self): super(Y, self).a() print 'b' >>> c = Y() >>> c.a() a b ```
In addition, don't use super() unless you have to. It's not the general-purpose "right thing" to do with new-style classes that you might suspect. There are times when you're expecting multiple inheritance and you might possibly want it, but until you know the hairy details of the MRO, best leave it alone and stick to: ``` X.a(self) ```
Python super() raises TypeError
[ "", "python", "inheritance", "python-2.x", "super", "" ]
does somebody know how can I embedd an exe file into a dll ? I have a tool which is an exe file that I call from c# code. The thing is that I want to have 1 dll containing this tool (exe file) and the dll containg my c# code. Is it possible to embedd this exe file within the resources? Thx in advance
Sure it is. You can add any file as RC\_DATA in application as resource. But I believe you will need to extract it to disk first before calling it! Which IDE/Language you are using? [EDIT] Sorry! you did mention that you are using C#. 1. Add a resource file to you application (right click application in IDE and select "Add new item". 2. Use the toolbar in resource editor to add an existing file. 3. Then extract the exe whenever required by calling code something like: System.IO.File.WriteAllBytes (@"C:\MyEXE\", Resource1.MyEXE);
It's worth baring in mind that your uses may not be too happy about you doing this. Embedding an executable that they've got no control over into a DLL that you'll extract and run will probably make people worry about the running a Trojan on their machine. It's better to leave the .EXE in the filesystem and be transparent about what your application is doing.
Embedded a *.exe into a dll
[ "", "c#", "dll", "exe", "" ]
We are looking into using an ORM and I wanted some opinions/comparisons The basic criteria we have for an ORM is: Easy to use/configure(short learning curve), flexible, the ability to abstract it away, easy to maintain Here is a list of what ORM we are looking at and what our initial impressions are 1. Open Access - seems really easy for simple stuff, but doesn't seem to have a lot of flexibility, cost isn't an issue we already own it 2. Ling to SQL - looks very simple to use and configure but is missing some functionality 3. Active Record - NHibernate made simple 4. SubSonic - looks very feature rich, but haven't really played with it much here are the ORMs we have looked at and ruled out 1. Entity is still in beta 2. NHibernate has far to much of a learning curve (we don't have 3 weeks to delicate to learning it)
We currently use SubSonic (2.0.3) and it has been an absolute lifesaver. I cannot stress enough how awesome it is. HOWEVER, we are now looking at switching away from it for various reasons (probably to NHibernate or Entity). Here are my Pros and Cons of it: Pros: * Very simple to setup and use. * Lots of great & useful, tools and features * Uses the "convention over configuration" philosophy, so very little configuration. It "just works". (As long as you do things the way it wants... :) ) Cons: * Your database design is very tightly coupled to your domain design. Make a change in your DB, and you need to change your code/domain design. * By default, SubSonic uses the ActiveRecord pattern for all data access instead of the Repository pattern, which makes it more difficult to "abstract it away". (Although I believe with v3.0 that you can swap out the default ActiveRecord templates to use the Repository pattern). * Lots of pessimistic rumours flying around about the future of SubSonic. But rumours are just that: Rumours.
I'd say you should take a look at DataObjects.NET (<http://www.x-tensive.com>). It's feature rich and pretty easy to use. It does, though, absolutely tie you to your object model, as it decides what the database structure should be based on what your object model looks like. That being said, if you want to be able to disregard the existence of the database, it's quite nice. We've used it for years and have had great success.
What ORM to Run: telerik Open Access VS Subsonic VS linq to sql VS Active Record
[ "", "c#", ".net", "orm", "data-access-layer", "" ]
I had an issue in building the resultset using Java. I am storing a collection object which is organized as row wise taken from a resultset object and putting the collection object (which is stored as vector/array list) in cache and trying to retrieve the same collection object. Here I need to build back the resultset again using the collection object. Now my doubt is building the resultset in this way possible or not?
The best idea if you are using a collection in place of a cache is to use a [CachedRowSet](http://java.sun.com/j2se/1.5.0/docs/api/javax/sql/rowset/CachedRowSet.html) instead of a ResultSet. CachedRowSet is a Subinterface of ResultSet, but the data is already cached. This is far simpler than to write all the data into an ArrayList. CachedRowSets can also be queried themselves. ``` CachedRowSet rs; ....................... ....................... Integer id; String name; while (rs.next()) { if (rs.getInt("id") == 13) { id = rs.getInt("id"); name = rs.getString("name")); } } ``` So you just call the CachedRowSet whenever you need the info. It's almost as good as sliced bread. :) **EDIT:** There are no set methods for ResultSet, while there are Update methods. The problem with using the Update method's for the purpose of rebuilding a ResultSet is that it requires selecting a Row to update. Once the ResultSet has freed itself, all rows are set to null. A null reference cannot be called. A List of Lists mimics a ResultSet itself, or more correctly, an array of arrays mimic a ResultSet. While Vectors are thread safe, there is a huge overhead attached to them. Use the ArrayList instead. As each nested List is created and placed into the outer nest List, insert it in this manner. ``` nest.add(Collections.unmodifiableList(nested)); ``` After all of the nested Lists are inserted, return the nest List as an umodifiableList as well. This will give you a thread-safe collection without the overhead of the vectors.
Take a look [at this page](http://h2database.com/html/features.html#user_defined_functions). Try to see if the SimpleResultSet class is fine for your needs. If you combine [its source](http://www.google.com/codesearch/p?hl=en#nNQkx37hnf0/trunk/h2/src/main/org/h2/tools/SimpleResultSet.java&q=SimpleResultSet%20package:http://h2database%5C.googlecode%5C.com) into a standalone set of classes, it should do the trick.
Building resultset using collection object
[ "", "java", "collections", "jdbc", "resultset", "" ]
I need to debug a web application that uses jQuery to do some fairly complex and messy [DOM](http://en.wikipedia.org/wiki/Document_Object_Model) manipulation. At one point, some of the events that were bound to particular elements, are not fired and simply stop working. If I had a capability to edit the application source, I would drill down and add a bunch of [Firebug](http://en.wikipedia.org/wiki/Firebug_%28software%29) `console.log()` statements and comment/uncomment pieces of code to try to pinpoint the problem. But let's assume I cannot edit the application code and need to work entirely in Firefox using Firebug or similar tools. Firebug is very good at letting me navigate and manipulate the DOM. So far, though, I have not been able to figure out how to do event debugging with Firebug. Specifically, I just want to see a list of event handlers bound to a particular element at a given time (using Firebug JavaScript breakpoints to trace the changes). But either Firebug does not have the capability to see bound events, or I'm too dumb to find it. :-) Any recommendations or ideas? Ideally, I would just like to see and edit events bound to elements, similarly to how I can edit DOM today.
See [How to find event listeners on a DOM node](https://stackoverflow.com/questions/446892/how-to-find-event-listeners-on-a-dom-node/447106#447106). In a nutshell, assuming at some point an event handler is attached to your element (eg): `$('#foo').click(function() { console.log('clicked!') });` You inspect it like so: * jQuery 1.3.x ``` var clickEvents = $('#foo').data("events").click; jQuery.each(clickEvents, function(key, value) { console.log(value) // prints "function() { console.log('clicked!') }" }) ``` * jQuery 1.4.x ``` var clickEvents = $('#foo').data("events").click; jQuery.each(clickEvents, function(key, handlerObj) { console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }" }) ``` See [`jQuery.fn.data`](http://docs.jquery.com/Core/data#name) (where jQuery stores your handler internally). * jQuery 1.8.x ``` var clickEvents = $._data($('#foo')[0], "events").click; jQuery.each(clickEvents, function(key, handlerObj) { console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }" }) ```
There's a nice bookmarklet called [Visual Event](http://www.sprymedia.co.uk/article/Visual+Event+2) that can show you all the events attached to an element. It has color-coded highlights for different types of events (mouse, keyboard, etc.). When you hover over them, it shows the body of the event handler, how it was attached, and the file/line number (on WebKit and Opera). You can also trigger the event manually. It can't find every event because there's no standard way to look up what event handlers are attached to an element, but it works with popular libraries like jQuery, Prototype, MooTools, YUI, etc.
How to debug JavaScript / jQuery event bindings with Firebug or similar tools?
[ "", "javascript", "jquery", "event-handling", "firebug", "jquery-events", "" ]
I'm trying to figure out how to open the system preferred editor for a given file. Say, we have a file manager, written in Java. User goes to folder and sees the list of files. And, for example, there is a file `Icon.jpg`. User double clicks on the filename and file opens in system's preferred editor (i.e. Gimp). The main issue is - how to do that? We can do `Runtime.getRuntime().exec("something file")`, but this way you should know which program is preferred in user environment. But how? We also are able to do `Desktop.getDesktop().edit(File file)`, but this way we cannot track process and aren't able to know then this child process is closed. Other issue - function doesn't work on linux (at least on Ubuntu 8.10). There is also `Desktop.getDesktop().open(File file)`, but it forces to open file viewer, instead of system viewer for that file type. I am searching for a solution all week, but didn't got any suitable and generic one. Do you know the other approaches to this question? For my project it would be enough if it would work on Windows+Linux+Mac. Thank you for your answers and advices. **Edit on 2009-02-08 23:04** Other suggestion: can I force "application selection" window in Windows and in Linux, as in Mac with "open file"? For example, then you trying to open file, you are being asked to choose application from list of system preferred ones? (something like "Open with..." in Windows explorer). Do you know?
Seems that if you can't use `java.awt.Desktop` you have to distinguish between the OSes: Windows: ``` RUNDLL32.EXE SHELL32.DLL,OpenAs_RunDLL <file.ext> ``` Linux: ``` edit <file.ext> ``` Mac: ``` open <file.ext> ``` HTH. Obviously, that is not very portable...
Check out the [java.awt.Desktop](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html) object. In your case, you want to invoke [`edit()`](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#edit(java.io.File)) If you want to ensure that a given platform supports this call, then you can do something like the following (I have not tested this code): ``` public boolean editFile(final File file) { if (!Desktop.isDesktopSupported()) { return false; } Desktop desktop = Desktop.getDesktop(); if (!desktop.isSupported(Desktop.Action.EDIT)) { return false; } try { desktop.edit(file); } catch (IOException e) { // Log an error return false; } return true; } ```
How to open user system preferred editor for given file?
[ "", "java", "file", "editor", "system", "" ]
StringBuilder has a reputation as being a faster string manipulation tool than simply concatenating strings. Whether or not that's true, I'm left wondering about the results of StringBuilder operations and the strings they produce. A quick jaunt into Reflector shows that StringBuilder.ToString() doesn't always return a copy, sometimes it seems to return an instance of the internal string. It also seems to use some internal functions to manipulate the internal strings. So what do I get if I do this? ``` string s = "Yo Ho Ho"; StringBuilder sb = new StringBuilder(s); string newString = sb.ToString(); sb.Append(" and a bottle of rum."); string newNewString = sb.ToString(); ``` Are newString and newNewString different string instances or the same? I've tried to figure this out via reflector, and I'm just not quite understanding everything. How about this code? ``` StringBuilder sb = new StringBuilder("Foo\n"); StringReader sr = new StringReader(sb.ToString()); string s = sr.ReadLine(); sb.Append("Bar\n"); s = sr.ReadLine(); ``` Will the last statement return null or "Bar"? And if it returns one or ther other, is this defined or undefined behavior? In other words, can I rely on it? The documentation is remarkably terse on this subject, and I'm reluctant to rely on observed behavior over specification.
Outside of mscorlib, any instance of a System.String is immutable, period. StringBuilder does some interesting manipulation of Strings internally but at the end of the day it won't return a string to you and then subsequently mutate it in a way that is visible to your code. As to whether subsequent calls to StringBuilder.ToString() returns the same instance of a String or a different String with the same value, that is implementation dependent and you should not rely on this behavior.
`newString` and `newNewString` are different string instances. Although `ToString()` returns the current string, it clears its current thread variable. That means next time you append, it will take a copy of the current string before appending. I'm not *entirely* sure what you're getting at in your second question, but `s` will be null: if the final characters in a file are the line termination character(s) for the previous line, the line is *not* deemed to have an empty line between those characters and the end of the file. The string which has been read previously makes no difference to this.
Are StringBuilder strings immutable?
[ "", "c#", ".net", "string", "" ]
I am trying to implement a function called "inet\_pton" which will convert a string representation of an IPv4 or IPv6 (like "66.102.1.147" [google]) into binary network-byte ordered form. Here is the relevant part of my code: ``` #if defined WIN32 int inet_pton (int af, const char *src, void *dst) { const void *data; size_t len; struct addrinfo hints, *res; hints.ai_family = af; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_NUMERICHOST; if (getaddrinfo (src, NULL, &hints, &res)) { std::cout << "ERROR : inet_pton() in " << __FILE__ << " at line " << __LINE__ << std::endl; std::cout << " : getaddrinfo() failed to get IP address info for \"" << src << "\"" << std::endl; return 0; } ... ``` So src is the incoming IP string. However, I always get an error like getaddrinfo() failed to get IP address info for "66.102.1.147" Can anyone with winsock experience comment? I also tried another method, the function ``` WSAStringToAddress ((LPTSTR)src, af, NULL, (LPSOCKADDR) &sa, &address_length) ``` But it always returns the error code WSAEINVAL, indicating an invalid IP string. This makes no sense to me. I'm using VS2005 as my IDE.
Well, for a start you're asking for a stream socket with UDP as a protocol and that just isn't going to happen. Try with: ``` hints.ai_family = af; hints.ai_socktype = 0; hints.ai_protocol = 0; hints.ai_flags = AI_NUMERICHOST; ``` and memset it to zero first as it has extra members that you're not setting... Also in my code I pass an empty string for the port or service when I don't have one rather than a null. The docs don't seem to specify what to do when you don't have a value; but either way an empty string works for me. Oh, and as always in these situations, it would be useful to know what value WSAGetLastError() returns...
MSDN has an excellent article on using getaddrinfo: <http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx> There is even an example using AI\_NUMERICHOST, which sounds like what you need. They setup their "hints" struct a bit differently than you: ``` ZeroMemory(&hints, sizeof(hints)); hints.ai_flags = AI_NUMERICHOST; hints.ai_family = AF_UNSPEC; ``` They don't set the other 2 properties. Maybe this will help?
winsock weirdness (c++)
[ "", "c++", "winsock", "" ]
Is there any difference at all between this: ``` dataContext.People.Select(ø => new { Name = ø.Name, }); ``` and this: ``` dataContext.People.Select(ø => new { ø.Name, }); ``` ?
They are identical; if no name is specified (and the right-hand-side is a simple member-access) then the name of the existing member is assumed. The name is only necessary to: * change the name to something *else* (for example `Name = grp.Key`) * to give a name to a non-member-access expression (for example `Count = grp.Count()`)
No. The second simply derives the name of the property for you, the actual code generated is the same.
C#: Anonymous types and property names
[ "", "c#", "linq", "anonymous-types", "" ]
actually i'm working with .Net Framework 3.5, so i have all these nice little features like lambdas, linq, etc. Given is a serial connection (or to be more abstract: a stream) where you receive some data, which will be in a format like this: ``` struct Packet { byte STX UInt16 DataLength string Data byte CRC byte ETX } ``` Using a simple mapping of the incoming data doesn't help due to the fact, that you don't really know how long one packet will be, cause it's written within the structure (the DataLength). So my first idea would be to read the stream by byte and put it into ???. Yes, that's the next question. Where to store this first Raw data? Into a simple byte array, with the maximum possible length (that would be 65540 bytes, due to the fact, that DataLength is an UInt16 plus the additional bytes from the other fields). Or should i open up a Queue and fill it up will all the incoming bytes or maybe exists there another nice possibility? Let's assume these problems are cleared and i have some kind of local buffer, that holds all the raw bytes from the stream. What's the nicest way to interpret it by the given structure?? Just doing some kind of for- or foreach-loop or exists there a smarter (with better performance) way (e.g. with regex or linq)? Best regards, Oliver
How about... ``` struct Packet { public byte STX; public UInt16 DataLength; public string Data; public byte CRC; public byte ETX; } //Warning: Need to add error handling class PacketReader { private BinaryReader _reader; public PacketReader(Stream stream) { _reader = new BinaryReader(stream); } Packet ReadPacket() { var packet = new Packet() { STX = _reader.ReadByte(), DataLength = _reader.ReadUInt16(), Data = Encoding.ASCII.GetString( _reader.ReadBytes(packet.DataLength)), CRC = _reader.ReadByte(), ETX = _reader.ReadByte() }; return packet; } } ``` Please note: I have not used BinaryReader.ReadString() on purpose because it is designed to operate on strings generated by BinaryWriter.WriteString(). The encoding is a bit different even though its a length prefixed string.
I would store them in a byte array and recreate them from there, its a fast and simple way to do it! I would read the bytes and convert them With BitConverter, Encoding.UTF8..
What's the 'best' way to parse a stream into a struct or class?
[ "", "c#", "" ]
Should I use LINQ's `Skip()` and `Take()` method for paging, or implement my own paging with a SQL query? Which is most efficient? Why would I choose one over the other? I'm using SQL Server 2008, ASP.NET MVC and LINQ.
Trying to give you a brief answer to your doubt, if you execute the `skip(n).take(m)` methods on linq (with SQL 2005 / 2008 as database server) your query will be using the `Select ROW_NUMBER() Over ...` statement, with is somehow direct paging in the SQL engine. Giving you an example, I have a db table called `mtcity` and I wrote the following query (work as well with linq to entities): ``` using (DataClasses1DataContext c = new DataClasses1DataContext()) { var query = (from MtCity2 c1 in c.MtCity2s select c1).Skip(3).Take(3); //Doing something with the query. } ``` The resulting query will be: ``` SELECT [t1].[CodCity], [t1].[CodCountry], [t1].[CodRegion], [t1].[Name], [t1].[Code] FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY [t0].[CodCity], [t0].[CodCountry], [t0].[CodRegion], [t0].[Name], [t0].[Code]) AS [ROW_NUMBER], [t0].[CodCity], [t0].[CodCountry], [t0].[CodRegion], [t0].[Name], [t0].[Code] FROM [dbo].[MtCity] AS [t0] ) AS [t1] WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1 ORDER BY [t1].[ROW_NUMBER] ``` Which is a windowed data access (pretty cool, btw cuz will be returning data since the very begining and will access the table as long as the conditions are met). This will be very similar to: ``` With CityEntities As ( Select ROW_NUMBER() Over (Order By CodCity) As Row, CodCity //here is only accessed by the Index as CodCity is the primary From dbo.mtcity ) Select [t0].[CodCity], [t0].[CodCountry], [t0].[CodRegion], [t0].[Name], [t0].[Code] From CityEntities c Inner Join dbo.MtCity t0 on c.CodCity = t0.CodCity Where c.Row Between @p0 + 1 AND @p0 + @p1 Order By c.Row Asc ``` With the exception that, this second query will be executed faster than the linq result because it will be using exclusively the index to create the data access window; this means, if you need some filtering, the filtering should be (or must be) in the Entity listing (where the row is created) and some indexes should be created as well to keep up the good performance. Now, whats better? If you have pretty much solid workflow in your logic, implementing the proper SQL way will be complicated. In that case LINQ will be the solution. If you can lower that part of the logic directly to SQL (in a stored procedure), it will be even better because you can implement the second query I showed you (using indexes) and allow SQL to generate and store the Execution Plan of the query (improving performance).
Try using ``` FROM [TableX] ORDER BY [FieldX] OFFSET 500 ROWS FETCH NEXT 100 ROWS ONLY ``` to get the rows from 501 to 600 in the SQL server, without loading them in memory. Note that this syntax has become available with [SQL Server 2012](http://technet.microsoft.com/en-us/library/gg699618.aspx) only
efficient way to implement paging
[ "", "sql", "sql-server", "asp.net-mvc", "linq-to-sql", "pagination", "" ]
For objects which compose another object as part of their implementation, what's the best way to write the unit test so only the principle object gets tested? Trivial example: ``` class myObj { public function doSomethingWhichIsLogged() { // ... $logger = new logger('/tmp/log.txt'); $logger->info('some message'); // ... } } ``` I know that the object could be designed so that the logger object dependency could be injected and hence mocked in a unit test, but that's not always the case - in more complicated scenarios, you do need to compose other objects or make calls to static methods. As we don't want to test the logger object, only the myObj, how do we proceed? Do we create a stubbed "double" with the test script? Something like: ``` class logger { public function __construct($filepath) {} public function info($message) {} } class TestMyObj extends PHPUnit_Framework_TestCase { // ... } ``` This seems feasible for small objects but would be a pain for more complicated APIs where the SUT depended on the return values. Also, what if you want to test the calls to the dependency object in the same was you can with mock objects? Is there a way of mocking objects which are instantiated by the SUT rather than being passed in? I've read the man page on mocks but it doesn't seem to cover this situation where the dependency is composed rather than aggregated. How do you do it?
As you seem to be aware already, Concrete Class Dependencies makes testing hard (or outright impossible). You need to decouple that dependency. A simple change, that doesn't break the existing API, is to default to the current behaviour, but provide a hook to override it. There are a number of ways that this could be implemented. Some languages have tools that can inject mock classes into code, but I don't know of anything like this for PHP. In most cases, you would probably be better off refactoring your code anyway.
Following **troelskn** advise here's a basic example of what you should do. ``` <?php class MyObj { /** * @var LoggerInterface */ protected $_logger; public function doSomethingWhichIsLogged() { // ... $this->getLogger()->info('some message'); // ... } public function setLogger(LoggerInterface $logger) { $this->_logger = $logger; } public function getLogger() { return $this->_logger; } } class MyObjText extends PHPUnit_Framework_TestCase { /** * @var MyObj */ protected $_myObj; public function setUp() { $this->_myObj = new MyObj; } public function testDoSomethingWhichIsLogged() { $mockedMethods = array('info'); $mock = $this->getMock('LoggerInterface', $mockedMethods); $mock->expects($this->any()) ->method('info') ->will($this->returnValue(null)); $this->_myObj->setLogger($mock); // do your testing } } ``` More information about mock objects can be found [in the manual](http://www.phpunit.de/manual/3.0/en/mock-objects.html).
Testing objects with dependencies in PHPUnit
[ "", "php", "unit-testing", "phpunit", "" ]
I'm building a C++ application, and I've got several utility objects that all of my classes need to use. These are things like the logging object, the global state object, the DAL object, etc... Up until this point, I've been passing all of these objects around as references into my class constructors. For example: ``` class Honda : public Car { public: Honda ( const GlobalState & state, const Log & logger, const DAL & dal ); ... private: const GlobalState & my_state; const Log & my_logger; const DAL & my_dal; } ``` This gets tedious fast, because each time I add a utility object that all of my classes need to access, I have to go and change the constructors everywhere. I've heard that the correct way to solve this problem is to create one struct that contains all the different utility objects and pass that around (as a reference) to all of the objects that need to access it. Is this the right way to handle this problem? Thanks! **UPDATE:** Thank you to everyone for the feedback. After some additional research, I've decided to continue using Dependency Injection.
You could make use of the **Service Locator** pattern. [This article](http://martinfowler.com/articles/injection.html) introduces both dependency injection (which you are currently using) and service locator. However, consider this: the idea of dependency injection is to have a system where each component has a well-defined responsibility and minimizes knowledge of other components where possible. If the component needs other components to do its job, then these are explicitly passed to it. This makes the component simpler to understand, more likely to be correct, and easier to maintain. If you regularly need to add components which need to be known throughout the system, then there may be something wrong with the design of the system (or the way new features are being added to it). The dependency injection pattern just results in this problem being explicitly visible.
You can make your GlobalState, Log, DAL classes singletons: ``` class GlobalState { public: static GlobalState& getInstance(); protected: GlobalState(); GlobalState(const GlobalState&); GlobalState& operator= (const GlobalState&); private: static GlobalState* p_instance; }; static GlobalState* GlobalState::p_instance = NULL; /*static*/ GlobalState& getInstance() { // TODO: acquire lock if multi-threaded if (!p_instance) { // first time? p_instance = new GlobalState(); // create sole instance } // TODO: release lock if multi-threaded return *p_instance; // sole instance } ``` Then, inside your various methods, ``` Honda::MyMethod() { ... const GlobalState& my_state = GlobalState::getInstance(); ... } ``` You can further simplify your life (and reduce the amount of code duplication) by [defining a singleton C++ template](http://gpwiki.org/index.php/Programming_Techniques:Singleton#A_Singleton_Class_Template_in_C.2B.2B), under certain conditions (e.g. all classes' constructors take the same number and types of arguments, etc.)
What is the best way to handle multiple object dependencies in C++?
[ "", "c++", "" ]
``` BufferedReader in; String line; while ((line = in.readLine() != null) { processor.doStuffWith(line); } ``` This is how I would process a file line-by-line. In this case, however, I want to send **two** lines of text to the processor in every iteration. (The text file I'm processing essentially stores one record on two lines, so I'm sending a single record to the processor each time.) What's the best way of doing this in Java?
Why not just read two lines? ``` BufferedReader in; String line; while ((line = in.readLine() != null) { processor.doStuffWith(line, in.readLine()); } ``` This assumes that you can rely on having full 2-line data sets in your input file.
``` BufferedReader in; String line1, line2; while((line1 = in.readLine()) != null && (line2 = in.readLine()) != null)) { processor.doStuffWith(line1, line2); } ``` Or you could concatenate them if you wanted.
What is the best way to read a text file two lines at a time in Java?
[ "", "java", "text-files", "fileparsing", "" ]
We have two PHP5 objects and would like to merge the content of one into the second. There are no notion of subclasses between them so the solutions described in the following topic cannot apply. [How do you copy a PHP object into a different object type](https://stackoverflow.com/questions/119281/how-do-you-copy-a-php-object-into-a-different-object-type) ``` //We have this: $objectA->a; $objectA->b; $objectB->c; $objectB->d; //We want the easiest way to get: $objectC->a; $objectC->b; $objectC->c; $objectC->d; ``` **Remarks:** * These are objects, not classes. * The objects contain quite a lot of fields so a **foreach** would be quite slow. * So far we consider transforming objects A and B into arrays then merging them using **array\_merge()** before re-transforming into an object but we can't say we are proud if this.
> If your objects only contain fields (no methods), this works: ``` $obj_merged = (object) array_merge((array) $obj1, (array) $obj2); ``` This actually also works when objects have methods. (tested with PHP 5.3 and 5.6)
``` foreach($objectA as $k => $v) $objectB->$k = $v; ```
What is the best method to merge two PHP objects?
[ "", "php", "oop", "object", "" ]
I've been using an OleDb connection to read excel files successfully for quite a while now, but I've run across a problem. I've got someone who is trying to upload an Excel spreadsheet with nothing in the first column and when I try to read the file, it doesn't recognize that column. I'm currently using the following OleDb connection string: Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\test.xls; Extended Properties="Excel 8.0;IMEX=1;" So, if there are 13 columns in the excel file, the OleDbDataReader I get back only has 12 columns/fields. Any insight would be appreciated.
[SpreadsheetGear for .NET](http://www.spreadsheetgear.com/products/spreadsheetgear.net.aspx) gives you an API for working with xls and xlsx workbooks from .NET. It is easier to use and faster than OleDB or the Excel COM object model. You can see the [live samples](http://www.spreadsheetgear.com/support/samples/) or try it for yourself with the [free trial](https://www.spreadsheetgear.com/downloads/register.aspx). Disclaimer: I own SpreadsheetGear LLC EDIT: StingyJack commented "*Faster than OleDb? Better back that claim up*". This is a reasonable request. I see claims all the time which I know for a fact to be false, so I cannot blame anyone for being skeptical. Below is the code to create a 50,000 row by 10 column workbook with SpreadsheetGear, save it to disk, and then sum the numbers using OleDb and SpreadsheetGear. SpreadsheetGear reads the 500K cells in 0.31 seconds compared to 0.63 seconds with OleDB - just over twice as fast. SpreadsheetGear actually creates and reads the workbook in less time than it takes to read the workbook with OleDB. The code is below. You can try it yourself with the SpreadsheetGear free trial. ``` using System; using System.Data; using System.Data.OleDb; using SpreadsheetGear; using SpreadsheetGear.Advanced.Cells; using System.Diagnostics; namespace SpreadsheetGearAndOleDBBenchmark { class Program { static void Main(string[] args) { // Warm up (get the code JITed). BM(10, 10); // Do it for real. BM(50000, 10); } static void BM(int rows, int cols) { // Compare the performance of OleDB to SpreadsheetGear for reading // workbooks. We sum numbers just to have something to do. // // Run on Windows Vista 32 bit, Visual Studio 2008, Release Build, // Run Without Debugger: // Create time: 0.25 seconds // OleDb Time: 0.63 seconds // SpreadsheetGear Time: 0.31 seconds // // SpreadsheetGear is more than twice as fast at reading. Furthermore, // SpreadsheetGear can create the file and read it faster than OleDB // can just read it. string filename = @"C:\tmp\SpreadsheetGearOleDbBenchmark.xls"; Console.WriteLine("\nCreating {0} rows x {1} columns", rows, cols); Stopwatch timer = Stopwatch.StartNew(); double createSum = CreateWorkbook(filename, rows, cols); double createTime = timer.Elapsed.TotalSeconds; Console.WriteLine("Create sum of {0} took {1} seconds.", createSum, createTime); timer = Stopwatch.StartNew(); double oleDbSum = ReadWithOleDB(filename); double oleDbTime = timer.Elapsed.TotalSeconds; Console.WriteLine("OleDb sum of {0} took {1} seconds.", oleDbSum, oleDbTime); timer = Stopwatch.StartNew(); double spreadsheetGearSum = ReadWithSpreadsheetGear(filename); double spreadsheetGearTime = timer.Elapsed.TotalSeconds; Console.WriteLine("SpreadsheetGear sum of {0} took {1} seconds.", spreadsheetGearSum, spreadsheetGearTime); } static double CreateWorkbook(string filename, int rows, int cols) { IWorkbook workbook = Factory.GetWorkbook(); IWorksheet worksheet = workbook.Worksheets[0]; IValues values = (IValues)worksheet; double sum = 0.0; Random rand = new Random(); // Put labels in the first row. foreach (IRange cell in worksheet.Cells[0, 0, 0, cols - 1]) cell.Value = "Cell-" + cell.Address; // Using IRange and foreach be less code, // but we'll do it the fast way. for (int row = 1; row <= rows; row++) { for (int col = 0; col < cols; col++) { double number = rand.NextDouble(); sum += number; values.SetNumber(row, col, number); } } workbook.SaveAs(filename, FileFormat.Excel8); return sum; } static double ReadWithSpreadsheetGear(string filename) { IWorkbook workbook = Factory.GetWorkbook(filename); IWorksheet worksheet = workbook.Worksheets[0]; IValues values = (IValues)worksheet; IRange usedRahge = worksheet.UsedRange; int rowCount = usedRahge.RowCount; int colCount = usedRahge.ColumnCount; double sum = 0.0; // We could use foreach (IRange cell in usedRange) for cleaner // code, but this is faster. for (int row = 1; row <= rowCount; row++) { for (int col = 0; col < colCount; col++) { IValue value = values[row, col]; if (value != null && value.Type == SpreadsheetGear.Advanced.Cells.ValueType.Number) sum += value.Number; } } return sum; } static double ReadWithOleDB(string filename) { String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties=Excel 8.0;"; OleDbConnection connection = new OleDbConnection(connectionString); connection.Open(); OleDbCommand selectCommand =new OleDbCommand("SELECT * FROM [Sheet1$]", connection); OleDbDataAdapter dataAdapter = new OleDbDataAdapter(); dataAdapter.SelectCommand = selectCommand; DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet); connection.Close(); double sum = 0.0; // We'll make some assumptions for brevity of the code. DataTable dataTable = dataSet.Tables[0]; int cols = dataTable.Columns.Count; foreach (DataRow row in dataTable.Rows) { for (int i = 0; i < cols; i++) { object val = row[i]; if (val is double) sum += (double)val; } } return sum; } } } ```
We always use Excel Interop to open the spreadsheet and parse directly (e.g. similar to how you would scan through cells in VBA), or we create locked down templates that enforce certain columns to be filled in before the user can save the data.
How do I read an excel file in c# without missing any columns?
[ "", "c#", ".net", "excel", "" ]
Are the following select statements SQL92 compliant? ``` SELECT table1.id, table2.id,* FROM table1, table2 WHERE table1.id = table2.id ``` --- ``` SELECT table1.Num, table2.id,* FROM table1, table2 WHERE table1.Num = table2.id ```
Yes, the queries you show use SQL92 compliant syntax. My copy of "[Understanding the New SQL: A Complete Guide](https://rads.stackoverflow.com/amzn/click/com/1558602453)" by Jim Melton & Alan R. Simon confirms it. SQL92 still supports joins using the comma syntax, for backward compatibility with SQL89. As far as I know, all SQL implementations support both comma syntax and `JOIN` syntax joins. In most cases, the SQL implementation knows how to optimize them so that they are identical in semantics (that is, they produce the same result) and performance.
Following on from StingyJack... ``` SELECT table1.id, table2.id, * FROM table1 INNER JOIN table2 ON table1.id = table2.id WHERE table1.column = 'bob' SELECT table1.id, table2.id,* FROM table1, table2 WHERE table1.id = table2.id and table1.column = 'bob' ``` Where's the JOIN? Where's the filter? JOIN also forces some discipline and basic checking: easier to avoid cross join or partial cross joins
Are the following select statements SQL92 compliant?
[ "", "sql", "ansi-92", "" ]
I am able use UTF-8 characters just fine in my scripts. As a matter of fact it is possible to [have names of variables and functions contain Unicode characters](http://www.script-tease.net/utfthis.php). There is also the [mb\_string extension](http://us.php.net/mb_string) which deals with multi-byte strings, yet in countless articles PHP is criticized for its lack of Unicode support. I don't get it; why is PHP said to not support Unicode?
When PHP was started several years ago, UTF-8 was not really supported. We are talking about a time when non-Unicode OS like Windows 98/Me was still current and when other big languages like Delphi were also non-Unicode. Not all languages were designed with Unicode in mind from day 1, and completely changing your language to Unicode without breaking a lot of stuff is hard. Delphi only became Unicode compatible a year or two ago for example, while other languages like Java or C# were designed in Unicode from Day 1. So when PHP grew and became PHP 3, PHP 4 and now PHP 5, simply no one decided to add Unicode. Why? Presumably to keep compatible with existing scripts or because utf8\_de/encode and mb\_string already existed and work. I do not know for sure, but I strongly believe that it has something to do with organic growth. Features do not simply exist by default, they have to be written by someone, and that simply did not happen for PHP yet. Edit: Ok, I read the question wrong. The question is: How are strings stored internally? If I type in "Währung" or "Écriture", which Encoding is used to create the bytes used? In case of PHP, it is ASCII with a Codepage. That means: If I encode the string using ISO-8859-15 and you decode it with some chinese codepage, you will get weird results. The alternative is in languages like C# or Java where everything is stored as Unicode, which means: There is no codepage anymore, and theoretically you cannot mess up. I recommend [Joel's article](http://www.joelonsoftware.com/articles/Unicode.html) about Unicode and Character Sets, but essentially it boils down to: How are strings stored internally, and the answer with PHP is "Not in Unicode", which means that you have to be very careful and explicit when processing strings to make sure to always keep the string in the proper encoding during input, storage (database) and output, which is very errorprone.
i believe it is largely a cultural difficulty, not a technical one. as for the technical problems---and its not downright all-trivial to implement unicode in an ecosystem built on the assumptions that 'one character equals one byte'---the developers could have copied much of java's or python's efforts (the latter with decent and largely working unicode compatibility since around 2001), but they never did. when i read [the discussion thread attached to the official, current documentation for php's `utf8_encode()` function](http://php.net/manual/en/function.utf8-encode.php), i get a feeling of vertigo. firstoff, that function is called `utf8_encode()`; however, the documentation states that the string it expects is expected to be in ISO-8859-1 (a.k.a. latin-1). that's sooo php, that's sooo 80s. most commenters seem to perceive unicode as a burden. there are many proposals how to convert strings 'of unknown content', how to deal with s'strings with mixed encodings' (wtf?), or dealing with codepoints that normally cause breakage because they are beyond that function's four-bytes-per-codepoint limit. the discussion is centered around fixups to get rid of squiggles or to avoid the problematic parts of that function's behavior. and that, to me, is sooo php: everyone's just doing fixes, few things are implemented in a fundamentally correct way. if you believe this to be slander on my side, here are some tidbits: > Although this seems to break german Umlaute [äöü] if the document is already UTF-8. (failure to understand that utf-8 is not designed to work when applied twice) > Look at iconv() function, which offers a way to convert from 8859 and dreaded 1252 into UTF8 (good point: neglection of prior art on part of the php developers; instead, buggy own implementation) > use of preg\_match to detect if utf8\_encode is needed [...] excluding surrogates [...] excluding overlongs (suggesting to silently erase all problematic content from strings, leaving only those things that do not break `utf8_encode()`; this may make texts unreadable (or vanish altogether), but hey, no more error messages) > to encode a string only if it is not yet UTF-8 [...] `mb_detect_encoding($s, "UTF-8")` (as pointed out [by another commenter](http://www.php.net/manual/en/function.mb-detect-encoding.php#102510), this is not going to work: ``` $str = 'áéóú'; // ISO-8859-1 mb_detect_encoding($str, 'UTF-8'); // 'UTF-8' mb_detect_encoding($str, 'UTF-8', true); // false ``` so here we're looking at one bug being replaced by another one. happy hunting. also, what they seem to propose here is to solve a problem using heuristics (slow, uncertain) means that could and should be solved with mechanical (fast, certain) means) > utf8\_[encode|decode] will actually translate windows-1252 characters as well, not just from/to ISO-8859-1 as the documentation says (you cannot ever rely on the official php documentation to be clear or exhaustive---you must always read through years of users experience which no-one will ever feed back to the docs) > I've been working on a is\_utf8 function and wanted to post it here, in addition to others i also took in consideration the 5000 char bug (a fix for a problem that largely only exists because unicode is not properly implemented. we also learn that not only will the `utf8_encode()` function give up beyond 4 bytes per codepoint, it will also break if the resulting (or output?) text exceeds a limit of 5000 characters) i could go on and on like this. you already get the idea: judging from this thread, the php community simply does not sound like they're anywhere ready to grasp what encodings and character sets are all about, what it takes to build a sound infrastructure in general or, specifically, to implement unicode in a proper way. instead, they're using their scaffolds, their cardboards, their nails and hammers and go on building this grand edifice called php, throwing their duct tape at every problems that can't be undone with another nail. of course, that building will suffer from every wind that comes blowing, such as the occasional legal but unexpected character. seeing this particular thread being active for eight years does not exactly instill confidence the situation is going to be any better in eight years from now.
What factors make PHP Unicode-incompatible?
[ "", "php", "unicode", "" ]
How can I convert strings which can denote decimal or rational numbers to floats ``` >>> ["0.1234", "1/2"] ['0.1234', '1/2'] ``` I'd want [0.1234, 0.5]. eval is what I was thinking but no luck: ``` >>> eval("1/2") 0 ```
I'd parse the string if conversion fails: ``` >>> def convert(s): try: return float(s) except ValueError: num, denom = s.split('/') return float(num) / float(denom) ... >>> convert("0.1234") 0.1234 >>> convert("1/2") 0.5 ``` Generally using eval is a bad idea, since it's a security risk. *Especially* if the string being evaluated came from outside the system.
As others have pointed out, using `eval` is potentially a security risk, and certainly a bad habit to get into. (if you don't think it's as risky as `exec`, imagine `eval`ing something like: `__import__('os').system('rm -rf /')`) However, if you have python 2.6 or up, you can use [`ast.literal_eval`](http://docs.python.org/library/ast.html#ast.literal_eval), for which the string provided: > may only consist of the following > Python literal structures: strings, > numbers, tuples, lists, dicts, > booleans, and None. Thus it should be quite safe :-)
How to convert rational and decimal number strings to floats in python?
[ "", "python", "rational-numbers", "" ]
I have this XAML: ``` <UserControl x:Class="M_Cubed.Controls.TagEditor" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:classes="clr-namespace:M_Cubed.Classes"> <UserControl.Resources> <DataTemplate DataType="{x:Type classes:TagEditorPic}"> <ComboBox DataContext="{StaticResource PicTypes}" ItemsSource="{Binding}"/> </DataTemplate> </UserControl.Resources> </UserControl> ``` I have this C#: ``` namespace M_Cubed.Classes { public class TagEditorPic : INotifyPropertyChanged { public TagEditorPic() { } } } ``` And I get this error: Type reference cannot find public type named 'TagEditorPic'. Any suggestions?
I decided I'll just set the x:Key attribute on the datatemplate and just bind the template properties onwards to the StaticResource of the x:Key. It works fine with me.
It's because you didn't implement INotifyPropertyChanged. If you implement that, then your control will compile. It doesn't find the control because it can't compile the TagEditorPic class in the first place. Since that isn't a viable class, the XAML parser doesn't know what to do.
WPF: Datatemplate For Class
[ "", "c#", "wpf", "datatemplate", "" ]
In this article: [<http://msdn.microsoft.com/en-us/library/ms171728(VS.80).aspx>](http://msdn.microsoft.com/en-us/library/ms171728(VS.80).aspx) The author uses the following method to make thread-safe calls to a Windows Forms control: ``` private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } } ``` Is there a shorter way to accomplish the same thing?
**C# 3.0 and after:** An extension method would generally be the way to go, since you're always going to want to perform an action on an [`ISynchronizeInvoke` interface](http://msdn.microsoft.com/en-us/library/system.componentmodel.isynchronizeinvoke.aspx) implementation, it's a good design choice. You can also take advantage of [anonymous methods](http://msdn.microsoft.com/en-us/library/0yw3tz5k%28v=vs.80%29.aspx) (closures) to account for the fact that you don't know what parameters to pass to the extension method; the closure will capture the state of everything needed. ``` // Extension method. static void SynchronizedInvoke(this ISynchronizeInvoke sync, Action action) { // If the invoke is not required, then invoke here and get out. if (!sync.InvokeRequired) { // Execute action. action(); // Get out. return; } // Marshal to the required context. sync.Invoke(action, new object[] { }); } ``` You'd then call it like this: ``` private void SetText(string text) { textBox1.SynchronizedInvoke(() => textBox1.Text = text); } ``` Here, the closure is over the `text` parameter, that state is captured and passed as part of the [`Action` delegate](http://msdn.microsoft.com/en-us/library/system.action.aspx) passed to the extension method. **Before C# 3.0:** You don't have the luxury of lambda expressions, but you can still generalize the code. It's pretty much the same, but not an extension method: ``` static void SynchronizedInvoke(ISynchronizeInvoke sync, Action action) { // If the invoke is not required, then invoke here and get out. if (!sync.InvokeRequired) { // Execute action. action(); // Get out. return; } // Marshal to the required context. sync.Invoke(action, new object[] { }); } ``` And then you call it with anonymous method syntax: ``` private void SetText(string text) { SynchronizedInvoke(textBox1, delegate() { textBox1.Text = text; }); } ```
1) Using anonymous delegate ``` private void SetText(string text) { if (this.InvokeRequired) { Invoke(new MethodInvoker(delegate() { SetText(text); })); } else { this.textBox1.Text = text; } } ``` 2) AOP approach ``` [RunInUIThread] private void SetText(string text) { this.textBox1.Text = text; } ``` <http://weblogs.asp.net/rosherove/archive/2007/05.aspx?PageIndex=2> 3) Using lambda expressions (outlined by others).
Shortest way to write a thread-safe access method to a windows forms control
[ "", "c#", "thread-safety", "" ]
I'm new to using Linq and just started a side project to learn some of the basics. I'm currently using Linq to Sql and all my DB Table relationships worked very well. Currently I have a Client table and a Project table. Each Client can have 1 or more Projects. Therefore, as you'd expect each Client object has a collection of Project objects after Linq does its magic. I'm using the below code and it works well, but I think there is a better way of doing it. I need to pass my method a ProjectID and then select that Project from the Client: ``` private void PopulateStatusView(int projectID) { MyDataContext db = new MyDataContext(); var client = (from u in db.Clients where u.id == Convert.ToInt32(Session["ClientID"]) select u).SingleOrDefault(); if (client != null) { foreach (Project currentProject in client.Projects) { if (currentProject.id == projectID) { // Project Selected Here statusProjectName.Text = currentProject.name; } } } else { // Session Expired } } ``` Can anyone let me know if there's a better solution rather than looping over each Project. Thank you.
To get the client which has the specific project ID: ``` var client = (from u in db.Clients where u.id == Convert.ToInt32(Session["ClientID"]) && u.Projects.Any(x=>x.id == projectID) select u).SingleOrDefault(); ``` To get the project: ``` var project = (from u in db.Clients where u.id == Convert.ToInt32(Session["ClientID"]) && u.Projects.Any(x=>x.id == projectID) select u.Projects.Where(x=>x.id == projectID).Single()).SingleOrDefault(); ```
Try something like this: ``` clients.Projects.Where( p => p.id == projectID && p.name == statusProjectName.Text); ```
Linq to Sql - Select from 1:Many
[ "", "c#", "asp.net", "linq-to-sql", "" ]
I have the following function: ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER FUNCTION [dbo].[IP4toBIGINT]( @ip4 varchar(15) ) RETURNS bigint WITH SCHEMABINDING AS BEGIN -- oc3 oc2 oc1 oc0 -- 255.255.255.255 -- Declared as BIGINTs to avoid overflows when multiplying later on DECLARE @oct0 bigint, @oct1 bigint, @oct2 bigint, @oct3 bigint; DECLARE @Result bigint; SET @oct3 = CAST(PARSENAME(@ip4, 4) as tinyint); SET @oct2 = CAST(PARSENAME(@ip4, 3) as tinyint); SET @oct1 = CAST(PARSENAME(@ip4, 2) as tinyint); SET @oct0 = CAST(PARSENAME(@ip4, 1) as tinyint); -- Combine all values, multiply by 2^8, 2^16, 2^24 to bitshift. SET @Result = @oct3 * 16777216 + @oct2 * 65536 + @oct1 * 256 + @oct0; RETURN @Result; END ``` But... ``` SELECT OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'IsDeterministic') as IsDeterministic ,OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'IsPrecise') as IsPrecise ,OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'IsSystemVerified') as IsSystemVerified ,OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'SystemDataAccess') as SystemDataAccess ,OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'UserDataAccess') as UserDataAccess ``` Returns (result transposed): IsDeterministic 0 IsPrecise 1 IsSystemVerified 1 SystemDataAccess 0 UserDataAccess 0 I tried dropping and recreating the function several times to make sure it's not some caching issue. CAST should be deterministic here since I'm using it for strings->integers. I'm completely stumped, any ideas?
PARSENAME is nondeterministic, on the whole. Yes, you are using it in a context which is deterministic, but I'm guessing that the server does not know that. Try replacing PARSENAME and see if it changes.
It's the PARSENAME causing problems. Replacing it with a hardcoded string results in determinism. No idea why... parse name is supposedly just a fancy split function. Check this out: ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER FUNCTION [dbo].[IP4toBIGINT]( @ip4 varchar(15) ) RETURNS bigint WITH SCHEMABINDING AS BEGIN -- oc3 oc2 oc1 oc0 -- 255.255.255.255 -- Declared as BIGINTs to avoid overflows when multiplying later on DECLARE @oct0 bigint, @oct1 bigint, @oct2 bigint, @oct3 bigint; DECLARE @Result bigint; SET @oct3 = CAST('1' as tinyint); SET @oct2 = CAST('2' as tinyint); SET @oct1 = CAST('3' as tinyint); SET @oct0 = CAST('4' as tinyint); -- Combine all values, multiply by 2^8, 2^16, 2^24 to bitshift. SET @Result = @oct3 * 16777216 + @oct2 * 65536 + @oct1 * 256 + @oct0 RETURN @Result END GO SELECT OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'IsDeterministic') as IsDeterministic ,OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'IsPrecise') as IsPrecise ,OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'IsSystemVerified') as IsSystemVerified ,OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'SystemDataAccess') as SystemDataAccess ,OBJECTPROPERTYEX(OBJECT_ID('dbo.IP4toBIGINT'), 'UserDataAccess') as UserDataAccess ``` Results: ``` IsDeterministic IsPrecise IsSystemVerified SystemDataAccess UserDataAccess 1 1 1 0 0 ```
Why does SQL 2005 say this UDF is non-deterministic?
[ "", "sql", "user-defined-functions", "deterministic", "non-deterministic", "" ]
When the user tabs into my `NumericUpDown` I would like all text to be selected. Is this possible?
``` private void NumericUpDown1_Enter(object sender, EventArgs e) { NumericUpDown1.Select(0, NumericUpDown1.Text.Length); } ``` (Note that the Text property is hidden in Intellisense, but it's there)
I wanted to add to this for future people who have been search for Tab and Click. Jon B answer works perfect for Tab but I needed to modify to include click Below will select the text if you tab in or click in. If you click and you enter the box then it will select the text. If you are already focused on the box then the click will do what it normally does. ``` bool selectByMouse = false; private void quickBoxs_Enter(object sender, EventArgs e) { NumericUpDown curBox = sender as NumericUpDown; curBox.Select(); curBox.Select(0, curBox.Text.Length); if (MouseButtons == MouseButtons.Left) { selectByMouse = true; } } private void quickBoxs_MouseDown(object sender, MouseEventArgs e) { NumericUpDown curBox = sender as NumericUpDown; if (selectByMouse) { curBox.Select(0, curBox.Text.Length); selectByMouse = false; } } ``` You can use this for multiple numericUpDown controls. Just need to set the Enter and MouseDown Events
How to select all text in Winforms NumericUpDown upon tab in?
[ "", "c#", ".net", "winforms", "numericupdown", "" ]
How can I paint in red every time I meet the letter "A" in RichTextBox?
Try this: ``` static void HighlightPhrase(RichTextBox box, string phrase, Color color) { int pos = box.SelectionStart; string s = box.Text; for (int ix = 0; ; ) { int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase); if (jx < 0) break; box.SelectionStart = jx; box.SelectionLength = phrase.Length; box.SelectionColor = color; ix = jx + 1; } box.SelectionStart = pos; box.SelectionLength = 0; } ``` ... ``` private void button1_Click(object sender, EventArgs e) { richTextBox1.Text = "Aardvarks are strange animals"; HighlightPhrase(richTextBox1, "a", Color.Red); } ```
Here is a snippet out of my wrapper class to do this job: ``` private delegate void AddMessageCallback(string message, Color color); public void AddMessage(string message) { Color color = Color.Empty; string searchedString = message.ToLowerInvariant(); if (searchedString.Contains("failed") || searchedString.Contains("error") || searchedString.Contains("warning")) { color = Color.Red; } else if (searchedString.Contains("success")) { color = Color.Green; } AddMessage(message, color); } public void AddMessage(string message, Color color) { if (_richTextBox.InvokeRequired) { AddMessageCallback cb = new AddMessageCallback(AddMessageInternal); _richTextBox.BeginInvoke(cb, message, color); } else { AddMessageInternal(message, color); } } private void AddMessageInternal(string message, Color color) { string formattedMessage = String.Format("{0:G} {1}{2}", DateTime.Now, message, Environment.NewLine); if (color != Color.Empty) { _richTextBox.SelectionColor = color; } _richTextBox.SelectedText = formattedMessage; _richTextBox.SelectionStart = _richTextBox.Text.Length; _richTextBox.ScrollToCaret(); } ``` Now you can call it with `AddMessage("The command failed")` to get it automatically highlight in red. Or you can call it with `AddMessage("Just a special message", Color.Purple)` to define a special color (Helpful e.g. within catch blocks to define a specific color, regardless of the message content)
Selectively coloring text in RichTextBox
[ "", "c#", "format", "richtextbox", "" ]
Suppose I've developed a general-purpose end user utility written in Python. Previously, I had just one version available which was suitable for Python later than version 2.3 or so. It was sufficient to say, "download Python if you need to, then run this script". There was just one version of the script in source control (I'm using Git) to keep track of. With Python 3, this is no longer necessarily true. For the foreseeable future, I will need to simultaneously develop two different versions, one suitable for Python 2.x and one suitable for Python 3.x. From a development perspective, I can think of a few options: 1. Maintain two different scripts in the same branch, making improvements to both simultaneously. 2. Maintain two separate branches, and merge common changes back and forth as development proceeds. 3. Maintain just one version of the script, plus check in a patch file that converts the script from one version to the other. When enough changes have been made that the patch no longer applies cleanly, resolve the conflicts and create a new patch. I am currently leaning toward option 3, as the first two would involve a lot of error-prone tedium. But option 3 seems messy and my source control system is supposed to be managing patches for me. For distribution packaging, there are more options to choose from: 1. Offer two different download packages, one suitable for Python 2 and one suitable for Python 3 (the user will have to know to download the correct one for whatever version of Python they have). 2. Offer one download package, with two different scripts inside (and then the user has to know to run the correct one). 3. One download package with two version-specific scripts, and a small stub loader that can run in both Python versions, that runs the correct script for the Python version installed. Again I am currently leaning toward option 3 here, although I haven't tried to develop such a stub loader yet. Any other ideas?
**Edit:** my original answer was based on the state of 2009, with Python 2.6 and 3.0 as the current versions. Now, with Python 2.7 and 3.3, there are other options. In particular, it is now quite feasible to use a single code base for Python 2 and Python 3. See [Porting Python 2 Code to Python 3](http://docs.python.org/3/howto/pyporting.html) **Original answer:** The [official recommendation](http://docs.python.org/3.0/whatsnew/3.0.html#porting-to-python-3-0) says: > For porting existing Python 2.5 or 2.6 > source code to Python 3.0, the best > strategy is the following: > > 1. (Prerequisite:) Start with excellent test coverage. > 2. Port to Python 2.6. This should be no more work than the average port > from Python 2.x to Python 2.(x+1). > Make sure all your tests pass. > 3. (Still using 2.6:) Turn on the -3 command line switch. This enables > warnings about features that will be > removed (or change) in 3.0. Run your > test suite again, and fix code that > you get warnings about until there are > no warnings left, and all your tests > still pass. > 4. Run the 2to3 source-to-source translator over your source code tree. > (See 2to3 - Automated Python 2 to 3 > code translation for more on this > tool.) Run the result of the > translation under Python 3.0. Manually > fix up any remaining issues, fixing > problems until all tests pass again. > > It is not recommended to try to write > source code that runs unchanged under > both Python 2.6 and 3.0; you’d have to > use a very contorted coding style, > e.g. avoiding print statements, > metaclasses, and much more. If you are > maintaining a library that needs to > support both Python 2.6 and Python > 3.0, the best approach is to modify step 3 above by editing the 2.6 > version of the source code and running > the 2to3 translator again, rather than > editing the 3.0 version of the source > code. Ideally, you would end up with a single version, that is 2.6 compatible and can be translated to 3.0 using 2to3. In practice, you might not be able to achieve this goal completely. So you might need some manual modifications to get it to work under 3.0. I would maintain these modifications in a branch, like your option 2. However, rather than maintaining the final 3.0-compatible version in this branch, I would consider to apply the manual modifications *before* the 2to3 translations, and put this modified 2.6 code into your branch. The advantage of this method would be that the difference between this branch and the 2.6 trunk would be rather small, and would only consist of manual changes, not the changes made by 2to3. This way, the separate branches should be easier to maintain and merge, and you should be able to benefit from future improvements in 2to3. Alternatively, take a bit of a "wait and see" approach. Proceed with your porting only so far as you can go with a single 2.6 version plus 2to3 translation, and postpone the remaining manual modification until you really need a 3.0 version. Maybe by this time, you don't need any manual tweaks anymore...
I don't think I'd take this path at all. It's painful whichever way you look at it. Really, unless there's strong commercial interest in keeping both versions simultaneously, this is more headache than gain. I think it makes more sense to just keep developing for 2.x for now, at least for a few months, up to a year. At some point in time it will be just time to declare on a final, stable version for 2.x and develop the next ones for 3.x+ For example, I won't switch to 3.x until some of the major frameworks go that way: PyQt, matplotlib, numpy, and some others. And I don't really mind if at some point they stop 2.x support and just start developing for 3.x, because I'll know that in a short time I'll be able to switch to 3.x too.
Python 3 development and distribution challenges
[ "", "python", "version-control", "python-3.x", "" ]
I have a 2 monitors and a WinForm app that launches a WPF window. I want to get the screen that the WinForm is on, and show the WPF window on the same screen. How can I do this?
WPF doesn't include the handy System.Windows.Forms.**Screen** class, but you can still use its properties to accomplish your task in your WinForms application. Assume that **this** means the WinForms window and **\_wpfWindow** is a defined variable referencing the WPF Window in the example below (this would be in whatever code handler you set to open the WPF Window, like some Button.Click handler): ``` Screen screen = Screen.FromControl(this); _wpfWindow.StartupLocation = System.Windows.WindowStartupLocation.Manual; _wpfWindow.Top = screen.Bounds.Top; _wpfWindow.Left = screen.Bounds.Left; _wpfWindow.Show(); ``` The above code will instantiate the WPF Window at the Top-Left corner of the screen containing your WinForms Window. I'll leave the math to you if you wish to place it in another location like the middle of the screen or in a "cascading" style below and to the right of your WinForms Window. Another method that gets the WPF Window in the middle of the screen would be to simply use ``` _wpfWIndow.StartupLocation = System.Windows.WindowStartupLocation.CenterScreen ``` However, this isn't quite as flexible because it uses the position of the mouse to figure out which screen to display the WPF Window (and obviously the mouse could be on a different screen as your WinForms app if the user moves it quickly, or you use a default button, or whatever). Edit: [Here's a link to an SDK document](http://blogs.msdn.com/wpfsdk/archive/2007/04/03/centering-wpf-windows-with-wpf-and-non-wpf-owner-windows.aspx) about using InterOp to get your WPF Window centered over the non-WPF Window. It does basically what I was describing in terms of figuring out the math, but correctly allows you to set the WPF Window's "Owner" property using the Window's HWND.
Here's the simplest way (uses WindowStartupLocation.CenterOwner). ``` MyDialogWindow dialogWindow = new MyDialogWindow(); dialogWindow.Owner = this; dialogWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; dialogWindow.ShowDialog(); ``` No need for interop or setting window coords :)
Showing a window with WPF, Winforms, and Dual monitors
[ "", "c#", "wpf", "winforms", "multiple-monitors", "" ]
I use the console.out.writeline() to print the coordinates belonging to the different sprites in a XNA game. But after a few seconds, the game starts to go really slow, and almost stop. (When not writing to the console, there are no problems with performance). (The sprite's positions are written in every update method) Is there a way to write to the console without destroying the performance to the game?
Are you able to write to a log file instead of the console? That may well be faster due to buffering and the lack of scrolling, displaying etc. Do you actually have a console up while this is running? If so, try minimising it when you're not interested. My guess is it's the scrolling which is causing the problem. EDIT: Okay, it seems some evidence is in order. A few tests... I don't have XNA installed, but different ways of writing to consoles are still interesting. I wrote the numbers 0-99999 to various consoles: * As a WinForms app, under the debugger, to the Visual Studio console: 135000ms, whether the console was visible or covered up. * As a WinForms app, under the debugger, writing to a file: 160ms * As a console app, not under the debugger, console minimised: 4149ms * As a console app, not under the debugger, console not minimised: 14514ms So as you can see, the Visual Studio console is painfully slow, a non-minimised "normal" console is next slowest, a minimised console is reasonably nippy, and writing to a file is very quick. I stand by my advice to try writing to a file instead of the console, and otherwise if it's a standalone console, try to minimise it for most of the time.
"Is there a way to write to the console without destroying the performance to the game?" Well, you could create your *own ingame console* like most game engines do (most notably Quake), and display the console when a key is pressed. Edit: if you don't want to implement your own console, there is a project doing this: <http://www.codeplex.com/XnaConsole> which has advantages over the Win32 console, because it runs in game, at game framerate, and won't make you loose your device when switching between the console and your xna app. (Although device recovery is automatic in XNA, loosing the device still happens under the covers)
Xna debugging
[ "", "c#", "debugging", "xna", "console.out.writeline", "" ]
Actually this question is based on a [Blog Entry](http://enricofoschi.wordpress.com/2008/08/21/how-to-check-with-javascript-if-a-firefox-add-on-extension-is-installed/), which discusses the topic for FF2. But how does this work with FireFox 3? I know that there must be a workaround, because recently I visited a site saying: "Please disable AdBlock+ before entering this site" :(
There's no general-purpose way to do that, for security reasons. Even the FF2 version mentioned there was specific to that particular extension -- you can't assume identically-named and -placed icons for all extensions. The AdBlock-spotters, as Stephen presumed, tend to be behavior-based and specific to that extension. Likewise Greasemonkey-spotters, etc.
Please see this url. <http://www.guyfromchennai.com/?p=104> This is worked for me
How to check with Javascript if a Firefox 3 Add-on / Extension is installed
[ "", "javascript", "firefox", "add-on", "" ]
Is there a way to monitor and capture all outgoing HTTP requests from a machine using C#? I need a browser independent way of logging visited URLs.
You may want to use existing network interfaces capturing libraries like pcap or winpcap to do so. Rewriting all the necessary stuff by yourself would be quite time expensive. Link to [Pcap](http://www.tcpdump.org/pcap.htm) Link to [WinPcap](http://www.winpcap.org/) Edit : Just saw someone also wrote the C# bindings to winpcap : [SharpPcap](http://www.codeproject.com/KB/IP/sharppcap.aspx)
I use fiddler ( <http://www.fiddler2.com> )
Capturing HTTP requests
[ "", "c#", "http", "" ]
In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class. But I'm wondering if there's any way around this. I'm trying to write a wrapper for someone else's (somewhat clunky) function. The function in question can be applied to lots of different data types but requires different flags and options for each. But 99% of the time, a default for each type would suffice. It would be nice if this could be done with inheritance, without having to write new functions each time. For example: ``` class Foo { public static $default = 'DEFAULT'; public static function doSomething ($param = FALSE ) { $param = ($param === FALSE) ? self::$default : $param; return $param; } } class Bar extends Foo { public static $default = 'NEW DEFAULT FOR CHILD CLASS'; } echo Foo::doSomething() . "\n"; // echoes 'DEFAULT' echo Bar::doSomething() . "\n"; // echoes 'DEFAULT' not 'NEW DEFAULT FOR CHILD CLASS' // because it references $default in the parent class :( ```
Classic example of why using statics as globals (functions in this case) is a bad idea no matter the language. The most robust method is to create multiple implementation sub classes of an abstract base "Action" class. Then to try and remove some of the annoyance of instantiating an instance of the class just to call it's methods, you can wrap it in a factory of some sort. For example: ``` abstract class AbstractAction { public abstract function do(); } class FooAction extends AbstractAction { public function do() { echo "Do Foo Action"; } } class BarAction extends AbstractAction { public function do() { echo "Do Bar Action"; } } ``` Then create a factory to "aid" in instantiation of the function ``` class ActionFactory { public static function get($action_name) { //... return AbstractAction instance here } } ``` Then use it as: ``` ActionFactory::get('foo')->do(); ```
Actually I think it is not true: you can ovverride static propeties (**you need >=5.3 PHP** for that). But you have to be careful when refrencing for that static property (and this is the mistake in the original code) You need to use **static::$myStaticProperty** instead of using self::$myStaticProperty **self::** will refrence to the **current class** so if you are inside an inherited static method this will refrence the static property of that class defined that method! While using reference keyword static:: will act like $this - when you are using instance methods/propeties. doSomething() is an inherited static method in class Bar in your example. Since you used self:: there, it will reference to the static property of class Foo. This is the reason why you didn't see any difference... **Try to change self:: to static::**! Here is a code example - I used it myself to test those things. We have static property/method inheritance, override and value change in it - run it and you will see the result! ``` class A { // a static property - we will test override with it protected static $var = 'class A var - override'; // a static property - we will test value overwrite with it protected static $var2 = 'class A var2 - value overwrite'; public static function myStaticOverridePropertyTest() { return static::$var; } public static function myStaticValueOverwritePropertyTest() { return static::$var2; } /** * This method is defined only here - class B will inherit this one! * We use it to test the difference btw self:: and static:: * * @return string */ public static function myStaticMethodTest() { //return self::getValue(); return static::getValue(); } /** * This method will be overwritten in class B * @return string */ protected static function getValue() { return 'value from class A'; } } class B extends A { // we override this inherited static property protected static $var = 'class B var - override'; /** * This method is overwritten from class A * @return string */ protected static function getValue() { return 'value from class B'; } /** * We modify the value of the inherited $var2 static property */ public static function modStaticProperty() { self::$var2 = 'class B - altered value! - value overwrite'; } } echo ("-- testing class A:\n"); echo (A::myStaticOverridePropertyTest(). "\n"); echo (A::myStaticValueOverwritePropertyTest(). "\n"); echo (A::myStaticMethodTest(). "\n"); echo ("-- now testing class B:\n"); echo (B::myStaticOverridePropertyTest(). "\n"); echo (B::myStaticValueOverwritePropertyTest(). "\n"); echo (" now invoking B::modStaticProperty() .\n"); B::modStaticProperty(); echo (B::myStaticValueOverwritePropertyTest(). "\n"); echo ("-- now re-testing class A:\n"); echo (A::myStaticOverridePropertyTest(). "\n"); echo (A::myStaticValueOverwritePropertyTest(). "\n"); echo (A::myStaticMethodTest(). "\n"); ``` This will output: -- testing class A: class A var - override class A var2 - value overwrite value from class A -- now testing class B: class B var - override class A var2 - value overwrite now invoking B::modStaticProperty() ... class B - altered value! - value overwrite -- now re-testing class A: class A var - override **class B - altered value! - value overwrite** value from class A And here we are, you can see the difference between overriden and only value overwritten static properties... look the output line I marked with bold! When we invoked the modStaticProperty() of class B, it changed the value of that static variable in class A too. Since that static property was inherited and was not overriden! Think about it...
Inheritance of static members in PHP
[ "", "php", "inheritance", "" ]
What is the set of valid outputs for the following, according to the standard? ``` bool x; cout << (x ? 1 : 2); ``` edit: **unknown(google)** has got it. In gcc my code was crashing because of `sprite.setFrame(isPressed ? 0 : 1)` with the conditional returning 28!
> Using a bool value in ways described > by This Standard as "undefined" such > as by examining the value of an > unitialized automatic variable, might > cause it to behave as it is neither > true or false. Welcome to the world of undefined behaviour. But first, why would you want to do that?
If x is uninitialized, it can be both true or false. So the valid outputs are 1 or 2.
What are the valid values of the expression (uninitialized_bool ? 1 : 2)?
[ "", "c++", "initialization", "" ]
Previously, when I needed to store a number of related variables, I'd create a class. ``` function Item(id, speaker, country) { this.id = id; this.speaker = speaker; this.country = country; } var myItems = [new Item(1, 'john', 'au'), new Item(2, 'mary', 'us')]; ``` But I'm wondering if this is a good practice. Are there any other, *better* ways to simulate a struct in JavaScript?
The only difference between object literals and constructed objects are the properties inherited from the prototype. ``` var o = { 'a': 3, 'b': 4, 'doStuff': function() { alert(this.a + this.b); } }; o.doStuff(); // displays: 7 ``` --- You could make a struct factory. ``` function makeStruct(names) { var names = names.split(' '); var count = names.length; function constructor() { for (var i = 0; i < count; i++) { this[names[i]] = arguments[i]; } } return constructor; } var Item = makeStruct("id speaker country"); var row = new Item(1, 'john', 'au'); alert(row.speaker); // displays: john ```
I always use object literals ``` {id: 1, speaker:"john", country: "au"} ```
Structs in Javascript
[ "", "javascript", "struct", "" ]
I am an experienced PHP programmer using Django for the first time, and I think it is incredible! I have a project that has a lot of apps, so I wanted to group them in an apps folder. So the structure of the project is: ``` /project/ /project/apps/ /project/apps/app1/ /project/apps/app2 ``` Then in Django settings I have put this: ``` INSTALLED_APPS = ( 'project.apps.app1', 'project.apps.app2', ) ``` This does not seem to work? Any ideas on how you can put all your apps into a seprate folder and not in the project root? Many thanks.
Make sure that the '\_\_init\_\_.py' file is in your apps directory, if it's not there it won't be recognized as part of the package. So each of the folders here should have '\_\_init\_\_.py' file in it. (empty is fine). ``` /project/ /project/apps/ /project/apps/app1/ /project/apps/app2 ``` Then as long as your root 'module' folder is in your PYTHONPATH you'll be able to import from your apps. Here's the documentation regarding the python search path for your reading pleasure: <http://docs.python.org/install/index.html#modifying-python-s-search-path> And a nice simple explanation of what \_\_init\_\_.py file is for: <http://effbot.org/pyfaq/what-is-init-py-used-for.htm>
As long as your apps are in your PYTHONPATH, everything should work. Try setting that environment variable to the folder containing your apps. ``` PYTHONPATH="/path/to/your/apps/dir/:$PYTHONPATH" ```
Django Installed Apps Location
[ "", "python", "django", "" ]
My memory usage increases over time and restarting Django is not kind to users. I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful. I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie. Can anyone suggest others? How much improvement would caching on low-traffic sites? In this case I'm running under Apache 2.x with mod\_python. I've heard mod\_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant. Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling? Also as mentioned there's a few things that will make it tricky to switch to mod\_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. **Edit:** Carl posted a slightly more detailed reply here that is worth reading: [Django Deployment: Cutting Apache's Overhead](https://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead) **Edit:** [Graham Dumpleton's article](http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html) is the best I've found on the MPM and mod\_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. **Final Edit:** Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter: > "I really don't think that you will get much of a benefit by switching to an MPM Worker + mod\_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that." So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django. Thanks for everyone's assistance but I think this question is still open! **Another final edit ;-)** I asked this on the django-users list and got some [*very* helpful replies](http://groups.google.com/group/django-users/browse_thread/thread/1d56d48fc192ceed?fwc=1&pli=1) **Honestly the last update ever!** This was just released. Could be the best solution yet: [Profiling Django object size and memory usage with Pympler](https://rk.edu.pl/en/profiling-django-object-size-and-memory-usage-pympler/)
Make sure you are not keeping global references to data. That prevents the python garbage collector from releasing the memory. Don't use `mod_python`. It loads an interpreter inside apache. If you need to use apache, use [`mod_wsgi`](http://code.google.com/p/modwsgi/) instead. It is not tricky to switch. It is very easy. `mod_wsgi` is way easier to [configure for django](http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango) than brain-dead `mod_python`. If you can remove apache from your requirements, that would be even better to your memory. [`spawning`](http://pypi.python.org/pypi/Spawning/0.7) seems to be the new fast scalable way to run python web applications. **EDIT**: I don't see how switching to mod\_wsgi could be "*tricky*". It should be a very easy task. Please elaborate on the problem you are having with the switch.
If you are running under mod\_wsgi, and presumably spawning since it is WSGI compliant, you can use [Dozer](http://pypi.python.org/pypi/Dozer) to look at your memory usage. Under mod\_wsgi just add this at the bottom of your WSGI script: ``` from dozer import Dozer application = Dozer(application) ``` Then point your browser at <http://domain/_dozer/index> to see a list of all your memory allocations. I'll also just add my voice of support for mod\_wsgi. It makes a world of difference in terms of performance and memory usage over mod\_python. Graham Dumpleton's support for mod\_wsgi is outstanding, both in terms of active development and in helping people on the mailing list to optimize their installations. David Cramer at [curse.com](http://www.curse.com/) has posted some charts (which I can't seem to find now unfortunately) showing the drastic reduction in cpu and memory usage after they switched to mod\_wsgi on that high traffic site. Several of the django devs have switched. Seriously, it's a no-brainer :)
Reducing Django Memory Usage. Low hanging fruit?
[ "", "python", "django", "profiling", "memory-management", "mod-python", "" ]
I am creating mail page for sending mails. I need to attach some file before sending. How could I do this using AJAX? Initially I need to store those files in server and then I have to send the mail. These actions are done with in a single send button.
Check these questions: * [JavaScript file uploads](https://stackoverflow.com/questions/408735/javascript-file-uploads) * [How can I get Gmail-like file uploads for my web app?](https://stackoverflow.com/questions/135123/how-can-i-get-gmail-like-file-uploads-for-my-web-app) * [What is the best multiple file JavaScript / Flash file uploader?](https://stackoverflow.com/questions/207298/what-is-the-best-multiple-file-javascript-flash-file-uploader)
Look on below snippet which send text data and attached multi-files. The `content-type='multipart/form-data'` is set by browser automatically, the file name is added automatically too to `filename` FormData parameter (and can be easy read by server). ``` async function sendEmail() { let formData = new FormData(); let msg = { message: emailText.value }; formData.append("email", JSON.stringify(msg)); [...attachment.files].map( (file,i) => formData.append("file"+i, file) ); try { await fetch('your/api/upload/email', { method: "POST", body: formData }); alert("Email was send!"); } catch(e) { alert("Problem with email sending"); } } ``` ``` <textarea id="emailText" placeholder="Type message here"></textarea><br> <input type="file" id="attachment" multiple /><br><br> <input type="button" value="Send email" onclick="sendEmail()" /> <br><br><span style="color:red">In this snippet API not exists so exception will be thrown but you can look on your request in:<br> chrome console> network tab</span> ```
Ajax using file upload
[ "", "javascript", "html", "ajax", "upload", "" ]
Here is source code for multithreaed server and client in python. In the code client and server closes connection after the job is finished. I want to keep the connections alive and send more data over the same connections to **avoid overhead of closing and opening sockets every time**. Following code is from : <http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/> ``` import pickle import socket import threading # We'll pickle a list of numbers: someList = [ 1, 2, 7, 9, 0 ] pickledList = pickle.dumps ( someList ) # Our thread class: class ClientThread ( threading.Thread ): # Override Thread's __init__ method to accept the parameters needed: def __init__ ( self, channel, details ): self.channel = channel self.details = details threading.Thread.__init__ ( self ) def run ( self ): print 'Received connection:', self.details [ 0 ] self.channel.send ( pickledList ) for x in xrange ( 10 ): print self.channel.recv ( 1024 ) self.channel.close() print 'Closed connection:', self.details [ 0 ] # Set up the server: server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) server.bind ( ( '', 2727 ) ) server.listen ( 5 ) # Have the server serve "forever": while True: channel, details = server.accept() ClientThread ( channel, details ).start() ``` --- ``` import pickle import socket import threading # Here's our thread: class ConnectionThread ( threading.Thread ): def run ( self ): # Connect to the server: client = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) client.connect ( ( 'localhost', 2727 ) ) # Retrieve and unpickle the list object: print pickle.loads ( client.recv ( 1024 ) ) # Send some messages: for x in xrange ( 10 ): client.send ( 'Hey. ' + str ( x ) + '\n' ) # Close the connection client.close() # Let's spawn a few threads: for x in xrange ( 5 ): ConnectionThread().start() ```
Spawning a new thread for every connection is a **really bad** design choice. What happens if you get hit by a lot of connections? In fact, using threads to wait for network IO is not worth it. Your program gets really complex and you get absolutely **no benefit** since waiting for network in threads won't make you **wait faster**. You only lose by using threads in this case. The following text is from python documentation: > There are only two ways to have a > program on a single processor do “more > than one thing at a time.” > Multi-threaded programming is the > simplest and most popular way to do > it, but there is another very > different technique, that lets you > have nearly all the advantages of > multi-threading, without actually > using multiple threads. It’s really > only practical if your program is > largely I/O bound. If your program is > processor bound, then pre-emptive > scheduled threads are probably what > you really need. Network servers are > rarely processor bound, however. And if it is a processor bound server case. you could always leave another process/thread to do the processor part. Continuing: > If your operating system supports the > select system call in its I/O library > (and nearly all do), then you can use > it to juggle multiple communication > channels at once; doing other work > while your I/O is taking place in the > “background.” Although this strategy > can seem strange and complex, > especially at first, it is in many > ways easier to understand and control > than multi-threaded programming. So instead of using threads, use non-blocking input/output: collect the sockets in a list and use an event loop with [select.select](http://docs.python.org/library/select.html#select.select) to know which socket has data to read. Do that in a single thread. You could choose a python asynchronous networking framework like [twisted](http://twistedmatrix.com/) to do that for you. That will save you a lot of headaches. Twisted's code has been improved for years, and covers some corner cases you'll take time to master. **EDIT**: Any existing async IO libraries (like Twisted) are python code. You could have written it yourself, but it has already been written for you. I don't see why you wouldn't use one of those libraries and write your own **worst** code instead, since you are a beginner. Networing IO is hard to get right.
I'm not sure I understand the question, but don't call `close()` if you don't want to close the connection...
Client Server programming in python?
[ "", "python", "multithreading", "client", "sockets", "" ]
Using Suversion and WinDiff its no problem to branch / merge class-projects and web-projects. The only kind of project I can never merge are winform projects. The InitializeComponent method is always scrambled after only little changes. Is there any good way to enable diff / merge for .Designer - files? **EDIT:** I used a 3 way diff like Bert suggested. It made things a lot more easy. But still Winform - files (.designer and .resx ) were not mergeable.
We have a different method of ensuring that diffs are a bit more managable. We have a trigger on checkin that will modify the designer files InitializeComponent section into a consistent and ordered manner, so that diffs show the real changes. we want to split InitializeComponent into 4 sections - creation, layout suspension, setup and layout resuming. Each of these sections are then separately ordered according to the names of the controls.
If you are using Resharper, reformat (including sorting members and whatever) those files before checking in.
How to diff changed form file - ( .Designer InitializeComponent )
[ "", "c#", "winforms", "svn", "merge", "branch", "" ]
There have been a few articles recently about Google's new imageless buttons: * <http://stopdesign.com/archive/2009/02/04/recreating-the-button.html> * <http://stopdesign.com/eg/buttons/3.0/code.html> * <http://stopdesign.com/eg/buttons/3.1/code.html> * <http://gmailblog.blogspot.com/2009/02/new-ways-to-label-with-move-to-and-auto.html> I really like how these new buttons work in Gmail. How can I use these or similar buttons on my site? Are there any open source projects with a similar look & feel? If I wanted to roll my own button package like this using JQuery/XHTML/CSS, what elements could I use? My initial thoughts are: 1. Standard `<input type="button">` with css to improve the look (the design article talked mostly about the css/imges involves.) 2. Jquery javascript to bring up a custom dialog rooted to the button on the "onclick" event which would have `<a>` tags in them and a search bar for filtering? Would a table layout for that popup be sane? I'm terrible at reverse engineering things on the web, what are some of the tools that I could use to help reverse engineer these buttons? Using Firefox's web developer toolbar I can't really see the css or javascript (even if it is minified) that is used on the buttons popup dialogs. What browser tool or other method could I use to peek at them and get some ideas? I'm not looking to steal any of Google's IP, just get an idea of how I could create similar button functionality.
-- EDIT -- I didn't see the link in the original post. Sorry! Will try and re-write to reflect actual question StopDesign has an excellent post on this [here](http://stopdesign.com/archive/2009/02/04/recreating-the-button.html). **[edit 20091107] These were released as part of the [closure library](http://code.google.com/closure/): see the [button demo](http://closure-library.googlecode.com/svn/trunk/closure/goog/demos/button.html).** Basically the custom buttons he [shows](http://stopdesign.com/eg/buttons/3.0/code.html) are created using a simple bit of CSS. He originally used 9 tables to get the effect: ![9 Tables](https://stopdesign.com/img/archive/2009/02/9-cell.png) But later he used a simple 1px left and right margin on the top and bottom borders to achieve the same effect. The gradient is faked by using three layers: ![Button Gradient](https://stopdesign.com/img/archive/2009/02/bands-spec.png) All of the code can be found at the [Custom Buttons 3.1](http://stopdesign.com/eg/buttons/3.1/code.html) page. (although the gradient without the image is only working in Firefox and Safari) ## Step by Step Instructions 1 - Insert the following CSS: ``` /* Start custom button CSS here ---------------------------------------- */ .btn { display:inline-block; background:none; margin:0; padding:3px 0; border-width:0; overflow:visible; font:100%/1.2 Arial,Sans-serif; text-decoration:none; color:#333; } * html button.btn { padding-bottom:1px; } /* Immediately below is a temporary hack to serve the following margin values only to Gecko browsers Gecko browsers add an extra 3px of left/right padding to button elements which can't be overriden. Thus, we use -3px of left/right margin to overcome this. */ html:not([lang*=""]) button.btn { margin:0 -3px; } .btn span { background:#f9f9f9; z-index:1; margin:0; padding:3px 0; border-left:1px solid #ccc; border-right:1px solid #bbb; } * html .btn span { padding-top:0; } .btn span span { background:none; position:relative; padding:3px .4em; border-width:0; border-top:1px solid #ccc; border-bottom:1px solid #bbb; } .btn b { background:#e3e3e3; position:absolute; z-index:2; bottom:0; left:0; width:100%; overflow:hidden; height:40%; border-top:3px solid #eee; } * html .btn b { top:1px; } .btn u { text-decoration:none; position:relative; z-index:3; } /* pill classes only needed if using pill style buttons ( LEFT | CENTER | RIGHT ) */ button.pill-l span { border-right-width:0; } button.pill-l span span { border-right:1px solid #ccc; } button.pill-c span { border-right-style:none; border-left-color:#fff; } button.pill-c span span { border-right:1px solid #ccc; } button.pill-r span { border-left-color:#fff; } /* only needed if implementing separate hover state for buttons */ .btn:hover span, .btn:hover span span { cursor:pointer; border-color:#9cf !important; color:#000; } /* use if one button should be the 'primary' button */ .primary { font-weight:bold; color:#000; } ``` 2 - Use one of the following ways to call it (more can be found in the links above) ``` <a href="#" class="btn"><span><span><b>&nbsp;</b><u>button</u></span></span></a> ``` or ``` <button type="button" class="btn"><span><span><b>&nbsp;</b><u>button</u></span></span></button> ```
This is their "Archive" Button, according to Firebug. ``` <div tabindex="0" act="7" class="goog-imageless-button goog-inline-block goog-imageless-button goog-imageless-button-collapse-right goog-imageless-button-primary" id=""> <div class="goog-inline-block goog-imageless-button-outer-box"> <div class="goog-inline-block goog-imageless-button-inner-box"> <div class="goog-imageless-button-pos"> <div class="goog-imageless-button-top-shadow"> </div> <div class="goog-imageless-button-content"><b>Archive</b></div> </div> </div> </div> </div> ``` The CSS is more than I care to organize/paste for this. Perhaps it's just me, but when the markup/css become this heavy, I think I would much rather **USE AN IMAGE** (or a couple images as backgrounds. Better yet, Sprites). Besides, an image for this button would be less than a single K. As much as I love Google, this seems a bit overkill. --- **Update:** Google is a unique case. If you're a massive site and you wish to internationalize your content, then this image-less technique is actually really cool. It allows you to apply just about any written language to your UI, without needing to generate new images, or fear of breaking your buttons. See Question: [What are the advantages of using an imageless button?](https://stackoverflow.com/questions/539703/what-are-the-advantages-of-using-an-imageless-button)
Google's Imageless Buttons
[ "", "javascript", "html", "css", "gmail", "reverse-engineering", "" ]
As far as I know, in C# all fields are private for default, if not marked otherwise. ``` class Foo { private string bar; } class Foo { string bar; } ``` I guess these two declarations are equal. So my question is: what for should I mark private variables as `private` if they already are private?
I've been on the fence for a while about this. I used to argue for leaving it implicit, but now I think I'm tipped over towards making it explicit. **Reasons for leaving it implicit:** * It means there's a bigger difference for non-private members (or anything with more access than the default); this highlights the difference when reading the code **Reasons for making it explicit:** * Some developers may not know the defaults: making it explicit means it's clear to *everyone* * It shows you've actively made a decision, rather than just leaving it up to the default These latter points are [basically the ones made by Eric Lippert](http://csharpindepth.com/ViewNote.aspx?NoteID=54) when we discussed it a while ago.
Now; fields should pretty-much always be private anyway, so it is an edge case whether you should bother. For the wider subject, I remember a comment by Eric Lippert - essentially saying that given a method / class / whatever: ``` void Foo() {} class Bar {} ``` Then it isn't clear whether they are private/internal deliberately, or whether the developer has thought about it, and *decided* that they should be private/internal/whatever. So his suggestion was: tell the reader that you are doing things deliberately instead of by accident - make it explicit.
What for should I mark private variables as private if they already are?
[ "", "c#", ".net", "default", "declaration", "" ]
Having toyed with this I suspect it isn't remotely possible, but I thought I'd ask the experts. I have the following C++ code: ``` class IInterface { virtual void SomeMethod() = 0; }; class Object { IInterface* GetInterface() { ... } }; class Container { private: struct Item { Object* pObject; [... other members ...] }; std::list<Item> m_items; }; ``` I want to add these methods to Container: ``` MagicIterator<IInterface*> Begin(); MagicIterator<IInterface*> End(); ``` In order that callers can write: ``` Container c = [...] for (MagicIterator<IInterface*> i = c.Begin(); i != c.End(); i++) { IInterface* pItf = *i; [...] } ``` So essentially I want to provide a class which appears to be iterating over some collection (which the caller of Begin() and End() is not allowed to see) of IInterface pointers, but which is actually iterating over a collection of pointers to other objects (private to the Container class) which can be converted into IInterface pointers. A few key points: * `MagicIterator` is to be defined outside `Container`.* `Container::Item` must remain private. * `MagicIterator` has to iterate over `IInterface` pointers, despite the fact that `Container` holds a `std::list<Container::Item>`. `Container::Item` contains an `Object*`, and `Object` can be used to fetch `IInterface*`. * `MagicIterator` has to be reusable with several classes which resemble Container, but might internally have different list implementations holding different objects (`std::vector<SomeOtherItem>`, `mylist<YetAnotherItem>`) and with `IInterface*` obtained in a different manner each time. * `MagicIterator` should not contain container-specific code, though it may delegate to classes which do, provided such delegation is not hard coded to to particular containers inside `MagicIterator` (so is somehow resolved automatically by the compiler, for example). * The solution must compile under Visual C++ without use of other libraries (such as boost) which would require a license agreement from their authors. * Also, iteration may not allocate any heap memory (so no `new()` or `malloc()` at any stage), and no `memcpy()`. Thanks for your time, even if you're just reading; this one's really been bugging me! **Update:** Whilst I've had some very interesting answers, none have met all the above requirements yet. Notably the tricky areas are i) decoupling MagicIterator from Container somehow (default template arguments don't cut it), and ii) avoiding heap allocation; but I'm really after a solution which covers all of the above bullets.
I've now found a solution which is fitter for my original purpose. I still don't like it though :) The solution involves MagicIterator being templated on IInterface\* and being constructed with both a void\* to an iterator, the byte size of said iterator, and a table of pointers to functions which perform standard iteration functions on said void\* such as increment, decrement, dereference, etc. MagicIterator assumes that it is safe to memcpy the given iterator into an internal buffer, and implements its own members by passing its own buffer as a void\* to the supplied functions as if it were the original iterator. Container then has to implement static iteration functions which cast back a supplied void\* to a std::list::iterator. Container::begin() and Container::end() simply construct a std::list::iterator, pass a pointer to it into a MagicIterator along with a table of its iteration functions, and return the MagicIterator. It's somewhat disgusting, and breaks my original rule regarding "no memcpy()", and makes assumptions about the internals of the iterators in question. But it avoids heap allocation, keeps Collection's internals (including Item) private, renders MagicIterator entirely independent of the collection in question and of IInterface\*, and in theory allows MagicIterators to work with any collection (provided its iterators can be safely memcopy()'d).
I think you have two separate issues here: First, create an iterator that will return the `IInterface*` from your `list<Container::Item>`. This is easily done with `boost::iterator_adaptor`: ``` class cont_iter : public boost::iterator_adaptor< cont_iter // Derived , std::list<Container::Item>::iterator // Base , IInterface* // Value , boost::forward_traversal_tag // CategoryOrTraversal , IInterface* // Reference :) > { public: cont_iter() : cont_iter::iterator_adaptor_() {} explicit cont_iter(const cont_iter::iterator_adaptor_::base_type& p) : cont_iter::iterator_adaptor_(p) {} private: friend class boost::iterator_core_access; IInterface* dereference() { return this->base()->pObject->GetInterface(); } }; ``` You would create this type as inner in `Container` and return in from its `begin()` and `end()` methods. Second, you want the runtime-polymorphic `MagicIterator`. This is exactly what `any_iterator` does. the `MagicIterator<IInterface*>` is just `any_iterator<IInterface*, boost::forward_traversal_tag, IInterface*>`, and `cont_iter` can be just assigned to it.
A C++ iterator adapter which wraps and hides an inner iterator and converts the iterated type
[ "", "c++", "templates", "iterator", "wrapper", "adapter", "" ]
When I'm developing in C#, I heavily use GhostDoc to speed up the process of commenting my code. I'm currently working on a C++ project and I haven't found an equivalent tool. I know about Doxygen, but from what I know it is used to create documentation outside the code, not comments in the code. Are there any good equivalent tools? I would prefer one that runs in VS, but I could handle one that works in any IDE. (Before someone brings it up, I don't rely solely on GhostDoc to create comments. I just use it to create the starting point for my comments.)
[Visual Assist](http://www.wholetomato.com/) helps by providing custom scripts executed while typing (or on other). For example, you can have a script for comments like this : ``` /************************************************************************/ /* My comment : $end$ */ /************************************************************************/ ``` That would be suggested (via a combo-box exactly like intellisense) when you start typing "/\*\*" for example. When you select this suggestion (via Enter/Space/Click - customizable), it will insert the script where your cursor is and just replace markers that are between '$' characters by special values (like the current file name for example). Here the $end$ marker will make the cursor be at this position when the script is executed. This way, you continue typing smoothly. For example with the previous script set, typing exactly : ``` /** this is a test comment to show you one of the many features Visual Assit! ``` will simply give : ``` /************************************************************************/ /* My comment : this is a test comment to show you one of the many features Visual Assit! */ /************************************************************************/ ``` It's really easy to customize and the behavior of the suggestion (read : intellisense++) system is customizable.
I've written an add-in, **[Atomineer Pro Documentation](http://www.atomineerutils.com/)**, which is very similar to GhostDoc (it generates/updates documentation comments to save a lot of time and effort when documenting), but it parses the code directly for itself and thus is able to handle C, C++, C++/CLI, C#, Java and Visual Basic code, and doesn't require the surrounding code to be in a compiling state before it will work. It will also automatically add/update documentation for more tricky things such as exceptions thrown within the body of a method. It runs under Visual Studio 11, 2010, 2008 and 2005, and supports Documentation-Xml, Doxygen, JavaDoc and Qt commenting formats, as well as the format/style of comment blocks and the auto-doc rules used being highly configurable. It has a number of other handy features such as aiding conversions of legacy doc-comments to the above formats, and word wrapping in doc-comments and normal block comments. The above is just a summary of some key features - This [comparison of features](http://www.atomineerutils.com/compare.php) with other products serves as a more complete list of the many other features available.
Is there anything like GhostDoc for C++
[ "", "c++", "ghostdoc", "" ]
How would I go about using a negative lookbehind(or any other method) regular expression to ignore strings that contains a specific substring? I've read two previous stackoverflow questions: [java-regexp-for-file-filtering](https://stackoverflow.com/questions/367862/java-regexp-for-file-filtering) [regex-to-match-against-something-that-is-not-a-specific-substring](https://stackoverflow.com/questions/42990/regex-to-match-against-something-that-is-not-a-specific-substring) They are *nearly* what I want... my problem is the string doesn't end with what I want to ignore. If it did this would not be a problem. I have a feeling this has to do with the fact that lookarounds are zero-width and something is matching on the second pass through the string... but, I'm none too sure of the internals. Anyway, if anyone is willing to take the time and explain it I will greatly appreciate it. Here is an example of an input string that I want to ignore: 192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] "GET /FOO/BAR/ HTTP/1.1" 200 2246 Here is an example of an input string that I want to keep for further evaluation: 192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] "GET /FOO/BAR/content.js HTTP/1.1" 200 2246 The key for me is that I want to ignore any HTTP GET that is going after a document root default page. Following is my little test harness and the best RegEx I've come up with so far. ``` public static void main(String[] args){ String inString = "192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] \"GET /FOO/BAR/ HTTP/1.1\" 200 2246"; //String inString = "192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] \"GET /FOO/BAR/content.js HTTP/1.1\" 200 2246"; //String inString = "192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] \"GET /FOO/BAR/content.js HTTP/"; // This works //String inString = "192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] \"GET /FOO/BAR/ HTTP/"; // This works String inRegEx = "^.*(?:GET).*$(?<!.?/ HTTP/)"; try { Pattern pattern = Pattern.compile(inRegEx); Matcher matcher = pattern.matcher(inString); if (matcher.find()) { System.out.printf("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end()); } else { System.out.printf("No match found.%n"); } } catch (PatternSyntaxException pse) { System.out.println("Invalid RegEx: " + inRegEx); pse.printStackTrace(); } } ```
Could you just match any path that doesn't end with a `/` ``` String inRegEx = "^.* \"GET (.*[^/]) HTTP/.*$"; ``` --- This can also be done using *negative lookbehind* ``` String inRegEx = "^.* \"GET (.+)(?<!/) HTTP/.*$"; ``` Here, `(?<!/)` says "the *preceding* sequence must *not* match `/`".
Maybe I'm missing something here, but couldn't you just go without any regular expression and ignore anything for which this is true: ``` string.contains("/ HTTP") ``` Because a file path will never end with a slash.
How would you use a regular expression to ignore strings that contain a specific substring?
[ "", "java", "regex", "regex-negation", "" ]
My application is processing IList's. ILists of different user defined types. I'm thinking that i can use reflection to to see what type of object the IList contains and then create a new instance of that type and subsequently add that to the IList itself? So at any one time I might be processing ``` IList<Customer> l; ``` and I'd like to create a new instance of Customer ``` Customer c = new Customer(0, "None") ``` and then add that onto the list ``` l.Add(c); ``` Obviously doing this dynamically at run-time is the crux of the problem. Hope somebody can give me some pointers. Thanks brendan
Try this: ``` public static void AddNewElement<T>(IList<T> l, int i, string s) { T obj = (T)Activator.CreateInstance(typeof(T), new object[] { i, s }); l.Add(obj); } ``` Usage: ``` IList<Customer> l = new List<Customer>(); l.Add(new Customer(1,"Hi there ...")); AddNewElement(l, 0, "None"); ``` **(EDIT):** Try this then: ``` public static void AddNewElement2(IList l, int i, string s) { if (l == null || l.Count == 0) throw new ArgumentNullException(); object obj = Activator.CreateInstance(l[0].GetType(), new object[] { i, s }); l.Add(obj); } ```
If you can use a parameterless constructor and set the properties afterwards then you can make your method generic, something like:- ``` void Process<T>(IList<T> list, int x, string y) where T : MyBase, new() { T t = new T(); t.X = x; t.Y = y; list.Add(t); } ``` Where MyBase is the base for your classes which expose the int and string properties. You can use an interface rather than a base class if you want.
Dynamically creating a new instance of IList's type
[ "", "c#", ".net", "generics", "reflection", "ilist", "" ]
We're customizing an Eclipse RCP based tool for a client. They have trouble loading it on one of their computers (it works on others) and have provided the following error log. > !SESSION 2009-01-23 12:09:05.593 > ----------------------------------------------- eclipse.buildId=unknown > java.version=1.5.0\_12 java.vendor=Sun > Microsystems Inc. BootLoader > constants: OS=win32, ARCH=x86, > WS=win32, NL=en\_GB Command-line > arguments: -os win32 -ws win32 -arch > x86 > > !ENTRY org.eclipse.osgi 4 0 2009-01-23 > 12:09:07.500 !MESSAGE Bundle > com.yantra.yfc.rcp.desktop.ri not > found. > > !ENTRY org.eclipse.osgi 4 0 2009-01-23 > 12:09:11.906 !MESSAGE Application > error !STACK 1 > org.eclipse.swt.SWTException: Invalid > thread access at > org.eclipse.swt.SWT.error(SWT.java:3374) > at > org.eclipse.swt.SWT.error(SWT.java:3297) > at > org.eclipse.swt.SWT.error(SWT.java:3268) > at > org.eclipse.swt.widgets.Display.error(Display.java:978) > at > org.eclipse.swt.widgets.Display.checkDevice(Display.java:638) > at > org.eclipse.swt.graphics.Device.dispose(Device.java:261) > at > com.yantra.yfc.rcp.YRCApplication.run(YRCApplication.java:176) > at > org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:78) > at > org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:92) > at > org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:68) > at > org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:400) > at > org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:177) > at > sun.reflect.NativeMethodAccessorImpl.invoke0(Native > Method) at > sun.reflect.NativeMethodAccessorImpl.invoke(Unknown > Source) at > sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown > Source) at > java.lang.reflect.Method.invoke(Unknown > Source) at > org.eclipse.core.launcher.Main.invokeFramework(Main.java:334) > at > org.eclipse.core.launcher.Main.basicRun(Main.java:278) > at > org.eclipse.core.launcher.Main.run(Main.java:973) > at > org.eclipse.core.launcher.Main.main(Main.java:948) I have googled the exception but this seems to happen mostly when people try to develop applications using different threads. Since we don't see this problem on any other computer I'm at a loss as to what might be causing it. It must be a configuration problem on the machine in question, as the code is from the vendor (so presumably well tested) and works on every other machine we've tested it on. Does anyone have any suggestions about what might be behind the problem for that computer? Or suggestions about lines of investigation which might reveal the issue?
It seems to me that an Exception is thrown in the application thread, that happens only in some machines. Probably there is code in the RCP application to display the exception on the GUI with some dialog box, but this is done in the wrong thread. That would explain why it happens only on some machines. It would also explain why the problem went undetected.... it probably never happens in the dev's computers so they never bothered to check that the UI Access is done using the right thread. I had a similar problem once. My suggestion would be to take a close look to: com.yantra.yfc.rcp.YRCApplication.run(YRCApplication.java:176) As the code is compiled with line numbers, you can attach a debugger to this line even if you have no source code, and try to see what happens. I am pretty sure that when you hit this breakpoint on the problematic machine, an Exception will be thrown. That will be your "Real" exception.
There's only one UI thread in Eclipse. In a nutshell, the rules are: * If you got called as part of a UI operation (e.g. event handler, view initialization) you are in the UI thread. * All other operations that invoke a UI (e.g. a job which needs to show a dialog or send information to a view which modifies a widget) - need to sync with the UI thread. This is basically done like this: ``` Display.getDefault().syncExec( new Runnable() { public void run() { } }); ``` Your code goes in the run method. You may also use the `asyncExec` method to continue without waiting for the UI to finish. Try using the snippet above to wrap the problematic code. **EDIT**: Ending bracket for Runnable() was missing in the snippet . After adding snippet works fine.
How to diagnose an Invalid thread access SWTException?
[ "", "java", "eclipse", "eclipse-rcp", "" ]
Following on from my BeginInvoke()/EndInvoke() question, are there major differences in performance/anything else between Delegate.BeginInvoke() and using QueueUserWorkItem() to invoke a delegate asynchronously?
[http://blogs.msdn.com/cbrumme/archive/2003/07/14/51495.aspx](https://web.archive.org/web/20090201230346/http://blogs.msdn.com/cbrumme/archive/2003/07/14/51495.aspx) says: > "One surprising fact is that this is > also why Delegate.BeginInvoke / > EndInvoke are so slow compared to > equivalent techniques like > ThreadPool.QueueUserWorkItem (or > UnsafeQueueUserWorkItem if you > understand the security implications > and want to be really efficient). The > codepath for BeginInvoke / EndInvoke > quickly turns into the common Message > processing code of the general > remoting pathway."
The main thing I can think of with `QueueUserWorkItem` is that you have to use the `WaitCallback` delegate type, which *looks* tricky if you already have a `SomeRandomDelegate` instance and some args. The good news is that you can fix this with a closure: ``` ThreadPool.QueueUserWorkItem( delegate { someDelegate(arg1, arg2); } ); ``` This pattern also ensures you get proper strong typing at compile time (unlike passing an `object` state arg to `QueueUserWorkItem` and casting it in the target method). This pattern can also be used when calling methods directly: ``` ThreadPool.QueueUserWorkItem( delegate { SomeMethod(arg1, arg2); } ); ``` Obviously, without an `EndInvoke` equivalent, you also can't get a return value back out unless you call a method / raise an event / etc at the end of your method... on a related note, you need to be careful with [exception handling](https://stackoverflow.com/questions/532282/532293#532293).
What's the difference between QueueUserWorkItem() and BeginInvoke(), for performing an asynchronous activity with no return types needed
[ "", "c#", "multithreading", "delegates", "" ]
Is it possible to restore a backup of a SQL Server 2008 database onto an instance of SQL Server 2005? I need to work on an sample application for which database backup is in sql server 2008. But I'll not be able to install 2008. So is it possible to restore that back up in 2005?
No. It is not possible to restore a database from a backup of a newer version. > If you are dead set on it, I think your best option is to selet the database in the Object Explorer in SQL 2008, > right-click, select Tasks->Generate Scripts.In the options dialog emable about everything, including Script Data. > > And make sure you select "Script for SQL 2005". [Source](http://social.msdn.microsoft.com/Forums/en-US/sqldatabaseengine/thread/32a67469-0636-4ded-923f-2e257f7e68e1/) When importing the objects into your target server, if the objects are large you may find that you can't open the SQL file via Management Studio (with a completely useless "The operation could not be completed" error, no less). That's okay, just load the file via [`sqlcmd`](http://msdn.microsoft.com/en-GB/library/ms170572(v=sql.90).aspx).
One important thing is missing in all answers and that is the fact that Generate Scripts in SSMS doesn’t order the scripts correctly. Scripts have to be ordered in the correct dependency order so that child tables are created after parent tables and such. This is not an issue for small databases where its easy to reorder the scripts manually but it can be a huge issue when dealing with databases that have 100+ objects. My experience is that its most convenient to use third party tools that can read backup and generate scripts in the correct order. I’m using [ApexSQL Diff](http://www.apexsql.com/sql_tools_diff.aspx) and Data Diff from ApexSQL but you can’t go wrong with any popular vendor.
Is it possible to restore Sql Server 2008 backup in sql server 2005
[ "", "sql", "sql-server-2005", "sql-server-2008", "" ]
How can I use Linq to SQL to retrieve @@DBTS using C#? Here is what I am trying: IEnumerable<System.Data.Linq.Binary> results = db.ExecuteQuery<System.Data.Linq.Binary>(@"SELECT @@DBTS"); However, this results in "The type 'System.Data.Linq.Binary' must declare a default (parameterless) constructor in order to be constructed during mapping." If I try to use byte[], I get the same error but with byte[] instead of System.Data.Linq.Binary.
I suspect you might have to use regular ADO.NET and ExecuteReader/ExecuteScalar... ``` using(SqlConnection conn = new SqlConnection(CONN_STRING)) using(SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT @@DBTS"; cmd.CommandType = CommandType.Text; conn.Open(); byte[] ts = (byte[]) cmd.ExecuteScalar(); foreach (byte b in ts) { Console.Write(b.ToString("X2")); } Console.WriteLine(); } ```
I found another way to do this using Linq to SQL alone: ``` IEnumerable<Int64> results = db.ExecuteQuery<Int64>(@"SELECT CONVERT(bigint,@@DBTS)"); Int64 latestver = results.First(); ```
SELECT @@DBTS using Linq to SQL
[ "", "c#", "asp.net", "linq-to-sql", "" ]
I've been assigned to make a custom grid control in C# with windows forms. One thing I'm unsure of is how to handle showing a blinking cursor (caret) to indicate where cell editing is taking place and the next character will be shown. Does anyone know how this is done with the standard textbox? Is there a standard framework construct that will do this for me? Obviously I can setup a timer and draw the cursor myself, but I was wondering if there was a better option. Note that this is a completely user drawn control, not a UserControl derivative and that subclassing an existing class is not an option for various reason.
Here you go: ``` using System; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; public class MyWidget : Control { public MyWidget() { this.BackColor = Color.Yellow; } protected override void OnGotFocus(EventArgs e) { CreateCaret(this.Handle, IntPtr.Zero, 2, this.Height - 2); SetCaretPos(2, 1); ShowCaret(this.Handle); base.OnGotFocus(e); } protected override void OnLostFocus(EventArgs e) { DestroyCaret(); base.OnLostFocus(e); } [DllImport("user32.dll", SetLastError = true)] private static extern bool CreateCaret(IntPtr hWnd, IntPtr hBmp, int w, int h); [DllImport("user32.dll", SetLastError = true)] private static extern bool SetCaretPos(int x, int y); [DllImport("user32.dll", SetLastError = true)] private static extern bool ShowCaret(IntPtr hWnd); [DllImport("user32.dll", SetLastError = true)] private static extern bool DestroyCaret(); } ``` I'll gladly pass the buck on figuring out where to put it.
The MSDN reference about [Carets is here](http://msdn.microsoft.com/en-us/library/ms646968(VS.85).aspx). The last time I looked (which was in 2.0 of the framework) carets weren't available as a managed API: and so you need to use the unmanaged API, or paint your own caret. One thing to remember, when you implement a caret, is that you should not show it whenever your control doesn't have the focus (only one control at a time on the user's desktop, i.e. the control which has the input focus, should ever be showing the input caret).
How do you include a cursor (caret) in a custom control?
[ "", "c#", "winforms", "" ]
In Python on Windows, is there a way to determine if a user has permission to access a directory? I've taken a look at `os.access` but it gives false results. ``` >>> os.access('C:\haveaccess', os.R_OK) False >>> os.access(r'C:\haveaccess', os.R_OK) True >>> os.access('C:\donthaveaccess', os.R_OK) False >>> os.access(r'C:\donthaveaccess', os.R_OK) True ``` Am I doing something wrong? Is there a better way to check if a user has permission to access a directory?
It can be complicated to check for permissions in Windows (beware of issues in Vista with UAC, for example! -- see this [related question](https://stackoverflow.com/questions/450210/how-to-check-if-a-file-can-be-created-inside-given-directory-on-ms-xp-vista)). Are you talking about simple read access, i.e. reading the directory's contents? The surest way of testing permissions would be to try to access the directory (e.g. do an `os.listdir`) and catch the exception. Also, in order for paths to be interpreted correctly you have to use raw strings or escape the backslashes ('\\'), -- or use forward slashes instead. (EDIT: you can avoid slashes altogether by using `os.path.join` -- the recommended way to build paths)
While os.access tries its best to tell if a path is accessible or not, it doesn't claim to be perfect. From the Python docs: > Note: I/O operations may fail even > when access() indicates that they > would succeed, particularly for > operations on network filesystems > which may have permissions semantics > beyond the usual POSIX permission-bit > model. The recommended way to find out if the user has access to do whatever is to try to do it, and catch any exceptions that occur.
Test directory permissions in Python?
[ "", "python", "windows", "permissions", "directory", "" ]
I would like to know some good resources (book or website) on learning PHP for those who are already familiar with programming. Many of the tutorials I've been finding are for people who never programmed before and take way to long to go through to even learn basic language constructs. The optimal resource would not assume previous web-development background however.
The [PHP Manual](http://www.php.net/manual/en/) is what I used, especially with the search box in Firefox. Type in a function name and go. If you haven't already, it's probably worth browsing through while you wait for more answers.
Learning raw PHP is probably the wrong way to go if you're already an experienced programmer. I'd recommend picking up one of the frameworks, such as PHP Cake, Code Ignitor or Symfony. These frameworks attempt to enforce the set of best-practices that have developed for PHP developers over the past six or seven years. To that end, Symfony has a great, ["24 hours" style tutorial](http://www.symfony-project.org/jobeet/1_2/Doctrine/en/) that can get you up and running with their framework, which will sneakily expose you to writing PHP code. Even if you decide you don't like symfony, concepts such as MVC, routing, templating, ORM, etc. will be covered. The other frameworks have similar tutorials, but I like the 24, one hour lessons approach. For questions on specific PHP core functions/classes, [php.net](http://php.net) serves as a good resource (although the document of some of the core helper classes like XMLReader and the Reflection hierarchy can be sparse).
Learning PHP and web-programming for intermediate programmers
[ "", "php", "" ]
I have a file that contains this: ``` <html> <head> <title> Hello! - {{ today }}</title> </head> <body> {{ runner_up }} avasd {{ blabla }} sdvas {{ oooo }} </body> </html> ``` What is the best or most Pythonic way to extract the `{{today}}`, `{{runner_up}}`, etc.? I know it can be done with splits/regular expressions, but I wondered if there were another way. PS: consider the data loaded in a variable called `thedata`. Edit: I think that the HTML example was bad, because it directed some commenters to BeautifulSoup. So, here is a new input data: ``` Fix grammatical or {{spelling}} errors. Clarify meaning without changing it. Correct minor {{mistakes}}. Add related resources or links. Always respect the original {{author}}. ``` Output: ``` spelling mistakes author ```
Mmkay, well here's a generator solution that seems to work well for me. You can also provide different open and close tags if you like. ``` def get_tags(s, open_delim ='{{', close_delim ='}}' ): while True: # Search for the next two delimiters in the source text start = s.find(open_delim) end = s.find(close_delim) # We found a non-empty match if -1 < start < end: # Skip the length of the open delimiter start += len(open_delim) # Spit out the tag yield s[start:end].strip() # Truncate string to start from last match s = s[end+len(close_delim):] else: return ``` Run against your target input like so: ``` # prints: today, runner_up, blabla, oooo for tag in get_tags(html): print tag ``` Edit: it also works against your new example :). In my obviously quick testing, it also seemed to handle malformed tags in a reasonable way, though I make no guarantees of its robustness!
try [templatemaker](http://code.google.com/p/templatemaker/), a reverse-template maker. it can actually learn them automatically from examples!
Split tags in python
[ "", "python", "split", "template-engine", "" ]
We want to display a pdf-file on a webpage. From what i can think of i see two possible solutions, displaying the file with some kind of pdf reader(maybe in flash?) or converting the pdf-file to html before displaying it. How would you proceed to solve a problem like this? Which would be the preferable method?
Well, there's always a third way: serve the PDF itself and leave the rest to the visitor.
For public websites, you can improve the user experience and reduce bandwidth overhead by embedding your PDF documents in your pages using one of the document sharing services such as: <http://www.scribd.com> <http://www.docstoc.com> I should also add that scribd also has an API for uploading documents (and more).
displaying pdf on a website
[ "", "php", "pdf", "" ]
I have an application written in .NET 1.1 that calls XmlDocument.Load on a URL. Just recently the xml file was updated. Now whenever I call XmlDocument.Load, the old file is returned. When I hit the same URL from a browser, I see the new file. I deleted all temporary files from IE and I still see the same issue. Any thoughts on why I am seeing a older version of the file when I access it programmatically?
Just a guess, but try clearing your IE's browser cache. .NET HTTP is sitting on top of the same stack as IE and also share proxy settings, so I would not be surprised if the cache is shared, too.
delete also the ASP.net temporary files
Why is XmlDocument.Load(url) returning a stale file?
[ "", "c#", "xml", ".net-1.1", "" ]
I am maintaining an application that uses SetupDiGetDeviceInterfaceDetail() to find out information on the installed serial ports on the computer. I have noticed while testing this that there are some devices, such as my Lucent WinModem, that do not show up in that enumeration. It turns out that I am having a similar issue with a set of devices manufactured by my company that implement the serial port interface. My assumption is that there is something that is missing from the INF file for the device. Does anyone know what kinds of conditions can result in this kind of omission? Edit: Here is a sample of the code that I am using to enumerate the serial ports. I have tried various combinations of flags but have not seen any significant difference in behaviour. ``` DEFINE_GUID(GUID_CLASS_COMPORT, 0x4d36e978, 0xe325, 0x11ce, 0xbf, 0xc1, \ 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18); GUID *serial_port_guid = const_cast<GUID *>(&GUID_CLASS_COMPORT); HDEVINFO device_info = INVALID_HANDLE_VALUE; SP_DEVICE_INTERFACE_DETAIL_DATA *detail_data = 0; device_info = SetupDiGetClassDevs( serial_port_guid, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if(device_info != INVALID_HANDLE_VALUE) { uint4 const detail_data_size = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + 256; detail_data = reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA *>(new char[detail_data_size]); SP_DEVICE_INTERFACE_DATA ifc_data; bool more_interfaces = true; int rcd; memset(&ifc_data, 0, sizeof(ifc_data)); memset(detail_data, 0, detail_data_size); ifc_data.cbSize = sizeof(ifc_data); detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); for(uint4 index = 0; more_interfaces; ++index) { rcd = SetupDiEnumDeviceInterfaces(device_info, 0, serial_port_guid, index, &ifc_data); if(rcd) { // we need to get the details of this device SP_DEVINFO_DATA device_data = { sizeof(SP_DEVINFO_DATA) }; rcd = SetupDiGetDeviceInterfaceDetail( device_info, &ifc_data, detail_data, detail_data_size, 0, &device_data); if(rcd) { StrAsc device_path(detail_data->DevicePath); byte friendly_name[256]; rcd = SetupDiGetDeviceRegistryProperty( device_info, &device_data, SPDRP_FRIENDLYNAME, 0, friendly_name, sizeof(friendly_name), 0); if(rcd) { std::for_each( port_names.begin(), port_names.end(), update_friendly_name( reinterpret_cast<char const *>(friendly_name))); } } else more_interfaces = false; } } } ```
I decided to punt on this and to do away with the dependency on the SetupDi() functions. Instead, I have written code that traverses the subkeys in HKEY\_LOCAL\_MACHINE\System\CurrentControlSet\Enum to find any drivers that support the serial port GUID. I have the feeling that this is what the device manager does. In case anyone is interested, my code fragment can be seen below: ``` typedef std::string StrAsc; typedef std::pair<StrAsc, StrAsc> port_name_type; typedef std::list<port_name_type> friendly_names_type; void SerialPortBase::list_ports_friendly(friendly_names_type &port_names) { // we will first get the list of names. This will ensure that, at the very least, we get // the same list of names as we would have otherwise obtained. port_names_type simple_list; list_ports(simple_list); port_names.clear(); for(port_names_type::iterator pi = simple_list.begin(); pi != simple_list.end(); ++pi) port_names.push_back(friendly_name_type(*pi, *pi)); // we will now need to enumerate the subkeys of the Enum registry key. We will need to // consider many levels of the registry key structure in doing this so we will use a list // of key handles as a stack. HKEY enum_key ; char const enum_key_name[] = "SYSTEM\\CurrentControlSet\\Enum"; StrAsc const com_port_guid("{4d36e978-e325-11ce-bfc1-08002be10318}"); char const class_guid_name[] = "ClassGUID"; char const friendly_name_name[] = "FriendlyName"; char const device_parameters_name[] = "Device Parameters"; char const port_name_name[] = "PortName"; long rcd = ::RegOpenKeyEx( HKEY_LOCAL_MACHINE, enum_key_name, 0, KEY_READ, &enum_key); char value_buff[MAX_PATH]; StrAsc port_name, friendly_name; if(!port_names.empty() && rcd == ERROR_SUCCESS) { std::list<HKEY> key_stack; key_stack.push_back(enum_key); while(!key_stack.empty()) { // we need to determine whether this key has a "ClassGUID" value HKEY current = key_stack.front(); uint4 value_buff_len = sizeof(value_buff); key_stack.pop_front(); rcd = ::RegQueryValueEx( current, class_guid_name, 0, 0, reinterpret_cast<byte *>(value_buff), &value_buff_len); if(rcd == ERROR_SUCCESS) { // we will only consider devices that match the com port GUID if(com_port_guid == value_buff) { // this key appears to identify a com port. We will need to get the friendly name // and try to get the 'PortName' from the 'Device Parameters' subkey. Once we // have those things, we can update the friendly name in our original list value_buff_len = sizeof(value_buff); rcd = ::RegQueryValueEx( current, friendly_name_name, 0, 0, reinterpret_cast<byte *>(value_buff), &value_buff_len); if(rcd == ERROR_SUCCESS) { HKEY device_parameters_key; rcd = ::RegOpenKeyEx( current, device_parameters_name, 0, KEY_READ, &device_parameters_key); if(rcd == ERROR_SUCCESS) { friendly_name = value_buff; value_buff_len = sizeof(value_buff); rcd = ::RegQueryValueEx( device_parameters_key, port_name_name, 0, 0, reinterpret_cast<byte *>(value_buff), &value_buff_len); if(rcd == ERROR_SUCCESS) { friendly_names_type::iterator fi; port_name = value_buff; fi = std::find_if( port_names.begin(), port_names.end(), port_has_name(port_name)); if(fi != port_names.end()) fi->second = friendly_name; } ::RegCloseKey(device_parameters_key); } } } } else { // since this key did not have what we expected, we will need to check its // children uint4 index = 0; rcd = ERROR_SUCCESS; while(rcd == ERROR_SUCCESS) { value_buff_len = sizeof(value_buff); rcd = ::RegEnumKeyEx( current, index, value_buff, &value_buff_len, 0, 0, 0, 0); if(rcd == ERROR_SUCCESS) { HKEY child; rcd = ::RegOpenKeyEx(current, value_buff, 0, KEY_READ, &child); if(rcd == ERROR_SUCCESS) key_stack.push_back(child); } ++index; } } ::RegCloseKey(current); } } } // list_ports_friendly ```
This is more of a question about the issue. When you call the function the first arg you pass in should be DeviceInfoSet which you likely got from the [SetupDiGetClassDevs](http://msdn.microsoft.com/en-us/library/ms792959.aspx) function. When you called the SetupDiGetClassDevs function what did you specify for the flags (Last Argument) Quoting Microsoft's Page on the function: > **DIGCF\_ALLCLASSES** > Return a list of installed devices for all device setup classes or all > device interface classes. > > **DIGCF\_DEVICEINTERFACE** > Return devices that support device interfaces for the specified device > interface classes. This flag must be > set in the Flags parameter if the > Enumerator parameter specifies a > device instance ID. > > **DIGCF\_DEFAULT** > Return only the device that is associated with the system default > device interface, if one is set, for > the specified device interface > classes. > > **DIGCF\_PRESENT** > Return only devices that are currently present in a system. > > **DIGCF\_PROFILE** > Return only devices that are a part of the current hardware profile. Depending on your choice the list of devices changes. For example The Present flag will only show devices plugged in actively. --- UPDATE: Thanks for the sample code. My question now, is if you want to know the friendly name of the modem why not use the same call but specify the Modem Guid instead of the COM Port? I have the Modem GUID being 4D36E96D-E325-11CE-BFC1-08002BE10318 In the registry I can see a value called 'AttachedTo' which specifies a COM Port. I'll have to research which property thats is tied to in the API. The registry key is at HKLM\SYSTEM\CurrentControlSet\Control\Class{4D36E96D-E325-11CE-BFC1-08002BE10318}\ --- ANOTHER UPDATE: Looking closer at the sample code. Based on this, if you are trying to get the device interface class that should return a [SP\_DEVICE\_INTERFACE\_DETAIL\_DATA](http://msdn.microsoft.com/en-us/library/ms793116.aspx) Structure. That wouldn't provide a way of getting the friendly name of the device. I believe instead you would want the device instance. From what I've read, the Device Interface is used to as a way to get the device path which can be used to write to it. One thing I did to test your code was try it again the Disk Device Interface. I made a few changes to get it to work on my system and it still isn't quite done. I think the one problem (probably more) is that I need to resize the DevicePath variable inbetween the SetupDiGetDeviceInterfaceDetail calls. ``` void Test() { GUID *serial_port_guid = const_cast<GUID *>(&GUID_DEVINTERFACE_DISK); HDEVINFO device_info = INVALID_HANDLE_VALUE; SP_DEVICE_INTERFACE_DETAIL_DATA detail_data; device_info = SetupDiGetClassDevs( serial_port_guid, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if(device_info != INVALID_HANDLE_VALUE) { //uint4 const detail_data_size = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);// + 256; //detail_data = reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA *>(new char[detail_data_size]); SP_DEVICE_INTERFACE_DATA ifc_data; bool more_interfaces = true; int rcd; memset(&ifc_data, 0, sizeof(ifc_data)); //memset(detail_data, 0, detail_data_size); ifc_data.cbSize = sizeof(ifc_data); detail_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); for(uint4 index = 0; more_interfaces; ++index) { rcd = SetupDiEnumDeviceInterfaces(device_info, 0, serial_port_guid, index, &ifc_data); if(rcd) { // we need to get the details of this device SP_DEVINFO_DATA device_data; device_data.cbSize = sizeof(SP_DEVINFO_DATA); DWORD intReqSize; rcd = SetupDiGetDeviceInterfaceDetail(device_info, &ifc_data, 0, 0, &intReqSize, &device_data); rcd = SetupDiGetDeviceInterfaceDetail(device_info, &ifc_data, &detail_data,intReqSize,&intReqSize,&device_data); if(rcd) { //StrAsc device_path(detail_data->DevicePath); byte friendly_name[256]; rcd = SetupDiGetDeviceRegistryProperty( device_info, &device_data, SPDRP_FRIENDLYNAME, 0, friendly_name, sizeof(friendly_name), reinterpret_cast<DWORD *>(sizeof(friendly_name))); if(rcd) { cout<<reinterpret_cast<char const *>(friendly_name); } else { int num = GetLastError(); } } else { int num = GetLastError(); } } else more_interfaces = false; } } SetupDiDestroyDeviceInfoList(device_info); } ``` Also, in the INF, you may have to add the [AddInterface](http://msdn.microsoft.com/en-us/library/ms794355.aspx) directive to associate your driver with the correct interface.
Why do some devices not enumerate with SetupDiGetDeviceInterfaceDetail()?
[ "", "c++", "winapi", "driver", "" ]
Aloha, I have a 8MB XML file that I wish to deserialize. I'm using this code: ``` public static T Deserialize<T>(string xml) { TextReader reader = new StringReader(xml); Type type = typeof(T); XmlSerializer serializer = new XmlSerializer(type); T obj = (T)serializer.Deserialize(reader); return obj; } ``` This code runs in about a minute, which seems rather slow to me. I've tried to use sgen.exe to precompile the serialization dll, but this didn't change the performance. What other options do I have to improve performance? [edit] I need the object that is created by the deserialization to perform (basic) transformations on. The XML is received from an external webservice.
The XmlSerializer uses reflection and is therefore not the best choice if performance is an issue. You could build up a DOM of your XML document using the `XmlDocument` or `XDocument` classes and work with that, or, even faster use an `XmlReader`. The `XmlReader` however requires you to write any object mapping - if needed - yourself. What approach is the best depends stronly on what you want to do with the XML data. Do you simply need to extract certain values or do you have to work and edit the whole document object model?
Yes it does use reflection, but performance is a gray area. When talking an 8mb file... yes it will be much slower. But if dealing with a small file it will not be. I would NOT saying reading the file vial XmlReader or XPath would be easier or really any faster. What is easier then telling something to turn your xml to an object or your object to XML...? not much. Now if you need fine grain control then maybe you need to do it by hand. Personally the choice is like this. I am willing to give up a bit of speed to save a TON of ugly nasty code. Like everything else in software development there are trade offs.
What is the most efficient way to Deserialze an XML file
[ "", "c#", "performance", "xml-serialization", "sgen", "" ]
Two somewhat unrelated questions: * Sometimes when I am working on a C++ project in Visual Studio 2008 Express, intellisense just does not want to "work" even though it really should. Auto completion box does not show and status bar says something along the lines of: "Intellisense: No further information is available". Sometimes it can be fixed by either rebuilding the solution or re-opening the solution, and sometimes even that doesn't work. Is this a known problem? If so: are there any known fixes? * Is there any C++ IDE for Linux that has compatibility with MSVC++'s .sln files? I sometimes want to work on some project without having to go through the hassle of creating a new project and adding the files or manually creating a Make file. edit: To answer my own questions: * Apparently there's no real fix other than to try and delete the .ncb file. Alternative would be a different IDE or to use a commercial package replacing intellisense. * Code::Blocks seems to be able to open Visual Studio files. Or at least import them easily. I posted these together as they both related to visual studio and I didn't deem them important enough to both deserve their own topic. Do think the downvote is a little harsh though!
Intellisense failing is usually because of a "corrupt" ncb file. The usual solution is to delete it. Reportly the next version VS 2010 will not be using ncb files anymore.
To avoid creating the Make files by hand try [CMake](http://www.cmake.org/)
Visual Studio: Intellisense Problems and Linux Compatibility
[ "", "c++", "linux", "visual-studio-2008", "intellisense", "" ]
So I did some reading of the related questions and had some interesting stuff but did not find my answer, at least did not understand the answer. I am very new to AJAX, javascript and sclient side scripting in general. I have been using C# asp.net for a bit and recently added some updatepanels to my side to smooth so of the user controls and bits being updated so that the page was not reloaded each time. All works brilliantly and I was very happy with it till I decided to try and use some JQuery. I have picked up the datepicker from ui.jquery.js which is cool and works great on a normal page. My problem arrives when I do a postback from within an updatepanel. The datepicker just stops working. from what I have read I need to manually wire this back up after the post back. 1) I don't really understand why. on my master page I have: ``` <script type="text/javascript"> $(function() { $(".mydatepickerclass").datepicker({dateFormat: 'dd-mm-yy'}); }); </script> ``` which picks up my input boxes with the mydatepickerclass assigned. and all works. Why would this stop working on the postback. 2) How do I fix this.... how do I wire it up so that after a postback in an updatepanel it still works. I understand that the ID might change on a postback, I think but as I am using classes I don't know what is going wrong. **edit** I have the following code in my usercontrol where the update is happening: ``` <asp:UpdatePanel ID="HistoryUpdatePanel" runat="server"> <ContentTemplate> <%-- Start of Company History section --%> <fieldset> <legend>Activity History</legend> <script type="text/javascript"> $(function() { $(".mydatepickerclass").datepicker({dateFormat: 'dd-mm-yy'}); }); </script> <div> <asp:ListBox ID="listBoxHistoryTypes" runat="server" SelectionMode="Multiple" AutoPostBack="true" OnSelectedIndexChanged="listBoxHistoryTypes_IndexChanged" /> <label>Date From:</label><asp:TextBox class="mydatepickerclass" ID="txtdatefrom" runat="server" /> <label>Date To:</label><input class="mydatepickerclass" type="text" /> <asp:TextBox class="mydatepickerclass" ID="txtdateto" runat="server" /> <asp:Button ID="btnFilterSearch" runat="server" Text="Filter Results" OnClick="btnFilterSearch_Click" /> </div> </fieldset> </ContentTemplate> ``` Does the script inside the updatepanel not rewire it? Thanks Jon Hawkins
the update panel is going to reload the contents of the html. You'll have to listen for the UpdatePanel to complete and recreate the datepicker. Here is a very basic sample. This doesn't take into account multiple update panels on your page or potential memory leaks from not properly destroying your datepicker. Another thing to note when mixing ASP.NET Ajax and jQuery be careful because the both use the $ in different contexts ``` <!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 runat="server"> <title></title> <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.js"> </script> <script type="text/javascript"> $(document).ready(function() { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); function EndRequestHandler(sender, args) { $('.mydatepickerclass').datepicker({ dateFormat: 'dd-mm-yy' }); } }); </script> </head> <body> <form id="form1" runat="server"> <div> </div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:TextBox ID="TextBox1" runat="server" CssClass="mydatepickerclass"></asp:TextBox> <br /> <asp:Button ID="Button1" runat="server" Text="UpdateMe" onclick="Button1_Click" /> </ContentTemplate> </asp:UpdatePanel> </form> </body> </html> ```
I know this is old but ... try replace: `$(document).ready(function() {` with: `Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function () {`
jquery datepicker ms ajax updatepanel doesn't work after post back
[ "", "c#", "jquery", "asp.net-ajax", "updatepanel", "" ]
I am having trouble getting my project to link to the Boost (version 1.37.0) Filesystem lib file in Microsoft Visual C++ 2008 Express Edition. The Filesystem library is **not** a header-only library. I have been following the *[Getting Started on Windows](http://www.boost.org/doc/libs/1_37_0/more/getting_started/windows.html)* guide posted on the official boost web page. Here are the steps I have taken: 1. I used bjam to build the complete set of lib files using: ``` bjam --build-dir="C:\Program Files\boost\build-boost" --toolset=msvc --build-type=complete ``` 2. I copied the */libs* directory (located in *C:\Program Files\boost\build-boost\boost\bin.v2*) to *C:\Program Files\boost\boost\_1\_37\_0\libs.* 3. In Visual C++, under *Project > Properties > Additional Library Directories* I added these paths: * *C:\Program Files\boost\boost\_1\_37\_0\libs* * *C:\Program Files\boost\boost\_1\_37\_0\libs\filesystem\build\msvc-9.0express\debug\link-static\threading-multi* I added the second one out of desperation. It is the exact directory where *libboost\_system-vc90-mt-gd-1\_37.lib* resides. 4. In *Configuration Properties > C/C++ > General > Additional Include Directories* I added the following path: * *C:\Program Files\boost\boost\_1\_37\_0* 5. Then, to put the icing on the cake, under *Tools > Options VC++ Directories > Library files*, I added the same directories mentioned in step 3. Despite all this, when I build my project I get the following error: ``` fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_37.lib' ``` Additionally, here is the code that I am attempting to compile as well as a screen shot of the aformentioned directory where the (assumedly correct) lib file resides: ``` #include "boost/filesystem.hpp" // includes all needed Boost.Filesystem declarations #include <iostream> // for std::cout using boost::filesystem; // for ease of tutorial presentation; // a namespace alias is preferred practice in real code using namespace std; int main() { cout << "Hello, world!" << endl; return 0; } ```
Ferruccio's answer contains most of the insight. However, Pukku made me realize my mistake. I am posting my own answer to give a full explanation. As Ferruccio explained, Filesystem relies on two libraries. For me, these are: * libboost\_system-vc90-mt-gd-1\_37.lib * libboost\_filesystem-vc90-mt-gd-1\_37.lib I must not have noticed that when I supplied the directory for *libboost\_filesystem-vc90-mt-gd-1\_37.lib*, the error output changed from ``` fatal error LNK1104: cannot open file 'libboost_filesystem-vc90-mt-gd-1_37.lib' ``` to ``` fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_37.lib' ``` Causing me to think that the error was persisting. This lead me to post some rather inaccurate information. Also, after reading that Filesystem requires two libraries, I now see the significance of the keyword **stage** for the bjam command. Supplying ``` bjam --build-dir="C:\Program Files\boost\build-boost" --toolset=msvc --build-type=complete stage ``` Causes bjam to place an additional directory, aptly named *stage*, in the *boost\_1\_37\_0* directory. This folder contains a folder named */lib*, which has copies of all of the lib files in one place. This is convenient for Visual C++ because you can supply it with this single directory and it will take care of all of the dependencies.
boost::filesystem is dependent on boost::system, so you need both paths. Part of the problem is you're using the boost libs out of the build directories instead of the install directory (the boost build process should create both). The install/lib directory has all the libs so you only need to specify one path. The boost build process builds each library in its own directory. At the end it copies all those .lib files into one common lib directory. Since you didn't specify an install directory as part of your build command (with --prefix=...), I believe the default is C:\Boost. Check to see if that directory is there and if so use C:\boost\include\ boost-1\_37 for your include path and C:\boost\lib for your library path.
How do I resolve LNK1104 error with Boost Filesystem Library in MSCV?
[ "", "c++", "visual-c++", "boost", "filesystems", "linker", "" ]
I have a table with a FooId and a CreatedTime column. During the day, multiple rows can be inserted for the same FooId. The CreatedTime column represent the time at the moment of the inserting. I would like a query which will return me the latest row for a given day (e.g. 2000-01-01). Is there a way to write a query which will do that with SQL Server 2005? Below is an example of the data and the result that I am expecting. **I would like the latest data created for the day.** So the MAX(CreatedDate) won't work. Thanks! ``` FooId Data CreatedTime --------------------------- 1 A 2000/01/01 12:00:00 1 B 2000/01/01 12:12:00 1 C 2000/01/01 12:25:00 2 A 2000/01/01 12:00:00 2 B 2000/01/01 12:26:00 3 A 2000/01/01 12:00:00 ``` Result ``` FooId Data CreatedTime --------------------------- 1 C 2000/01/01 12:25:00 2 B 2000/01/01 12:26:00 3 A 2000/01/01 12:00:00 ```
of course it will work with MAX since you didn't provide DDL and DML statements I used something I had laying around run this ``` CREATE TABLE #MaxVal(id INT,VALUE varchar(10),SomeDate DATETIME) INSERT #MaxVal VALUES(1,'a','2009-02-10 14:48:45.143') INSERT #MaxVal VALUES(1,'b','2009-02-10 13:48:45.143') INSERT #MaxVal VALUES(1,'c','2009-02-10 11:48:45.143') INSERT #MaxVal VALUES(2,'d','2009-02-10 11:48:45.143') INSERT #MaxVal VALUES(2,'e','2009-02-10 12:48:45.143') INSERT #MaxVal VALUES(2,'f','2009-02-10 13:48:45.143') INSERT #MaxVal VALUES(3,'g','2009-02-10 11:48:45.143') INSERT #MaxVal VALUES(3,'h','2009-02-10 14:48:45.143') SELECT t.* FROM( SELECT id,MAX(SomeDate) AS MaxValue FROM #MaxVal WHERE SomeDate >='2009-02-10' AND SomeDate < '2009-02-11' GROUP BY id) x JOIN #MaxVal t ON x.id =t.id AND x.MaxValue =t.SomeDate ``` output ``` id VALUE SomeDate 3 h 2009-02-10 14:48:45.143 2 f 2009-02-10 13:48:45.143 1 a 2009-02-10 14:48:45.143 ```
Isn't it kind of rude to delete your old post without warning because the requirements changed? Can't you just close it so people don't wonder what happened? In any case, **here is the updated answer:** ``` SELECT Foo.* FROM Foo JOIN ( SELECT FooId, MAX(CreatedTime) FROM Foo Q -- Only change the dates in the next line. WHERE Q.CreatedTime >= '20000101' AND Q.CreatedTime < '20000102' GROUP BY Q.FooId, DATEADD(day, DATEDIFF(day, '19000101', Q.CreatedTime), '19000101') ) Q2 (FooID, CreatedTime) ON Q2.FooID = Foo.FooID AND Q2.CreatedTime = Foo.CreatedTime ORDER BY FooID ``` **Results** ``` FooId Data CreatedTime 1 C 2000-01-02 12:25:00.000 2 B 2000-01-02 12:26:00.000 3 A 2000-01-02 12:00:00.000 ``` **DDL** ``` CREATE TABLE Foo (FooId int NOT NULL, Data varchar(10), CreatedTime datetime NOT NULL) INSERT INTO Foo VALUES (1, 'A', '2000-01-01 12:00:00') INSERT INTO Foo VALUES (1, 'B', '2000-01-01 12:12:00') INSERT INTO Foo VALUES (1, 'C', '2000-01-01 12:25:00') INSERT INTO Foo VALUES (2, 'A', '2000-01-01 12:00:00') INSERT INTO Foo VALUES (2, 'B', '2000-01-01 12:26:00') INSERT INTO Foo VALUES (3, 'A', '2000-01-01 12:00:00') INSERT INTO Foo VALUES (1, 'A', '2000-01-02 12:00:00') INSERT INTO Foo VALUES (1, 'B', '2000-01-02 12:12:00') INSERT INTO Foo VALUES (1, 'C', '2000-01-02 12:25:00') INSERT INTO Foo VALUES (2, 'A', '2000-01-02 12:00:00') INSERT INTO Foo VALUES (2, 'B', '2000-01-02 12:26:00') INSERT INTO Foo VALUES (3, 'A', '2000-01-02 12:00:00') ```
How to return the latest row written for the day?
[ "", "sql", "sql-server", "" ]
I've been spending some time refactoring my C# code, and I'm struck by how large my parameter lists are getting for local variables, especially when you start getting several levels deep and have to pass local variables from higher up the call stack. As an example, I have some rather complex code that uses Linq to sql. I instantiate a data context early in a procedure and use it throughout the procedure. However, after refactoring, I find that i'm passing this DC throughout all my sub-methods, along with various other state variables. One solution, of course, is to make these local variables into member variables, but that makes the entire class non-thread safe, and when dealing with async i/o that means crippling things with locks and mutexes to make them safe. What are your best practices when factoring in regards to local variables? Do you give in and make them members? or do you carry around the state baggage? Or do you do something else? EDIT: I'm not sure what more detail you need. I don't want to dump a bunch of code, because by it's nature in order to illustrate this I have to show a very complex set of procedures. I have a number of local variables, such as a Linq to Sql DC, various stages of processing, various stages of updates of a lot of raw data processed and written to a database. I thought about creating a state context and passing that, but it seems kind of hackish to me, although I suppose that's precisely what the Linq to SQL dc is.
Potentially, make them members of another type. Nested types work well here, too. That makes a lot of sense if they form a logical group, and let you write several methods using the same type. Beyond that, we'd have to know details of what you're doing to comment further I suspect.
Do *not* turn them into member/global variables. They make reasoning about application state an order of magnitude more difficult, even without multithreading - and with it, as you say, it becomes a total nightmare. You might try collapsing them into simple objects and passing those around instead, if you notice that certain parameters are always being passed around in groups.
Best Practices for Refactoring with local variables
[ "", "c#", "refactoring", "" ]
I have two tables, one an import table, the other a FK constraint on the table the import table will eventually be put into. In the import table a user can provide a list of semicolon separated values that correspond to values in the 2nd table. So we're looking at something like this: ``` TABLE 1 ID | Column1 1 | A; B; C; D TABLE 2 ID | Column2 1 | A 2 | B 3 | D 4 | E ``` The requirement is: Rows in TABLE 1 with a value not in TABLE 2 (C in our example) should be marked as invalid for manual cleanup by the user. Rows where all values are valid are handled by another script that already works. In production we'll be dealing with 6 columns that need to be checked and imports of AT LEAST 100k rows at a time. As a result I'd like to do all the work in the DB, not in another app. BTW, it's SQL2008. I'm stuck, anyone have any ideas. Thanks!
Seems to me you could pass ID & Column1 values from Table1 to a Table-Valued function (or a temp table in-line) which would parse the ;-delimited list, returning individual values per record. Here are a couple options: * [T-SQL: Parse a delimited string](http://pietschsoft.com/post/2006/02/T-SQL-Parse-a-delimited-string.aspx) * [Quick T-Sql to parse a delimited string](http://codebetter.com/blogs/raymond.lewallen/archive/2005/10/26/133774.aspx) The result (`ID, value`) from the function could be used to compare (unmatched query) against values in Table 2. ``` SELECT tmp.ID FROM tmp LEFT JOIN Table2 ON Table2.id = tmp.ID WHERE Table2.id is null ``` The `ID` results of the comparison would then be used to flag records in Table 1.
Perhaps inserting those composite values into 'TABLE 1' may have seemed like the most convenient solution at one time. However, unless your users are using SQL Server Management Studio or something similar to enter the values directly into the table then I assume there must be a software layer between the UI and the database. If so, you're going to save yourself a lot headaches both now and in the long run by investing a little time in altering your code to split the semi-colon delimited inputs into discrete values before inserting them into the database. This will result in 'TABLE 1' looking something like this ``` TABLE 1 ID | Column1 1 | A 1 | B 1 | C 1 | D ``` It's then trivial to write the SQL to find those IDs which are invalid.
How to compare string data to table data in SQL Server - I need to know if a value in a string doesn't exist in a column
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "" ]
I was working on my website written in php/mysql. When I first wrote it, it was spaghetti with lots of php embedded in html and the like - very hard to maintain. I rewrote the whole thing with a nice modular structure with OOPS, and now it is much easier to maintain and expand. But when testing the site performance using [webwait](http://webwait.com/) and siege, the newer, better structured version seems to run and load slower than the spaghetti code version. There's a difference of nearly 1 second in loading time - 2.39s vs 3.81s Nothing else was changed except the php code - not the js, not the css So what is the problem here? Should I revert back to the old code? Has this happened to others? Edit: * I have done some analysis using cachegrind, inclued and I think the code is pretty good. * I also know that the problem is not entirely OOPS but the greater structure etc. and also that OOP doesn't at all guarantee better performance. * I have run the code multiple times too. * I've used cachegrind with kcachegrind, inclued, siege (most of the tools Rasmus lerdorf outlined in his drupalcon 2008 talk on ['Simple is Hard'](http://szeged2008.drupalcon.org/program/sessions/rasmus-lerdorf-keynote-simple-hard)) **What I want to know is how others deal with this.**
I can think of a couple of points to consider: * It's not a choice of OOP vs spaghetti code. There are other paradigms that may be just as maintainable and structured as OOP, but with different performance characteristics. It is possible to write OOP code using only simple procedural language features (many big C frameworks use a very OOP-ey style.) A more functional style may also be simpler in some cases. OOP isn't the One True Paradigm. * There are different degrees of OOP. Modelling data as objects does not in most languages cause a noticeable performance difference (I don't know how PHP performs in this area, though, but with PHP I always expect the worst). However, virtual functions, inheritance (and especially multiple inheritance) are slower and add overhead that often could have been avoided. Which OOP features do you use? Is there a simpler OOP design that would do the job, but with less reliance on "slow" language features? On top of that, the usual obviously applies (can you optimize the algorithm, enable caching or precompilation, and so on - but while those may help dramatically, they're not specific to OOP)
**"Should I revert back to the old code?"** If I say revert, you'll say "see, I knew OO was a blown unit, no one can make an OO application that works." That would be wrong. If I say don't revert, you'll say, "but it's unacceptably slow." So, what's left? You have to write it **better**. Go forward. Rewrite your OO so that it actually works. OO isn't "magic" -- it doesn't guarantee anything. There are bad OO programs and good OO programs. In your case, you obviously have room for improvement. So get some performance profiling tools and find out where the time has gone. Also, don't "optimize" -- rewrite. Odds are very good that you have some kind of search going on that takes up a lot of time. Eliminate search. Use better containers and collections (hash maps, sets, etc.)
OOPS, there goes the performance?
[ "", "php", "oop", "" ]
Is it possible to call a method by reflection from a class? ``` class MyObject { ... //some methods public void fce() { //call another method of this object via reflection? } } ``` Thank you.
``` import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { public static void main(final String[] argv) { final Main main; main = new Main(); main.foo(); } public void foo() { final Class clazz; final Method method; clazz = Main.class; try { method = clazz.getDeclaredMethod("bar", String.class); method.invoke(this, "foo"); } catch(final NoSuchMethodException ex) { // handle it however you want ex.printStackTrace(); } catch(final IllegalAccessException ex) { // handle it however you want ex.printStackTrace(); } catch(final InvocationTargetException ex) { // handle it however you want ex.printStackTrace(); } } private void bar(final String msg) { System.out.println("hello from: " + msg); } } ```
Absolutely: ``` import java.lang.reflect.*; public class Test { public static void main(String args[]) throws Exception { Test test = new Test(); Method method = Test.class.getMethod("sayHello"); method.invoke(test); } public void sayHello() { System.out.println("Hello!"); } } ``` If you have problems, post a specific question (preferrably with a short but complete program demonstrating the problem) and we'll try to sort it out.
Calling a method using reflection
[ "", "java", "reflection", "" ]
I tried running the service in the "Local System" : didn't work. I tried running the service in an account having rights on the network shared folder : didn't work. Do I have to create a standalone application for this and launch this application as a user with rights on the network shared folder? Thanks, Nic
Both your scenarios should work. The "local system" is the computer account in the active directory that you can give share permissions to. I have no idea why it doesn't work for you. But here is what you can do. * Use an regualar account (its just easier). * Test your application as console application. * Tweak the auditing on the client to log everything to the security log. It is done from the local security policy application. And do the same on the server (If you can). This should be enough to locate the problem. **Update 1**: In response to the comment which I think is wrong (but maybe I am...). The service which the comment refers to ( The one without network access) is called local service account( NT AUTHORITY\LocalService ). It is usually used in the identity of application pools, but can be used in services. It is not the same as local system account. [from msdn](http://msdn.microsoft.com/en-us/library/ms677973(VS.85).aspx): > When a service runs under the > LocalSystem account on a computer that > is a domain member, the service has > whatever network access is granted to > the computer account, or to any groups > of which the computer account is a > member.
You should use UNC paths (as Scott suggested), and run the system under an explicit account which has access to the network resource; that should work. It *probably* will not work under LocalSystem because that's a special user account in Windows with local system access only. LocalSystem had no network access in NT4, and in 2000+ it's treated as the computer accounts for network access purposes, and subject to access restrictions in the local security policy. See [this page](http://msdn.microsoft.com/en-us/library/ms677973(VS.85).aspx) for more info. Short answer: use an explicit account to run the service which has access to the UNC path. :)
Is there a way to allow a Windows service (unmanaged c++) to write files on a shared network folder?
[ "", "c++", "windows", "service", "networking", "" ]
I have a WinForm that uses an ElementHost to display a WPF UserControl. Once every 50 times or so when the form loads the WPF content fails to paint. You can see through the WinForm chrome to whatever is beneath. Resizing the window gets the WPF content to show up. Is this a known issue? Can anyone suggest a workaround?
We have fought these types of issues before. See this WPF forum [post](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a8a5eebc-3d9e-44bb-abe3-8ce0d4e48263/) for more info on our particular flavor (I don't know if it is the same issue or not). The only thing that we found to work was to **change the size of the ElementHost**. ``` _elementHost.Width++; ``` It's a complete hack, ugly, and I'm embarrassed to even post it. But nothing else ever worked for us. So, it is definitely a workaround. (Grin) We tried Invalidate, Refresh and everything we could think of ... on the ElementHost. We also tried InvalidateMeasure, InvalidateArrange, and InvalidateVisual on the WPF hosted content. No luck. If you find another way to fix your issue, I would love to hear about it. Good luck, I know I have lost some hair on this one. **Update 1:** I have submitted another WPF forum [post](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c221382e-82f1-4736-956a-806dc2a8cb37) on this. Maybe we can get a response from Microsoft. Sure seems like a bug to me. **Update 2:** After I fixed the refresh issue with the above hack ... I still had another problem to solve that I thought worth mentioning here. That is: there was a definite delay until the screen refreshed. This made it seem like the user was navigating to another screen (it wasn't ... it was just the contents of the double buffering buffer). I ended up having to manually call System.Windows.Forms.Control.Refresh() on the Control that was hosting the ElementHost. In this way, even though the pause was still there ... at least the screen was blank ... and it didn't look like the user was navigating somewhere ...
the following worked for me. On the `Form_Activated` event, I added the following ``` elementHost1.HostContainer.InvalidateVisual(); ```
Winforms WPF Interop - WPF content fails to paint
[ "", "c#", ".net", "wpf", "winforms", "" ]
I know I can do something like the following code to dynamically create a client endpoint connection in WCF: ``` BasicHttpBinding basic = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly); basic.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm; EndpointAddress serviceAddress = new EndpointAddress("http://whatever/service.svc"); YourServiceClient m_client = new YourServiceClient(basic, serviceAddress); ``` The problem is that in this case I need to know what 'YourServiceClient' is. What I want to be able to do is be getting the type 'YourServiceClient' from a DB, where its stored as an object. Does anyone know how I would go about doing something like this? Where I have the value of 'YourServiceClient' in an object I've retrieved from the DB?
You aren't going to be able to do this. Basically, you are asking to get an unknown at runtime, but while binding to a known type at compile time. This simply cannot be done if the services that you are trying to access have some sort of shared interface. If they do have the same interface (meaning, the same set of methods, etc, etc) then you can use the example here to create your own channel factory at runtime, and get a proxy that implements the interface for the service: <http://msdn.microsoft.com/en-us/library/ms734681.aspx>
Nicholas Allen has covered something (I think) like this in his blog, start with [part 1](http://blogs.msdn.com/drnick/archive/2009/01/05/forwarding-service-part-1.aspx) There is also, IIRC, an ability to just receive the raw XML message, which you could then process yourself rather than working with a type specific proxy.
How to create a Dynamic Client Proxy Connection when the type is unknown?
[ "", "c#", ".net", "wcf", "" ]
I need to use a cursor to call a stored procedure that has 2 parameters that i need to pass into from Customers table. Here is what I mean; My goal is to pass all the CustomerID and CustomerName from Customers table into my stored procedure called AddCustomers which has 2 parameters of CustomerID and CustomerName. ie: AddCustomer [CustomerID],[CustomerName] [side note: this AddCustomer stored procedure does some filtering things that i need for my apps] So the end result of using this CURSOR with an stored procedure is to DUMP/PASS all of customerID and CustomerName from Customers table into AddCustomer stored procedure. I have used sp\_executesql, but not successfully. Here is what i have tried but not working. ``` Declare @CustomerID int Declare @CustomerName varchar(100) Declare cur CURSOR READ_ONLY FOR SELECT CustomerID, CustomerName from Customers OPEN cur FETCH NEXT FROM cur INTO @CustomerID, @CustomerName WHILE @@FETCH_STATUS = 0 BEGIN EXEC AddCustomer @CustomerID, @CustomerName FETCH NEXT FROM cur INTO @CustomerID, @CustomerName END CLOSE cur DEALLOCATE cur ``` --- I am new to the use of cursors so I am not sure why this isn't working. If you can provide any clues or links, I'd would appreciate it. ### Update: OK, if Cursor CANNOT loop thru stored procedure, THEN can anyone provide a solution or hints to my problem, which is to PASS all CustomerID and CustomerName from Customers table into my AddCustomer stored procedure so that i can do some filtering stuff on each of the CustomerID and CustomerName that i pass into AddCustomer Stored procedure.
Sam, There are times when using a stored procedure to do a task like this is *perfectly appropriate.* Le Dorfier has certainly given me lots of good advice but I have to disagree with him on this one. Especially if this is a one-time processing of your records to achieve some form of transformation, then you are *really* close to your solution as I don't see any obvious flaws in your code. BTW, I've taken the same approach on more than one occasion and it has worked very well. So...post the stored procedure as well as we'll see if that doesn't help. Also, what specific error are you seeing? **UPDATE:** Wait, are you just running this in the SQL Window? I usually package this stuff up in another stored procedure (often just a temporary one) and then run it. Of course, it may also be that you just need to execute this code - not using EXEC but just using the Execute button...it is hard to tell based on your description. **UPDATE 2:** You say above that the error is something about the table. Are you sure that the data types that you have defined are correct? Could the error be a mismatch between the data pulled from the table and the type of the var into which you are placing it?
Your cursor is fine from syntax perspective. I'm guessing that the issue has something to do with your stored procedure throwing an error. You should post the code for the stored procedure as well. And the error message(s).
Cursor with Stored Procedure Question
[ "", "sql", "sql-server", "stored-procedures", "" ]
I inherited some code that is using XPath for which I am a novice. I have it now so that it loads the document, but when the document.selectPath(queryPath) it always fails with the following error: ```` ``` java.lang.RuntimeException: Trying XBeans path engine... Trying XQRL... Trying delegated path engine... FAILED on // at org.apache.xmlbeans.impl.store.Path.getCompiledPath(Path.java:173) at org.apache.xmlbeans.impl.store.Path.getCompiledPath(Path.java:130) at org.apache.xmlbeans.impl.store.Cursor._selectPath(Cursor.java:902) at org.apache.xmlbeans.impl.store.Cursor.selectPath(Cursor.java:2634) at org.apache.xmlbeans.impl.values.XmlObjectBase.selectPath(XmlObjectBase.java:462) at org.apache.xmlbeans.impl.values.XmlObjectBase.selectPath(XmlObjectBase.java:446) ``` ````
You need an XPath engine in your classpath, which one bepends on the XMLBeans version, see <http://wiki.apache.org/xmlbeans/XmlBeansFaq#whatJars>
Thank you jor for the post. I was confused as earlier commands to xml beans were successful. Without saxon, this still works: ``` MapDocument doc; ... String cityQuery = "$this//City"; XmlObject[] cities = doc.selectPath(cityQuery); ``` However saxon is required for explicit selection of fields within tags: ``` String aveQuery= "$this//Street[Kind='Avenue']"; XmlObject[] avenues = doc.selectPath(aveQuery); // RuntimeException without saxon on path ``` ``` java.lang.RuntimeException: Trying XBeans path engine... Trying XQRL... Trying delegated path engine... FAILED on $this//Street[Kind='Avenue'] ``` I hope this might be of use to others that encounter a similar issue.
XPath can't find an engine
[ "", "java", "xpath", "" ]
I have to implement a set of 60 functions, according to the predefined signatures. They must be global functions, and not some class's member functions. When I implement them, I use a set of nicely done classes provided by 3rd party. My implementation of most functions is quite short, about 5-10 lines, and deals mostly with different accesses to that 3rd party classes. For some more complicated functions I created a couple of new classes that deal with all the complicated stuff, and I use them in the functions too. All the state information is stored in the static members of my and 3rd party's classes, so I don't have to create global variables. Question: Would it be better if I implement one big class with 60 member functions, and do all the implementation (that is now in the global functions) there? And each of the functions that I have to write will just call to the corresponding member function in the class.
> All the state information is stored in the static members of my and 3rd party's classes, so I don't have to create global variables. That is the keypoint. No, they should definitely not be put into classes. Classes are made to be used for creating objects. In your situation, you would use them just as a scope, for the data and functions. But this is what *namespaces* already solve better: ``` namespace stuff { ... 60 functions ... namespace baz { ... if you want, you can have nested namespaces, to ... ... categorize the functions ... } namespace data { ... you can put data into an extra namespace if you want ... } } ``` Creating classes that consist purely only of static members is a bad idea.
Do the users of your code really need this big class? If yes, implement it. If no, don't waste your time on implementing it and don't waste the time of others mandated to test it or trying to understand what is the exact role of this class beyond the OOP look.
Implementation in global functions, or in a class wrapped by global functions
[ "", "c++", "oop", "static", "namespaces", "global", "" ]
I'm making an application that makes use of session variables. I have created a class "HistoryLine" and another called "HistoryLineCollection" with a list of "HistoryLine"s in it. I then save the instance of the HistoryLineCollection to the session like this: Session["HistoryLines"] = hLines; The problem is that when I watch this on another computer, I see the same list! I thought sessions where client unique? I have looked into the sessionState and maybe the SessionID is cloned or something, but I just can't see it. Anyone has an idea?
No, the asp.net session is not shared. One way for this to happen is browsing the app on one computer, and then using the link on another computer (say you im it to someone). In that scenario, if you happen to have cookies disabled, the session ID is on the Url. The other person would be on the same session. If that is not the case, then really have a look at the classes you are using, specially anything marked as static.
Are the members of the the class that is created and then put into Session somehow static (aka shared)?
ASP.net session is shared by default?
[ "", "c#", "asp.net", "session-variables", "" ]
When I try to POST to a URL it results in the following exception: > The remote server returned an error: > (417) Expectation Failed. Here's a sample code: ``` var client = new WebClient(); var postData = new NameValueCollection(); postData.Add("postParamName", "postParamValue"); byte[] responseBytes = client.UploadValues("http://...", postData); string response = Encoding.UTF8.GetString(responseBytes); // (417) Expectation Failed. ``` Using an `HttpWebRequest/HttpWebResponse` pair or an `HttpClient` doesn't make a difference. What's causing this exception?
System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting [this static property](http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.expect100continue(VS.80).aspx) to false: ``` System.Net.ServicePointManager.Expect100Continue = false; ``` Some servers choke on that header and send back the 417 error you're seeing. Give that a shot.
Another way - Add these lines to your application config file configuration section: ``` <system.net> <settings> <servicePointManager expect100Continue="false" /> </settings> </system.net> ```
HTTP POST Returns Error: 417 "Expectation Failed."
[ "", "c#", ".net", "http", "http-post", "webclient", "" ]
I have a temp table that has numeric integer values in one column. I want to either replace the integer values with character values based on some criteria or I want to add another column of character type that automatically inserts values into itself based on some criteria. If x <= 1, change to "SP" or make new column and store "SP" in that row If x > 1, change to "FA" or make new column and store "FA" in that row Also, alter commands are not allowed on temp tables in my version of Informix.
SELECT id, yr, CASE WHEN yr\_offset <= 1 THEN "SP" ELSE "FA" END CASE <http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls.doc/sqls909.htm>
You're correct, you cannot alter a temp table. Adding an extra column with this derived value can be done with a `CASE` statement, ie: ``` SELECT enroll.ud, enroll.yr, (CASE WHEN enrollsess.yr_offset <=1 THEN "FA" ELSE "SP" END)::CHAR(2) AS sess, ... ``` The casting (ie the parentheses and `::CHAR(2)`) are probably not necessary. If the logic can be expressed as zero/non-zero (it's not clear in your example if yr\_offset can be negative), then it's even simpler: ``` SELECT enroll.id, enroll.yr, DECODE(enrollsess.yr_offset, 0, "FA", "SP")::CHAR(2) AS sess, ... ``` [More details on CASE syntax from the manual](http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls.doc/sqls909.htm)
SQL - Informix - Changing the datatype of a column from numeric to character
[ "", "sql", "types", "informix", "alter", "" ]
I'm resizing jpegs by using the Graphics.DrawImage method (see code fragment below). Can anyone confirm that this will not affect the compression of the new image? I have seen [this thread](https://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality), but I am talking specifically about compression of jpegs. ``` private byte[] getResizedImage(String url, int newWidth) { Bitmap bmpOut = null; System.IO.MemoryStream outStream = new System.IO.MemoryStream(); //input image is disposable using (Bitmap inputImage = LoadImageFromURL(url)) { ImageFormat format = inputImage.RawFormat; decimal ratio; //ratio old width:new width int newHeight = 0; //*** If the image is smaller than a thumbnail just return it if (inputImage.Width < newWidth) return null; ratio = (decimal)newWidth / inputImage.Width; decimal h = inputImage.Height * ratio; newHeight = (int)h; bmpOut = new Bitmap(newWidth, newHeight); Graphics g = Graphics.FromImage(bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // try testing with following options: //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; //g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight); g.DrawImage(inputImage, 0, 0, newWidth, newHeight); bmpOut.Save(outStream, getImageFormat(url)); } return outStream.ToArray(); } ```
When you call "bmpOut.Save" you have to pass in some EncoderParameters to tell the method what quality level you would like to save it with. <http://msdn.microsoft.com/en-us/library/system.drawing.imaging.encoderparameters(VS.80).aspx>
JPEGs have no "compression" value saved within them. When you resize and save them, they are compressed with whatever value you tell your save function to use. As you are not passing a value, it will just use whatever default for the library is.
Does resizing jpeg images affect their compression?
[ "", "c#", ".net", "image", "compression", "resize", "" ]
In my drupal6 site I have wizard form. I implemented it with FormAPI using form storage and the rebuild property. My form validation is being done with the #required property and with functions in the #element\_validate property. It's working fine but for one thing, when I click on the previous button the form is being validated and I don't want it to. Is there a smart and right way to disable the validations when a specific button of the form is clicked?
The only way to do this cleanly (unfortunately) is to avoid the use of #required = TRUE and validate it yourself in a validation handler, taking into account knowledge of what 'step' the form is on in the wizard process. One common approach is to accumulate all of your in-progress data in $form\_state['storage'], where it will persist between rebuilds.
``` // hack to clear validation errors during wizard processing form_set_error(NULL, FALSE, TRUE); unset($_SESSION['messages']['error']); ```
Drupal wizard form: Validation and previous button
[ "", "php", "drupal", "drupal-6", "drupal-fapi", "drupal-form-validation", "" ]
While trying to get to all green, i got the following suggestion by Resharper. Original code: ``` static public string ToNonNullString(this XmlAttribute attr) { if (attr != null) return attr.Value; else return string.Empty; } ``` Suggestion: remove redundant 'else' resulting in following: ``` static public string ToNonNullString(this XmlAttribute attr) { if (attr != null) return attr.Value; return string.Empty; } ``` To me, the suggested version seems less readable than the original. Does Resharper suggestion reflect the definition of good maintainable code?
Technically Resharper is correct in that the "else" is unnecessary, I prefer the former version though as the intent is more obvious. Having said that, I'd rather go with: ``` return attr != null ? attr.Value : string.Empty; ```
Ah, code aesthetics. Holy war time. *(ducks)* I'd go with either a ?: expression: ``` return attr != null ? attr.Value : String.Empty ``` or invert the if and remove the line break to produce a [guard clause](http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html): ``` if (attr == null) return String.Empty; return attr.Value; ```
Code suggestions by Resharper making code less readable?
[ "", "c#", "resharper", "" ]
Is it possible to append elements to a python generator? I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator. Any help would be much appreciated. Related: * [Flattening a shallow list in python](https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python)
This should do it, where `directories` is your list of directories: ``` import os import itertools generators = [os.walk(d) for d in directories] for root, dirs, files in itertools.chain(*generators): print root, dirs, files ```
You are looking for [`itertools.chain`](https://docs.python.org/library/itertools.html#itertools.chain). It will combine multiple iterables into a single one, like this: ``` >>> import itertools >>> for i in itertools.chain([1,2,3], [4,5,6]): ... print(i) ... 1 2 3 4 5 6 ```
Adding elements to python generators
[ "", "python", "append", "generator", "" ]
This is a very basic question, I'm just not that good with Java. I have a Map and I want to get a list or something of the keys in sorted order so I can iterate over them.
Use a [`TreeMap`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html), which is an implementation of the `SortedMap` interface. It presents its keys in sorted order. ``` Map<String, Object> map = new TreeMap<String, Object>(); /* Add entries to the map in any order. */ ... /* Now, iterate over the map's contents, sorted by key. */ for (Map.Entry<String, ?> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } ``` If you are working with another Map implementation that isn't sorted as you like, you can pass it to the [constructor](http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html#TreeMap(java.util.Map)) of `TreeMap` to create a new map with sorted keys. ``` void process(Map<String, Object> original) { Map<String, Object> copy = new TreeMap<String, Object>(original); /* Now use "copy", which will have keys in sorted order. */ ... } ``` A `TreeMap` works with any type of key that implements the `Comparable` interface, putting them in their "natural" order. For keys that aren't `Comparable`, or whose natural ordering isn't what you need, you can implement your own [`Comparator`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html) and specify that in the [constructor](http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html#TreeMap(java.util.Comparator)).
You have several options. Listed in order of preference: 1. Use a [`SortedMap`](http://java.sun.com/javase/6/docs/api/java/util/SortedMap.html): `SortedMap<whatever> myNewMap = new TreeMap<whatever>(myOldMap);` This is vastly preferable if you want to iterate more than once. It keeps the keys sorted so you don't have to sort them before iterating. 2. There is no #2. 3. There is no #3, either. 4. `SortedSet<whatever> keys = new TreeSet<whatever>(myMap.keySet());` 5. `List<whatever> keys = new ArrayList<whatever>(myMap.keySet()); Collections.sort(keys);` The last two will get you what you want, but should only be used if you only want to iterate once and then forget the whole thing.
How can I sort the keys of a Map in Java?
[ "", "java", "" ]
All I want to do is to check whether an element exists in the vector or not, so I can deal with each case. ``` if ( item_present ) do_this(); else do_that(); ```
You can use [`std::find`](http://en.cppreference.com/w/cpp/algorithm/find) from `<algorithm>`: ``` #include <algorithm> #include <vector> vector<int> vec; //can have other data types instead of int but must same datatype as item std::find(vec.begin(), vec.end(), item) != vec.end() ``` This returns an iterator to the first element found. If not present, it returns an iterator to one-past-the-end. With your example: ``` #include <algorithm> #include <vector> if ( std::find(vec.begin(), vec.end(), item) != vec.end() ) do_this(); else do_that(); ```
As others have said, use the STL [`find`](http://en.cppreference.com/w/cpp/algorithm/find) or [`find_if`](http://en.cppreference.com/w/cpp/algorithm/find) functions. But if you are searching in very large vectors and this impacts performance, you may want to sort your vector and then use the [`binary_search`](http://en.cppreference.com/w/cpp/algorithm/binary_search), [`lower_bound`](http://en.cppreference.com/w/cpp/algorithm/lower_bound), or [`upper_bound`](http://en.cppreference.com/w/cpp/algorithm/upper_bound) algorithms.
How to find out if an item is present in a std::vector?
[ "", "c++", "std", "stdvector", "" ]
I've followed the helpful instructions here: [Install GD for PHP on Mac OS X 10.5 Leopard](http://www.gigoblog.com/2008/10/08/install-gd-for-php-on-mac-os-x-105-leopard/) And I have my extension directory in php.ini file like this: > extension\_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/" But when I try and load GD, I get an error: > PHP Startup: Unable to load dynamic library '/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/gd.so' - (null) in Unknown on line 0 > GDB - GNU Debugger protocol => $Revision: 1.88 $ This is a common error. Can someone point me in the right direction.
The path to extension\_dir was wrong.
I had exactly the same error, and it took me several hours to track down. The answer is that you need to make sure you're compiling the right version for your processor. In my case, I was not remembering that the PPC G5 is a 64-bit processor, and this was failing because I was using the 32-bit versions. I also found it was helpful to change the two config lines to be more specific about setting things up for the PPC64 architecture, as follows **For jpeg-6b:** THE FOLLOWING LINE DOES NOT WORK PROPERLY: ``` MACOSX_DEPLOYMENT_TARGET=10.5 CFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp" CCFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe" CXXFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe" LDFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -bind_at_load" ./configure --enable-shared ``` BUT THIS ONE DOES (ON THE G5 AT LEAST): ``` MACOSX_DEPLOYMENT_TARGET=10.5 CFLAGS=" -arch ppc64 -g -Os -pipe -no-cpp-precomp" CCFLAGS=" -arch ppc64 -g -Os -pipe" CXXFLAGS="-arch ppc64 -g -Os -pipe" LDFLAGS="-arch ppc64 -bind_at_load" ./configure --enable-shared ``` **For GD:** THE FOLLOWING LINE DOES NOT WORK PROPERLY: ``` MACOSX_DEPLOYMENT_TARGET=10.5 CFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp" CCFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe" CXXFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe" LDFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -bind_at_load" ./configure --with-zlib-dir=/usr --with-jpeg-dir=/usr/local/lib --with-png-dir=/usr/X11R6 --with-freetype-dir=/usr/X11R6 --with-xpm-dir=/usr/X11R6 ``` BUT THIS ONE DOES (ON THE G5 AT LEAST): ``` MACOSX_DEPLOYMENT_TARGET=10.5 CFLAGS=" -arch ppc64 -g -Os -pipe -no-cpp-precomp" CCFLAGS=" -arch ppc64 -g -Os -pipe" CXXFLAGS="-arch ppc64 -g -Os -pipe" LDFLAGS=" -arch ppc64 -bind_at_load" ./configure --with-zlib-dir=/usr --with-jpeg-dir=/usr/local/lib --with-png-dir=/usr/X11R6 --with-freetype-dir=/usr/X11R6 --with-xpm-dir=/usr/X11R6 ```
Compiling PHP-GD on Mac OSX 10.5
[ "", "php", "macos", "gd", "" ]
I am trying to find somebody smarter than me to validate some syntax I wrote up. The idea is to configure the filename of my RollingFileAppender to the name of the assembly in order to make it more re-usable for my projects. I've seen [this previous SO article](https://stackoverflow.com/questions/308436/log4net-programmatcially-specify-multiple-loggers-with-multiple-file-appenders) but it wasn't exactly able to answer my question... I've had a dickens of a time trying to understand the inner components of Log4net and this is what I came up with (residing in the Global.asax file - Application\_Start method): ``` // Bind to the root hierarchy of log4net log4net.Repository.Hierarchy.Hierarchy root = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy; if (root != null) { // Bind to the RollingFileAppender log4net.Appender.RollingFileAppender rfa = (log4net.Appender.RollingFileAppender)root.Root.GetAppender("RollingLogFileAppender"); if (rfa != null) { // Set the file name based on the assembly name string filePath = string.Format("~/App_Data/{0}.log", GetType().Assembly.GetName().Name); // Assign the value to the appender rfa.File = Server.MapPath(filePath); // Apply changes to the appender rfa.ActivateOptions(); } } ``` Can anyone tell me, 'this is hideous', or 'this should work fine'? Also, if I set the file dynamically can I still expect the log4net behavior to rotate the files based on the log4net.config file settings? Much appreciated!
You are doing this the hard way! Define your log4net config as XML in your application's configuration file and use `%property{}` to advantage: ``` <appender name="YourAppender" type="log4net.Appender.RollingFileAppender"> <file type="log4net.Util.PatternString" value="~/App_Data/%property{LogName}" /> .... </appender> ``` This is dynamic -- you just have to set the log4net property "`LogName`" **before** you initialize log4net. Thus, in your code any time before you configure log4net, set the desired value of this property: ``` string LogName = GetType().Assembly.GetName().Name + ".log"; log4net.GlobalContext.Properties["LogName"] = LogName; ``` Of course, you may use any property name. I've chosen "LogName" for a simple example, but you can have one per application if you want, as long as your code knows what the correct property name is and what the correct value should be.
Here is way to set or change the logfile of the first appender at runtime: ``` var appender = (log4net.Appender.FileAppender)LogManager.GetRepository().GetAppenders()[0]; appender.File = "C:\whatever.log"; appender.ActivateOptions(); ```
Best way to dynamically set an appender file path
[ "", "c#", "log4net", "" ]