Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to join a select disinct statement to a select sum statement. Here is an example of the data ``` CD STDATE ENDDATE PR F1 01/02/09 01/04/09 $10 F1 01/02/09 01/04/09 $40 F1 01/02/09 01/04/09 $20 F1 01/02/09 01/04/09 $30 F1 01/22/09 01/26/09 $10 F1 01/22/09 01/26/09 $50 F1 01/22/09 01/26/09 $20 ``` My desired output is - ``` F1 01/02/09 01/04/09 $100 F1 01/22/09 01/26/09 $80 ``` So far, I have the foll statement, which is incorrect: ``` SELECT DISTINCT STDATE, ENDDATE, CD FROM TABLE AS A INNER JOIN (SELECT SUM(PR) FROM TABLE) AS B ON A.STDATE=B.STDATE ``` How can I do that???
I think you are looking for grouping: ``` select t.cd, t.stdate, t.enddate, sum(t.pr) from table t group by t.cd, t.stdate, t.enddate ```
``` Select cd, stdate, enddate, sum(PR) from Table group by cd, stdate, enddate ```
How do I join a select distinct to a select sum?
[ "", "asp.net", "sql", "sql-server", "" ]
This is a jstack output from a running JVM ``` "FooThread" prio=10 tid=0x00007f159c2ca000 nid=0x6e21 waiting on condition ..snipped java.lang.Thread.State: TIMED_WAITING (sleeping) at java.lang.Thread.sleep(Native Method) at com.myco.impl.QueueFooThread.run(Unknown Source) ``` I want the line number in QueueFooThread to show up like this frame for the Catalina process ``` at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1548) ``` What should I do during compilation/bootstrap time to enable this ? Thanks
This may not be a complete answer, but passing the `-g` (debugging) option to `javac` enables the debugger (`jdb`) to display source information, including line numbers. I'm not sure if it'll work for your case.
Compile your source with debug option. E.g. ``` <javac target="1.5" source="1.5" classpathref="class.path" srcdir="${src}" destdir="${build}" debug="true" encoding="UTF-8"/> ```
How to show source line numbers in jstack output?
[ "", "java", "debugging", "concurrency", "jvm", "" ]
I am trying for the first time to create an extension method and i am having some trouble... maybe you guys can help out :) ``` public static class Extentions { public static int myMethod(this MyClass c) { return 1; } } ``` then when i do "MyClass.myMethod" i get q compiler error saying that the method does not exists... Why is that?
First, you need a "using" directive to include the namespace that includes your class with extension methods. Second - re "MyClass.myMethod" - extension methods work on *instances*, not as static - so you'd need: ``` MyClass foo = ... int i = foo.myMethod(); // translates as: int i = Extentions.myMethod(foo); ``` Finally - if you want to use the extension method *inside* `MyClass` (or a subclass), you need an explicit `this` - i.e. ``` int i = this.myMethod(); // translates as: int i = Extentions.myMethod(this); ``` This is one of the few cases where `this` matters.
Did you include the namespace where your extension is defined? I've been burned by that before. And a way to get around having to add the namespace where your extension is to define the extension in that namespace. This is not a good practice though
Compiler error referencing custom C# extension method
[ "", "c#", "extension-methods", "" ]
I'm used to ASPNET and Django's methods of doing forms: nice object-orientated handlers, where you can specify regexes for validation and do everything in a very simple way. After months living happily without it, I've had to come back to PHP for a project and noticed that everything I used to do with PHP forms (manual output, manual validation, extreme pain) was utter rubbish. Is there a nice, simple and free class that does form generation and validation like it *should* be done? Clonefish has the right idea, but it's way off on the price tag.
The simplest solution (rather than going through the process of learning another framework) turned out to be just writing the forms and their processing code in Django and pulling their output into the PHP using CURL. FILTHY but it was quick, has all the power of Django and it works.
I have recently used the project listed above - <http://code.google.com/p/php-form-builder-class/> - in development and noticed that the latest release (version 1.0.3) replaces the table markup with a more flexible div layout that can be easily styled to render forms however you'd like. There are many examples that can help you get started quickly. I would recommend this project.
PHP form class
[ "", "php", "validation", "" ]
So I'm building the pacman game in Java to teach myself game programming. I have the basic game window with the pacman sprite and the ghost sprites drawn, the pacman moves with the arrow keys, doesn't move beyond the walls of the window, etc. Now I'm trying to build the maze, as in this picture: ![Pacman maze](https://upload.wikimedia.org/wikipedia/en/5/59/Pac-man.png) Without giving me the direct/complete solution to this, can someone guide me as to how this can be built? I'm talking only about the boundaries and the pipes('T' marks) here which you can't go through and you have to go around. Not the dots which the pacman eats yet. Here are my questions: 1) What's the most efficient algorithm/method for creating this maze? Will it have to be drawn each time the paint() method is called or is there a way to draw it only at the start of the game and never again? 2) How will this actually be drawn to the screen? I assume the `fillRect()` will be used? 3) Any hints on collision detection (so the pacman/ghosts can't go through the walls) would be helpful. 4) Any hints on how the vacant space between the pipes will be calculated so the dots can be filled between them will also be very helpful. Thanks
I wouldn't do it that way. I'd draw the graphical map and then create a 2D data array which represents the map. The data map would be responsible for determining collisions, eating dots, where candy is and where the ghosts are. Once all the logic for everything is handled just use the 2D array to display everything in their proper pixel coordinates over the graphical map. For example the user is pressing the left key. First you determine that pacman is at element 3, 3. Element 3, 2 contains information denoting a wall so you can implement the code to make him ignore the command. EDIT: Each element would represent about where a dot could be. For example: No, looking at the board I would say the array would look something like this. ``` d,d,d,d,d,d,d,d,d,d,d,d,w,w,d,d,d,d,d,d,d,d,d,d,d,d d,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,d p,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,p d,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,d d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d ``` And so on. You might want to pick a more flexible data structure than just characters however since some areas need to contain a bunch of different information. IE even though the ghost spawning area is blank, pacman isn't allowed in there. The movement of the ghosts and pacman is different for the side escapes, the candy spawn point is a blank spot but if you want to remain flexible you'll want to denote where this is on a per map basis. Another thing you'll want to remember is that pacman and the ghosts are often inbetween points so containing information that represents a percentage of a space they're taking up between 1,2 and 1,3 is important for collision detection as well as determining when you want to remove dots, powerups and candy from the board.
1. You can paint the map into a BufferedImage and just drawImage that on every paint(). You'll get quite reasonable performance this way. 2. If you are happy with the walls being solid, you can draw each square wall block with fillRect. If you wish to get the same look as in the picture, you need to figure how to draw the lines in the right way and use arcs for corners. 3. The Pacman game map is made of squares and Pacman and the ghosts always move from one square to the neighbouring square in an animated step (i.e. you press right, the pacman moves one square to the right). That means that collision detection is easy: simply don't allow moves to squares that are not empty. 4. I do not understand what you are trying to ask here.
Pacman maze in Java
[ "", "java", "algorithm", "2d", "maze", "" ]
I have a SocketState object which I am using to wrap a buffer and a socket together and pass it along for use with the Begin/End async socket methods. In the destructor, I have this: ``` ~SocketState() { if (!_socket.Connected) return; _socket.Shutdown(SocketShutdown.Both); _socket.Close(); } ``` When it gets to Close(), I get an ObjectDisposed exception. If I comment out the call Shutdown(), I do not get the error when it gets to the Close() method. What am I doing wrong? ## Edit: I know that the IDisposable solution seems to be how my code should be *laid out*, but that doesn't actually solve my problem. It's not like the destructor is getting called twice, so why would calling dispose() instead of using the destructor help me? I still get the same exception when calling these 2 functions in succession. I have looked at the source for a similar server, and all they do is wrap these 2 statements in a try block and swallow the exception. I'll do that if I have to because it seems harmless (we're closing it anyway), but I would like to avoid it if possible.
\_socket implements IDisposable, and when your finalizer runs, the socket is already disposed (or finalized for that matter). You should implement IDisposable on your class and follow the dispose pattern. Example: ``` public class SocketState : IDisposable { Socket _socket; public SocketState() { _socket = new Socket(); } public bool IsDisposed { get; private set; } public void SomeMethod() { if (IsDisposed) throw new ObjectDisposedException("SocketState"); // Some other code } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!IsDisposed) { if (disposing) { if (_socket != null) { _socket.Close(); } } // disposed unmanaged resources IsDisposed = true; } } ~SocketState() { Dispose(false); } #endregion } ```
Using reflector; it appears that `Close()` essentially just calls `Dispose()` on the Socket (it does a bit of logging either side). Looking at `Shutdown()` it calls `ws2_32.dll!shutdown()` on the socket handle, which is *also* called by `Dispose()`. What's likely happening is that it's trying to call `ws2_32.dll!shutdown()` twice on the same socket handle. The answer in short is to just call `Close()`.
Getting an ObjectDisposed exception when calling Shutdown then Close on a Socket
[ "", "c#", "networking", "sockets", "" ]
I am passing a boolean value to a javascript function in my .net mvc action page. problem is, it is outputting the value True and javascript apparently only accepts 'true' (in lower case). I don't want to hack the variable and make it a string and convert it to lower case in my action, but it looks like I have no choice?
If you're using the ToString() method on a .NET boolean to send the value to Javascript, try replacing it with something like ``` (myBoolean ? "true" : "false") ``` so that it gets sent to Javascript as the appropriate string representation of the required bool value. **EDIT:** Note the difference between: ``` <script type="text/javascript"> var myBoolean = <%= (myBoolean ? "true" : "false") %>; </script> ``` and ``` <script type="text/javascript"> var myBoolean = '<%= (myBoolean ? "true" : "false") %>'; </script> ``` In the first example, you end up with: ``` var myBoolean = false; ``` and that's a literal Boolean false. In the second, you end up with: ``` var myBoolean = 'false'; ``` and in JavaScript, 'false' is a non-empty string and consequently if evaluated in a Boolean context, it'll be true. Well, true-ish. :)
I created an extension method to use it in any boolean property of a Model. ``` public static class GeneralExtensions { public static string GetValueForJS(this bool argValue) { return argValue ? "true" : "false"; } } ``` Now in a view I can simply use: ``` <script type="text/javascript"> var variable = @Model.IsFoo.GetValueForJS(); </script> ```
Passing a boolean value in my .net MVC view to a javascript, but JS doesn't accept True, wants true
[ "", "javascript", "asp.net-mvc", "view", "" ]
I have a [`BitArray`](https://msdn.microsoft.com/en-us/library/system.collections.bitarray(v=vs.110).aspx) with the length of 8, and I need a function to convert it to a `byte`. How to do it? Specifically, I need a correct function of `ConvertToByte`: ``` BitArray bit = new BitArray(new bool[] { false, false, false, false, false, false, false, true }); //How to write ConvertToByte byte myByte = ConvertToByte(bit); var recoveredBit = new BitArray(new[] { myByte }); Assert.AreEqual(bit, recoveredBit); ```
This should work: ``` byte ConvertToByte(BitArray bits) { if (bits.Count != 8) { throw new ArgumentException("bits"); } byte[] bytes = new byte[1]; bits.CopyTo(bytes, 0); return bytes[0]; } ```
A bit late post, but this works for me: ``` public static byte[] BitArrayToByteArray(BitArray bits) { byte[] ret = new byte[(bits.Length - 1) / 8 + 1]; bits.CopyTo(ret, 0); return ret; } ``` Works with: ``` string text = "Test"; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(text); BitArray bits = new BitArray(bytes); bytes[] bytesBack = BitArrayToByteArray(bits); string textBack = System.Text.Encoding.ASCII.GetString(bytesBack); // bytes == bytesBack // text = textBack ``` .
Convert from BitArray to Byte
[ "", "c#", ".net", "binary", "bitarray", "base-class-library", "" ]
I need to interface an existing application with Acegi/Spring security. In order to get started I am looking for one simple piece of information: in this context, will HttpServletRequest.getUserPrincipal() called from my application properly return the username obtained through Spring (as opposed to using Spring-specific objects)? I have Googled conflicting information on this. I assume that if Acegi is implemented with filters, it is able to overload the Servlet API's getUserPrincipal(), right? Subsidiary question: if this is not the case by default, is there any way to turn it on? Thanks, -Erik
As previous user has answer, spring security support the getUserPrincipal and isUserInRole. Here is how spring security does it. When you configure spring, it can load the following filters: <http://static.springframework.org/spring-security/site/reference/html/ns-config.html#filter-stack> As part of the standard filter configuration the `SecurityContextHolderAwareRequestFilter` filter is loaded. Examining the filter @ <https://fisheye.springsource.org/browse/spring-security/tags/spring-security-parent-2.0.4/core/src/main/java/org/springframework/security/wrapper/SecurityContextHolderAwareRequestFilter.java?r=2514> You can see it wraps and changes the `HttpServletRequest` object to the `SecurityContextHolderAwareRequestWrapper` class which extends `HttpServletRequestWrapper` which implements `HttpServletRequest` and feed it back to the standard Servlet Filter doFilter chain. Since spring security filter *should* be configured as the first filter, all subsequent classes will see the `SecurityContextHolderAwareRequestWrapper` instead. This includes JSP pages or Servlets behind this filter. When you make a call to `isUserInRole` or `getUserPrincipal` from the JSP page, Servlet or any framework behind this filter, it is calling the `HttpServletRequest` implementation from Spring Security.
If you use the security filter, yes it does. I believe this is the default behavior. Exactly which class you're getting back depends on your configuration, but they all implement the Principal interface by way of Spring's own org.springframework.security.Authentication interface which extends it. I've used request.getUserPrincipal() and request.isUserInRole() in a Spring application and it works seamlessly, even within JSPs.
Does Acegi/Spring security support getUserPrincipal()?
[ "", "java", "security", "spring", "servlets", "spring-security", "" ]
I'm trying to write some code that catches a particular exception and throw a more useful one for something higher up the call stack to deal with but also catch more general exceptions and handle them. The code is something like this: ``` try { // Do stuff } catch (SomeException e) { throw new SomeExceptionWithContextInfo(); } catch (Exception e) { // Handle unexpected exception gracefully } ``` The problem I'm having is that the general exception is catching my new exception. is there a way to avoid this? My current solution involves checking the type of the exception and throwing it again if it's type is what I just created.
The code you've posted should work, as shown in this test app: ``` using System; class OtherException : Exception {} class Test { static void Main(string[] args) { try { Foo(); } catch (OtherException) { Console.WriteLine("Caught OtherException"); } } static void Foo() { try { string x = null; int y = x.Length; } catch (NullReferenceException) { throw new OtherException(); } catch (Exception) { Console.WriteLine("Caught plain Exception"); } } } ``` This just prints "Caught OtherException" not "Caught plain Exception". Are you sure you don't have a nested try block in your real code? Could you post a short but complete example which shows your problem? Do you really need to catch Exception in your method though? That's very rarely a good idea.
The code you posted is the way to do it (catch for more specific exception must appear first). I suggest looking again at the code, as either they are not in that order, or the code isn't actually throwing that exception type. Here is a link on msdn about try-catch: <http://msdn.microsoft.com/en-us/library/0yd65esw(VS.80).aspx>
Exception handling problem
[ "", "c#", "exception", "" ]
[LinkedHashMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html) is the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additional linked list maintaining the insertion order. Is there an equivalent to that in Python?
As of Python 3.7, `dict` objects maintain their insertion order by default. If you're on Python 2.7 or Python >=3.1 you can use [collections.OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) in the standard library. [This answer](https://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted/61031#61031) to the question [How do you retrieve items from a dictionary in the order that they’re inserted?](https://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted) contains an implementation of an ordered dict, in case you're not using Python 3.x and don't want to give yourself a dependency on the third-party [ordereddict module](http://www.xs4all.nl/~anthon/Python/ordereddict/).
Although you can do the same thing by maintaining a list to keep track of insertion order, [Python 2.7](https://docs.python.org/2/library/collections.html) and [Python >=3.1](https://docs.python.org/3/library/collections.html) have an OrderedDict class in the collections module. Before 2.7, you can subclass `dict` [following this recipe](http://code.activestate.com/recipes/576693/).
Equivalent for LinkedHashMap in Python
[ "", "python", "" ]
I am querying a database field that returns a money value, I am assigning this to a string but it is adding extra 00 on the end. e.g. Query returns `30.00` I assign this to a string (`string value = Convert.ToString(ReturnValue);`) but when I output it, it is showing as `30.0000` Can you advise me where I'm going wrong and the best way to approach this?
You can use [string format codes](http://msdn.microsoft.com/en-us/library/0c899ak8.aspx) in your ToString call.
MartGriff, My best advice would be to convert it to a double using the SqlMoney type. From there, you can output it however you would like! Here's an example: ``` System.Data.SqlTypes.SqlMoney ReturnValue; //Set your returnValue with your SQL statement ReturnValue = ExecuteMySqlStatement(); //Get the format you want //$30.00 string currencyFormat = ReturnValue.ToDouble().ToString("c"); //30.00 string otherFormat = ReturnValue.ToDouble().ToString("0.00"); ``` For more formatting options, check out the MSDN: <http://msdn.microsoft.com/en-us/library/system.double.tostring.aspx> Best of luck, I hope this helps.
C# Currency to string
[ "", "c#", "" ]
I recently run into trouble when trying to AddRange(IEnumerable) to a List. Probably a classic issue, but I do not really get it yet. I understand that methods expecting a List parameter are not satisfied with a List, because they might try to add a Base to the List, which is obviously impossible. But if i get this correctly, since IEnumerables themselves cannot be changed, it ought to work in this case. The code i thought of looks like this: ``` class Foo { } class Bar : Foo { } class FooCol { private List<Foo> m_Foos = new List<Foo> (); public void AddRange1(IEnumerable<Foo> foos) { m_Foos.AddRange (foos); // does work } public void AddRange2<T>(IEnumerable<T> foos) where T : Foo { m_Foos.AddRange (foos); // does not work } } class Program { static void Main(string[] args) { FooCol fooCol = new FooCol (); List<Foo> foos = new List<Foo> (); List<Bar> bars = new List<Bar> (); fooCol.AddRange1 (foos); // does work fooCol.AddRange1 (bars); // does not work fooCol.AddRange2 (foos); // does work fooCol.AddRange2 (bars); // does work } } ``` I tried to pass a hint to the compiler in the AddRange2 method, but this just moved to problem around. Is my way of thinking flawed? Is this a limitation of the language or is it by design? IIRC, support for this kind of operations was added to Java 1.5, so maybe it will be added to C# at some point in the future, too...?
This is covariance, and will be fixed in C# 4.0 / .NET 4.0. For now, the generic option is the best answer (for `IEnumerable<T>` - [not `IList<T>` etc](http://marcgravell.blogspot.com/2009/02/what-c-40-covariance-doesn-do.html)). But within the generic method, you have to think in terms of `T`. You could also use `Cast<T>` or `OfType<T>` with LINQ to achieve something similar.
In C# 3.0 you can use the "Cast" extension method. If you import System.Linq and then use this code: ``` public void AddRange2<T>(IEnumerable<T> foos) where T : Foo { m_Foos.AddRange (foos.Cast<Foo>()); } ``` Then it should work for you.
C# Cannot convert from IEnumerable<Base> to IEnumerable<Derived>
[ "", "c#", "inheritance", "collections", "ienumerable", "" ]
I saw some .NET 2.0 code which looked like this: ``` public enum abc : int { value1 = 1, value2 = 2, value3 = 4 } ``` etc... Now I know the flags enum can be used for bit values (like above, right?) so you can do | "or" &, etc, but what is the reason for not using that? What is the point in overriding int? If I design an enum for choosing multiple values I would use the flags attribute and not override anything (what I don't understand). What does the above approach net? Thanks
It's not "overriding" `int`, it's indicating what type the enumeration is based on. The default is `int` so this actually isn't achieving anything, but in some cases you might want to base an enum on `long` to store more flags, or `byte` to save space if there will be very many instances of the enum around and it only has a few values, however the recommendation in the framework design guidelines is to use `int` unless you have a very good reason not to. If this is intended to be a flags enumeration then it should be marked with `[Flags]`, and this appears to be the intention here, so the omission looks like a mistake. You can still combine the values using the bitwise operators even if it isn't marked with `[Flags]`, but from memory I think you get a compiler warning (or it might be an FxCop warning, or possibly a ReSharper warning...).
The ": int" is specifying what to use as the underlying type for enum values; any integral type other than char can be used here. The default is int, so it is redundant in this case.
Overriding int on a bit enum
[ "", "c#", ".net", "enums", "" ]
I've been looking at the JMS API from J2EE and found a strange behavior where certain methods that are declared in an interface (e.g., createQueue in Session) are declared again in the subinterfaces such as QueueSession, and with identical documentation. Since an subinterface "inherits" all the method declarations of the interface it inherits, and since the JavaDoc tool has no problem sorting out the JavaDocs of the subinterface and creating an "inherited operations" list, I can't figure out what this achieves. The only think of is that initially the call was in Session, and then moved to QueueSession when the specific subclass was created, though then I would have expected to see something in the documentation of the upperclass. But this is just conjecture. So the question is: Is there a convincing reason to redeclare a method in a subinterface?
Having seen this happen on occasion while working for Sun, I can tell you how it usually happens. Someone defines an interface, let's say Alice, with some methods; many developers implement that interface. Some time later, it's realized that they need some other interface, call it Bob, that has a subset of the methods of Alice, in order to allow it to serve as a base interface for *another* interface, Clara. If you move the methods of Alice into Bob, you break all the code that implements Alice; you have to go back and at least recompile a whole bunch of code, some of which you may not own, and for political reasons can't break. So you don't.
In Java 5 you can change the return type of a overriding method, by making it more specific. More commonly the documentation is different so the method has to be declared again. However if the method and documentation are the same, there is no need for it. However, you will see plenty of code which isn't strictly needed. It is possible it was needed once, but something was changed so it is no longer needed. It is quite likely that it was never needed but was done because the developer thought something needed to be done when actually there wasn't a good basis for it. BTW: Different people have different views of what is needed or handy to have or better to make explicit.
In Java when one interface extends another, why would one redeclare a method in a subinterface?
[ "", "java", "interface", "" ]
``` #include <iostream> using namespace std; class Marks { public: char* name(); }; char* Marks::name() { char temp[30]; cout<<"Enter a name:"<<endl; cin.getline(temp,30); return temp; } int main () { char *name; Marks test1; name=test1.name(); //cout<<"name:"; //uncomment this line to see the problem cout<<name<<endl; return 0; } ```
The problem is because the value that name is pointing to has been destroyed. You are returning the address of a local variable from `Marks::name()`. Most likely a side affect of the first `cout` is causing the contents of `name` to be destroyed. You're probably just getting lucky when the first `cout` is commented out. The correct way to do this is to allocate some memory, return that, and then destroy it when you're done: ``` char* Marks::name() { char* temp = new char[30]; cout<<"Enter a name:"<<endl; cin.getline(temp,30); return temp; } int main () { char *name; Marks test1; name=test1.name(); cout<<"name:"; cout<<name<<endl; delete[] name; return 0; } ``` Don't forget to use `delete[]`, rather than just `delete`, since otherwise only the first character would be deallocated.
You are returning address of a local variable: ``` char temp[30]; // ... return temp; ``` This is a strict no-no in C or C++. The moment you come out of `Marks::name()` your `temp` variable goes BOOM! You can no longer access it -- doing that invokes Undefined Behavior. Try this, ``` #include <string> // somewhere at the top // ... std::string Marks::name() { std::string line; cout<<"Enter a name:"<<endl; std::getline(cout, line); return line; } ```
Why does the output fail to show the content of a variable after merely adding a cout line?
[ "", "c++", "" ]
I'm looking for ways/tools/projects to translate Java bytecode into other programming languages or, failing that, at least into a structured representation (like XML). Ideally open source, naturally. I've looked at [ASM](http://asm.objectweb.org/), the "bytecode manipulation and analysis framework". It doesn't support translation to other representations, but looks like a good foundation for such a project. Sadly, none of the projects listed on their [users page](http://asm.objectweb.org/users.html) comes close.
ASM has the tree api which can basically give you the full structure of the bytecode. Seems like it's pretty easy to use that or even the visitor api to print that out in XML or some other format. Not sure what use that is though. Translating back into Java is a decompiler's job and ones like Jad do ok. But that's hard because a) there is information lost during the source to bytecode translation and b) there is ambiguity in that multiple source can yield the same byte code. If you actually want to go from bytecode to another high level language directly, that's going to be tough to do both comprehensively and meaningfully, for all the same reasons decompiling is hard, except even worse into another language. If you want to go from Java source to another language's source, this has been done before, as in this [Java-to-Python converter](http://blog.melhase.net/articles/2007/02/15/automated-translation-of-java-to-python). That's somewhat easier as you can convert Java to an AST with something like [Antlr](http://antlr.org/), or the built-in Java compiler tools, [Project Jackpot](http://jackpot.netbeans.org/), etc. Even then, I presume you won't get very idiomatic code in the target language.
Try [BCEL](http://jakarta.apache.org/bcel/manual.html) (byte code engineering library). You can implement a Visitor interface, which you can use to generate what ever you want (source code in another language, a custom AST , xml, what ever). I used it for a project in college where I (mostly) modified a program analysis framework that worked over Java source code into one that could also work against Java byte code. That task involved generating nodes for the analysis framework's internal AST representation. Also, I briefly skimmed the documentation for the "ASM" project you mentioned. It looks like it defines several vistior classes. You should be able to use those to do what you want as well. If you are not familiar with the visitor pattern, check out the description [here](http://en.wikipedia.org/wiki/Visitor_pattern). Also, if you haven't read it yet, the "[Gang of Four](https://rads.stackoverflow.com/amzn/click/com/0201633612)" book is a good read.
Translating Java bytecode into other representations and programming languages
[ "", "java", "translation", "bytecode", "decompiling", "" ]
Which of the following code is fastest/best practice for converting some object x? ``` int myInt = (int)x; ``` or ``` int myInt = Convert.ToInt32(x); ``` or ``` int myInt = Int32.Parse(x); ``` or in the case of a string 's' ``` int myInt; Int32.TryParse(s, out myInt); ``` I'm curious on which performs the fastest for datatypes which have a method in Convert, not just ints. I just used int as an example. Edit: This case arose from getting information back from a datatable. Will (int) still work the fastest? From some testing, when object x =123123123, int performs the fastest, like many have said. When x is a string, Parse runs the fastest (note: cast throws an exception). What I am really curious is how they run when the value is being retrieved in the following way: ``` foreach(DataRow row in someTable.Rows) { myInt = (int)row["some int value"]; myInt2 = Int.Parse(row["some int value"]); myInt2 = Convert.ToInt32(row["some int value"]); } ```
Why don't you just try it a couple of thousand times? (this goes for all "What is fastest:" questions) --- Hmmm, lots of downvotes over the years... I guess I should expand on this answer. The above statement was made with a degree of flippancy in my youth, however I still agree with its sentiment. It is not worthwhile spending time creating a SO question asking others what they think is faster out of two or three operations that take less than 1ms each. The fact that one might take a cycle or two longer than the other will almost certainly be negligible in day-to-day usage. And if you ever notice a performance problem in your application when you are converting millions of objects to ints, **that's** the point where you can profile the *actual* code, and you'll easily be able to test whether the int conversion is actually the bottleneck. And whereas today it's the object-int converter, tomorrow maybe you'll think your object-DateTime converter is taking a long time. Would you create another SO question to find out what's the fastest method? As for your situation (no doubt long since resolved by now), as mentioned in a comment, you are querying a database, so object-int conversion is the least of your worries. If I was you I would use any of the conversion methods you mentioned. If a problem arises I would isolate the call, using a profiler or logging. Then when I notice that object-int conversion is being done a million times and the total time taken by that conversion seems relatively high, I would change to using a different conversion method and re-profile. Pick the conversion method that takes the least time. You could even test this in a separate solution, or even LINQPad, or Powershell etc.
## It depends on what you expect x to be If x is a boxed int then `(int)x` is quickest. If x is a string but is definitely a valid number then `int.Parse(x)` is best If x is a string but it might not be valid then `int.TryParse(x)` is far quicker than a try-catch block. The difference between Parse and TryParse is negligible in all but the very largest loops. If you don't know what x is (maybe a string or a boxed int) then `Convert.ToInt32(x)` is best. These generalised rules are also true for all value types with static Parse and TryParse methods.
What is fastest: (int), Convert.ToInt32(x) or Int32.Parse(x)?
[ "", "c#", "optimization", "casting", "" ]
I'm trying to create a dictionary of two-dimensional arrays in C#, I can't figure out the proper syntax. I've tried the following to no avail, but it shows what I'm trying to accomplish. ``` Dictionary dictLocOne = new Dictionary<String,double[][]>(); ```
A couple of things here: Definition must match initialization. You are definining Dictionary and instantiating Dictionary<TKey, TValue>. What this means, based on what you are saying here: ``` Dictionary<string, double[][]> dict = new Dictionary<string, double[][]>(); ``` I assume this is what you want. If so, your code might be something like this: ``` double[] d1 = { 1.0, 2.0 }; double[] d2 = { 3.0, 4.0 }; double[] d3 = { 5.0, 6.0, 7.0 }; double[][] dd1 = { d1 }; double[][] dd2 = { d2, d3 }; Dictionary<string, double[][]> dict = new Dictionary<string, double[][]>(); dict.Add("dd1", dd1); dict.Add("dd2", dd2); ``` If that is it, your issue is solved.
Just gonna update my answer to include the correct declaration as per other answers: ``` Dictionary<String,double[][]> = new Dictionary<String,double[][]>(); ``` Alsoyours is a ***array of array*** and not a ***MultiDimensional*** one..Not sure if that's what you want.. If you want a MultiDimensional Array it's ``` Dictionary<String,double[,]> = new Dictionary<String,double[,]>(); ```
Creating a dictionary of two-dimensional arrays in c#
[ "", "c#", "" ]
Here is some code that I can't seem to understand how it works. I know it is using generics but what does the "new" in the where clause mean? ``` public class MediaPresenter<T> where T : Media, new() { public MediaPresenter(string mediaPath, params string[] extensions) { _mediaPath = mediaPath; _fileExtensions = extensions; } private void LoadMedia() { if(string.IsNullOrEmpty(_mediaPath)) return; _media = new ObservableCollection<Media>(); DirectoryInfo directoryInfo = new DirectoryInfo(_mediaPath); foreach(string extension in _fileExtensions) { FileInfo[] pictureFiles = directoryInfo.GetFiles( extension, SearchOption.AllDirectories ); foreach(FileInfo fileInfo in pictureFiles) { if(_media.Count == 50) break; T media = new T(); media.SetFile(fileInfo); _media.Add(media); } } } } ``` I also don't understand in the LoadMedia method how the T is used? Can the T get referenced anywhere in the class?
> Here is some code that I can't seem to understand how it works. I know it is using generics but what does the "new" in the where clause mean? The new() in the where clause means that T must be of a type that can be instantiated. If T does not have a parameterless constructor, T is not a valid type to pass to this class as a type parameter. See <http://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx>. > I also don't understand in the LoadMedia method how the T is used? Can the T get referenced anywhere in the class? Yes. T is a type parameter of the class, so the whole class knows about it. It would also be valid to have a field in the class that was of type T, or a method that returned T, for example.
new() means that T needs to have a parameterless constructor. (In this case it also needs to inherit the Media class)
Generics syntax
[ "", "c#", "generics", "" ]
I'm somewhat new to Python, Django, and I'd like some advice on how to layout the code I'd like to write. I have the model written that allows a file to be uploaded. In the models save method I'm checking if the file has a specific extension. If it has an XML extension I'm opening the file and grabbing some information from the file to save in the database. I have this model working. I've tested it in the built-in administration. It works. Currently when there's an error (it's not an XML file; the file can't be opened; a specific attribute doesn't exist) I'm throwing an custom "Exception" error. What I *would* like to do is some how pass these "Exception" error messages to the view (whether that's a custom view or the built-in administration view) and have an error message displayed like if the forms library was being used. Is that possible? I'm starting to think I'm going to have to write the validation checks again using the forms library. If that's the case, is it possible to still use the built-in administration template, but extend the form it uses to add these custom validations? Anything to help my confusion would be appreciated. --- **UPDATE:** Here's my model so far, for those who are asking, "nzb" is the XML file field. <http://dpaste.com/hold/6101/> > The admin interface will use the Form you associate with your model; your own views can also use the form. This is exactly what I'd like to do. However, I don't know how to associate my forms with my models. When ever I've created forms in the past they've always acted as their own entity. I could never get the administration views to use them while using the ModelForm class. Can you shead any light on this? I've read over the link you gave me and it seams to be what I've done in the past, with no luck. > Getting attributes from the file, should probably be a method. Sorry, could you please elaborate on this? A method where? --- **UPDATE:** It seams I've been compleatly missing this step to link a form to the administration view. <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin> This should now allow me to do the validation in a Form. However, I'm still confused about how to actually handle the validation. S.Lott says it should be a method?
The Form errors are automatically part of the administrative view. See <http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation> You're happiest if you validate in a Form -- that's what Forms are for. The admin interface will use the Form you associate with your model; your own views can also use the form. Getting attributes from the file, should probably be a separate method of the model class. The separate method of the model class can be used by the `save()` method of the model class or invoked at other times by view functions. --- "I could never get the administration views to use them while using the ModelForm class." <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form> <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin> --- "I'm still confused about how to actually handle the validation. S.Lott says it should be a method?" Validation in a form is done with a `clean()` method or a `clean_somefield()` method. The "Adding custom validation to the admin" link (above) shows how to add the `clean_name` method to the "MyArticleAdminForm" form. If you're still confused, trying actually typing the code from the Django web page and see what it does.
You can provide a form that will be used by the admin site. You can then perform validations in the form code that will be displayed in the admin area. See the docs on the admin site, and in particular [the form attribute of ModelAdmin](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form).
Model and Validation Confusion - Looking for advice
[ "", "python", "django", "validation", "" ]
When I'm writing a function in a utility module to be used again, I tend to leave lots of comments at the top of functions and some simple input checks to throw up a message in the debugger if a function is used inappropriately, w/o simply using a throw command. What's the best methodology of handling such situations? What functionality is easiest to use for this in C#? In my CS classes a decade ago, we would simply use an assert(...) command in C++ and let the program bomb out if something was used incorrectly. Now that I'm using C# I've used two methods, throwing up a MessageBox.Show("...") to clarify why a function is returning prematurely or a Console.WriteLine("...") to have it explained only in the debug console. I'm currently leaning toward writing a custom ErrorMessage function that would check the build type and possibly a #define master toggle before displaying anything and probably saving to a .log file if I'm in a beta environment. What's the best method to use in such utility modules?
If the method is being called with invalid arguments then it should throw an ArgumentException, or an exception derived from it. If the method is being called that cannot be called currently due to the state of the object then it should throw an InvalidOperationException. Other people calling your library will not thank you for doing things in a non-standard or a non-obvious manner. Such as showing message boxes. Especially if they are calling your library from a web site or a windows service that can't display UI. And outputting to the debug window is far too likely to get missed.
Throw an exception. It's the clearest way of indicating that something's wrong, and it's much harder to ignore than a console message or even a message box. In particular, it means that that code path *won't* keep going, assuming that everything's fine. Even if the user (whether in beta or not) notices the message box, they're not going to be happy to find out that as soon as they click on "OK" the application goes ahead and wipes their data out just because the utility method wasn't used properly.
What's the best way to handle exceptions over the lifetime of your code?
[ "", "c#", "exception", "" ]
I have a regular C# code. ***I have no exceptions***. I want to programmatically log the current stack trace for debugging purpose. Example: ``` public void executeMethod() { logStackTrace(); method(); } ```
Have a look at the [`System.Diagnostics`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics) namespace. Lots of goodies in there! ``` System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); ``` This is really good to have a poke around in to learn what's going on under the hood. I'd recommend that you have a look into logging solutions (Such as NLog, log4net or the Microsoft patterns and practices Enterprise Library) which may achieve your purposes and then some.
An alternative to `System.Diagnostics.StackTrace` is to use [System.Environment.StackTrace](https://learn.microsoft.com/en-us/dotnet/api/system.environment.stacktrace) which returns a string-representation of the stacktrace. Another useful option is to use the `$CALLER` and `$CALLSTACK` [debugging variables in Visual Studio](https://learn.microsoft.com/en-us/visualstudio/debugger/using-breakpoints#BKMK_Print_to_the_Output_window_with_tracepoints) since this can be enabled run-time without rebuilding the application.
How to print the current Stack Trace in .NET without any exception?
[ "", "c#", ".net", "logging", "stack-trace", "printstacktrace", "" ]
We've used ANTLR to create a parser for a SQL-like grammar, and while the results are satisfactory in most cases, there are a few edge cases that we need to fix; and since we didn't write the parser ourselves we don't really understand it well enough to be able to make sensible changes. So, we'd like to write our own parser. What's the best way to go about writing a parser by hand? What sort of parser should we use - recursive descent has been recommended; is that right? We'll be writing it in C#, so any tutorials for writing parsers in that language would be gratefully received. UPDATE: I'd also be interested in answers that involve F# - I've been looking for a reason to use that in a project.
I would highly recommend the F# language as your language of choice for parsing on the .NET Platform. It's roots in the ML family of languages means it has excellent support for language-oriented programming. Discriminated unions and pattern-matching allow for a very succinct and powerful specification of your AST. Higher-order functions allow for definition of parse operations and their composition. First-class support for monadic types allows for state management to be handled implicitly greatly simplifying the composition of parsers. Powerful type-inference greatly aides the definition of these (complex) types. And all of this can be specified and executed interactively allowing you to rapidly prototype. Stephan Tolksdorf has put this into practice with his parser combinator library [FParsec](http://www.quanttec.com/fparsec/) From his examples we see how naturally an AST is specified: ``` type expr = | Val of string | Int of int | Float of float | Decr of expr type stmt = | Assign of string * expr | While of expr * stmt | Seq of stmt list | IfThen of expr * stmt | IfThenElse of expr * stmt * stmt | Print of expr type prog = Prog of stmt list ``` the implementation of the parser (partially elided) is just as succinct: ``` let stmt, stmtRef = createParserForwardedToRef() let stmtList = sepBy1 stmt (ch ';') let assign = pipe2 id (str ":=" >>. expr) (fun id e -> Assign(id, e)) let print = str "print" >>. expr |>> Print let pwhile = pipe2 (str "while" >>. expr) (str "do" >>. stmt) (fun e s -> While(e, s)) let seq = str "begin" >>. stmtList .>> str "end" |>> Seq let ifthen = pipe3 (str "if" >>. expr) (str "then" >>. stmt) (opt (str "else" >>. stmt)) (fun e s1 optS2 -> match optS2 with | None -> IfThen(e, s1) | Some s2 -> IfThenElse(e, s1, s2)) do stmtRef:= choice [ifthen; pwhile; seq; print; assign] let prog = ws >>. stmtList .>> eof |>> Prog ``` On the second line, as an example, `stmt` and `ch` are parsers and `sepBy1` is a monadic parser combinator that takes two simple parsers and returns a combination parser. In this case `sepBy1 p sep` returns a parser that parses one or more occurrences of `p` separated by `sep`. You can thus see how quickly a powerful parser can be combined from simple parsers. F#'s support for overridden operators also allow for concise infix notation e.g. the sequencing combinator and the choice combinator can be specified as `>>.` and `<|>`. Best of luck, Danny
The only kind of parser that can be handwritten by a sane human being is a recursive-descent. That said, writing bottom-up parser by hand is still possible but is very undesirable. If you're up for RD parser you have to verify that SQL grammar is not left-recursive (and eliminate the recursion if necessary), and then basically write a function for each grammar rule. See [this](http://www.mollypages.org/page/grammar/index.mp) for further reference.
What's the best way to write a parser by hand?
[ "", "c#", ".net", "parsing", "f#", "" ]
Currently developing an ASP.NET WebApplication with VS2008. I stopped development for a few weeks, and when I came back, my project is exhibiting the following problem: The whole project compiles fine (all targeted to Framework3.5SP1). However, when I launch it (with ASP.NET Development Server), I get a message (from the browser) that there was a compilation error "Compiler Error Message: CS0234: The type or namespace name 'DirectoryServices' does not exist in the namespace 'System' (are you missing an assembly reference?)" At the bottom of the error page, the version information: Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053 The server is using .NET Framework Version 2? But all my projects are targetted to 3.5 Is there a simple way to prevent this from happening? I should add: re-installed .net framework version 3.5 + sp1, still same issue. important to note here is that i'm not using full blown IIS, just the "Asp.net development server" supplied with VS2008. (CTRL + F5/Launch)
The reason being .NET 3.5 is not a stand alone framework like v2.0 or v1.1 . It is just an extension of the 2.0 framework. The extension provides developers with new language features like Anonymous Types, Extension Methods, Lambda Expressions and of course LINQ .... and AJAX is now integrated. Therefore you just use 2.0 in IIS. You should try to install .NET Framework 3.5 on that server, the IIS server will automatically use the correct version.
Just guessing here. Could it be that one of either your development machine or the server has upgraded to .Net 3.5 SP1 while the other has not?
Asp.net Dev Server using wrong version of the framework?
[ "", "c#", "asp.net", "visual-studio", "asp.net-development-serv", "" ]
I have a .net 2.0 C# application in Visual Studio 2005 for which I'd like to automatically generate the correct version build number which should contain a number that allows me to guess the build date of the application. I tried to use the ['AssemblyInfo Task'](http://code.msdn.microsoft.com/AssemblyInfoTaskvers) tool from Microsoft but by default this tool doesn't work. For today it would generate a build number '090227' which exceeds the maximum of 65535 and thus geneartes an error. I could also live with a build number which contains the year and the day in the year, like 09001 for January 1 2009... Do you know any solution for this problem? Do I have to update the source code for this 'AssemblyInfo Task' or would this be possible to achieve in VS2008 or so? Thanks for your help.
[msbuildtasks](http://msbuildtasks.tigris.org/) didn't solve my problem. As explained in the description I need a special format. Also the documentation for msbuildtasks is well... go find it. I've modified the source code for [AssemblyInfo Task](http://code.msdn.microsoft.com/AssemblyInfoTaskvers) by adding a new increment type 'YearAndDay' with my needs: ``` case IncrementMethod.YearAndDay: { DateTime dDate = DateTime.Now; long buildNumber = dDate.Year % 2000 * 1000; buildNumber += dDate.DayOfYear; string newVersionNumber = buildNumber.ToString(); Log.LogMessage(MessageImportance.Low, logMessage, newVersionNumber); return newVersionNumber; } ``` Seemed to be the simplest solution.
You'll want to look at [msbuildtasks](http://msbuildtasks.tigris.org/). It is an open source set of msbuild tasks. The module has a task to increment/modify/etc a build number. It's also super easy to use and super easy to extend.
VS2005: How to automatically generate a build number with date?
[ "", "c#", ".net", "msbuild", "build-process", "versioning", "" ]
I use a default IDisposable implementation template (pattern) for my code. snippet: ``` public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { if (!this.disposed) { if (isDisposing) { //cleanup managed resources } //cleanup unmanaged resources this.disposed = true; } } ``` My question: why is the call "GC.SuppressFinalize(this)" in the Dispose public method? I would place "GC.SuppressFinalize(this)" in the "if (isDisposing)" section of the protected method, after disposing managed resources. Like this: ``` protected virtual void Dispose(bool isDisposing) { if (!this.disposed) { if (isDisposing) { //cleanup managed resources GC.SuppressFinalize(this); } //cleanup unmanaged resources this.disposed = true; } } ```
I suppose its a clear case of Template Design pattern. Your abstract class is Designed to take care of all important/necessary tasks required (Here, GC.SuppressFinalize(this)), and allowing a derived class to override only some part of the code. There are 2 cases here: Snippet 1, SuppressFinalize, in Dispose Snippet 2, SuppressFinalize, in Dispose(true) Here, Snippet 1, makes sure that GC.SuppressFinalize is always executed. While snippet 2, leaves the execution of GC.SuppressFinalize at the mercy of **derived class**. So, by putting GC.SuppressFinalize, in Dispose method, you as a designer of your class will always make sure that irrespective of whatever code written by derived classes, GC.SuppressFinalize will be executed. This is only the benefit of writing SuppressFinalize in Dispose rather then Dispose(true).
The `Dispose(bool isDisposing)` method isn't part of the [`IDisposable`](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx) interface. You would normally call `Dispose(true)` from your [`Dispose`](http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) method, and call `Dispose(false)` from your finalizer, as a fallback in the case where the object hasn't already been disposed. Calling [`SuppressFinalize`](http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx) tells the GC that there's no need to call your object's finalizer, presumably because all your cleanup was done when `Dispose` was called. If you don't have a finalizer on your class, then you don't need to call `SuppressFinalize` at all, since there's no finalizer to suppress! Joe Duffy has some great [guidelines on disposal, finalization, garbage collection etc](http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx).
IDisposable GC.SuppressFinalize(this) location
[ "", "c#", ".net", "idisposable", "suppressfinalize", "" ]
This code behaves weird in MS Visual Studio: ``` char *s = "hello"; s[0] = 'a'; printf(s); ``` In release build with optimization turned on it ignores s[0] = 'a' and prints "hello". Without optimization or in debug build it crashes with access violation. Is this behavior is c++ standard compliant or no? In my opinion, compiler should only allow constant references to string literals, i.e. ``` const char *s = "hello"; ``` **EDIT**: I know why it works like this, I do not understand why I am allowed to make non const reference to read only memory.
The reason why this code is allowed in the first place (rather than requiring the declaration to be of type `char const*`) is backwards compatibility to old C code. Most modern compilers in strict mode will issue a **warning** for the above code, though!
No, it's not a bug in the compiler. When you write: ``` char* s = "hello"; ``` The string constant `"hello"` will be placed in a read-only section and should generate an exception if you try to modify it. (an OS exception, not a C++ exception). To make it writable, you have to either use an array: ``` char s[] = { 'h', 'e', 'l', 'l', 'o', 0 }; ``` or, if you really need a pointer, make it point to an array: ``` char _s[] = { 'h', 'e', 'l', 'l', 'o', 0 }; char* s = _s; ``` I can see your point about only allowing const pointers to be initialized with string literals, but I think that would break a *lot* of existing code.
Bug in Visual Studio C++ compiler?
[ "", "c++", "visual-studio", "visual-c++", "standards-compliance", "" ]
I have a method that contains an asynchronous call like this: ``` public void MyMethod() { ... (new Action<string>(worker.DoWork)).BeginInvoke(myString, null, null); ... } ``` I'm using Unity and creating mock objects is not a problem, but how can I test that DoWork is called without worrying about race conditions? A [previous question](https://stackoverflow.com/questions/400552/what-is-the-best-way-to-unit-test-an-asynchronous-method) offers a solution, but it seems to me that wait-handles is a hack (the race condition is still there, although it should be virtually impossible to raise). --- EDIT: Okay, I thought I could ask this question in a very general manner, but it seems I have to elaborate further on the problem: I want to create a test for the above mentioned MyMethod, so I do something like this: ``` [TestMethod] public void TestMyMethod() { ...setup... MockWorker worker = new MockWorker(); MyObject myObj = new MyObject(worker); ...assert preconditions... myObj.MyMethod(); ...assert postconditions... } ``` The naïve approach would be to create a MockWorker() that simply sets a flag when DoWork has been called, and test that flag in the postconditions. This would of course lead to a race condition, where the postconditions are checked before the flag is set in the MockWorker. The more correct approach (which I'll probably end up using) is using a wait-handle: ``` class MockWorker : Worker { public AutoResetEvent AutoResetEvent = new AutoResetEvent(); public override void DoWork(string arg) { AutoResetEvent.Set(); } } ``` ...and use the following assertion: ``` Assert.IsTrue(worker.AutoResetEvent.WaitOne(1000, false)); ``` This is using a semaphore-like approach, which is fine... but in *theory* the following could happen: 1. BeginInvoke is called on my DoWork delegate 2. For some reason neither the main-thread or the DoWork-thread is given execution time for 1000ms. 3. The main-thread is given execution time, and because of the timeout the assertion fails, even though the DoWork thread is yet to be executed. Have I misunderstood how AutoResetEvent works? Am I just being too paranoid, or is there a clever solution to this problem?
Wait handle would be the way I would do it. AFAIK (and I dont know for sure) asynchronous methods are using wait handles to fire off that method anyway. I'm not sure why you think the race condition would occur, unless you are giving an abnormally short amount of time on the WaitOne call. I would put 4-5 seconds on the waitone, that way you'd know for sure if it was broken and it wasn't just a race. Also, don't forget how wait handles work, as long as the wait handle is created, you can have the following order of execution a * Thread 1 - create wait handle * Thread 1 - set wait handle * Thread 2 - waitone on the wait handle * Thread 2 - blows through the wait handle and continues execution Even though the normal execution is * Thread 1 - create wait handle * Thread 2 - waitone on the wait handle * Thread 1 - set wait handle * Thread 2 - blows through the wait handle and continues execution Either works correctly, the wait handle can be set before Thread2 begins waiting on it and everything is handled for you.
When testing a straight delegate, just use the EndInvoke call to ensure the delegate is called and returns the appropriate value. For instance. ``` var del = new Action<string>(worker.DoWork); var async = del.BeginInvoke(myString,null,null); ... var result = del.EndInvoke(async); ``` **EDIT** OP commented that they are trying to unit test MyMethod versus the worker.DoWork method. In that case you will have to rely on a visible side effect from calling the DoWork method. Based on your example I can't really offer too much here because none of the inner workings of DoWork are exposed. **EDIT2** [OP] For some reason neither the main-thread or the DoWork-thread is given execution time for 1000ms. This won't happen. When you call WaitOne on an AutoResetEvent the thread goes to sleep. It will recieve no processor time until the event is set or the timeout period expires. It's definitely pheasible that some other thread gets a significant time slice and causes a false failure. But I think that is fairly unlikely. I have several tests that run in the same manner and I don't get very many/any false failures like this. I usually pick a timeout though of ~2 minutes.
How do I unit test a method containing an asynchronous call?
[ "", "c#", "unit-testing", "concurrency", "" ]
Is there a simple way to use the existing Html Helpers to generate a list of checkboxes with explicit values (as was possible in Beta)? Example in Beta (possibly with MVC Contrib): `.CheckBox("Field", 6, new { value = 6})` would output: ``` <input id="Field1" type="checkbox" value="6" name="Field" /> <input id="Field2" type="hidden" value="6" name="Field" /> ``` yet in RC2 I get: ``` <input id="Field1" type="checkbox" value="6" name="Field" /> <input type="hidden" value="false" name="Field" /> ``` > NB: I use a custom helper extension > that generates unique HTML `id`s and > sets the checked HTML attribute when > appropriate Besides using raw HTML and not using Html Helpers is there a way of setting checkboxes with explicit values? Looking at the Codeplex source code for RC2 there doesn't appear to be an easy way as `.InputHelper()` is marked `private` so you can't use it to help. NB: There's more than one `checkbox` in the page to allow multiple selection, so the `false` value is of no use, as I need the values from the hidden field to know which items were ticked and which weren't (as non-checked `checkbox` values aren't posted - only the hidden fields are).
As a workaround I've come up with the following based loosely on the RC2 sourcecode's InputHelper method, but adapted it to allow multiple values: ``` private static string CheckBoxWithValue(this HtmlHelper htmlHelper, string name, object value, bool isChecked, bool setId, IDictionary htmlAttributes) { const InputType inputType = InputType.CheckBox; if (String.IsNullOrEmpty(name)) { throw new ArgumentException("null or empty error", "name"); } var tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("type", HtmlHelper.GetInputTypeString(inputType)); tagBuilder.MergeAttribute("name", name, true); string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture); if (isChecked) { tagBuilder.MergeAttribute("checked", "checked"); } tagBuilder.MergeAttribute("value", valueParameter, true); if (setId) tagBuilder.GenerateId(name); // If there are any errors for a named field, we add the css attribute. ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState)) { if (modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } var inputItemBuilder = new StringBuilder(); inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.SelfClosing)); var hiddenInput = new TagBuilder("input"); hiddenInput.MergeAttributes(htmlAttributes); hiddenInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden)); hiddenInput.MergeAttribute("name", name); if (setId) { hiddenInput.GenerateId(name); } hiddenInput.MergeAttribute("value", valueParameter); inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing)); return inputItemBuilder.ToString(); } ``` This relies on .ToString() your evaluate the object's value, but is adequate for my scenario where i'm using integers to represent options with the lookup done in the backend database. Note the setId boolean seems to just replace dots in the Html name with underscore characters. When using multiple checkboxes in HTML the IDs should be unique so I simply pass in the unique Id via htmlAttributes collection instead.
If the property that field maps to is of type Int, then false will be converted to 0, i think. That's how you know how the box was checked or not.
ASP.net MVC RC2 - Checkboxes with explicit values
[ "", "c#", ".net", "asp.net", "asp.net-mvc", "" ]
I have a MySQL table called bb\_posts used by a bbPress forum. It has an autoincrement field called topid\_id and another field called topic\_poster. I'm trying to write a function that finds the "next post by the same author". So, for instance, say the user is on a particular page that displays topic 123. If you do a SQL query: ``` SELECT * FROM `bb_topics` WHERE `topic_poster` = 5 ORDER BY `topic_id` ASC ``` This might return the following rows: ``` topic_id topic_poster 6 5 50 5 123 5 199 5 2039 5 ``` What I'd like to do is write a SQL query that returns these two rows: ``` topic_id topic_poster 50 5 199 5 ``` This would be the row PRIOR to the row with topic\_id of 123, and the row AFTER that row. If it's too hard to do this in one query, it's definitely OK to break this up into two queries... I'd like to avoid doing the whole SQL query ("SELECT \* FROM `bb_topics` WHERE `topic_poster` = 5") and looping through the results, because the result set is sometimes huge. Is this possible? :-)
Next one: ``` SELECT * FROM `bb_topics` WHERE `topic_id` = (select min(`topic_id`) FROM `bb_topics` where `topic_id` > 123 and `topic_poster` = 5) ``` Previous one: ``` SELECT * FROM `bb_topics` WHERE `topic_id` = (select max(`topic_id`) FROM `bb_topics` where `topic_id` < 123 and `topic_poster` = 5) ``` Both: ``` SELECT * FROM `bb_topics` WHERE `topic_id` = (select min(`topic_id`) FROM `bb_topics` where `topic_id` > 123 and `topic_poster` = 5) or `topic_id` = (select max(`topic_id`) FROM `bb_topics` where `topic_id` < 123 and `topic_poster` = 5) ```
Look at this [older question](https://stackoverflow.com/questions/169233/mysql-conditionally-selecting-next-and-previous-rows) as well. My guess is that the UNION with LIMIT 1 performs better than the aggregates in my answer here.
SQL - find next and previous rows given a particular WHERE clause
[ "", "sql", "mysql", "" ]
This question is specifically regarding C#, but I am also interested in answers for C++ and Java (or even other languages if they've got something cool). I am replacing switch statements with polymorphism in a "C using C# syntax" code I've inherited. I've been puzzling over the best way to create these objects. I have two fall-back methods I tend to use. I would like to know if there are other, viable alternatives that I should be considering or just a sanity check that I'm actually going about this in a reasonable way. The techniques I normally use: 1. Use an all-knowing method/class. This class will either populate a data structure (most likely a Map) or construct on-the-fly using a switch statement. 2. Use a blind-and-dumb class that uses a config file and reflection to create a map of instances/delegates/factories/etc. Then use map in a manner similar to above. 3. ??? Is there a #3, #4... etc that I should *strongly* consider? --- Some details... please note, the original design is not mine and my time is limited as far as rewriting/refactoring the entire thing. Previous pseudo-code: ``` public string[] HandleMessage(object input) { object parser = null; string command = null; if(input is XmlMessage) { parser = new XmlMessageParser(); ((XmlMessageParser)parser).setInput(input); command = ((XmlMessageParser)parser).getCommand(); } else if(input is NameValuePairMessage) { parser = new NameValuePairMessageParser(); ((NameValuePairMessageParser)parser).setInput(input); command = ((XmlMessageParser)parser).getCommand(); } else if(...) { //blah blah blah } string[] result = new string[3]; switch(command) { case "Add": result = Utility.AddData(parser); break; case "Modify": result = Utility.ModifyData(parser); break; case ... //blah blah break; } return result; } ``` What I plan to replace that with (after much refactoring of the other objects) is something like: ``` public ResultStruct HandleMessage(IParserInput input) { IParser parser = this.GetParser(input.Type); //either Type or a property Map<string,string> parameters = parser.Parse(input); ICommand command = this.GetCommand(parameters); //in future, may need multiple params return command.Execute(parameters); //to figure out which object to return. } ``` The question is what should the implementation of GetParser and GetCommand be? Putting a switch statement there (or an invokation of a factory that consists of switch statements) doesn't seem like it *really* fixes the problem. I'm just moving the switch somewhere else... which maybe is fine as its no longer in the middle of my primary logic.
You may want to put your parser instantiators on the objects themselves, e.g., ``` public interface IParserInput { ... IParser GetParser() ICommand GetCommand() } ``` Any parameters that `GetParser` needs should, theoretically, be supplied by your object. What will happen is that the object itself will return those, and what happens with your code is: ``` public ResultStruct HandleMessage(IParserInput input) { IParser parser = input.GetParser(); Map<string,string> parameters = parser.Parse(input); ICommand command = input.GetCommand(); return command.Execute(parameters); } ``` Now this solution is not perfect. If you do not have access to the `IParserInput` objects, it might not work. But at least the responsibility of providing information on the proper handler now falls with the parsee, not the handler, which seems to be more correct at this point.
You can have an ``` public interface IParser<SomeType> : IParser{} ``` And set up structuremap to look up for a Parser for "SomeType" It seems that Commands are related to the parser in the existing code, if you find it clean for your scenario, you might want to leave that as is, and just ask the Parser for the Command. **Update 1:** I re-read the original code. I think for your scenario it will probably be the least change to define an IParser as above, which has the appropiate GetCommand and SetInput. The command/input piece, would look something along the lines: ``` public string[] HandleMessage<MessageType>(MessageType input) { var parser = StructureMap.GetInstance<IParser<MessageType>>(); parser.SetInput(input); var command = parser.GetCommand(); //do something about the rest } ``` Ps. actually, your implementation makes me feel that the old code, even without the if and switch had issues. Can you provide more info on what is supposed to happen in the GetCommand in your implementation, does the command actually varies with the parameters, as I am unsure what to suggest for that because of it.
Logic is now Polymorphism instead of Switch, but what about constructing?
[ "", "c#", "design-patterns", "oop", "" ]
I have a class that has several properties that refer to file/directory locations on the local disk. These values can be dynamic and i want to ensure that anytime they are accessed, i verify that it exists first without having to include this code in every method that uses the values. My question is, does putting this in the getter incur a performance penalty? It would not be called thousands of times in a loop, so that is not a consideration. Just want to make sure i am not doing something that would cause unnecessary bottle necks. I know that generally it is not wise to optimize too early, but i would rather have this error checking in place now before i have to go back and remove it from the getter and add it all over the place. --- Clarification: The files/directories being pointed to by the properties are going to be used by System.Diagnostics.Process. i won't be reading/writing to these files/directories directly, i just want to make sure they exist before i spawn a child process.
Anything that's not a simple lookup or computation should go in a method, not a property. Properties should be conceptually similar to just accessing a field - if there is any additional overhead or chance of failure (and IO - even just checking a file exists - would fail that test on both counts) then properties are not the right choice. Remember that properties even get called by the debugger when looking at object state. Your question about what the overhead actually is, and optimising early, becomes irrelevant when looked at from this perspective. Hope this helps.
If you are reusing an object you should consider using the FileInfo class vs the static File class. The static methods of the File class does a possible unnecessary security check each time. [FileInfo](http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx) - [DirectoryInfo](http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx) - [File](http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx) - [Directory](http://msdn.microsoft.com/en-us/library/system.io.directory.exists.aspx) **EDIT:** My answer would still apply. To make sure your file exists you would do something like so in your getter: ``` if(File.Exists(string)) //do stuff else //file doesn't exist ``` OR ``` FileInfo fi = new FileInfo(fName); if (fi.Exists) //do stuff else //file doesn't exist ``` Correct? What I am saying is that if your are looping through this logic thousands of time then use the **FileInfo** instance VS the static **File** class because you will get a negative performance impact if you use the static **File.Exits** method.
Overhead of File/Directory.Exists in getter?
[ "", "c#", "" ]
I've got a method which currently takes an IList as a parameter, where UserBO is similar to the following: ``` public class UserBO { public string Username { get; set; } public string Password { get; set; } public string Pin { get; set; } } public class SomeClass { // An example method giving the basic idea of what I need to do public void WriteUsers(IList<UserBO> users) { // Do stuff with users for (var user in users) { Console.WriteLine(String.Format(User: {0}: {1}, users.Username, Hash(users.Pin)); // Now needs to optionally be users.Password } } private string Hash(string pin) { return // Hashed Pin } } ``` This method then uses the Username/Pin pairs to create some XML used by another program (we'll use the above method as an example). The thing is, now I need to be able to produce the same code except using the Password field instead of the Pin field (there's a good reason for having both fields). Instead of just creating another method with a similar name, I'd prefer to refactor the code so as to remove the BO specific code from this class entirely, and make it so that the decision about what class/members to use are made not in the method itself but the code calling it. One option would be to pass an IDictionary and use the Linq ToDictionary method to create a dictionary on the fly in the calling code. This would however lose the ordering of the items (which would be nice but not essential to keep). I could use an IList or something, but that would be more difficult to convert the IList into. Does anybody have any good suggestions of how to do this? P.S. If anybody has a better idea of how to title this post, feel free to have a go at it.
You could also use Expressions: ``` WriteUsers(IList<T> users, u => u.Username, u => u.Password); ``` if you're using Net 3.5.
It's not clear *exactly* what you need to do with the strings after formatting. You could make the method take an `IEnumerable<string>`, and then make the calling code: ``` WriteUsers(users.Select(user => string.Format("{0}: {1}", users.Username, users.Pin))); ``` Whether that works for you or not will depend on the details.
How do I make this class more reusable? (specific example inside)
[ "", "c#", ".net", "refactoring", "" ]
I'm trying to make a "bubble" that can popup when the `onmouseover` event is fired and will stay open as long as the mouse is over the item that threw the `onmouseover` event OR if the mouse is moved into the bubble. My bubble will need to have all manners of HTML and styling including hyperlinks, images, etc. I've basically accomplished this by writing about 200 lines of ugly JavaScript but I would really like to find a jQuery plugin or some other way to clean this up a bit.
[Qtip is the best one I've seen.](http://craigsworks.com/projects/qtip2/) It's MIT licensed, beautiful, has all the configuration you need. My favorite lightweight option is [tipsy](https://github.com/jaz303/tipsy). Also MIT licensed. It inspired [Bootstrap's tooltip plugin](http://getbootstrap.com/javascript/#tooltips).
This can be done easily with the mouseover event as well. I've done it and it doesn't take 200 lines at all. Start with triggering the event, then use a function that will create the tooltip. ``` $('span.clickme').mouseover(function(event) { createTooltip(event); }).mouseout(function(){ // create a hidefunction on the callback if you want //hideTooltip(); }); function createTooltip(event){ $('<div class="tooltip">test</div>').appendTo('body'); positionTooltip(event); }; ``` Then you create a function that position the tooltip with the offset position of the DOM-element that triggered the mouseover event, this is doable with css. ``` function positionTooltip(event){ var tPosX = event.pageX - 10; var tPosY = event.pageY - 100; $('div.tooltip').css({'position': 'absolute', 'top': tPosY, 'left': tPosX}); }; ```
jQuery Popup Bubble/Tooltip
[ "", "javascript", "jquery", "html", "css", "" ]
## Background I am writing a data access library using the ADO Entity Framework in Visual Studio 2008 SP1 using the .NET Framework 3.5 SP1. I am trying to create associations between two entities that are both derived from an abstract type. I am representing both entity inheritance hierarchies using [Table Per Hierarchy](http://www.hibernate.org/hib_docs/reference/en/html/inheritance.html) (TPH) which means there are just two tables - one for each entity inheritance hierarchy. **NOTE** You can use Table Per Type (TPT) to avoid this problem, but it comes with it's own drawbacks. See [here](https://stackoverflow.com/questions/190296/how-do-you-effectively-model-inheritance-in-a-database) and [here](http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/09/30/how-to-model-inheritance-in-databases.aspx) for more details when choosing between inheritance persistence models. Here is a screenshot of the Designer view of the Entity Model: [![ Design View of the Entity Model in Visual Studio 2008 SP1](https://i.stack.imgur.com/vgMgb.jpg)](http://img153.imageshack.us/my.php?image=adoefgraphexamplescreenxz0.png) And here is a screenshot of the database schema: [![Database Schema](https://i.stack.imgur.com/6lQWf.jpg)](http://img7.imageshack.us/my.php?image=graphexampledatabaseschik0.png) ## Assumptions When you create associations in the ADO Entity Framework Designer between derived types modeled with TPH using Visual Studio 2008 SP1 and the .NET Framework 3.5 SP1 you are likely to receive the following an "Error 3034: Two entities with different keys are mapped to the same row. Ensure these two mapping fragments do no map two groups of entities with overlapping keys to the same group of rows." Based on what I have [read online](http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/12191f0d-3010-425d-9c52-ed0542458eaf/), in order to resolve this issue, you must add a Condition to the association on the Foreign Key like so: ``` <Condition ColumnName="Endpoint1" IsNull="false" /> ``` Here's a screenshot of this edit for the PersonPersonToPerson1 association: [![ Visual Studio 2008 SP1 Editing of GraphModel.edmx](https://i.stack.imgur.com/neseQ.jpg)](http://img153.imageshack.us/my.php?image=edmxassociationsetmappiah8.png) ## Constraints * The base classes of each hierarchy (i.e. Node and Link) *must* be abstract. * The navigation properties from the associations between two derived types *must* be distinguishable by link type (e.g. PersonToPerson and PersonToLocation). This means you *cannot* create the associations between the Link and Node abstract base classes. ## Problem: When I create the Entity Model as described above and add the Conditions to the AssociationMappings as described in the Assumptions above, I receive an "Error 3023" when I build/validate the model. ``` Error 1 Error 3023: Problem in Mapping Fragments starting at lines 146, 153, 159, 186, 195, 204, 213: Column Link.Endpoint1 has no default value and is not nullable. A column value is required to store entity data. An Entity with Key (PK) will not round-trip when: ((PK is NOT in 'LinkSet' EntitySet OR PK does NOT play Role 'PersonToPerson' in AssociationSet 'PersonPersonToPerson1') AND (PK is in 'LinkSet' EntitySet OR PK plays Role 'PersonToPerson' in AssociationSet 'PersonPersonToPerson1' OR PK plays Role 'PersonToPerson' in AssociationSet 'PersonPersonToPerson')) C:\Documents and Settings\Demo\My Documents\Visual Studio 2008\Projects\GraphExample2.BusinessEntities\GraphExample2.BusinessEntities\GraphModel.edmx 147 15 GraphExample2.BusinessEntities ``` The thing that the Entity Framework is getting hung up on in the above scenario is that there are two properties being mapped on to the same foreign keys. For example, the column and foreign key for Endpoint1 is mapped to the Person property in the PersonToLocation derived type and it's mapped to the Leader property in the PersonToPerson derived type. I don't understand why this is an issue. Since the Leader/Follower Properties are only in the PersonToPerson derived type - not any other derived type or base type - and the same is true of the Person/Location property, why isn't the TypeDiscriminator field sufficient for the EF to figure out which set a given row belongs in? To me it seems like, if you are dealing with an object where TypeDiscriminator = 1, you place Endpoint1 in Leader and Endpoint2 in Follower. Likewise, if you are dealing with an object where TypeDiscriminator = 2, you place Endpoint1 in Person and Endpoint2 in Location. ## Question: **How do you resolve the Error 3023 to allow these associations to occur ?** OR **How do you create the type of associations in the ADO Entity Framework that I have described above?** ## References: * MSDN Forum - [Error 3034: Problem in Mapping Fragments starting at lines ...](http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/4aa46c4a-05d5-49e7-82ef-33b79904fcc9/) * Zeeshan Hirani's Blog - [Contributions to Entity framework community](http://weblogs.asp.net/zeeshanhirani/archive/2008/12/05/my-christmas-present-to-the-entity-framework-community.aspx) * Zeeshan Hirani's [Entity Framework learning guide](http://cid-245ed00edb4c374e.skydrive.live.com/self.aspx/Public/entity%20framework%20learning%20guide.pdf) (this is an Excellent 514 page step-by-step guide to numerous concepts and gotchas with ADO EF. HIGHLY recommended!) ## Code SQL: ``` USE [GraphExample2] GO /****** Object: Table [dbo].[Node] Script Date: 02/17/2009 14:36:13 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Node]( [NodeID] [int] NOT NULL, [NodeTypeDiscriminator] [int] NOT NULL, [Name] [varchar](255) NOT NULL, [Description] [varchar](1023) NULL, CONSTRAINT [PK_Node] PRIMARY KEY CLUSTERED ( [NodeID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO /****** Object: Table [dbo].[Link] Script Date: 02/17/2009 14:36:12 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Link]( [LinkID] [int] NOT NULL, [LinkTypeDiscriminator] [int] NOT NULL, [Endpoint1] [int] NOT NULL, [Endpoint2] [int] NOT NULL, [Name] [varchar](255) NULL, [Description] [varchar](1023) NULL, CONSTRAINT [PK_Link] PRIMARY KEY CLUSTERED ( [LinkID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO /****** Object: ForeignKey [FK_Link_Node_Endpoint1] Script Date: 02/17/2009 14:36:12 ******/ ALTER TABLE [dbo].[Link] WITH CHECK ADD CONSTRAINT [FK_Link_Node_Endpoint1] FOREIGN KEY([Endpoint1]) REFERENCES [dbo].[Node] ([NodeID]) GO ALTER TABLE [dbo].[Link] CHECK CONSTRAINT [FK_Link_Node_Endpoint1] GO /****** Object: ForeignKey [FK_Link_Node_Endpoint2] Script Date: 02/17/2009 14:36:12 ******/ ALTER TABLE [dbo].[Link] WITH CHECK ADD CONSTRAINT [FK_Link_Node_Endpoint2] FOREIGN KEY([Endpoint2]) REFERENCES [dbo].[Node] ([NodeID]) GO ALTER TABLE [dbo].[Link] CHECK CONSTRAINT [FK_Link_Node_Endpoint2] GO ``` EDMX: ``` <?xml version="1.0" encoding="utf-8"?> <edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"> <!-- EF Runtime content --> <edmx:Runtime> <!-- SSDL content --> <edmx:StorageModels> <Schema Namespace="GraphModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl"> <EntityContainer Name="GraphModelStoreContainer"> <EntitySet Name="Link" EntityType="GraphModel.Store.Link" store:Type="Tables" Schema="dbo" /> <EntitySet Name="Node" EntityType="GraphModel.Store.Node" store:Type="Tables" Schema="dbo" /> <AssociationSet Name="FK_Link_Node_Endpoint1" Association="GraphModel.Store.FK_Link_Node_Endpoint1"> <End Role="Node" EntitySet="Node" /> <End Role="Link" EntitySet="Link" /> </AssociationSet> <AssociationSet Name="FK_Link_Node_Endpoint2" Association="GraphModel.Store.FK_Link_Node_Endpoint2"> <End Role="Node" EntitySet="Node" /> <End Role="Link" EntitySet="Link" /> </AssociationSet> </EntityContainer> <EntityType Name="Link"> <Key> <PropertyRef Name="LinkID" /> </Key> <Property Name="LinkID" Type="int" Nullable="false" /> <Property Name="LinkTypeDiscriminator" Type="int" Nullable="false" /> <Property Name="Endpoint1" Type="int" Nullable="false" /> <Property Name="Endpoint2" Type="int" Nullable="false" /> <Property Name="Name" Type="varchar" MaxLength="255" /> <Property Name="Description" Type="varchar" MaxLength="1023" /> </EntityType> <EntityType Name="Node"> <Key> <PropertyRef Name="NodeID" /> </Key> <Property Name="NodeID" Type="int" Nullable="false" /> <Property Name="NodeTypeDiscriminator" Type="int" Nullable="false" /> <Property Name="Name" Type="varchar" Nullable="false" MaxLength="255" /> <Property Name="Description" Type="varchar" MaxLength="1023" /> </EntityType> <Association Name="FK_Link_Node_Endpoint1"> <End Role="Node" Type="GraphModel.Store.Node" Multiplicity="1" /> <End Role="Link" Type="GraphModel.Store.Link" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="Node"> <PropertyRef Name="NodeID" /> </Principal> <Dependent Role="Link"> <PropertyRef Name="Endpoint1" /> </Dependent> </ReferentialConstraint> </Association> <Association Name="FK_Link_Node_Endpoint2"> <End Role="Node" Type="GraphModel.Store.Node" Multiplicity="1" /> <End Role="Link" Type="GraphModel.Store.Link" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="Node"> <PropertyRef Name="NodeID" /> </Principal> <Dependent Role="Link"> <PropertyRef Name="Endpoint2" /> </Dependent> </ReferentialConstraint> </Association> </Schema> </edmx:StorageModels> <!-- CSDL content --> <edmx:ConceptualModels> <Schema xmlns="http://schemas.microsoft.com/ado/2006/04/edm" Namespace="GraphModel" Alias="Self"> <EntityContainer Name="GraphModelContainer" > <EntitySet Name="NodeSet" EntityType="GraphModel.Node" /> <EntitySet Name="LinkSet" EntityType="GraphModel.Link" /> <AssociationSet Name="PersonPersonToPerson" Association="GraphModel.PersonPersonToPerson"> <End Role="Person" EntitySet="NodeSet" /> <End Role="PersonToPerson" EntitySet="LinkSet" /> </AssociationSet> <AssociationSet Name="PersonPersonToPerson1" Association="GraphModel.PersonPersonToPerson1"> <End Role="Person" EntitySet="NodeSet" /> <End Role="PersonToPerson" EntitySet="LinkSet" /> </AssociationSet> <AssociationSet Name="Person_PersonToLocation" Association="GraphModel.Person_PersonToLocation"> <End Role="Person" EntitySet="NodeSet" /> <End Role="PersonToLocation" EntitySet="LinkSet" /> </AssociationSet> <AssociationSet Name="Location_PersonToLocation" Association="GraphModel.Location_PersonToLocation"> <End Role="Location" EntitySet="NodeSet" /> <End Role="PersonToLocation" EntitySet="LinkSet" /> </AssociationSet> </EntityContainer> <EntityType Name="Node" Abstract="true"> <Key> <PropertyRef Name="NodeId" /> </Key> <Property Name="NodeId" Type="Int32" Nullable="false" /> <Property Name="Name" Type="String" Nullable="false" /> <Property Name="Description" Type="String" Nullable="true" /> </EntityType> <EntityType Name="Person" BaseType="GraphModel.Node" > <NavigationProperty Name="Leaders" Relationship="GraphModel.PersonPersonToPerson" FromRole="Person" ToRole="PersonToPerson" /> <NavigationProperty Name="Followers" Relationship="GraphModel.PersonPersonToPerson1" FromRole="Person" ToRole="PersonToPerson" /> <NavigationProperty Name="Locations" Relationship="GraphModel.Person_PersonToLocation" FromRole="Person" ToRole="PersonToLocation" /> </EntityType> <EntityType Name="Location" BaseType="GraphModel.Node" > <NavigationProperty Name="Visitors" Relationship="GraphModel.Location_PersonToLocation" FromRole="Location" ToRole="PersonToLocation" /> </EntityType> <EntityType Name="Link" Abstract="true"> <Key> <PropertyRef Name="LinkId" /> </Key> <Property Name="LinkId" Type="Int32" Nullable="false" /> <Property Name="Name" Type="String" Nullable="true" /> <Property Name="Description" Type="String" Nullable="true" /> </EntityType> <EntityType Name="PersonToPerson" BaseType="GraphModel.Link" > <NavigationProperty Name="Leader" Relationship="GraphModel.PersonPersonToPerson" FromRole="PersonToPerson" ToRole="Person" /> <NavigationProperty Name="Follower" Relationship="GraphModel.PersonPersonToPerson1" FromRole="PersonToPerson" ToRole="Person" /> </EntityType> <EntityType Name="PersonToLocation" BaseType="GraphModel.Link" > <NavigationProperty Name="Person" Relationship="GraphModel.Person_PersonToLocation" FromRole="PersonToLocation" ToRole="Person" /> <NavigationProperty Name="Location" Relationship="GraphModel.Location_PersonToLocation" FromRole="PersonToLocation" ToRole="Location" /> </EntityType> <Association Name="PersonPersonToPerson"> <End Type="GraphModel.Person" Role="Person" Multiplicity="1" /> <End Type="GraphModel.PersonToPerson" Role="PersonToPerson" Multiplicity="*" /> </Association> <Association Name="PersonPersonToPerson1"> <End Type="GraphModel.Person" Role="Person" Multiplicity="1" /> <End Type="GraphModel.PersonToPerson" Role="PersonToPerson" Multiplicity="*" /> </Association> <Association Name="Person_PersonToLocation"> <End Type="GraphModel.Person" Role="Person" Multiplicity="1" /> <End Type="GraphModel.PersonToLocation" Role="PersonToLocation" Multiplicity="*" /> </Association> <Association Name="Location_PersonToLocation"> <End Type="GraphModel.Location" Role="Location" Multiplicity="1" /> <End Type="GraphModel.PersonToLocation" Role="PersonToLocation" Multiplicity="*" /> </Association> </Schema> </edmx:ConceptualModels> <!-- C-S mapping content --> <edmx:Mappings> <Mapping xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS" Space="C-S"> <Alias Key="Model" Value="GraphModel" /> <Alias Key="Target" Value="GraphModel.Store" /> <EntityContainerMapping CdmEntityContainer="GraphModelContainer" StorageEntityContainer="GraphModelStoreContainer"> <EntitySetMapping Name="LinkSet"> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.Link)"> <MappingFragment StoreEntitySet="Link"> <ScalarProperty Name="Description" ColumnName="Description" /> <ScalarProperty Name="Name" ColumnName="Name" /> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </MappingFragment> </EntityTypeMapping> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.PersonToPerson)"> <MappingFragment StoreEntitySet="Link" > <ScalarProperty Name="LinkId" ColumnName="LinkID" /> <Condition ColumnName="LinkTypeDiscriminator" Value="1" /> </MappingFragment> </EntityTypeMapping> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.PersonToLocation)"> <MappingFragment StoreEntitySet="Link" > <ScalarProperty Name="LinkId" ColumnName="LinkID" /> <Condition ColumnName="LinkTypeDiscriminator" Value="2" /> </MappingFragment> </EntityTypeMapping> </EntitySetMapping> <EntitySetMapping Name="NodeSet"> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.Node)"> <MappingFragment StoreEntitySet="Node"> <ScalarProperty Name="Description" ColumnName="Description" /> <ScalarProperty Name="Name" ColumnName="Name" /> <ScalarProperty Name="NodeId" ColumnName="NodeID" /> </MappingFragment> </EntityTypeMapping> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.Person)"> <MappingFragment StoreEntitySet="Node" > <ScalarProperty Name="NodeId" ColumnName="NodeID" /> <Condition ColumnName="NodeTypeDiscriminator" Value="1" /> </MappingFragment> </EntityTypeMapping> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.Location)"> <MappingFragment StoreEntitySet="Node" > <ScalarProperty Name="NodeId" ColumnName="NodeID" /> <Condition ColumnName="NodeTypeDiscriminator" Value="2" /> </MappingFragment> </EntityTypeMapping> </EntitySetMapping> <AssociationSetMapping Name="PersonPersonToPerson1" TypeName="GraphModel.PersonPersonToPerson1" StoreEntitySet="Link"> <EndProperty Name="Person"> <ScalarProperty Name="NodeId" ColumnName="Endpoint1" /> </EndProperty> <EndProperty Name="PersonToPerson"> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </EndProperty> <Condition ColumnName="Endpoint1" IsNull="false" /> </AssociationSetMapping> <AssociationSetMapping Name="PersonPersonToPerson" TypeName="GraphModel.PersonPersonToPerson" StoreEntitySet="Link"> <EndProperty Name="Person"> <ScalarProperty Name="NodeId" ColumnName="Endpoint2" /> </EndProperty> <EndProperty Name="PersonToPerson"> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </EndProperty> <Condition ColumnName="Endpoint2" IsNull="false" /> </AssociationSetMapping> <AssociationSetMapping Name="Person_PersonToLocation" TypeName="GraphModel.Person_PersonToLocation" StoreEntitySet="Link"> <EndProperty Name="Person"> <ScalarProperty Name="NodeId" ColumnName="Endpoint1" /> </EndProperty> <EndProperty Name="PersonToLocation"> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </EndProperty> <Condition ColumnName="Endpoint1" IsNull="false" /> </AssociationSetMapping> <AssociationSetMapping Name="Location_PersonToLocation" TypeName="GraphModel.Location_PersonToLocation" StoreEntitySet="Link"> <EndProperty Name="Location"> <ScalarProperty Name="NodeId" ColumnName="Endpoint2" /> </EndProperty> <EndProperty Name="PersonToLocation"> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </EndProperty> <Condition ColumnName="Endpoint2" IsNull="false" /> </AssociationSetMapping> </EntityContainerMapping> </Mapping> </edmx:Mappings> </edmx:Runtime> <!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) --> <edmx:Designer xmlns="http://schemas.microsoft.com/ado/2007/06/edmx"> <edmx:Connection> <DesignerInfoPropertySet> <DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" /> </DesignerInfoPropertySet> </edmx:Connection> <edmx:Options> <DesignerInfoPropertySet> <DesignerProperty Name="ValidateOnBuild" Value="true" /> </DesignerInfoPropertySet> </edmx:Options> <!-- Diagram content (shape and connector positions) --> <edmx:Diagrams> <Diagram Name="GraphModel" ZoomLevel="114" > <EntityTypeShape EntityType="GraphModel.Node" Width="1.5" PointX="5.875" PointY="1.375" Height="1.427958984375" /> <EntityTypeShape EntityType="GraphModel.Person" Width="1.5" PointX="5.875" PointY="3.25" Height="1.4279589843749996" /> <EntityTypeShape EntityType="GraphModel.Location" Width="1.5" PointX="7.75" PointY="4.625" Height="1.0992643229166665" /> <InheritanceConnector EntityType="GraphModel.Location"> <ConnectorPoint PointX="7.375" PointY="2.0889794921875" /> <ConnectorPoint PointX="8.5" PointY="2.0889794921875" /> <ConnectorPoint PointX="8.5" PointY="4.625" /> </InheritanceConnector> <EntityTypeShape EntityType="GraphModel.Link" Width="1.5" PointX="2.875" PointY="1.375" Height="1.427958984375" /> <EntityTypeShape EntityType="GraphModel.PersonToPerson" Width="1.75" PointX="2.625" PointY="3.125" Height="0.9349169921875" /> <InheritanceConnector EntityType="GraphModel.PersonToPerson"> <ConnectorPoint PointX="3.625" PointY="2.802958984375" /> <ConnectorPoint PointX="3.625" PointY="3.125" /> </InheritanceConnector> <InheritanceConnector EntityType="GraphModel.Person"> <ConnectorPoint PointX="6.625" PointY="2.802958984375" /> <ConnectorPoint PointX="6.625" PointY="3.25" /> </InheritanceConnector> <EntityTypeShape EntityType="GraphModel.PersonToLocation" Width="1.875" PointX="0.75" PointY="4.625" Height="1.2636116536458326" /> <InheritanceConnector EntityType="GraphModel.PersonToLocation"> <ConnectorPoint PointX="2.875" PointY="2.0889794921875" /> <ConnectorPoint PointX="1.65625" PointY="2.0889794921875" /> <ConnectorPoint PointX="1.65625" PointY="4.625" /> </InheritanceConnector> <AssociationConnector Association="GraphModel.PersonPersonToPerson"> <ConnectorPoint PointX="5.875" PointY="3.8193058268229163" /> <ConnectorPoint PointX="4.375" PointY="3.8193058268229163" /> </AssociationConnector> <AssociationConnector Association="GraphModel.PersonPersonToPerson1"> <ConnectorPoint PointX="5.875" PointY="3.4721529134114579" /> <ConnectorPoint PointX="4.375" PointY="3.4721529134114579" /> </AssociationConnector> <AssociationConnector Association="GraphModel.Person_PersonToLocation"> <ConnectorPoint PointX="6.625" PointY="4.677958984375" /> <ConnectorPoint PointX="6.625" PointY="5.1875" /> <ConnectorPoint PointX="2.625" PointY="5.1875" /> </AssociationConnector> <AssociationConnector Association="GraphModel.Location_PersonToLocation"> <ConnectorPoint PointX="7.75" PointY="5.4791666666666661" /> <ConnectorPoint PointX="2.625" PointY="5.4791666666666661" /> </AssociationConnector> </Diagram> </edmx:Diagrams> </edmx:Designer> </edmx:Edmx> ```
## Possible Workaround 1. Create a separate column for each association between derived types and make each of these columns **nullable** 2. Create a foreign key between each of these new columns and the primary key table. 3. Map each association in your Entity Model to a specific, unique column and foreign key so that each column and foreign key is only used once. --- ## Problems This is quite an undesirable solution because it explodes out the number of columns you need. * **More Columns** - Adding a column for each association between derived types results in an explosion on the number of columns. * **Empty Columns** In the case of TPH, it means you'll have a lot of *empty* columns in your table. * **SQL JOIN** - Switching from TPH to TPT to avoid the number of empty columns results in the necessity for EF to use a JOIN which will have to occur extremely frequently (almost every time you deal with any of the derived types). * **Refactoring** If you add a derived type in the future, you not only have to update your Entity model (\*.edmx) and the it's mapping but you will also have to change the database schema by adding additional columns! --- ## Example For the Link/Node example above, the resulting database schema would look like this: [![GraphExample Workaround Database Schema](https://i.stack.imgur.com/D7QFw.jpg)](http://img230.imageshack.us/my.php?image=graphexampledatabasewor.png) --- ## Code SQL: ``` USE [GraphExample2] GO /****** Object: Table [dbo].[Node] Script Date: 02/26/2009 15:45:53 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Node]( [NodeID] [int] IDENTITY(1,1) NOT NULL, [NodeTypeDiscriminator] [int] NOT NULL, [Name] [varchar](255) NOT NULL, [Description] [varchar](1023) NULL, CONSTRAINT [PK_Node] PRIMARY KEY CLUSTERED ( [NodeID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO /****** Object: Table [dbo].[Link] Script Date: 02/26/2009 15:45:53 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Link]( [LinkID] [int] IDENTITY(1,1) NOT NULL, [LinkTypeDiscriminator] [int] NOT NULL, [LeaderID] [int] NULL, [FollowerID] [int] NULL, [PersonID] [int] NULL, [LocationID] [int] NULL, [Name] [varchar](255) NULL, [Description] [varchar](1023) NULL, CONSTRAINT [PK_Link] PRIMARY KEY CLUSTERED ( [LinkID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO /****** Object: ForeignKey [FK_Link_Node_Follower] Script Date: 02/26/2009 15:45:53 ******/ ALTER TABLE [dbo].[Link] WITH CHECK ADD CONSTRAINT [FK_Link_Node_Follower] FOREIGN KEY([FollowerID]) REFERENCES [dbo].[Node] ([NodeID]) GO ALTER TABLE [dbo].[Link] CHECK CONSTRAINT [FK_Link_Node_Follower] GO /****** Object: ForeignKey [FK_Link_Node_Leader] Script Date: 02/26/2009 15:45:53 ******/ ALTER TABLE [dbo].[Link] WITH CHECK ADD CONSTRAINT [FK_Link_Node_Leader] FOREIGN KEY([LeaderID]) REFERENCES [dbo].[Node] ([NodeID]) GO ALTER TABLE [dbo].[Link] CHECK CONSTRAINT [FK_Link_Node_Leader] GO /****** Object: ForeignKey [FK_Link_Node_Location] Script Date: 02/26/2009 15:45:53 ******/ ALTER TABLE [dbo].[Link] WITH CHECK ADD CONSTRAINT [FK_Link_Node_Location] FOREIGN KEY([LocationID]) REFERENCES [dbo].[Node] ([NodeID]) GO ALTER TABLE [dbo].[Link] CHECK CONSTRAINT [FK_Link_Node_Location] GO /****** Object: ForeignKey [FK_Link_Node_Person] Script Date: 02/26/2009 15:45:53 ******/ ALTER TABLE [dbo].[Link] WITH CHECK ADD CONSTRAINT [FK_Link_Node_Person] FOREIGN KEY([PersonID]) REFERENCES [dbo].[Node] ([NodeID]) GO ALTER TABLE [dbo].[Link] CHECK CONSTRAINT [FK_Link_Node_Person] GO ``` EDMX: ``` <?xml version="1.0" encoding="utf-8"?> <edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"> <!-- EF Runtime content --> <edmx:Runtime> <!-- SSDL content --> <edmx:StorageModels> <Schema Namespace="GraphModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl"> <EntityContainer Name="GraphModelStoreContainer"> <EntitySet Name="Link" EntityType="GraphModel.Store.Link" store:Type="Tables" Schema="dbo" /> <EntitySet Name="Node" EntityType="GraphModel.Store.Node" store:Type="Tables" Schema="dbo" /> <AssociationSet Name="FK_Link_Node_Follower" Association="GraphModel.Store.FK_Link_Node_Follower"> <End Role="Node" EntitySet="Node" /> <End Role="Link" EntitySet="Link" /> </AssociationSet> <AssociationSet Name="FK_Link_Node_Leader" Association="GraphModel.Store.FK_Link_Node_Leader"> <End Role="Node" EntitySet="Node" /> <End Role="Link" EntitySet="Link" /> </AssociationSet> <AssociationSet Name="FK_Link_Node_Location" Association="GraphModel.Store.FK_Link_Node_Location"> <End Role="Node" EntitySet="Node" /> <End Role="Link" EntitySet="Link" /> </AssociationSet> <AssociationSet Name="FK_Link_Node_Person" Association="GraphModel.Store.FK_Link_Node_Person"> <End Role="Node" EntitySet="Node" /> <End Role="Link" EntitySet="Link" /> </AssociationSet> </EntityContainer> <EntityType Name="Link"> <Key> <PropertyRef Name="LinkID" /> </Key> <Property Name="LinkID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" /> <Property Name="LinkTypeDiscriminator" Type="int" Nullable="false" /> <Property Name="LeaderID" Type="int" /> <Property Name="FollowerID" Type="int" /> <Property Name="PersonID" Type="int" /> <Property Name="LocationID" Type="int" /> <Property Name="Name" Type="varchar" MaxLength="255" /> <Property Name="Description" Type="varchar" MaxLength="1023" /> </EntityType> <EntityType Name="Node"> <Key> <PropertyRef Name="NodeID" /> </Key> <Property Name="NodeID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" /> <Property Name="NodeTypeDiscriminator" Type="int" Nullable="false" /> <Property Name="Name" Type="varchar" Nullable="false" MaxLength="255" /> <Property Name="Description" Type="varchar" MaxLength="1023" /> </EntityType> <Association Name="FK_Link_Node_Follower"> <End Role="Node" Type="GraphModel.Store.Node" Multiplicity="0..1" /> <End Role="Link" Type="GraphModel.Store.Link" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="Node"> <PropertyRef Name="NodeID" /> </Principal> <Dependent Role="Link"> <PropertyRef Name="FollowerID" /> </Dependent> </ReferentialConstraint> </Association> <Association Name="FK_Link_Node_Leader"> <End Role="Node" Type="GraphModel.Store.Node" Multiplicity="0..1" /> <End Role="Link" Type="GraphModel.Store.Link" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="Node"> <PropertyRef Name="NodeID" /> </Principal> <Dependent Role="Link"> <PropertyRef Name="LeaderID" /> </Dependent> </ReferentialConstraint> </Association> <Association Name="FK_Link_Node_Location"> <End Role="Node" Type="GraphModel.Store.Node" Multiplicity="0..1" /> <End Role="Link" Type="GraphModel.Store.Link" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="Node"> <PropertyRef Name="NodeID" /> </Principal> <Dependent Role="Link"> <PropertyRef Name="LocationID" /> </Dependent> </ReferentialConstraint> </Association> <Association Name="FK_Link_Node_Person"> <End Role="Node" Type="GraphModel.Store.Node" Multiplicity="0..1" /> <End Role="Link" Type="GraphModel.Store.Link" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="Node"> <PropertyRef Name="NodeID" /> </Principal> <Dependent Role="Link"> <PropertyRef Name="PersonID" /> </Dependent> </ReferentialConstraint> </Association> </Schema> </edmx:StorageModels> <!-- CSDL content --> <edmx:ConceptualModels> <Schema xmlns="http://schemas.microsoft.com/ado/2006/04/edm" Namespace="GraphModel" Alias="Self"> <EntityContainer Name="GraphModelContainer" > <EntitySet Name="NodeSet" EntityType="GraphModel.Node" /> <EntitySet Name="LinkSet" EntityType="GraphModel.Link" /> <AssociationSet Name="PersonPersonToPerson_Leader" Association="GraphModel.PersonPersonToPerson_Leader"> <End Role="Person" EntitySet="NodeSet" /> <End Role="PersonToPerson" EntitySet="LinkSet" /> </AssociationSet> <AssociationSet Name="PersonPersonToPerson_Follower" Association="GraphModel.PersonPersonToPerson_Follower"> <End Role="Person" EntitySet="NodeSet" /> <End Role="PersonToPerson" EntitySet="LinkSet" /> </AssociationSet> <AssociationSet Name="Person_PersonToLocation" Association="GraphModel.Person_PersonToLocation"> <End Role="Person" EntitySet="NodeSet" /> <End Role="PersonToLocation" EntitySet="LinkSet" /> </AssociationSet> <AssociationSet Name="Location_PersonToLocation" Association="GraphModel.Location_PersonToLocation"> <End Role="Location" EntitySet="NodeSet" /> <End Role="PersonToLocation" EntitySet="LinkSet" /> </AssociationSet> </EntityContainer> <EntityType Name="Node" Abstract="true"> <Key> <PropertyRef Name="NodeId" /> </Key> <Property Name="NodeId" Type="Int32" Nullable="false" /> <Property Name="Name" Type="String" Nullable="false" /> <Property Name="Description" Type="String" Nullable="true" /> </EntityType> <EntityType Name="Person" BaseType="GraphModel.Node" > <NavigationProperty Name="Leaders" Relationship="GraphModel.PersonPersonToPerson_Leader" FromRole="Person" ToRole="PersonToPerson" /> <NavigationProperty Name="Followers" Relationship="GraphModel.PersonPersonToPerson_Follower" FromRole="Person" ToRole="PersonToPerson" /> <NavigationProperty Name="Locations" Relationship="GraphModel.Person_PersonToLocation" FromRole="Person" ToRole="PersonToLocation" /> </EntityType> <EntityType Name="Location" BaseType="GraphModel.Node" > <NavigationProperty Name="Visitors" Relationship="GraphModel.Location_PersonToLocation" FromRole="Location" ToRole="PersonToLocation" /> </EntityType> <EntityType Name="Link" Abstract="true"> <Key> <PropertyRef Name="LinkId" /> </Key> <Property Name="LinkId" Type="Int32" Nullable="false" /> <Property Name="Name" Type="String" Nullable="true" /> <Property Name="Description" Type="String" Nullable="true" /> </EntityType> <EntityType Name="PersonToPerson" BaseType="GraphModel.Link" > <NavigationProperty Name="Leader" Relationship="GraphModel.PersonPersonToPerson_Leader" FromRole="PersonToPerson" ToRole="Person" /> <NavigationProperty Name="Follower" Relationship="GraphModel.PersonPersonToPerson_Follower" FromRole="PersonToPerson" ToRole="Person" /> </EntityType> <EntityType Name="PersonToLocation" BaseType="GraphModel.Link" > <NavigationProperty Name="Person" Relationship="GraphModel.Person_PersonToLocation" FromRole="PersonToLocation" ToRole="Person" /> <NavigationProperty Name="Location" Relationship="GraphModel.Location_PersonToLocation" FromRole="PersonToLocation" ToRole="Location" /> </EntityType> <Association Name="PersonPersonToPerson_Leader"> <End Type="GraphModel.Person" Role="Person" Multiplicity="1" /> <End Type="GraphModel.PersonToPerson" Role="PersonToPerson" Multiplicity="*" /> </Association> <Association Name="PersonPersonToPerson_Follower"> <End Type="GraphModel.Person" Role="Person" Multiplicity="1" /> <End Type="GraphModel.PersonToPerson" Role="PersonToPerson" Multiplicity="*" /> </Association> <Association Name="Person_PersonToLocation"> <End Type="GraphModel.Person" Role="Person" Multiplicity="1" /> <End Type="GraphModel.PersonToLocation" Role="PersonToLocation" Multiplicity="*" /> </Association> <Association Name="Location_PersonToLocation"> <End Type="GraphModel.Location" Role="Location" Multiplicity="1" /> <End Type="GraphModel.PersonToLocation" Role="PersonToLocation" Multiplicity="*" /> </Association> </Schema> </edmx:ConceptualModels> <!-- C-S mapping content --> <edmx:Mappings> <Mapping xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS" Space="C-S"> <Alias Key="Model" Value="GraphModel" /> <Alias Key="Target" Value="GraphModel.Store" /> <EntityContainerMapping CdmEntityContainer="GraphModelContainer" StorageEntityContainer="GraphModelStoreContainer"> <EntitySetMapping Name="LinkSet"> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.Link)"> <MappingFragment StoreEntitySet="Link"> <ScalarProperty Name="Description" ColumnName="Description" /> <ScalarProperty Name="Name" ColumnName="Name" /> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </MappingFragment> </EntityTypeMapping> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.PersonToPerson)"> <MappingFragment StoreEntitySet="Link" > <ScalarProperty Name="LinkId" ColumnName="LinkID" /> <Condition ColumnName="LinkTypeDiscriminator" Value="1" /> </MappingFragment> </EntityTypeMapping> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.PersonToLocation)"> <MappingFragment StoreEntitySet="Link" > <ScalarProperty Name="LinkId" ColumnName="LinkID" /> <Condition ColumnName="LinkTypeDiscriminator" Value="2" /> </MappingFragment> </EntityTypeMapping> </EntitySetMapping> <EntitySetMapping Name="NodeSet"> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.Node)"> <MappingFragment StoreEntitySet="Node"> <ScalarProperty Name="Description" ColumnName="Description" /> <ScalarProperty Name="Name" ColumnName="Name" /> <ScalarProperty Name="NodeId" ColumnName="NodeID" /> </MappingFragment> </EntityTypeMapping> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.Person)"> <MappingFragment StoreEntitySet="Node" > <ScalarProperty Name="NodeId" ColumnName="NodeID" /> <Condition ColumnName="NodeTypeDiscriminator" Value="1" /> </MappingFragment> </EntityTypeMapping> <EntityTypeMapping TypeName="IsTypeOf(GraphModel.Location)"> <MappingFragment StoreEntitySet="Node" > <ScalarProperty Name="NodeId" ColumnName="NodeID" /> <Condition ColumnName="NodeTypeDiscriminator" Value="2" /> </MappingFragment> </EntityTypeMapping> </EntitySetMapping> <AssociationSetMapping Name="PersonPersonToPerson_Follower" TypeName="GraphModel.PersonPersonToPerson_Follower" StoreEntitySet="Link"> <EndProperty Name="Person"> <ScalarProperty Name="NodeId" ColumnName="FollowerID" /> </EndProperty> <EndProperty Name="PersonToPerson"> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </EndProperty> </AssociationSetMapping> <AssociationSetMapping Name="PersonPersonToPerson_Leader" TypeName="GraphModel.PersonPersonToPerson_Leader" StoreEntitySet="Link"> <EndProperty Name="Person"> <ScalarProperty Name="NodeId" ColumnName="LeaderID" /> </EndProperty> <EndProperty Name="PersonToPerson"> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </EndProperty> </AssociationSetMapping> <AssociationSetMapping Name="Person_PersonToLocation" TypeName="GraphModel.Person_PersonToLocation" StoreEntitySet="Link"> <EndProperty Name="Person"> <ScalarProperty Name="NodeId" ColumnName="PersonID" /> </EndProperty> <EndProperty Name="PersonToLocation"> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </EndProperty> </AssociationSetMapping> <AssociationSetMapping Name="Location_PersonToLocation" TypeName="GraphModel.Location_PersonToLocation" StoreEntitySet="Link"> <EndProperty Name="Location"> <ScalarProperty Name="NodeId" ColumnName="LocationID" /> </EndProperty> <EndProperty Name="PersonToLocation"> <ScalarProperty Name="LinkId" ColumnName="LinkID" /> </EndProperty> </AssociationSetMapping> </EntityContainerMapping> </Mapping> </edmx:Mappings> </edmx:Runtime> <!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) --> <edmx:Designer xmlns="http://schemas.microsoft.com/ado/2007/06/edmx"> <edmx:Connection> <DesignerInfoPropertySet> <DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" /> </DesignerInfoPropertySet> </edmx:Connection> <edmx:Options> <DesignerInfoPropertySet> <DesignerProperty Name="ValidateOnBuild" Value="true" /> </DesignerInfoPropertySet> </edmx:Options> <!-- Diagram content (shape and connector positions) --> <edmx:Diagrams> <Diagram Name="GraphModel" ZoomLevel="114" > <EntityTypeShape EntityType="GraphModel.Node" Width="1.5" PointX="5.875" PointY="1.375" Height="1.427958984375" /> <EntityTypeShape EntityType="GraphModel.Person" Width="1.5" PointX="5.875" PointY="3.25" Height="1.4279589843749996" /> <EntityTypeShape EntityType="GraphModel.Location" Width="1.5" PointX="7.75" PointY="4.625" Height="1.0992643229166665" /> <InheritanceConnector EntityType="GraphModel.Location"> <ConnectorPoint PointX="7.375" PointY="2.4176741536458342" /> <ConnectorPoint PointX="8.5" PointY="2.4176741536458342" /> <ConnectorPoint PointX="8.5" PointY="4.625" /> </InheritanceConnector> <EntityTypeShape EntityType="GraphModel.Link" Width="1.5" PointX="2.875" PointY="1.375" Height="1.427958984375" /> <EntityTypeShape EntityType="GraphModel.PersonToPerson" Width="1.75" PointX="2.75" PointY="3.25" Height="1.2636116536458326" /> <InheritanceConnector EntityType="GraphModel.PersonToPerson" ManuallyRouted="false"> <ConnectorPoint PointX="3.625" PointY="2.802958984375" /> <ConnectorPoint PointX="3.625" PointY="3.25" /> </InheritanceConnector> <InheritanceConnector EntityType="GraphModel.Person"> <ConnectorPoint PointX="6.625" PointY="3.4603483072916683" /> <ConnectorPoint PointX="6.625" PointY="3.25" /> </InheritanceConnector> <EntityTypeShape EntityType="GraphModel.PersonToLocation" Width="1.875" PointX="0.75" PointY="4.625" Height="1.2636116536458326" /> <InheritanceConnector EntityType="GraphModel.PersonToLocation"> <ConnectorPoint PointX="2.875" PointY="2.4176741536458342" /> <ConnectorPoint PointX="1.65625" PointY="2.4176741536458342" /> <ConnectorPoint PointX="1.65625" PointY="4.625" /> </InheritanceConnector> <AssociationConnector Association="GraphModel.PersonPersonToPerson_Leader"> <ConnectorPoint PointX="5.875" PointY="3.8818058268229163" /> <ConnectorPoint PointX="4.5" PointY="3.8818058268229163" /> </AssociationConnector> <AssociationConnector Association="GraphModel.PersonPersonToPerson_Follower"> <ConnectorPoint PointX="5.875" PointY="3.5034029134114579" /> <ConnectorPoint PointX="4.5" PointY="3.5034029134114579" /> </AssociationConnector> <AssociationConnector Association="GraphModel.Person_PersonToLocation"> <ConnectorPoint PointX="6.625" PointY="4.677958984375" /> <ConnectorPoint PointX="6.625" PointY="5.0078214863281243" /> <ConnectorPoint PointX="2.625" PointY="5.0078214863281243" /> </AssociationConnector> <AssociationConnector Association="GraphModel.Location_PersonToLocation"> <ConnectorPoint PointX="7.75" PointY="5.40018798828125" /> <ConnectorPoint PointX="2.625" PointY="5.40018798828125" /> </AssociationConnector> </Diagram> </edmx:Diagrams> </edmx:Designer> </edmx:Edmx> ```
AoA! EntityModelCodeGenerator create **0..1 to many** relation between two tables, Make it **1 to many**. In this kind of case it may be a possible Solution. Best Regards! Salahuddin
ADO EF - Errors Mapping Associations between Derived Types in TPH
[ "", "c#", "entity-framework", "orm", "" ]
**database.php**: ``` $db['default']['hostname'] = "192.168.2.104"; $db['default']['username'] = "webuser"; $db['default']['password'] = "----"; $db['default']['database'] = "vad"; $db['default']['dbdriver'] = "mysql"; $db['default']['dbprefix'] = ""; $db['default']['pconnect'] = TRUE; $db['default']['db_debug'] = TRUE; $db['default']['cache_on'] = FALSE; $db['default']['cachedir'] = ""; $db['default']['char_set'] = "utf8"; $db['default']['dbcollat'] = "utf8_general_ci"; $db['stats']['hostname'] = "192.168.2.104"; $db['stats']['username'] = "webuser"; $db['stats']['password'] = "---"; $db['stats']['database'] = "vad_stats"; $db['stats']['dbdriver'] = "mysql"; $db['stats']['dbprefix'] = ""; $db['stats']['pconnect'] = TRUE; $db['stats']['db_debug'] = TRUE; $db['stats']['cache_on'] = FALSE; $db['stats']['cachedir'] = ""; $db['stats']['char_set'] = "utf8"; $db['stats']['dbcollat'] = "utf8_general_ci"; ``` The issue is I can only define in the configuration one `$active_group`, default, or stats. I followed the CodeIgniter documentation and I added the following: ``` $DB2 = $this->load->database('stats', TRUE); ``` This way I connect to the second database, but I lose the connection to the first one. Does anyone have any ideas on how can I load the two database without having to do the following in all models constructors? ``` $database1 = $this->load->database('database1', TRUE); $database2 = $this->load->database('database2', TRUE); ``` Regards, Pedro
Instead of applying the hack as mentioned by Camacho you can also set the 'pconnect'-flag in the database.php file to FALSE for all connections.
There is a bug in codeigniter. Inserting one line into a class will fix the whole thing. Here is the original source: <http://koorb.wordpress.com/2007/11/16/codeigniter-connect-to-multiple-databases/> \*\* This fix does not apply to PostgreSQL Here is a copy just in case that site goes down. The line number has changed. Here is the bug fix from codeigniter: start bugfix Description all of the database calls go to the same database (last one initialized) To fix the problem change the simple\_query function in /system/database/DB\_driver.php: ``` function simple_query($sql) { if ( ! $this->conn_id) { $this->initialize(); } $this->db_select(); //<----------------- Added this line return $this->_execute($sql); } ``` This completely fixes the problem, so you can do stuff like this in a model ``` $this->legacy_db = $this->load->database('legacy', true); ```
Codeigniter - Using Multiple Databases
[ "", "php", "database", "codeigniter", "" ]
If I declare a JavaScript boolean variable like this: ``` var IsLoggedIn; ``` And then initialize it with either `true` or `1`, is that safe? Or will initializing it with `1` make the variable a number?
Types are dependent to your initialization: ``` var IsLoggedIn1 = "true"; //string var IsLoggedIn2 = 1; //integer var IsLoggedIn3 = true; //bool ``` But take a look at this example: ``` var IsLoggedIn1 = "true"; //string IsLoggedIn1 = true; //now your variable is a boolean ``` Your variables' type depends on the assigned value in JavaScript.
No it is not safe. You could later do var `IsLoggedIn = "Foo";` and JavaScript will not throw an error. It is possible to do ``` var IsLoggedIn = new Boolean(false); var IsLoggedIn = new Boolean(true); ``` You can also pass the non boolean variable into the `new Boolean()` and it will make IsLoggedIn boolean. ``` var IsLoggedIn = new Boolean(0); // false var IsLoggedIn = new Boolean(NaN); // false var IsLoggedIn = new Boolean("Foo"); // true var IsLoggedIn = new Boolean(1); // true ```
Declaring a boolean in JavaScript using just var
[ "", "javascript", "boolean", "" ]
I've got an IDbTransaction in a using statement but I'm unsure if it will be rolled back if an exception is thrown in a using statement. I know that a using statement will enforce the calling of Dispose()...but does anyone know if the same is true for Rollback()? **Update:** Also, do I need to call Commit() explicitly as I have below or will that also be taken care of by the using statement? My code looks sort of like this: ``` using Microsoft.Practices.EnterpriseLibrary.Data; ... using(IDbConnection connection = DatabaseInstance.CreateConnection()) { connection.Open(); using(IDbTransaction transaction = connection.BeginTransaction()) { //Attempt to do stuff in the database //potentially throw an exception transaction.Commit(); } } ```
Dispose method for transaction class performs a rollback while Oracle's class doesn't. So from transaction's perspective it's implementation dependent. The `using` statement for the connection object on the other hand would either close the connection to the database or return the connection to the pool after resetting it. In either case, the outstanding transactions should be rolled back. That's why an exception never leaves an active transaction lying around. Also, yes, you should call `Commit()` explicitly.
You have to call commit. The using statement will not commit anything for you.
Will a using statement rollback a database transaction if an error occurs?
[ "", "c#", "transactions", "rollback", "using-statement", "" ]
``` <script type="text/javascript"> var p = s.getMaximum(); </script> <form action="/cgi-bin/Lib.exe" method="POST" name="checks" ID="Form1"> <INPUT TYPE="text" NAME="inputbox" VALUE="VAR P FROM JAVA SCRIPT HERE?" ID="Text1"><P></form> ``` Possible to pass the javascript value 'p' as the value of input form? Thanks.
You want to read about the Javascript DOM. Start with the following: <http://www.w3schools.com/htmldom/dom_obj_form.asp> Specifically you're looking to manipulate document.checks.inputbox.value Edit: Page removed. Answer can be found here now: <http://www.w3schools.com/jsref/coll_doc_forms.asp>
You can use javascript to set the value of that element to `p`. ``` <script type="text/javascript"> document.getElementById("Text1").value = p; </script> ```
html value set from javascript?
[ "", "javascript", "forms", "variables", "" ]
I have my own inherited `App.Controller` from `Mvc.Controller` which then all of my controllers inherit from. I wrote a provider utilizing an interface and implemented it as `MyService` and the constructor takes the `Server` property of `Mvc.Controller` which is of `HttpServerUtilityBase`. However, I instantiate `MyService` in `App.Controller`'s constructor. The problem is that the `Server` property of the Controller is `null` when constructing `MyService`. I have used `public Controller () : base() { }` to get the base to be constructed. However, `Server` remains `null`. I would like to avoid `Web.HttpContext.Current.Server` if possible. Has any one have a work around for this problem? **Edit:** Well, I have implemented tvanfosson's suggestion, and when my app constructs `MyService` in the property `get` method, `Server` is still null. **Edit 2:** Nevermind, I was a goof. I had another `Controller` using `Server` aswell and did not change that. Case closed.
Use delayed initialization to construct your service. ``` private MyService service; public MyService Service { get { if (this.service == null) { this.service = new MyService(this.Server); } return this.service; } } ``` Then, your service isn't actually instantiated until it is used in the controller action and by that time the Server property has been set.
> I instantiate `MyService` in `App.Controller`'s constructor. There's your problem. You need to pass an instance of `MyService` which has already been constructed into your `App.Controller`'s constructor. Take a look at the Inversion of Control / Dependency Injection patterns, and take a look at some of the libraries which make these patterns easy ([see this list](http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx)).
Using Server in Mvc.Controller
[ "", "c#", "asp.net-mvc", "controller", "" ]
The code looks like this: ``` StringBuilder builder = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; using (XmlWriter xmlWriter = XmlWriter.Create(builder, settings)) { XmlSerializer s = new XmlSerializer(objectToSerialize.GetType()); s.Serialize(xmlWriter, objectToSerialize); } ``` The resulting serialized document includes namespaces, like so: ``` <message xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns="urn:something"> ... </message> ``` To remove the xsi and xsd namespaces, I can follow the answer from [How to serialize an object to XML without getting xmlns=”…”?](https://stackoverflow.com/questions/258960). I want my message tag as `<message>` (without any namespace attributes). How can I do this?
``` ... XmlSerializer s = new XmlSerializer(objectToSerialize.GetType()); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("",""); s.Serialize(xmlWriter, objectToSerialize, ns); ```
This is the 2nd of two answers. If you want to just strip all namespaces arbitrarily from a document during serialization, you can do this by implementing your own XmlWriter. The easiest way is to derive from XmlTextWriter and override the StartElement method that emits namespaces. The StartElement method is invoked by the XmlSerializer when emitting any elements, including the root. By overriding the namespace for each element, and replacing it with the empty string, you've stripped the namespaces from the output. ``` public class NoNamespaceXmlWriter : XmlTextWriter { //Provide as many contructors as you need public NoNamespaceXmlWriter(System.IO.TextWriter output) : base(output) { Formatting= System.Xml.Formatting.Indented;} public override void WriteStartDocument () { } public override void WriteStartElement(string prefix, string localName, string ns) { base.WriteStartElement("", localName, ""); } } ``` Suppose this is the type: ``` // explicitly specify a namespace for this type, // to be used during XML serialization. [XmlRoot(Namespace="urn:Abracadabra")] public class MyTypeWithNamespaces { // private fields backing the properties private int _Epoch; private string _Label; // explicitly define a distinct namespace for this element [XmlElement(Namespace="urn:Whoohoo")] public string Label { set { _Label= value; } get { return _Label; } } // this property will be implicitly serialized to XML using the // member name for the element name, and inheriting the namespace from // the type. public int Epoch { set { _Epoch= value; } get { return _Epoch; } } } ``` Here's how you would use such a thing during serialization: ``` var o2= new MyTypeWithNamespaces { ..intializers.. }; var builder = new System.Text.StringBuilder(); using ( XmlWriter writer = new NoNamespaceXmlWriter(new System.IO.StringWriter(builder))) { s2.Serialize(writer, o2, ns2); } Console.WriteLine("{0}",builder.ToString()); ``` The XmlTextWriter is sort of broken, though. According to the [reference doc](http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx), when it writes it does not check for the following: > * Invalid characters in attribute and element names. > * Unicode characters that do not fit the specified encoding. If the Unicode > characters do not fit the specified > encoding, the XmlTextWriter does not > escape the Unicode characters into > character entities. > * Duplicate attributes. > * Characters in the DOCTYPE public > identifier or system identifier. These problems with XmlTextWriter have been around since v1.1 of the .NET Framework, and they will remain, for backward compatibility. If you have no concerns about those problems, then by all means use the XmlTextWriter. But most people would like a bit more reliability. To get that, while still suppressing namespaces during serialization, instead of deriving from XmlTextWriter, define a concrete implementation of the abstract [XmlWriter](http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx) and its 24 methods. An example is here: ``` public class XmlWriterWrapper : XmlWriter { protected XmlWriter writer; public XmlWriterWrapper(XmlWriter baseWriter) { this.Writer = baseWriter; } public override void Close() { this.writer.Close(); } protected override void Dispose(bool disposing) { ((IDisposable) this.writer).Dispose(); } public override void Flush() { this.writer.Flush(); } public override string LookupPrefix(string ns) { return this.writer.LookupPrefix(ns); } public override void WriteBase64(byte[] buffer, int index, int count) { this.writer.WriteBase64(buffer, index, count); } public override void WriteCData(string text) { this.writer.WriteCData(text); } public override void WriteCharEntity(char ch) { this.writer.WriteCharEntity(ch); } public override void WriteChars(char[] buffer, int index, int count) { this.writer.WriteChars(buffer, index, count); } public override void WriteComment(string text) { this.writer.WriteComment(text); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { this.writer.WriteDocType(name, pubid, sysid, subset); } public override void WriteEndAttribute() { this.writer.WriteEndAttribute(); } public override void WriteEndDocument() { this.writer.WriteEndDocument(); } public override void WriteEndElement() { this.writer.WriteEndElement(); } public override void WriteEntityRef(string name) { this.writer.WriteEntityRef(name); } public override void WriteFullEndElement() { this.writer.WriteFullEndElement(); } public override void WriteProcessingInstruction(string name, string text) { this.writer.WriteProcessingInstruction(name, text); } public override void WriteRaw(string data) { this.writer.WriteRaw(data); } public override void WriteRaw(char[] buffer, int index, int count) { this.writer.WriteRaw(buffer, index, count); } public override void WriteStartAttribute(string prefix, string localName, string ns) { this.writer.WriteStartAttribute(prefix, localName, ns); } public override void WriteStartDocument() { this.writer.WriteStartDocument(); } public override void WriteStartDocument(bool standalone) { this.writer.WriteStartDocument(standalone); } public override void WriteStartElement(string prefix, string localName, string ns) { this.writer.WriteStartElement(prefix, localName, ns); } public override void WriteString(string text) { this.writer.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { this.writer.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteValue(bool value) { this.writer.WriteValue(value); } public override void WriteValue(DateTime value) { this.writer.WriteValue(value); } public override void WriteValue(decimal value) { this.writer.WriteValue(value); } public override void WriteValue(double value) { this.writer.WriteValue(value); } public override void WriteValue(int value) { this.writer.WriteValue(value); } public override void WriteValue(long value) { this.writer.WriteValue(value); } public override void WriteValue(object value) { this.writer.WriteValue(value); } public override void WriteValue(float value) { this.writer.WriteValue(value); } public override void WriteValue(string value) { this.writer.WriteValue(value); } public override void WriteWhitespace(string ws) { this.writer.WriteWhitespace(ws); } public override XmlWriterSettings Settings { get { return this.writer.Settings; } } protected XmlWriter Writer { get { return this.writer; } set { this.writer = value; } } public override System.Xml.WriteState WriteState { get { return this.writer.WriteState; } } public override string XmlLang { get { return this.writer.XmlLang; } } public override System.Xml.XmlSpace XmlSpace { get { return this.writer.XmlSpace; } } } ``` Then, provide a derived class that overrides the StartElement method, as before: ``` public class NamespaceSupressingXmlWriter : XmlWriterWrapper { //Provide as many contructors as you need public NamespaceSupressingXmlWriter(System.IO.TextWriter output) : base(XmlWriter.Create(output)) { } public NamespaceSupressingXmlWriter(XmlWriter output) : base(XmlWriter.Create(output)) { } public override void WriteStartElement(string prefix, string localName, string ns) { base.WriteStartElement("", localName, ""); } } ``` And then use this writer like so: ``` var o2= new MyTypeWithNamespaces { ..intializers.. }; var builder = new System.Text.StringBuilder(); var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent= true }; using ( XmlWriter innerWriter = XmlWriter.Create(builder, settings)) using ( XmlWriter writer = new NamespaceSupressingXmlWriter(innerWriter)) { s2.Serialize(writer, o2, ns2); } Console.WriteLine("{0}",builder.ToString()); ``` Credit for this to [Oleg Tkachenko](http://www.tkachenko.com/blog/archives/000584.html).
Omitting all xsi and xsd namespaces when serializing an object in .NET?
[ "", "c#", ".net", "xml-serialization", "" ]
The following code is used for playing a sound file in my java applet: ``` public synchronized void play() { try { //Here filename is a URL retreived through //getClassLoader().getResource() InputStream in = new FileInputStream(filename.getFile()); AudioStream as = new AudioStream(in); AudioPlayer.player.start(as); } catch (IOException e) { e.printStackTrace(); } ``` It works when i run the applet locally using Eclipse, but if I try packaging it in a .jar and running it as an applet in the web browser, it doesn't work. Commenting out this code makes the applet work. What shall I substitute the above code with so it'll work in the applet?
Try using getResourceAsStream() on the ClassLoader instead of new FileInputStream(). This will return an InputStream that you can pass to the AudioStream. So something like: ``` InputStream in = getClassLoader().getResourceAsStream(getClassLoader().getResource()); AudioStream as = new AudioStream(in) ```
Either use [ClassLoader.getResourceAsStream](http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream(java.lang.String)) or [URL.openStream](http://java.sun.com/javase/6/docs/api/java/net/URL.html#openStream()). Remember to close your streams to avoid resource leaks. Alternatively, check to see if the [AudioClip](http://java.sun.com/javase/6/docs/api/java/applet/AudioClip.html) class suits your needs: ``` private AudioClip sound = null; private AudioClip getSound() { if (sound == null) { ClassLoader classLoader = TestApplet.class .getClassLoader(); URL url = classLoader.getResource("assets/sound.wav"); sound = JApplet.newAudioClip(url); } return sound; } ```
What to replace this java code with?
[ "", "java", "applet", "audio", "" ]
My team has recently started using [Lance Hunt's C# Coding Standards](http://weblogs.asp.net/lhunt/pages/CSharp-Coding-Standards-document.aspx) document as a starting point for consolidating our coding standards. There is one item that we just don't understand the point of, can anyone here shed any light on it? The item is number 77: > *Always validate an enumeration > variable or parameter value before > consuming it. They may contain any > value that the underlying Enum type > (default int) supports.* > > *Example:* > > ``` > public void Test(BookCategory cat) > { > if (Enum.IsDefined(typeof(BookCategory), cat)) > {…} > } > ```
I think the comments above pretty much answered the question. Essentially, when I wrote this rule I was trying to convey a defensive coding practice of validating all inputs. Enums are a special case because many developers incorrectly assume that they are validated, when they are not. As a result, you will often see if statements or switch statements fail for an undefined enum value. Just keep in mind that by default an enum is nothing more than a wrapper around an INT, and validate it just as if it were an int. For a more detailed discussion of proper enum usage, you might check out blog posts by Brad Abrams and Krzysztof Cwalina or their excellent book "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries"
The point is that you might hope that by having a parameter of type BookCategory, you'd always have a *meaningful* book category. That isn't the case. I could call: ``` BookCategory weirdCategory = (BookCategory) 123456; Test(weirdCategory); ``` If an enum is meant to represent a well-known set of values, code shouldn't be expected to sensibly handle a value outside that well-known set. The test checks whether the argument is appropriate first. I'd personally reverse the logic though: ``` public void Test(BookCategory cat) { if (!Enum.IsDefined(typeof(BookCategory), cat)) { throw new ArgumentOutOfRangeException("cat"); } } ``` In C# 3 this can easily be done with an extension method: ``` // Can't constrain T to be an enum, unfortunately. This will have to do :) public static void ThrowIfNotDefined<T>(this T value, string name) where T : struct { if (!Enum.IsDefined(typeof(T), value)) { throw new ArgumentOutOfRangeException(name); } } ``` Usage: ``` public void Test(BookCategory cat) { cat.ThrowIfNotDefined("cat"); } ```
Lance Hunt's C# Coding Standards - enum confusion
[ "", "c#", ".net", "coding-style", "" ]
[![alt text](https://i.stack.imgur.com/TH6TL.png)](https://i.stack.imgur.com/TH6TL.png) (source: [ctho.org](http://www.ctho.org/blog/wp-content/uploads/2008/10/error-dialog.png)) is there a similar control for c# i am trying to create a uploading app that will display further detail's of status on the update if the user clicks the details button but i dont know the name of that c# control and i fiddle a little with the panel control and coudnt find any options for it anybody know a name for it or a technique that will achieve the same behavior? EDIT: yes it's a desktop application windows specifically.
There isn't a WinForms control that imitates that functionality natively. You'll have to roll your own in one form or another, or find a third-party control. One somewhat similar control that you might be able to coerce into doing your bidding is a SplitContainer oriented horizontally. If you wire up a button to switch the visibility on the top panel on and off, that would produce an "expanding/hiding" sort of effect.
I don't know of any control that does this because, frankly, it's so simple to implement yourself. Just put a button on your form that says "more details", and in the OnClick event change the size of the panel (and form if necessary), marking the controls you want visible at the same time.
C# expanding panel
[ "", "c#", "" ]
### Background In some sufficiently large applications, you can spend more time figuring out how to drill down to the various layers than you do actually debugging: That's the case with a piece of software I work on now. Layout/separation of concerns issues aside, it'd be nice to have a breakpoint plug-in that would allow you to load breakpoints depending on which Bugzilla/Jira/Fogbugz/SVN defect entry you're working off of. ### Question Do any plug-ins exist for Visual Studio that allow you to 'save' toggled breakpoints to a file, allowing you to load various breakpoints depending on what bug you're working on? As an adjunct to that question; if there aren't any such plug-ins, can anyone point me to a 'good' (quite a subjective term, but in this case I mean explanatory and useful) resource on creating plug-ins for Visual Studio?
How about this: "[Debugger Settings Visual Studio Add In– Easily Copy Breakpoints between Machines](https://www.wintellect.com/debugger-settings-visual-studio-add-in-easily-copy-breakpoints-between-machines/)"?
It seems that Visual Studio 2010 (Professional) has added an "export breakpoints to file" function. (You can find it in the Breakpoints window.)
Is there a Breakpoint Plugin for Visual Studio?
[ "", "c#", ".net", "visual-studio", "visual-studio-2008", "plugins", "" ]
I get "database table is locked" error in my sqlite3 db. My script is single threaded, no other app is using the program (i did have it open once in "SQLite Database Browser.exe"). I copied the file, del the original (success) and renamed the copy so i know no process is locking it yet when i run my script everything in table B cannot be written to and it looks like table A is fine. Whats happening? -edit- I fixed it but unsure how. I notice the code not doing the correct things (i copied the wrong field) and after fixing it up and cleaning it, it magically started working again. -edit2- Someone else posted so i might as well update. I think the problem was i was trying to do a statement with a command/cursor in use.
I have run into this problem before also. It occurs often when you have a cursor and connection open and then your program crashes before you can close it properly. In some cases the following function can be used to make sure that the database is unlocked, even after it was not properly committed and closed beforehand: ``` from sqlite3 import dbapi2 as sqlite def unlock_db(db_filename): """Replace db_filename with the name of the SQLite database.""" connection = sqlite.connect(db_filename) connection.commit() connection.close() ```
Maybe your application terminated prematurely after a SQLite transaction began. Look for stale `-journal` files in the directory and delete them. It might be worth skimming through the [documentation](http://www.sqlite.org/lockingv3.html) as well.
python, sqlite error? db is locked? but it isnt?
[ "", "python", "sqlite", "locking", "" ]
I've noticed as soon as I added joins to some of my queries the time it took to execute these was more than just completing multiple queries. Times include page load and averaged over 20 page loads. 7-9 queries with no joins 159ms 3 queries with 2 joins 235ms Should I just go ahead with multiple queries instead of the joins considering they seem to have such a significant impact on performance? I can probably even optimize the multiple query method since I was even lazy loading during those tests. **EDIT** I'll create some false information for sake of the question. Table Objects ID (int, identity, PK, clustered index) UserID (int, nonclustered index) CategoryID (int, nonclustered index) Table Users ID (int, identity, PK, clustered index) Table Categories ID (int, identity, PK, clustered index) Pretty simple. It's a double inner-join query onto the Objects table. Querying all 3 separately seems to be faster than the join. The query plan for the join shows 42% done for 2 clustered index seeks and 23% is a clustered index scan and the rest is a Top N Sort.
If you're doing joins for no reason, sure. Usually the reason you're joining tables is to be able to pull related data and deal with it. Your question above doesn't also take into account the programmatic time you're going to need to pull that data back together (probably via a loop structure or something like that). Query analysis should be the first step here. I'm not very familiar with your particular flavor of SQL, but it would likely be something like EXPLAIN. If I had to give a likely culprit based on the limited information I have here, it would be missing indexes. Are the fields you're joining on indexed properly? This can garner HUGE performance gains. Second, are you joining on proper fields? For instance, if you're joining two strings together, your performance is going to be much worse than joining an integer or other optimized field.
No, you should actually try to go the other way instead. You should try to have as few queries as possible. When done correctly, that is the fastest. Check that you have proper indexes on the table. For example, for a query like this: ``` select a.Some, b.Other from TableA a inner join TableB b on b.Id = a.Id ``` You should make sure that there is an index on the TableB.Id field. The primary key of a table normally gets an index by default, but other indexes you have to create yourself.
Multiple queries to avoid joins?
[ "", "sql", "linq-to-sql", "" ]
I have a `double[][]` that I want to convert to a CSV string format (i.e. each row in a line, and row elements separated by commas). I wrote it like this: ``` public static string ToCSV(double[][] array) { return String.Join(Environment.NewLine, Array.ConvertAll(array, row => String.Join(",", Array.ConvertAll(row, x => x.ToString()))); } ``` Is there a more elegant way to write this using LINQ? (I know, one could use temporary variables to make this look better, but this code format better conveys what I am looking for.)
This is compatible with any nested sequences of `double`. It also defers the `ToString` implementation to the caller, allowing formatting while avoiding messy `IFormatProvider` overloads: ``` public static string Join(this IEnumerable<string> source, string separator) { return String.Join(separator, source.ToArray()); } public static string ToCsv<TRow>(this IEnumerable<TRow> rows, Func<double, string> valueToString) where TRow : IEnumerable<double> { return rows .Select(row => row.Select(valueToString).Join(", ")) .Join(Environment.NewLine); } ```
You can, but I wouldn't personally do all the lines at once - I'd use an iterator block: ``` public static IEnumerable<string> ToCSV(IEnumerable<double[]> source) { return source.Select(row => string.Join(",", Array.ConvertAll(row, x=>x.ToString()))); } ``` This returns each line (the caller can then `WriteLine` etc efficiently, without buffering everything). It is also now callable from any source of `double[]` rows (including but not limited to a jagged array). Also - with a local variable you could use `StringBuilder` to make each line slightly cheaper. --- To return the entire string at once, I'd optimize it to use a single `StringBuilder` for all the string work; a bit more long-winded, but much more efficient (far fewer intermediate strings): ``` public static string ToCSV(IEnumerable<double[]> source) { StringBuilder sb = new StringBuilder(); foreach(var row in source) { if (row.Length > 0) { sb.Append(row[0]); for (int i = 1; i < row.Length; i++) { sb.Append(',').Append(row[i]); } } } return sb.ToString(); } ```
Can I rewrite this more elegantly using LINQ?
[ "", "c#", "linq", "linq-to-objects", "" ]
Can I have a great list of common C++ optimization practices? What I mean by optimization is that you have to modify the source code to be able to run a program faster, not changing the compiler settings.
Two ways to write better programs: **Make best use of language** 1. Code Complete by Steve McConnell 2. Effective C++ 3. Exceptional C++ **profile your application** 1. Identify what areas of code are taking how much time 2. See if you can use better data structures/ algorithms to make things faster There is not much language specific optimization one can do - it is limited to using language constructs (learn from #1). The main benefit comes from #2 above.
I will echo what others have said: a better algorithm is going to win in terms of performance gains. That said, I work in image processing, which as a problem domain can be stickier. For example, many years ago I had a chunk of code that looked like this: ``` void FlipBuffer(unsigned char *start, unsigned char *end) { unsigned char temp; while (start <= end) { temp = _bitRev[*start]; *start++ = _bitRev[*end]; *end-- = temp; } } ``` which rotates a 1-bit frame buffer 180 degrees. \_bitRev is a 256 byte table of reversed bits. This code is about as tight as you can get it. It ran on an 8MHz 68K laser printer controller and took roughly 2.5 seconds for a legal sized piece of paper. To spare you the details, the customer couldn't bear 2.5 seconds. The solution was an identical algorithm to this. The difference was that 1. I used a 128K table and operated on words instead of bytes (the 68K is much happier on words) 2. I used Duff's device to unroll the loop as much as would fit within a short branch 3. I put in an optimization to skip blank words 4. I finally rewrote it in assembly to take advantage of the sobgtr instruction (subtract one and branch on greater) and have "free" post increment and pre-decrements in the right places. So 5x: no algorithm change. The point is that you also need to understand your problem domain and what bottlenecks means. In image processing, algorithm is still king, but if your loops are doing extra work, multiply that work by several million and that's the price you pay.
List of common C++ Optimization Techniques
[ "", "c++", "c", "optimization", "gcc", "g++", "" ]
What is the best way to post a Button Press to a component? I tried using the Robot class and it works, normally. However, this class has some problems under some Linux platforms, so I wonder what is the best Java-only way to post an event to a component. In this particular case, I want to post backspace events to a JTextField when I press a button. **EDIT: I've used the Robot class after all. I fixed the problem that prevented this class from working correctly under Linux**
I ended up using the robot class, which was the easiest way after all. The problem is that in the specific Linux distro I was using, the instantiation of the Robot class would hang the Virtual Machine. Looking at the log files I found out that java was trying to load a DLL that wasn't available: libXi.so.6 After adding this library to the distro I was able to continue
You can find example of such key post event, like in [this class](http://www.koders.com/java/fid0A047C32296B5D1311C4B7D28D7A663F37068D02.aspx?s=backspace+dispatchEvent#L52) Those posts are using the [dispatchEvent()](http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Component.html#dispatchEvent%28java.awt.AWTEvent%29) function ``` public void mousePressed(MouseEvent event) { KeyboardButton key = getKey(event.getX(), event.getY()); [...] KeyEvent ke; Component source = Component.getFocusComponent(); lastPressed = key; lastSource = source; key.setPressed(true); if(source != null) { if((key == k_accent || key == k_circle) && (lastKey instanceof KeyboardButtonTextJapanese)) { int accent = ((KeyboardButtonTextJapanese)lastKey).getAccent(); if(accent >= 1 && key == k_accent) { /* ** First send a backspace to delete the previous character, then send the character with the accent. */ source.dispatchEvent(new KeyEvent(source, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, k_backspace.getKeyEvent(), k_backspace.getKeyChar())); source.dispatchEvent(new KeyEvent(source, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, k_backspace.getKeyEvent(), k_backspace.getKeyChar())); ```
Post a KeyEvent to the focused component
[ "", "java", "swing", "events", "" ]
I have a good understanding of OO from java and C# and I'm lucky in my engineering courses to have been exposed to the evils of both assembler and C (pointers are my playground :D ). However, I've tried looking into C++ and the thing that gets me is the library code. There are so many nice examples of how to perform the bread and butter tasks in java and C#, but I've not been able to find a good explanation of how to do these things in C++. I'd love to expand my knowledge into C++ to add to my skillset but I've not had a chance to be exposed to people and communities that are keen on these things. Could anyone here recommend some good open source projects or tutorials which are useful. Bonus marks if they involve coming from java or C# into this environment.
I'd suggest that you work your way through the excellent Andrew Koenig and Barbara Moo book "Accelerated C++" ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/020170353X)). This book teaches you C++ rather than assume that you know C and then look at the C++ bits bolted on. In fact, you dive in and are using STL containers in the early chapters. Highly recommended.
As well as the other answers here, I think you should take a look at the [QT](http://en.wikipedia.org/wiki/Qt_(toolkit)) toolkit. Not only does it have GUI widgets, it also has libraries to work with things like databases, multithreading and sockets. A combination of BOOST and QT, IMHO, provides you with the tools to address in C++ any problem you might be faced with.
C++ for the C# Programmer
[ "", "c++", "programming-languages", "" ]
Is there a cost associated with overloading methods in .Net? So if I have 3 methods like: ``` Calculate (int) Calculate (float) Calculate (double) ``` and these methods are called at runtime "dynamically" based on what's passed to the Calculate method, what would be the cost of this overload resolution? Alternatively I could have a single Calculate and make the difference in the method body, but I thought that would require the method to evaluate the type every time it's called. Are there better ways/designs to solves this with maybe no overhead? Or better yet, what's the best practice to handle cases like these? I want to have the same class/method name, but different behaviour. EDIT: Thanks all. Jusdt one thing if it's any different. I was wondering say you have a DLL for these methods and a program written in C# that allows the user to add these methods as UI items (without specifying the type). So the user adds UI item Calculate (5), and then Calculate (12.5), etc, and the C# app executes this, would there still be no overhead?
As far as the runtime is concerned these are **different methods**. Is the same as writing: ``` CalculateInt(int) CalculateFloat(float) ``` Regarding the performance issues, except **very** special cases, you can safely ignore the method call overhead.
This question is about method overloading, not polymorphism. As far as I know, there isn't a penalty for method overloading, since the compiler will figure out which method to call at compile time based on the type of the argument being pass to it. Polymorphism only comes into play where you are using a derived type as a substitute for a base class.
Method Overloading Cost In .Net
[ "", "c#", ".net", "methods", "overloading", "" ]
Say I have a variable named `choice` it is equal to 2. How would I access the name of the variable? Something equivalent to ``` In [53]: namestr(choice) Out[53]: 'choice' ``` for use in making a dictionary. There's a good way to do this and I'm just missing it. EDIT: The reason to do this is thus. I am running some data analysis stuff where I call the program with multiple parameters that I would like to tweak, or not tweak, at runtime. I read in the parameters I used in the last run from a .config file formated as ``` filename no_sig_resonance.dat mass_peak 700 choice 1,2,3 ``` When prompted for values, the previously used is displayed and an empty string input will use the previously used value. My question comes about because when it comes to writing the dictionary that these values have been scanned into. If a parameter is needed I run `get_param` which accesses the file and finds the parameter. I think I will avoid the problem all together by reading the .`config` file once and producing a dictionary from that. I avoided that originally for... reasons I no longer remember. Perfect situation to update my code!
If you insist, here is some horrible inspect-based solution. ``` import inspect, re def varname(p): for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]: m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) if m: return m.group(1) if __name__ == '__main__': spam = 42 print varname(spam) ``` I hope it will inspire you to reevaluate the problem you have and look for another approach.
### To answer your original question: ``` def namestr(obj, namespace): return [name for name in namespace if namespace[name] is obj] ``` Example: ``` >>> a = 'some var' >>> namestr(a, globals()) ['a'] ``` As [@rbright already pointed out](https://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python/592809#592809) whatever you do there are probably better ways to do it.
How can you print a variable name in python?
[ "", "python", "dictionary", "variables", "introspection", "" ]
I have the following code which I am are currently using .... Basically, this method assigns the correct boolean flag (TRUE/FALSE) for each Task. As more and more tasks need to be added .. I can see that the switch statement will have to grow to cater for every task. There has to be an easier way ... to keep the method small. Code: (forget naming convention, it has been changed for posting) ``` public ClassStructure.User AssignTaskStatusToUser(ClassStructure.User, List<ClassStructure.Tasks> TaskStatus) { foreach (ClassStructure.Tasks data in TaskStatus) { string Task_CallID = data.Task_Call_ID; switch (Task_CallID) { case ClassStructure.Tasks_CallIDs_Strings.TASK1: User.TASK1 = data.Task_Flag; break; case ClassStructure.Tasks_CallIDs_Strings.TASK2: User.TASK2 = data.Task_Flag; break; case ClassStructure.Tasks_CallIDs_Strings.TASK3: User.TASK3 = data.Task_Flag; break; } } return User; } ``` ClassStructure.Tasks\_CallIDs\_Strings = String Representation of the Tasks data.Task\_Flag = boolean User.TASKX = boolean Any feedback is welcome. I am sure there is an easy solution.
For a lot of values like these, I would use a map something like this: ``` Dictionary<ClassStructure.Tasks_CallIDs_Strings, Task_Flag> ``` and retrieve values by mapping the CallIDs strings. Edit: As everyone can now see, the real problem of refactoring this example lies in refactoring User.TASKX. Making it a list should suffice - as it could then be indexed by the same string **ClassStructure.Tasks\_CallIDs\_Strings**
I was thinking something like this - but maybe I missed the point of what it is all for? ``` public class User { private Dictionary<string,Task> tasks; internal Dictionary<string,Task> Tasks { get { return tasks; } set { tasks = value; } } internal void AddTask(Task task) { tasks.Add(task.Task_Call_ID,task); } internal void AddTasks(List<Task> task) { foreach(Task task in Tasks) { tasks.Add(task.Task_Call_ID,task); } } } ``` The Task class could have properties that allowed you to pass a function pointer (to the function that actually executes a task) if you needed that kind of flexibility - and you could add other methods like ExecuteTasks to User as well...
Refactor my C# code - Switch statement
[ "", "c#", "refactoring", "switch-statement", "" ]
If I run a python source file through pygments, it outputs html code whose elements class belong to some CSS file pygments is using. Could the style attributes be included in the outputted html so that I don't have to provide a CSS file?
By setting the **noclasses** attribute to **True**, only inline styles will be generated. Here's a snippet that does the job just fine: ``` formatter = HtmlFormatter(style=MyStyle) formatter.noclasses = True print highlight(content,PythonLexer(),formatter) ```
@Ignacio: quite the opposite: ``` from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter code = 'print "Hello World"' print highlight(code, PythonLexer(), HtmlFormatter(noclasses=True)) ``` [ ref.: <http://pygments.org/docs/formatters/>, see HtmlFormatter ] ( Basically it is the same as Tempus's answer, I just thought that a full code snippet may save a few seconds ) ) PS. The ones who think that the original question is ill-posed, may imagine e.g. the task of pasting highlighted code into a blog entry hosted by a third-party service.
How can I customize the output from pygments?
[ "", "python", "html", "css", "pygments", "" ]
If you plan to write a very computationally intensive parallel application, what guidelines would you use to design your objects (whether classes or structs, or anything else) to maximize your potential of getting the most out of the parallelism. I am thinking of an application that say interprets/compiles a tree-like graph of objects that require creating stuff, passing it to another object to be processed, and so on, with tree like structure. What should one consider from the early design process?
If you're creating stuff and then passing it to be processed then almost surely you can design your application to make use of [message passing](http://en.wikipedia.org/wiki/Message_passing) and **object isolation.** First step will be identify responsibilities, that is, identifying who is gonna handle what. Every who is rounded by a box. Second step will be defining the information flow between your boxes, that is, if A produces X... who consumes it? After that two steps you'll have a **simple graph with leafs representing workers and arrows representing messages.** Every arrow represents a **dependency order** (that is, if an arrow goes from A to B then A needs to be executed before B). With this you'll be able to easily see what actions can be made parallel and what actions are indeed sequential in a graphical easy to see, easy to show way. Then just implement a [Pipe](http://www.stackframe.net/en/content/06-2008/data-types-pipe) structure to let you **pass messages between workers** so that every worker has a pipeline of work. On a final note: Once the original design is done, it's relatively easy to refactor it in order to improve. For example, nodes which make the same work can share work PIPES, so that 8 syntax analyzer consume from the "lexic token" pipe, or change it so that workers can "steal" work from other workers pipes, etc.
If you can get away with using a lot of immutable data structures, that will save you a lot of time, typing, and headache.
Planning for parallelism
[ "", "c#", ".net", "parallel-processing", "" ]
I have a class, which I have simplified to this: ``` final class Thing { private final int value; public Thing(int value) { this.value = value; } public int getValue() { return value; } @Override public String toString() { return Integer.toString(value); } } ``` I want to sort an array of this thing. So I have created a simple copmarator: ``` private static final Comparator<Thing> reverse = new Comparator<Thing>() { public int compare(Thing a, Thing b) { return a.getValue() - b.getValue(); } }; ``` I then use the two argument form of `Arrays.sort`. This works fine for my test cases, but sometimes it goes all wrong with the array ending up in a strange but repeatable order. How can this be?
Integer overflow… or more precisely, underflow. Instead, do an explicit comparison: ``` private static final Comparator<Thing> reverse = new Comparator<Thing>() { public int compare(Thing a, Thing b) { int av = a.getValue(), bv = b.getValue(); return (av == bv) ? 0 : ((av < bv) ? -1 : +1); } }; ``` Using subtraction is fine if you are sure that the difference won't "wrap around". For example, when the values in question are constrained to be non-negative.
You cannot use minus to create the comparison. You'll overflow when the absolute difference exceeds `Integer.MAX_VALUE`. Instead, use this algorithm: ``` int compareInts( int x, int y ) { if ( x < y ) return -1; if ( x > y ) return 1; return 0; } ``` I like to have this function in a library for such purposes.
Why is my simple comparator broken?
[ "", "java", "sorting", "puzzle", "" ]
As only reference types and a few primitives (including float, but not double, I'm not sure the reason why, I'm happy to hear why) can be declared as volatile, if I wrap a double in a class then declare it as volatile (as below), will the double property be 'read write' thread safe as any other volatile, or should I still be looking at locking? ``` public class MyThreadedClass { volatile VolatileDouble voldub; } public class VolatileDouble { public double Double { get; set; } } ```
Reason why double can't be declared volatile: it's 64 bits, which makes it more than the word size on x86, which prevents it from being declared volatile in the CLI if I remember correctly. With your current answer, only the *reference* is treated as being volatile. That means the memory model will make sure it always uses the most recent reference, but it could still use a stale value. I'd go with locking if I were you, but one alternative is to use [`Interlocked.Read`](http://msdn.microsoft.com/en-us/library/system.threading.interlocked.read.aspx) and [`Interlocked.Exchange`](http://msdn.microsoft.com/en-us/library/dk0121zy.aspx) acting on longs, in conjunction with [`BitConverter.Int64BitsToDouble`](http://msdn.microsoft.com/en-us/library/system.bitconverter.int64bitstodouble.aspx) and [`BitConverter.DoubleToInt64Bits`](http://msdn.microsoft.com/en-us/library/system.bitconverter.doubletoint64bits.aspx). You could encapsulate this within a `VolatileDouble` struct. (I'd probably make it a struct rather than a class.)
To work as above, you'd need to have it immutable (no setter) - perhaps with some implicit conversion operators for convenience. Otherwise, people could change the value without changing the (volatile) reference. ``` public class MyThreadedClass { volatile Box<double> volDouble = 123.45; } public class Box<T> where T : struct { private readonly T value; public Box(T value) { this.value = value; } public T Value {get {return value;}} // explicit as nulls are a problem... public static explicit operator T(Box<T> box) { return box.value; } public static implicit operator T?(Box<T> box) { return box == null ? new T?() : new T?(box.value); } public static implicit operator Box<T>(T value) { return new Box<T>(value); } public static implicit operator Box<T>(T? value) { return value.HasValue ? new Box<T>(value.Value) : null; } } ``` Beyond that - locking would be the best option.
C# volatile double
[ "", "c#", ".net", "volatile", "" ]
I am currently using the meta http-equiv='Refresh' to automatic start PDF downloads. however this has different effect on each of the browsers. The main problem is with IE (6 & 7) once the user is redirected to the PDF if the user click the back button they are sent back to the page that initiated the download and then promptly redirect to the PDF again. Firefox on windows has a better affect but still not perfect the user gets to the download page and is redirected to the PDF. However if they use the back button the completely miss the download page. Currently Firefox on Linux has the exact effect i want. Being that the download page redirects you to the PDF and the back button from the PDF sends you back to the download page and there you stay. I have tried using the javascript setTimeout() function to delay a pop-up of the PDF however the delay does not seem to work in any browser and the pop-up does not seem to work in IE7. Has anyone implemented an elegant solution to the problem that i could use? Thanks in advance for you help
## Referrer You could check the referrer: ``` if (document.referrer != "http://homepage.com/file.pdf") { // go to the file } ``` It's a little bit more complex because you have to compare to the absolute URL of the referrer, but this shouldn't be a problem. ## Cookies You could set a cookie the first time you enter the download page. If the cookie is set (for every file another entry in the cookie) then you shouldn't redirect. A disadvantage is that if someone reloads the page (because he wants to see the file a second time) he can't access the file anymore. There are some possibilities around it: * Set a timestamp which expires in the cookie. * Add a link to the page which the user can click manually. Setting/Getting a cookie: ``` if (document.cookie && document.cookie == "I was here!") { alert(document.cookie); } else { // set a cookie document.cookie = "I was here!"; } ``` Javascript can redirect like this: ``` window.location.href = "http://www.google.com"; ```
If I understood you need right, you want to do *something like* file-shares behavior: user waits few seconds with counter and after timeout you are redirecting him to the page wich starts download. Maybe you should simply *show link* to download page instead of redirecting? This page should send headers "force-download" to avoid browser navigating on it. If someone will try to access this page directly -- check referer or headers or any other protection you can imagine (like dynamic links), maybe you already have one. This solution will allow you to avoid JS magic and should make your code cross-browser without troubles.
elegant solution for automatic downloads
[ "", "javascript", "html", "pdf", "download", "meta-tags", "" ]
Is there any way to encrypt a bytearray without using a stream??
If you are concerned about disk I/O you can use a MemoryStream. However, the RSACryptoServiceProvider class will operate on byte arrays. This class performs asymmetric encryption and decryption using an implementation of the RSA algorithm. The examples [here](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx) show how you can do this with byte arrays
In fact you don't need to use any streams at all to operate with bytes. The only thing you need is to call TransformFinalBlock() method of ICryptoTransform which can be encryptor or decryptor of any algorithm derived from SymmetricAlgorithm class ``` public class CryptoProvider { private SymmetricAlgorithm _algorithm = new RijndaelManaged(); public byte[] EncryptData(byte[] data, string password) { GetKey(password); ICryptoTransform encryptor = _algorithm.CreateEncryptor(); byte[] cryptoData = encryptor.TransformFinalBlock(data, 0, data.Length); return cryptoData; } public byte[] DecryptData(byte[] cryptoData, string password) { GetKey(password); ICryptoTransform decryptor = _algorithm.CreateDecryptor(); byte[] data = decryptor.TransformFinalBlock(cryptoData, 0, cryptoData.Length); return data; } private void GetKey(string password) { byte[] salt = new byte[8]; byte[] passwordBytes = Encoding.ASCII.GetBytes(password); int length = Math.Min(passwordBytes.Length, salt.Length); for (int i = 0; i < length; i++) salt[i] = passwordBytes[i]; Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt); _algorithm.Key = key.GetBytes(_algorithm.KeySize / 8); _algorithm.IV = key.GetBytes(_algorithm.BlockSize / 8); } } ```
.NET Encrypt bytearray
[ "", "c#", ".net", "encryption", "" ]
Suppose I declare a generic List containing values of a struct type: ``` struct MyStruct { public MyStruct(int val1, decimal val2) : this() { Val1 = val1; Val2 = val2; } public int Val1 {get; private set;} public decimal Val2 {get; private set;} } List<MyStruct> list; ``` Does the List<> store each individual value as a boxed struct, allocated individually on the heap? Or is it smarter than that?
There is no boxing. > "No, there will be no boxing. That was one of the main design goals of Generics." <http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/359cf58a-f53d-478e-bc31-1507e77c9454/> > "If a value type is used for type T, the compiler generates an implementation of the `List<T>` class specifically for that value type. That means a list element of a `List<T>` object does not have to be boxed before the element can be used, and after about 500 list elements are created the memory saved not boxing list elements is greater than the memory used to generate the class implementation." <http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx>
It isn't boxed, but the data will be a **copy** of the original, and every time you get the data out, it will copy **again**. This tends to make it easy to lose changes. As such, you should aim to not write mutable structs. Unless `MyStruct` actually represents a unit-of-measure (or similar), make it a class. And if it *is* a measure, make it immutable (no public settable members). And either way, don't expose fields! Use properties ;-p For example: ``` struct MyStruct { public MyStruct(int val1, decimal val2) { this.val1 = val1; this.val2 = val2; } private readonly int val1; private readonly decimal val2; public int Val1 {get {return val1;}} public decimal Val2 {get {return val2;}} } ``` Or alternatively (C# 3.0): ``` struct MyStruct { public MyStruct(int val1, decimal val2) : this() { Val1 = val1; Val2 = val2; } public int Val1 {get; private set;} public decimal Val2 {get; private set;} } ```
In C#, are the values in a List<struct> boxed?
[ "", "c#", "generics", "" ]
I have code that correctly finds the line number of an IMethod in Eclipse under Windows: ``` IMethod method= ...; String source= type.getCompilationUnit().getSource(); int lineNumber= 1; for (int i= 0; i < method.getSourceRange().getOffset(); i++) if (source.charAt(i) == Character.LINE_SEPARATOR) lineNumber++; ``` However, this doesn't work on the Mac, presume because the line separator character is different even though the source code it is operating on is the same. 1. is there a built-in way to get the line number without having to traverse every character of the source? (seems like there should be but I couldn't find it) 2. if not, is there a platform independent way to count line breaks in a string? Thanks, Kent Beck
I can't answer (1), but I'll give (2) a shot. Oddly enough, I think your code was only working by coincidence. [`Character.LINE_SEPARATOR`](http://java.sun.com/javase/6/docs/api/java/lang/Character.html#LINE_SEPARATOR) indicates a Unicode category; it isn't supposed to be the platform's newline character, but it *just so happens* to have the value [13](http://java.sun.com/javase/6/docs/api/constant-values.html#java.lang.Character.LINE_SEPARATOR), which (as you probably know) is [`'\r'`](http://www.asciitable.com/). If I remember correctly, Macs since OS X have used `'\n'` for newlines, so this is why it doesn't work. The way I've gotten the line separator character in the past is [`System.getProperty("line.separator")`](http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperty(java.lang.String)). This returns a `String`, so it might not be suitable. Since it seemed to work with `'\r'` on Windows, I'd guess that a simple check for `'\n'` would suffice as well. Alternatively, you could use a `BufferedReader` wrapped around a [`StringReader`](http://java.sun.com/javase/6/docs/api/java/io/StringReader.html), as Wouter Lievens suggested.
I ended up using regex instead, because it was simpler. This makes the code O(n^2) in the number of methods I need to take in the file, but I expect this should be a small number so it's acceptable for now. ``` private int getMethodLineNumber(final IType type, IMethod method) throws JavaModelException { String source= type.getCompilationUnit().getSource(); String sourceUpToMethod= source.substring(0, method.getSourceRange().getOffset()); Pattern lineEnd= Pattern.compile("$", Pattern.MULTILINE | Pattern.DOTALL); return lineEnd.split(sourceUpToMethod).length; } ``` Thank you all for the help. Regards, Kent
How to find the line number of the start of a procedure in Eclipse
[ "", "java", "eclipse", "" ]
I'm learning C++ at the moment, and I'm coming across a lot of null-terminated strings. This has got me thinking, what makes more sense when declaring pointers: ``` char* string ``` or ``` char *string ``` ? To me, the char\* format makes more sense, because the type of "string" is a pointer to a char, rather than a char. However, I generally see the latter format. This applies to references as well, obviously. Could someone tell me if there is a logical reason for the latter format?
In the following declaration: ``` char* string1, string2; ``` `string1` is a character pointer, but `string2` is a single character only. For this reason, the declaration is usually formatted like: ``` char *string1, string2; ``` which makes it slightly clearer that the `*` applies to `string1` but not `string2`. Good practice is to avoid declaring multiple variables in one declaration, especially if some of them are pointers.
Bjarne Stroustrup has [something to say about this](http://www.stroustrup.com/bs_faq2.html#whitespace): > The critical confusion comes (only) when people try to declare several pointers with a single declaration: ``` int* p, p1; // probable error: p1 is not an int* ```
What makes more sense - char* string or char *string?
[ "", "c++", "string", "pointers", "" ]
Need to develop a .NET solution to graphically represent seats in sections, plotted in a stadium layout view, and output as a report... the seats would have different colours displaying sales status...
Indeed, it might look scary at first sight, but [2D drawing](http://msdn.microsoft.com/en-us/library/system.drawing.aspx) in .NET Framework is actually easy to use. Here is a small example that draws a couple of color filled circles with antialised margin: ``` using System.Drawing; ... Font font = new Font(FontFamily.GenericMonospace, 8); Image reportImage = new Bitmap(270, 45); using (Graphics graphics = Graphics.FromImage(reportImage)) { graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; graphics.FillRectangle(Brushes.White, new Rectangle(new Point(0, 0), reportImage.Size)); for (int i = 0; i != 6; i++) { Rectangle r = new Rectangle(20 + i * 40, 15, 25, 15); graphics.FillEllipse( i % 2 == 0 ? Brushes.DarkOrange : Brushes.DarkKhaki, r); graphics.DrawEllipse(Pens.Black, r); r.Offset(2, 0); graphics.DrawString(i.ToString(), font, Brushes.Black, r); } } reportImage.Save("C:\\test.bmp"); ```
seems simple enough that regular old GDI+ might do the trick. You would of course have to set up a GUI in which each stadiums seating plan can be "mapped" by point and click.
Can any one recommend a vector graphics engine for reporting purposes?
[ "", "c#", ".net", "vector", "reporting", "" ]
I have a C++ project that compiles to different versions, including release, debug, shared library, and executable, with different compiler flags for each. I am trying out Jam as an alternative to Make, because it looks like a simpler system. Is Jam capable of this? The main problem is that it always places the .o files into the same folder as the source file, so it overwrites them when building multiple versions. ### Update I found a solution that seems to work. Using this file, I can build debug and release configurations of a library or executable. Command to build release library: ``` jam -s config=lib -s release=1 ``` If you only type `jam`, it builds the debug executable. Here is the Jamfile: ``` FILES = main.cpp ; BASENAME = steve ; OBJ = obj ; if $(release) { OBJ = $(OBJ)r ; } else { DEFINES += DEBUG ; OBJ = $(OBJ)d ; } if $(config) = lib { OBJ = $(OBJ)_lib ; OUTFILE = lib$(BASENAME).so ; DEFINES += SHARED_LIBRARY ; LINKFLAGS += -shared -Wl,-soname,$(OUTFILE) -fvisibility=hidden -fPICS ; } else { OUTFILE = $(BASENAME) ; } LOCATE_TARGET = $(OBJ) ; MkDir $(LOCATE_TARGET) ; Main $(OUTFILE) : $(FILES) ; ```
I'm not familiar with Perforce's Jam however [bjam](http://www.boost.org/doc/tools/build/index.html) allows this - and it's trivially easy. `bjam` does not place the intermediate files in the same directory as the source; it creates debug/release/static/shared directories depending on the type of project you're building. For example if you wanted to build release and debug version of a library and you wanted to build it statically: ``` bjam debug release link=static ``` `bjam` does have some quirks but we've found it very effective. Currently we're using (almost) identical build scripts to build our system using msvc (8.0 and 9.0), gcc 4.3 on x86, gcc 3.4 on ARM and gcc 4.3 for the PowerPC. Very nice.
Yes, it's capable of this. It's called 'variants', boost.build comes with 'debug' and 'release' predefined. It's also possible to add 'features' of your own, defining them as link-incompatible will put generated object files into different subdirectories: feature magic : off on : propagated composite ; feature.compose on : USE\_MAGIC ; I find the ease of maintaining co-existing variants is one of the strongest features of boost.build. Also, it's very easy to maintain project hierarchies (e.g., application requiring libraries); this is done on the file level, not by recursing into directories, making parallel builds very efficient.
How can I build different versions of a project using the Jam make tool?
[ "", "c++", "makefile", "jam", "" ]
Is there a control that will allow me to click through folders on the FS? Like the left tab after you right click a file and hit explore in explorer?
I don't think there is a control to do this for you, but it's relatively easy with the TreeView control. Check out [this example](http://www.java2s.com/Code/CSharp/GUI-Windows-Form/RecursivelyloadDirectoryinfointoTreeView.htm).
If you're asking is there a WinForms/WPF **control** that will allow you to do this then the answer is no. There is no such built-in control that can be used for this purpose. You can however open up a modal dialog which does this by using the OpenFileDialog. ``` using (var diag = new OpenFileDialog()) { var result = diag.ShowDialog(); var fileName = diag.FileName; } ```
Filesystem TreeView
[ "", "c#", "filesystems", "explorer", "" ]
I have a search form with a number of text inputs & drop downs that submits via a GET. I'd like to have a cleaner search url by removing the empty fields from the querystring when a search is performed. ``` var form = $("form"); var serializedFormStr = form.serialize(); // I'd like to remove inputs where value is '' or '.' here window.location.href = '/search?' + serializedFormStr ``` Any idea how I can do this using jQuery?
I've been looking over the [jQuery docs](http://docs.jquery.com/) and I think we can do this in one line using [selectors](http://docs.jquery.com/Selectors): ``` $("#myForm :input[value!='']").serialize() // does the job! ``` Obviously #myForm gets the element with id "myForm" but what was less obvious to me at first was that the **space character** is needed between #myForm and :input as it is the [descendant](http://docs.jquery.com/Selectors/descendant) operator. [**:input**](http://docs.jquery.com/Selectors/input) matches all input, textarea, select and button elements. [**[value!='']**](http://docs.jquery.com/Selectors/attributeNotEqual) is an attribute not equal filter. The weird (and helpful) thing is that **all :input** element types have value attributes even selects and checkboxes etc. Finally to also remove inputs where the value was '.' (as mentioned in the question): ``` $("#myForm :input[value!=''][value!='.']").serialize() ``` In this case juxtaposition, ie [placing two attribute selectors next to each other](http://docs.jquery.com/Selectors/attributeMultiple), implies an AND. [Using a comma](http://docs.jquery.com/Selectors/multiple) implies an OR. Sorry if that's obvious to CSS people!
I wasn't able to get Tom's solution to work (?), but I was able to do this using `.filter()` with a short function to identify empty fields. I'm using jQuery 2.1.1. ``` var formData = $("#formid :input") .filter(function(index, element) { return $(element).val() != ''; }) .serialize(); ```
How do I use jQuery's form.serialize but exclude empty fields
[ "", "javascript", "jquery", "forms", "serialization", "input", "" ]
I'm using DateTime.ParseExact to parse a string from input. What is the simplest way to make sure the date complies to rules like max days in a month or no 0. month?
You could do additional validation using... ``` DateTime.TryParse(); ``` <http://msdn.microsoft.com/en-us/library/9h21f14e.aspx> Hope this helps.
The answers for doing the DateTime.TryParse() are great if you are doing this check in your code behind, but if you are capturing this data on the UI, then I would highly reccomend validing the input as well before the postback to the code behind occurs. ``` <strong>Date:</strong> <asp:textbox ID="txtEnterDate" runat="server"></asp:textbox> <asp:CompareValidator ID="cvEnterDate" runat="server" ControlToValidate="txtEnterDate" ErrorMessage="Must Be Valid Date" Operator="DataTypeCheck" SetFocusOnError="True" Type="Date"></asp:CompareValidator> ```
What is the simplest way to validate a date in asp.net C#?
[ "", "c#", "asp.net", "" ]
I would like to see the structure of object in JavaScript (for debugging). Is there anything similar to var\_dump in PHP?
Most modern browsers have a console in their developer tools, useful for this sort of debugging. ``` console.log(myvar); ``` Then you will get a nicely mapped out interface of the object/whatever in the console. Check out the [`console`](https://developer.mozilla.org/en-US/docs/Web/API/Console) documentation for more details.
Most common way: ``` console.log(object); ``` However I must mention `JSON.stringify` which is useful to dump variables in non-browser scripts: ``` console.log( JSON.stringify(object) ); ``` The `JSON.stringify` function also supports built-in prettification as pointed out by *Simon Zyx*. Example: ``` var obj = {x: 1, y: 2, z: 3}; console.log( JSON.stringify(obj, null, 2) ); // spacing level = 2 ``` The above snippet will print: ``` { "x": 1, "y": 2, "z": 3 } ``` On **caniuse.com** you can view the browsers that support natively the `JSON.stringify` function: <http://caniuse.com/json> You can also use the Douglas Crockford library to add `JSON.stringify` support on old browsers: <https://github.com/douglascrockford/JSON-js> Docs for `JSON.stringify`: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify> I hope this helps :-)
What is the JavaScript equivalent of var_dump or print_r in PHP?
[ "", "javascript", "object", "dump", "var-dump", "" ]
Say I have: ``` int someValue = 42; ``` Now I want to convert that int value to a String. Which way is more efficient? ``` // One String stringValue = Integer.toString(someValue); // Two String stringValue = String.valueOf(someValue); // Three String stringValue = someValue + ""; ``` I am just curious if there is any real difference or one is better than the other?
tested it for 10m assignments of the number 10 ``` One: real 0m5.610s user 0m5.098s sys 0m0.220s Two: real 0m6.216s user 0m5.700s sys 0m0.213s Three: real 0m12.986s user 0m11.767s sys 0m0.489s ``` One seems to win Edit: JVM is standard '/usr/bin/java' under Mac OS X 10.5 ``` java version "1.5.0_16" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284) Java HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing) ``` More edit: Code as requested ``` public class One { public static void main(String[] args) { int someValue = 10; for (int i = 0; i < 10000000; i++) { String stringValue = Integer.toString(someValue); } } } ``` case 2 and 3 similarly run using ``` javac *.java; time java One; time java Two; time java Three ```
Even though according to the [measurements of cobbal](https://stackoverflow.com/questions/653990/what-is-the-most-efficient-way-to-convert-an-int-to-a-string/654031#654031), #1 seems to be the fastest, I'd strongly recommend the usage of `String.valueOf()`. My reason for that is that this call does not explicitly contain the type of the argument, so if later on you decide to change it from int to double, there is no need to modify this call. The speed gain on #1 compared to #2 is only minimal, and as we all know, "premature optimization is the root of all evil". The third solution is out of the question, since it implicitly creates a `StringBuilder` and appends the components (in this case, the number and the empty string) to that, and finally converts that to a string.
What is the most efficient way to convert an int to a String?
[ "", "java", "string", "" ]
I have a DataGridView that I'm binding to a DataTable. The DataTable is a all numeric values. There is a requirement that every n rows in the DataGridView has text in it, rather than the numeric values (to visually separate sections for the user). I am happy to put this text data in the DataTable or in the DataGridView after binding, but I can't see a way to put this text data in either as the column formats for both require numeric data - I get a "can't put a string in a decimal" error for both. Any ideas how I change the format of a particular row or cell in either the DataTable or DataGridView?
You can provide a handler for the DataGridView's `CellFormatting` event, such as: ``` public partial class Form1 : Form { DataGridViewCellStyle _myStyle = new DataGridViewCellStyle(); public Form1() { InitializeComponent(); _myStyle.BackColor = Color.Pink; // We could also provide a custom format string here // with the _myStyle.Format property } private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { // Every five rows I want my custom format instead of the default if (e.RowIndex % 5 == 0) { e.CellStyle = _myStyle; e.FormattingApplied = true; } } //... } ``` For assistance on creating your own styles, refer to the `DataGridView.CellFormatting Event` topic in the online help.
Does this solve your problem? ``` // Set the data source. dataGridView1.DataSource = dataTable1; // Create a new text box column. DataGridViewColumn c1 = new DataGridViewTextBoxColumn(); const string C1_COL_NAME = "Custom1"; c1.Name = C1_COL_NAME; // Insert the new column where needed. dataGridView1.Columns.Insert(1, c1); // Text can then be placed in the rows of the new column. dataGridView1.Rows[0].Cells[C1_COL_NAME].Value = "Some text..."; ``` The original data table bindings should still exist.
How can I create different cell formats in Winform DataGridView
[ "", "c#", "winforms", "datagridview", "" ]
I'm aware of the range iterators in boost, and as for [this reference](http://www.boost.org/doc/libs/1_37_0/libs/range/doc/boost_range.html), it seems there should be an easy way of doing what I want, but it's not obvious to me. Say I want to represent a numerical range, 0 to 100 (inclusive or not), say `range(0,100)`. I would like to do something like: ``` for_each(range<int>(0,100).begin(), range<int>(0,100).end(), do_something); ``` where `do_something` is a functor. This iterators shouldn't have the overhead of having an underneath vector or something like this, but to just offer a sequence of integers. Is this possible with the range implementation in boost? Possible at all with normal, standard STL iterators?
[boost::counting\_iterator](http://www.boost.org/doc/libs/1_38_0/libs/iterator/doc/counting_iterator.html) ``` #include <boost/iterator/counting_iterator.hpp> std::for_each( boost::counting_iterator<int>(0), boost::counting_iterator<int>(100), do_something ); ```
Just to add to the other answers if you're coming from a C++11 perspective - if you'd rather use modern for-each loops, you can do this even more cleanly with [boost counting\_range](http://www.boost.org/doc/libs/1_57_0/libs/range/doc/html/range/reference/ranges/counting_range.html): ``` #include <boost/range/counting_range.hpp> for(auto const &i : boost::counting_range(0, 10)) { std::cout << i; } ``` Outputs: > 0123456789
Numerical range iterators in boost?
[ "", "c++", "stl", "boost", "iterator", "range", "" ]
I've created a hashtable of two-dimensional arrays in c# and cannot figure out how to directly access the array values, the following is my current code: ``` // create the hashtable Hashtable hashLocOne = new Hashtable(); // add to the hashtable if we don't yet have this location if (!hashLocOne.ContainsKey(strCurrentLocationId)) hashLocOne.Add(strCurrentLocationId,new double[20, 2] { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } }); // add to the value at a given array position, this does not work hashLocAll[strReportLocationId][iPNLLine, 0] += pnl_value; ```
The Hashtable doesn't know what kind of objects are stored in it; you have to manually cast each one: ``` double result = ((double[,]) table["foo"])[4][5]; ``` You should use a Dictionary instead of a Hashtable if possible: ``` var dict = new Dictionary<String, double[,]>(); double result = dict["foo"][4][5]; ```
``` ((double[,])hashLocAll[strReportLocationId])[iPNLLine, 0] += pnl_value; ``` Why dont you use Dictionary<string, double[,]> ?
c# accessing hashtable of two-dimensional arrays
[ "", "c#", "" ]
I haven't done much work with .NET, so forgive me if this has a trivial solution. The "problem" (more of an annoyance, really) is that the VC# IDE opens all files that have a class which inherits from `System.Windows.Forms.Form` in design-view, *by default*. The only exception being "\*.Designer.cs" files. Generally speaking, this is fine. However, if I have a `partial class` that implements some control handler code, this becomes quite an annoyance. When double-clicking on the source file, for instance, you are taken to the Winforms designer and presented with an empty form. Totally useless. To get around this, you are required to right-click on the source file in question, and select "View Code" from the context menu. My question is rather simple: is there *any* frigging way to get around this absurdity? If not, I'm wondering how people organize their UI-handling code. Thanks!
Yes. In the file's context menu, select "Open With..." and use the "Set as Default" button with your prefered editor selected (in your case, probably the CSharp Editor).
Rather than right-click and view-code, I always use Doubleclick and it goes to the code page, focussed on the Form\_load event, which can be left blank and ignored. If you really want to fix the behavior, I suggest somehow making your file not be a Form! Cant blame VS for thinking you want to work with a form when you open a form's file!
Visual C#, Winforms, and Partial Class Madness
[ "", "c#", "visual-studio", "winforms", "partial-classes", "" ]
What can you do in SQL Server 2008 Standard Edition that you cannot do in SQL Server 2008 Web Edition? I've seen the Microsoft feature lists, but I am wondering from a very practicle standpoint where I am going to run into limitations.
Have you seen this matrix as well? <http://msdn.microsoft.com/en-us/library/cc645993.aspx> From what I can tell Web excludes a lot of the more advanced features, especially those related to development and data mining, but nothing that would stop you from using it for a non-enterprise web site's data source. It seems to be between the Express version and Standard version.
One of the biggest limitations is that it can't be a publisher for SQL replication. If you want to have multiple database and replication data between them, then you need at least one SQL server to be Standard or Enterprise to act as the publisher.
What cannot be done in SQL Server 2008 Web Edition?
[ "", "sql", "sql-server", "" ]
I have a structure in C#.net. I have created an object of that structure. I need to cast this object of structure into ArrayList. I am using : ``` OrderMessageStructure.OrderMessage orderToModify = new OrderMessageStructure.OrderMessage(); object neworderobject = (object)orderToModify; ArrayList arr = new ArrayList(); arr = (ArrayList)neworderobject; ``` But I am getting error "Unable to cast object of type 'OrderMessage' to type 'System.Collections.ArrayList'." How to convert object/structure into ArrayList?
Your question doesn't have quite enough information to give a sure answer. If you want to make an ArrayList of OrderMessage objects then you need to create the arraylist FIRST and then ADD instances of OrderMessage. If you want a strongly typed ArrayList of OrderMessage then use List from the Generic Namespace and ADD instances of OrderMessage to it. If your OrderMessage has an array structure in it then you will need to add a method to it that returns an arraylist. You will have to write the code converting the OrderMessage to an ArrayList.
You can't just cast any object into another object in C#. Its a type safe language. You need to create an `ArrayList` and `Add()` your struct to it. Better yet, create a `List<StructType>()` and add your struct to that. [CLR Via C#](https://rads.stackoverflow.com/amzn/click/com/0735621632). Read it. --- ``` OrderMessageStructure.OrderMessage orderToModify = new OrderMessageStructure.OrderMessage(); ArrayList arr = new ArrayList(); arr.Add(orderToModify); ```
How to cast object/structure into arraylist?
[ "", "c#", ".net", "" ]
I realize C# and .NET in general already has the Hashtable and Dictionary classes. Can anyone demonstrate in C# an implementation of a Hashtable? **Update:** To clarify, I'm not ncessarily looking for a complete implementation, just an example of the core features of a hashtable (i.e. add,remove, find by key).
There is also the Mono version of the class libraries of course: * [System.Collections.Hashtable](https://github.com/mono/mono/tree/mono-3.0.3/mcs/class/corlib/System.Collections/Hashtable.cs?view=markup) * [System.Collections.Generic.Dictionary](https://github.com/mono/mono/tree/mono-3.0.3/mcs/class/corlib/System.Collections.Generic/Dictionary.cs?view=markup)
Long after the question has been asked, so I don't expect to earn much rep. However I decided it would be fun to write my own very basic example (in less than 90 lines of code): ``` public struct KeyValue<K, V> { public K Key { get; set; } public V Value { get; set; } } public class FixedSizeGenericHashTable<K,V> { private readonly int size; private readonly LinkedList<KeyValue<K,V>>[] items; public FixedSizeGenericHashTable(int size) { this.size = size; items = new LinkedList<KeyValue<K,V>>[size]; } protected int GetArrayPosition(K key) { int position = key.GetHashCode() % size; return Math.Abs(position); } public V Find(K key) { int position = GetArrayPosition(key); LinkedList<KeyValue<K, V>> linkedList = GetLinkedList(position); foreach (KeyValue<K,V> item in linkedList) { if (item.Key.Equals(key)) { return item.Value; } } return default(V); } public void Add(K key, V value) { int position = GetArrayPosition(key); LinkedList<KeyValue<K, V>> linkedList = GetLinkedList(position); KeyValue<K, V> item = new KeyValue<K, V>() { Key = key, Value = value }; linkedList.AddLast(item); } public void Remove(K key) { int position = GetArrayPosition(key); LinkedList<KeyValue<K, V>> linkedList = GetLinkedList(position); bool itemFound = false; KeyValue<K, V> foundItem = default(KeyValue<K, V>); foreach (KeyValue<K,V> item in linkedList) { if (item.Key.Equals(key)) { itemFound = true; foundItem = item; } } if (itemFound) { linkedList.Remove(foundItem); } } protected LinkedList<KeyValue<K, V>> GetLinkedList(int position) { LinkedList<KeyValue<K, V>> linkedList = items[position]; if (linkedList == null) { linkedList = new LinkedList<KeyValue<K, V>>(); items[position] = linkedList; } return linkedList; } } ``` Here's a little test application: ``` static void Main(string[] args) { FixedSizeGenericHashTable<string, string> hash = new FixedSizeGenericHashTable<string, string>(20); hash.Add("1", "item 1"); hash.Add("2", "item 2"); hash.Add("dsfdsdsd", "sadsadsadsad"); string one = hash.Find("1"); string two = hash.Find("2"); string dsfdsdsd = hash.Find("dsfdsdsd"); hash.Remove("1"); Console.ReadLine(); } ``` It's not the best implementation, but it works for Add, Remove and Find. It uses [chaining](http://en.wikipedia.org/wiki/Hash_table#Separate_chaining) and a simple modulo algorithm to find the appropriate bucket.
What is an example of a Hashtable implementation in C#?
[ "", "c#", ".net", "hashtable", "" ]
I have an address class that uses a regular expression to parse the house number, street name, and street type from the first line of an address. This code is generally working well, but I'm posting here to share with the community and to see if anyone has suggestions for improvement. Note: The STREETTYPES and QUADRANT constants contain all of the relevant street types and quadrants respectively. I've included a subset here: ``` private const string STREETTYPES = @"ALLEY|ALY|ANNEX|AX|ARCADE|ARC|AVENUE|AV|AVE|BAYOU|BYU|BEACH|..."; private const string QUADRANTS = "N|NORTH|S|SOUTH|E|EAST|W|WEST|NE|NORTHEAST|NW|NORTHWEST|SE|SOUTHEAST|SW|SOUTHWEST"; ``` HouseNumber, Quadrant, StreetName, and StreetType are all properties on the class. ``` private void Parse(string line1) { HouseNumber = string.Empty; Quadrant = string.Empty; StreetName = string.Empty; StreetType = string.Empty; if (!String.IsNullOrEmpty(line1)) { string noPeriodsLine1 = String.Copy(line1); noPeriodsLine1 = noPeriodsLine1.Replace(".", ""); string addressParseRegEx = @"(?ix) ^ \s* (?: (?<housenumber>\d+) (?:(?:\s+|-)(?<quadrant>" + QUADRANTS + @"))? (?:(?:\s+|-)(?<streetname>\S+(?:\s+\S+)*?))?? (?:(?:\s+|-)(?<quadrant>" + QUADRANTS + @"))? (?:(?:\s+|-)(?<streettype>" + STREETTYPES + @"))? (?:(?:\s+|-)(?<streettypequalifier>(?!(?:" + QUADRANTS + @"))(?:\d+|\S+)))? (?:(?:\s+|-)(?<streettypequadrant>(" + QUADRANTS + @")))?? (?:(?:\s+|-)(?<suffix>(?:ste|suite|po\sbox|apt)\s*\S*))? | (?:(?:po|postoffice|post\s+office)\s+box\s+(?<postofficebox>\S+)) ) \s* $ "; Match match = Regex.Match(noPeriodsLine1, addressParseRegEx); if (match.Success) { HouseNumber = match.Groups["housenumber"].Value; Quadrant = (string.IsNullOrEmpty(match.Groups["quadrant"].Value)) ? match.Groups["streettypequadrant"].Value : match.Groups["quadrant"].Value; if (match.Groups["streetname"].Captures.Count > 1) { foreach (Capture capture in match.Groups["streetname"].Captures) { StreetName += capture.Value + " "; } StreetName = StreetName.Trim(); } else { StreetName = (string.IsNullOrEmpty(match.Groups["streetname"].Value)) ? match.Groups["streettypequalifier"].Value : match.Groups["streetname"].Value; } StreetType = match.Groups["streettype"].Value; //if the matched street type is found //use the abbreviated version...especially for credit bureau calls string streetTypeAbbreviation; if (StreetTypes.TryGetValue(StreetType.ToUpper(), out streetTypeAbbreviation)) { StreetType = streetTypeAbbreviation; } } } } ```
I don't know what country you're in, but if you're in the USA and want to spend some money on address validation, you can buy related USPS products [here](http://www.usps.com/ncsc/addressinfo/addressinfomenu.htm?from=zclsearch&page=ais&WT.z_zip4link=AIS). And [here](http://www.usps.com/ncsc/lookups/usps_abbreviations.htm) is a good place to find free word lists from the USPS for expected words and abbreviations. I'm sure similar pages are available for other countries.
Have fun with addresses and regexs, you're in for a long, horrible ride. You're trying to lay order upon chaos. For every "123 Simple Way", there's a "14 1/2 South". Then, for extra laughs, there's Salt Lake City: "855 South 1300 East". Have fun with that. There are more exceptions than rules when it comes to street adresses.
Regular expression for parsing mailing addresses
[ "", "c#", "regex", "" ]
I'm revisiting and re-implementing the code that caused me to ask [this question](https://stackoverflow.com/questions/15917/data-auditing-in-nhibernate-and-sqlserver) about data auditing in NHibernate. However this time, I want go with [Sean Carpenter](https://stackoverflow.com/users/729/sean-carpenter)'s [suggestion](https://stackoverflow.com/questions/15917/data-auditing-in-nhibernate-and-sqlserver/142767#142767) and implement the ISaveOrUpdateEventListener (new in NHibernate 2.x) I want to add a row in a database for each change to each property with the old value and the new so later on in the UI I can say stuff like *"User Bob changed Wibble's Property from A to B on 9th March 2009 at 21:04"* What's the best way to compare the object state to work out which of the object's properties have changed? You can get the loaded state of the object by the following: ``` public void OnSaveOrUpdate(SaveOrUpdateEvent saveOrUpdateEvent) { object[] foo = saveOrUpdateEvent.Entry.LoadedState; } ``` And I suppose I could use reflection to work out which properties have changed, but I've been digging around and there doesn't seem to be a matching set of properties to compare. I would've thought there would a GetChangedProperties() method or something. I could always get the old object from the database as it is and compare it, but that's yet another database hit and would seem heavy handed in this scenario. What's the best direction to take with this? P.S. In case it makes any difference, this is an ASP.NET-MVC / S#arp Architecture project.
I would not know how to achieve what you want with the `ISaveOrUpdateListener` interface - you could however take advantage of the fact that `IPreUpdateEventListener` and `IPreInsertEventListener` interfaces both provide what you need... e.g. do something like this: ``` public bool OnPreUpdate(PreUpdateEvent evt) { string[] names = evt.Persister.PropertyNames; for(int index = 0; index < names.Length; index++) { // compare evt.State[index] to evt.OldState[index] and get // the name of the changed property from 'names' // (...) } } ``` and do the same thing for pre insert.
You could also use the FindDirty method on the Persister to let NHibernate do the comparisons for you: ``` var dirtyFieldIndexes = @event.Persister.FindDirty(@event.State, @event.OldState, @event.Entity, @event.Session); foreach (var dirtyFieldIndex in dirtyFieldIndexes) { var oldValue = @event.OldState[dirtyFieldIndex]; var newValue = @event.State[dirtyFieldIndex]; // Log values to new "AuditLog" object and save appropriately. } ```
Data Auditing in NHibernate using events
[ "", "c#", ".net", "nhibernate", "reflection", "" ]
How can I implement jquery in my Zend Framework application in a custom manner. * appending jquery.js **ok** * appending script **ok** * send POST data to controller **ok** * process POSTed data **ok** * send 'AjaxContext' respond to client **now ok** (thanks) I'm using jquery for the first time, what am I doing wrong?
Early on, the best practice to get Zend to respond to ajax requests without the full layout was to check a variable made available via request headers. According to the [documentation](http://framework.zend.com/manual/en/zend.controller.request.html#zend.controller.request.http.ajax) many client side libraries including jQuery, Prototype, Yahoo UI, MockiKit all send the the right header for this to work. ``` if($this->_request->isXmlHttpRequest()) { //The request was made with via ajax } ``` However, modern practice, and what you're likely looking for, is now to use one of two new helpers: * [ContextSwitcher](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch) * **[AjaxContent](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch.ajaxcontext)** Which make the process considerably more elegant. ``` class CommentController extends Zend_Controller_Action { public function init() { $ajaxContext = $this->_helper->getHelper('AjaxContext'); $ajaxContext->addActionContext('view', 'html') ->initContext(); } public function viewAction() { // Pull a single comment to view. // When AjaxContext detected, uses the comment/view.ajax.phtml // view script. } ``` **Please Note:** This modern approach **requires** that you request a format in order for the context to be triggered. It's not made very obvious in the documentation and is somewhat confusing when you end up just getting strange results in the browser. ``` /url/path?format=html ``` Hopefully there's a workaround we can discover. Check out the [full documentation](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch.ajaxcontext) for more details.
Make sure your using `$(document).ready()` for any jQuery events that touch the DOM. Also, check the javascript/parser error console. In Firefox it's located in Tools->Error Console. And if you don't already have it installed, I would highly recommend [Firebug](http://getfirebug.com).
How can I implement jquery in my Zend Framework application in a custom manner?
[ "", "php", "jquery", "zend-framework", "" ]
Is there a Java library to access the native Windows API? Either with COM or JNI.
You could try these two, I have seen success with both. <http://jawinproject.sourceforge.net> > The Java/Win32 integration project > (Jawin) is a free, open source > architecture for interoperation > between Java and components exposed > through Microsoft's Component Object > Model (COM) or through Win32 Dynamic > Link Libraries (DLLs). <https://github.com/twall/jna/> > JNA provides Java programs easy access > to native shared libraries (DLLs on > Windows) without writing anything but > Java code—no JNI or native code is > required. This functionality is > comparable to Windows' Platform/Invoke > and Python's ctypes. Access is dynamic > at runtime without code generation. > > JNA allows you to call directly into > native functions using natural Java > method invocation. The Java call looks > just like it does in native code. Most > calls require no special handling or > configuration; no boilerplate or > generated code is required. Also read up here: <http://en.wikipedia.org/wiki/Java_Native_Interface> > The Java Native Interface (JNI) is a > programming framework that allows Java > code running in a Java Virtual Machine > (JVM) to call and to be called[1](https://github.com/twall/jna/) by > native applications (programs specific > to a hardware and operating system > platform) and libraries written in > other languages, such as C, C++ and > assembly. <http://en.wikipedia.org/wiki/Java_Native_Access> > Java Native Access provides Java > programs easy access to native shared > libraries without using the Java > Native Interface. JNA's design aims to > provide native access in a natural way > with a minimum of effort. No > boilerplate or generated glue code is > required.
[JNA](https://github.com/twall/jna/#getting_started) is pretty nice. I'm just a beginner and I found it very easy. Works not only for the Win32 API but for almost any other DLL.
Is there a Java library to access the native Windows API?
[ "", "java", "windows", "winapi", "" ]
I have a queue of uniform message objects with multiple producers and a single consumer. The consumer is publishing the information and needs to be able to grant access based on the data's origin, so I want the producer send a suitable identifier along with the message. The producers themselves can't be responsible for the far side access restrictions. The id should relate to the role of the producer in my application. I want to enforce that all producers have to define one and that a subclassed producer may choose to inherit or redefine it. The producer's class name would be a good approximation, but the property I want to identify is not really inherent in the class structure, it's rather something I define. I could use reflection to find out the class name or maybe an interface name, but this smells of too much overhead. Also, I'm unsure what the appropriate property would be to look for. As all producers subclass the same abstract parent class, I thought a good way would be to put a constant in there (or in an interface), but then I realised that in Java, a "constant" is really a "static final", which means I can't override it, so it doesn't work that way. How would a more experienced Java programmer do this?
If there's a "type" that you need to identify, define an interface that forces a class to give you that type, then implement that interface everywhere. Example: ``` public interface IHasType { public String getTypeId(); } ``` However, if the list of types is fixed, I would go one step further and make the type an `Enum`: ``` public enum MyType { TYPE_A, TYPE_B; } ``` And then return this `enum` instead of a `String`.
Can the producer classes encapsulate the restrictions and "other things" in a method in themselves? That way each different producer could implement the appropriate method accordingly. Or just have that method return some sort of capability identifier, like an Enum of some sort. If that won't work, like say if you want other consumers to do different things, then the obvious solution is to have a bunch of "if (object instanceof ....)" statements. I've done it both ways, I can't say either is particularly "better" in all cases.
In Java, how should message producers identify themselves?
[ "", "java", "design-patterns", "" ]
Lets say I have this table: ``` PetID Name Age Weight ``` How can I in a Linq2SQL get the name, age and weight of each pet that is the heaviest in its age group? So if I have one pet of age 5 and four pets of age 2, I would like the Name, Age and Weight of the one that is age 5, and the one of the four with age 2 that is the heaveiest of those four. This should probably not be too difficult, but I am not too into query thinking yet. Working on it though. And this is one kind of problem that I will need many times, but doesn't quite manage to wrap my head around how to do... I think it would include using the Max or a > operator, and some sort of grouping or joining, but thats about as far as I've gotten.... --- Thanks for the answers. All of them put me on the right track when it comes to the GroupBy stuff. The one I marked as an answer, was the one that was closest to what I ended up with.
It could be something like this: ``` var pets = from pet in petSource group pet by pet.Age into g let max = g.OrderByDescending(p => p.Weight).FirstOrDefault<Pet>() select new { Name = max.Name, Age = max.Age, Weight = max.Weight }; ```
Try this query: ``` var petsGroup = ctx.Pets.GroupBy(p => p.Age) .Select(g => g.First(x => x.Weight == g.Max(y => y.Weight))); ``` It groups the Pets by Age, and then selects the first element on the group, that matchs with the maximum weight of the group.
C#, Linq2SQL: Getting the highest of each group
[ "", "c#", "linq-to-sql", "" ]
Not sure how to approach this problem. Basically, I want a Pixel -> Tile representation of a 400x400 window. Each coordinate on the screen, e.g `120x300` should be part of a tile. My smallest sprite is 4 pixels, so we can say that 1 tile = 4 pixels. The player and enemy sprites are all 20 x 20, so each player/bad guy will occupy 5 tiles. Then I want to use this Map class to: * Retrieve the x/y coordinates of a player/monster sprite by suppling the index/id of the tile. * Knowing where the boundaries are, so it doesn't move the sprite beyond `400x400`, thus hiding it. * Collision detection, knowing whether a tile is vacant or not. How can this be done? Talking specifically about the x,y->tile or tile index->x,y conversion (for drawing the sprites appropriately) here.
Firstly, split out the concept of a pixel, which is just concerned with representation, with a tile, which is an actual game object with constraints it places on the game. I find a good way to disentangle things like this is to start out sketching out the rough API of what you want. Something like: ``` public class Board { public Board (int width, int height){.. } public boolean isOccupied(int x, int y){.. } public void moveTo(Point from, Point to) { .. (maybe throws an exception for outofbounds ) ``` where all internal units of the board are in tiles, not pixels. Then pixel information can be derived from the board independantly from the tile representation with a bit of internal multiplication- ``` public Point getPixelPosition(int xTilePos, int yTilePos, int pixelsPerTile).. ``` The tiles can be internally represented as a 2d array or a single array, in which case you'd use some kind of internal representation scheme to map your array to the board squares, thus the mod arithmetic.
Short answer: Multiplication and Modulo operations. But if this is stumping you, I'd suggest you do a serious math refresher before trying to write a game. Also your statement > My smallest sprite is 4 pixels, so we > can say that 1 tile = 4 pixels. The > player and enemy sprites are all 20 x > 20, so each player/bad guy will occupy > 5 tiles. doesn't work out for any reasonable geometry. If by "1 tile = 4 pixels" you mean that the tiles are 2x2, then a player takes 100, not five. If you mean they are 4x4 then players take 25, which still isn't 5.
How to build a Tiled map in Java for a 2D game?
[ "", "java", "algorithm", "2d", "tiles", "" ]
I've got an [algorithm that compares two sorted lists](https://stackoverflow.com/questions/161432/best-algorithm-for-synchronizing-two-ilist-in-c-2-0/161535#161535), and I'm planning to make it more LINQ-y. My first question: is there anything like this in LINQ already? If not, I'm planning on writing it as an extension method, something like this: ``` public static class SortedCompareExtension { public static IEnumerable<Pair<T, U>> CompareTo<T,U>(this IEnumerable<T> left, IEnumerable<U> right, Func<T, U, int> comparison) { /* ... */ } } ``` It'll return `new Pair<T, U>(t, u)` if both elements are equivalent, `new Pair<T, U>(t, null)` if the element only exists in the left-hand list, etc. My second question: `CompareTo` is not a great name for this. What is it? Is it comparing, collating, correlating? What?
You are [Synchronizing](http://en.wikipedia.org/wiki/Data_synchronization) the lists, though the name has unfortunate connotations of thread synchronization. I would say that 'ReconcileOrdered' (perhaps OrderedReconcile) is a reasonable name (it is probably very important to indicate in the function's name that the arguments must both be ordered for it to behave correctly
How about `Diff`? I don't believe there's anything already in LINQ to do everything, but there's [`Except`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx) and [`Intersect`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx). It sounds like your code is mostly a mixture of the two - except those are *set* operations, whereas you've got sorted lists. It that mostly a case of efficiency, or is there a semantic difference in your case? (One example would be repeated entries.) Personally I'm not sure I'd use a pair in this case. There's only ever one value involved, isn't there? Isn't it really a case of Value, PresentInLeft (bool) and PresentInRight (bool)? I'm sure each representation has its pros and cons, and you can certainly expose either API from the same underlying data...
Naming an algorithm for comparing two sorted lists?
[ "", "c#", "linq", "" ]
I want to get the string which has a delimiter in it, between two specific words, using a regex. e.g. I need a regex which matches: > Statements1 start Statements2 ; Statements3 end fun; There can be multiple occurrences of ' `;` ' between 'start' and 'end'. Statements are multiple words where (.\*) can be used in the regex for a word. But the regex should not match if there is no ' `;` ' between the 'start' and 'end'. Also, the 'end' should be the first 'end' encountered after 'start' So, the regex should not match > Statements1 start Statements2 end Statements3 ; end fun I want the matches as 1. statements before 'start' 2. keyword 3. statements after 'start' So, in this case it would be a group(for the 1st string since 2nd should not match) as: 1. Statements1 2. start 3. Statements2 ; Statements3 end fun;
So the below regex will match your positive case and fail the negative case and place the results into group 1, 2, & 3. `(.*?) (start) ((?:(?:.*?) ;)+ (?:.*?) end fun)` In case you're unfamiliar with the (?:) syntax - they signify non-capturing parentheses. Check out [Mastering Regular Expressions](http://oreilly.com/catalog/9780596002893/), it's a great reference for this topic!
``` start ((Statements) ;)+ (Statements) end fun ```
C# regex to match a string which has a delimiter
[ "", "c#", "regex", "parsing", "csv", "" ]
In Windows Forms, I'd just override `WndProc`, and start handling messages as they came in. Can someone show me an example of how to achieve the same thing in WPF?
Actually, as far as I understand such a thing is indeed possible in WPF using `HwndSource` and `HwndSourceHook`. See [this thread on MSDN](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/6b97a6de-0480-4339-8ed0-cb7cdb27bd83/) as an example. (Relevant code included below) ``` // 'this' is a Window HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); source.AddHook(new HwndSourceHook(WndProc)); private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { // do stuff return IntPtr.Zero; } ``` Now, I'm not quite sure why you'd want to handle Windows Messaging messages in a WPF application (unless it's the most obvious form of interop for working with another WinForms app). The design ideology and the nature of the API is very different in WPF from WinForms, so I would suggest you just familiarise yourself with WPF more to see exactly *why* there is no equivalent of WndProc.
You can do this via the `System.Windows.Interop` namespace which contains a class named `HwndSource`. Example of using this ``` using System; using System.Windows; using System.Windows.Interop; namespace WpfApplication1 { public partial class Window1 : Window { public Window1() { InitializeComponent(); } protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); HwndSource source = PresentationSource.FromVisual(this) as HwndSource; source.AddHook(WndProc); } private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { // Handle messages... return IntPtr.Zero; } } } ``` Completely taken from the excellent blog post: [Using a custom WndProc in WPF apps by Steve Rands](http://web.archive.org/web/20091019124817/http://www.steverands.com/2009/03/19/custom-wndproc-wpf-apps/)
How to handle WndProc messages in WPF?
[ "", "c#", "wpf", "wndproc", "" ]
Is it somehow possible to use the XmlSerializer to deserialize its data into an existing instance of a class rather than into a new one? This would be helpful in two cases: 1. Easily merge two XML files into one object instance. 2. Let object constructer itself be the one who is loading its data from the XML file. If the is not possible by default it should work by using reflection (copying each property after the deserialisation) but this would be an ugly solution.
I think you're on the right track with the Reflection idea. Since you probably have a wrapper around the XML operations anyway, you could take in the destination object, do the deserialization normally into a new object, then do something similar to cloning by copying over one by one only the properties holding non-default values. It shouldn't be that complex to implement this, and it would look to consumers from the rest of your application just like in-place deserialization.
Basically, you can't. `XmlSerializer` is strictly constructive. The only interesting thing you can do to customize `XmlSerializer` is to implement `IXmlSerializable` and do everything yourself - not an attractive option (and it will still create new instances with the default constructor, etc). Is `xml` a strict requirement? If you can use a different format, [protobuf-net](http://code.google.com/p/protobuf-net/) supports merging fragments into existing instances, as simply as: ``` Serializer.Merge(source, obj); ```
How to use XmlSerializer to deserialize into an existing instance?
[ "", "c#", ".net", "serialization", ".net-2.0", "" ]
What I want is a hyperlink More when clicked on runs some javascript function and also changes to a hyperlink Less. Heres what I have which doesnt work. It runs the ajaxpage function fine but not moreToLess. I think its my use of " and ' in the javascript. ``` <script type="text/javascript"> function moreToLess(){ document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage('/TagCloud?id=EDI_0009&count=20', 'tagcloud');lessToMore()" >Less</a>'; } function lessToMore(){ document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage('/TagCloud?id=EDI_0009&count=50', 'tagcloud');moreToLess()" >More</a>'; } </script> <span id=tagLinks ><a href=# OnClick="ajaxpage('/TagCloud?id=EDI_0009&count=50', 'tagcloud');moreToLess()" >More</a></span> ```
Yes it is, just escape your single quotes inside of the double quotes that you have in your javascript.. ala \' ``` <script type="text/javascript"> function moreToLess(){ document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage(\'/TagCloud?id=EDI_0009&count=20\', \'tagcloud\');lessToMore()" >Less</a>'; } function lessToMore(){ document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage(\'/TagCloud?id=EDI_0009&count=50\', \'tagcloud\');moreToLess()" >More</a>'; } </script> <span id=tagLinks ><a href=# OnClick="ajaxpage('/TagCloud?id=EDI_0009&count=50', 'tagcloud');moreToLess()" >More</a></span> ```
You have to escape the `'` characters inside the quote: ``` '<a href=# OnClick="ajaxpage(\'/TagCloud?id=EDI_0009&count=20\', \'tagcloud\');lessToMore()" >Less</a>' ```
AJAX innerHTML. Change links. Possibly a " or ' problem
[ "", "javascript", "html", "ajax", "" ]
**Summary** I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason *why* I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle *all* my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing. **Pros** * Consistency of versions means easier testing and troubleshooting. * Application may reach a wider audience since there appear to be fewer components to install. * Small tweaks to the dependency can more easily be made downstream and delivered with the application, rather than waiting for them to percolate into the upstream code base. **Cons** * More complex packaging process to include dependencies. * User may end up with multiple copies of a dependency on their machine. * Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components. **Notes** For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about. All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking? **Addendum 1** It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.
I favor bundling dependencies, *if* it's not feasible to use a system for automatic dependency resolution (i.e. setuptools), and *if* you can do it without introducing version conflicts. You still have to consider your application and your audience; serious developers or enthusiasts are more likely to want to work with a specific (latest) version of the dependency. Bundling stuff in may be annoying for them, since it's not what they expect. But, especially for end-users of an application, I seriously doubt most people enjoy having to search for dependencies. As far as having duplicate copies goes, I would much rather spend an extra 10 milliseconds downloading some additional kilobytes, or spend whatever fraction of a cent on the extra meg of disk space, than spend 10+ minutes searching through websites (which may be down), downloading, installing (which may fail if versions are incompatible), etc. I don't care how many copies of a library I have on my disk, as long as they don't get in each others' way. Disk space is really, really cheap.
An important point seems to have been forgotten in the Cons of bundling libraries/frameworks/etc with the application: security updates. Most Web frameworks are full of security holes and require frequent patching. Any library, anyway, may have to be upgraded one day or the other for a security bug. If you do not bundle, sysadmins will just upgrade one copy of the library and restart depending applications. If you bundle, sysadmins will probably not even **know** they have to upgrade something. So, the issue with bundling is not the disk space, it's the risk of letting old and dangerous copies around.
When is it (not) appropriate to bundle dependencies with an application?
[ "", "python", "dependencies", "distribution", "packaging", "" ]
Which PHP RPC (XML or JSON) library have you successfully used? I have done some research but haven't been able to find one library that stands out from the others. I've found the following: [XML-RPC for PHP](http://phpxmlrpc.sourceforge.net/) [XML\_RPC (PEAR)](http://pear.php.net/package/XML_RPC/) [JSON-RPC PHP](http://jsonrpcphp.org/) And a few others that either don't look very active or mature.
I've used XML\_RPC (PEAR) successfully. I'm not personally a fan of the xml-rpc "way" but the library was simple to use and we have a few dozen clients using it daily and pulling a fair amount of data over the wire and we've never had any problems. We aren't pushing the envelope with this at all, in any way, but i'm very happy with the library since I don't even think about it anymore. The library isn't elegant or anything but neither is php or rpc, right?
I've written a simple XML-RPC library for PHP 5, called Ripcord. You can download it at <http://ripcord.googlecode.com/>. It is as easy to use as I could make it, even for the more advanced features like system.multicall. Give it a try.
Which PHP RPC (XML or JSON) library have you successfully used?
[ "", "php", "xml", "json", "rpc", "" ]
I would like to implement conversion between two library classes by Convert.ChangeType in C#. I can change neither of the two types. For example converting between Guid and byte[]. ``` Guid g = new Guid(); object o1 = g; byte[] b = (byte[]) Convert.ChangeType(o1, typeof(byte[])); // throws exception ``` I am aware that Guid provides a ToByteArray() method, but I would like to have that called when Guid is converted to byte[]. The reason behind this is that the conversion also takes place in library code (AseDataAdapter) which I can not modify. So is it possible to define a conversion rule between two types without modifying the sourcecode of either of the two classes? I was experimenting with TypeConverter, but doesn't seem to work either: ``` Guid g = new Guid(); TypeConverter tc = TypeDescriptor.GetConverter(typeof(Guid)); byte[] b2 = (byte[])tc.ConvertTo(g, typeof(byte[])); // throws exception ``` The variable tc gets set to System.ComponentModel.GuidConverter which doesn't support conversions to byte[]. Can I have two TypeConverters for the same class? Even if I could, wouldn't I need to prepend an attribute to the source code of the class to assign a TypeConverter? Thanks
You can change the registered `TypeConverter` for something using `TypeDescriptor.AddAttributes`; this isn't quite the same as `Convert.ChangeType`, but it may suffice: ``` using System; using System.ComponentModel; static class Program { static void Main() { TypeDescriptor.AddAttributes(typeof(Guid), new TypeConverterAttribute( typeof(MyGuidConverter))); Guid guid = Guid.NewGuid(); TypeConverter conv = TypeDescriptor.GetConverter(guid); byte[] data = (byte[])conv.ConvertTo(guid, typeof(byte[])); Guid newGuid = (Guid)conv.ConvertFrom(data); } } class MyGuidConverter : GuidConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(byte[]) || base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(byte[]) || base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value != null && value is byte[]) { return new Guid((byte[])value); } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(byte[])) { return ((Guid)value).ToByteArray(); } return base.ConvertTo(context, culture, value, destinationType); } } ```
If the code that is performing the conversion supports `TypeConverter`s you can use `TypeConverterAttribute` at an assembly level.
Inject custom type conversion to .NET library classes
[ "", "c#", ".net", "guid", "" ]
I'm getting compile error in this code ``` #include<iostream> #include<cstdio> #include<string> using namespace std; void main(int argc,char *argv[]) { int i; for(i = 0;i<10;i++) fprintf(cout,"%d\n",i); fprintf(cout,"abc:\n"); string s; cin>>s; if(s == "resume") { for(i = 0;i<10;i++) fprintf(cout,"%d\n",i); } } ``` Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. try.cpp C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C 4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc try.cpp(9) : error C2664: 'fprintf' : cannot convert parameter 1 from 'std::ostr eam' to 'FILE \*' No user-defined-conversion operator available that can perform this conv ersion, or the operator cannot be called try.cpp(10) : error C2664: 'fprintf' : cannot convert parameter 1 from 'std::ost ream' to 'FILE \*' No user-defined-conversion operator available that can perform this conv ersion, or the operator cannot be called try.cpp(16) : error C2664: 'fprintf' : cannot convert parameter 1 from 'std::ost ream' to 'FILE \*' No user-defined-conversion operator available that can perform this conv ersion, or the operator cannot be called what is wrong?
``` std::fprintf(stdout, ) ```
You are mixing up C++ and C output styles. Change your fprintfs to look like: ``` cout << "value is: " << i << "\n"; ```
Compile error using cl.exe (Visual Studio 2008) for this cpp code
[ "", "c++", "visual-studio", "compiler-construction", "" ]
Hi I have a Java enum and I want serialize a variable containing an enum value back and forth from XML for persistence. My enum is defined like this... ``` public enum e_Type { e_Unknown, e_Categoric, e_Numeric } ``` My variable is declared like this... ``` private e_Type type; ``` I want it to go into an XML tag like this... ``` <type>value</type> ``` What's the best practice for persisting values of enums in XML?
After getting responses about 3rd party libraries I decided to fix it myself and thought I would post my solution in case anyone else needs to see it. I just added two static methods to the enum that take care of what to send back and forth to XML... ``` public enum e_Type { e_Unknown, e_Categoric, e_Numeric; public static e_Type type(String token) { return e_Type.valueOf(token); } public static String token(e_Type t) { return t.name(); } } ``` This is a good approach for me because it means I can call my getters and setters with the type() and token() methods during serialisation/deserialisation. I have extended this into all my enums. I have two main problems with using a 3rd party library for something like this: 1. Bloat. That's a lot of sledgehammer for my little nut 2. Dependency. Adding a new 3rd party library means I have to go through licensing and legal checks and ESCROW etc. Really not worth it for 8 lines of code.
have a look at JAXB annotations, which are part of the JDK: ``` public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(Foo.class); StringWriter sw = new StringWriter(); context.createMarshaller().marshal(new Foo(), sw); System.out.println(sw); } @XmlRootElement public static class Foo { @XmlElement private e_Type type = e_Type.e_Unknown; } @XmlEnum public enum e_Type { e_Unknown, e_Categoric, e_Numeric } ``` you can customize the output further, e.g. if you wanted your external XML representation to be different from your internal java enum item names: ``` @XmlEnumValue("UNKNOWN") e_Unknown ``` btw: it is a very strong convention to use upper-case names for java classes/enums
What is best practice for serializing Java enums to XML?
[ "", "java", "xml", "serialization", "enums", "persistence", "" ]
I have the following code in one of my methods: ``` foreach (var s in vars) { foreach (var type in statusList) { if (type.Id == s) { Add(new NameValuePair(type.Id, type.Text)); break; } } } ``` This seems sort of ineffective to me, and I was wondering if there was a way to substitute at least one of the foreaches wih a LINQ query. Any suggestions? **EDIT:** vars is an array of strings and the Add method adds an item to a CSLA NameValueList.
EDIT: **I hadn't noticed the `break;` before** If there could be more than one type with the relevant ID, then you need to use `FirstOrDefault` as per [Keith's answer](https://stackoverflow.com/questions/589737/replacing-foreach-with-linq-query/589770#589770) or my second code sample below. EDIT: Removing "multi-from" version as it's unnecessarily inefficient assuming equality/hashcode works for whatever the type of `type.Id` is. A join is probably more appropriate though: ``` var query = from s in vars join type in statusList on s equals type.Id select new NameValuePair(type.Id, type.Text); foreach (var pair in query) { Add(pair); } ``` You might want to make an `AddRange` method which takes an `IEnumerable<NameValuePair>` at which point you could just call `AddRange(query)`. Alternatively, you can use a LookUp. This version makes sure it only adds one type per "s". ``` var lookup = types.ToLookup(type => type.Id); foreach (var s in vars) { var types = lookup[s]; if (types != null) { var type = types.First(); // Guaranteed to be at least one entry Add(new NameValuePair(type.Id, type.Text)); } } ``` The benefit of this is that it only goes through the list of types once to build up a dictionary, basically.
Basically: ``` var types = from s in vars let type = ( from tp in statusList where tp.Id == s ).FirstOrDefault() where type != null select new NameValuePair(type.Id, type.Text) ```
Replacing foreach with LINQ query
[ "", "c#", ".net", "linq", "" ]
I have a website where users can create albums and then add images to those albums. I then have a section on the page where I display all images added by the users. You can see it here: <http://www.mojvideo.com/slike> The problem is that we have a few users who upload a lot (anything between 20 to 100) of images at once and they kinda "spam" the first few pages (especially as some images are almost identical). I'm now struggling to find a better way to display these images so that content from more users is shown. My database structure looks like this: foto\_albums: id | title | user\_id foto\_images: id | foto\_albums\_id (reference to the album the image is in) | user\_id | title (the reason user\_id is duplicated in foto\_images is that I have a "special" personal album that isn't stored in the database, so if a user uploads an image to that album the foto\_albums\_id get's a value of 0, just thought I'd mention that to avoid any confusion) I'm looking for ideas and some help implementing them...
The dreaded `is_private` column :) I don't know that there's an efficient way of doing what you're looking for without adding some extra columns to your schema. You could assign a random number to each image, then order by that (faster than `ORDER BY RAND()`, since it's not computed each time). You could add an upload timestamp, then order by (say) `seconds * 60 + hours`; although that looks strange, it should prevent clustering of same-upload images (supposing that parsing an image takes at least 0.5s, which is a somewhat reasonable assumption given current upload speeds and image file sizes). You could invert the index column (as in, string reversal) and order by that. None of these fundamentally change the concept, but to get them to work quickly you'd need to alter your schema. Have you considered modifying your presentation? Maybe a sample of a user's most recent (highest id?) images, followed by the necessary "read more below the fold." Something like: ``` [img_1/kyle] [img_2/kyle] [img_3/kyle] "See all of Kyle's 50 pix" [img_1/jan] [img_1/soulmerge] [img_2/soulmerge] [img_1/jason] [img_2/jason] [img_3/jason] "See all of Jason's 72 pix" ``` Just a thought. **Edit:** based on your comments, if you'd like to display the most recent on a per-album basis, well, it's highly database-dependent; I think some databases make this easy, but MySQL definitely does not. Here's an example of a way to accomplish this (in MySQL 5.0+): ``` SELECT i.id, i.user_id, i.title FROM foto_images i, ( SELECT foto_albums_id, MAX(id) AS image_id FROM foto_images WHERE foto_albums_id <> 0 GROUP BY foto_albums_id ) tmp WHERE i.foto_albums_id <> 0 AND i.foto_albums_id = t.foto_albums_id AND ( SELECT COUNT(*) FROM foto_image WHERE foto_albums_id = i.foto_albums_id AND id BETWEEN i.id AND t.image_id ) < @NUMBER_OF_PREVIEW_IMAGES_TO_SELECT ORDER BY i.id; ``` Note that, somewhat dependent on your indexing and amount of data, this query can be highly inefficient. Possibly consider warehousing the information? An extra column, `display_on_main_page`, defined at upload termination?
Why don't you randomize the pictures? [WARNING Horrible performance!]Something like [ORDER BY RAND()](http://dev.mysql.com/doc/refman/5.1/de/mathematical-functions.html)?[/WARNING]
Displaying images from albums
[ "", "sql", "" ]
I have a source container of strings I want to remove any strings from the source container that match a predicate and add them into the destination container. `remove_copy_if` and other algorithms can only reorder the elements in the container, and therefore have to be followed up by the `erase` member function. My book (Josuttis) says that `remove_copy_if` returns an iterator after the last position in the destination container. Therefore if I only have an iterator into the destination container, how can I call `erase` on the source container? I have tried using the size of the destination to determine how far back from the end of the source container to erase from, but had no luck. I have only come up with the following code, but it makes two calls (`remove_if` and `remove_copy_if`). Can someone let me know the correct way to do this? I'm sure that two linear calls is not the way to do this. ``` #include <iostream> #include <iterator> #include <vector> #include <string> #include <algorithm> #include <functional> using namespace std; class CPred : public unary_function<string, bool> { public: CPred(const string& arString) :mString(arString) { } bool operator()(const string& arString) const { return (arString.find(mString) == std::string::npos); } private: string mString; }; int main() { vector<string> Strings; vector<string> Container; Strings.push_back("123"); Strings.push_back("145"); Strings.push_back("ABC"); Strings.push_back("167"); Strings.push_back("DEF"); cout << "Original list" << endl; copy(Strings.begin(), Strings.end(),ostream_iterator<string>(cout,"\n")); CPred Pred("1"); remove_copy_if(Strings.begin(), Strings.end(), back_inserter(Container), Pred); Strings.erase(remove_if(Strings.begin(), Strings.end(), not1(Pred)), Strings.end()); cout << "Elements beginning with 1 removed" << endl; copy(Strings.begin(), Strings.end(),ostream_iterator<string>(cout,"\n")); cout << "Elements beginning with 1" << endl; copy(Container.begin(), Container.end(),ostream_iterator<string>(cout,"\n")); return 0; } ```
I see your point, that you'd like to avoid doing two passes over your source container. Unfortunately, I don't believe there's a standard algorithm that will do this. It would be possible to create your own algorithm that would copy elements to a new container and remove from the source container (in the same sense as remove\_if; you'd have to do an erase afterward) in one pass. Your container size and performance requirements would dictate whether the effort of creating such an algorithm would be better than making two passes. Edit: I came up with a quick implementation: ``` template<typename F_ITER, typename O_ITER, typename FTOR> F_ITER move_if(F_ITER begin, F_ITER end, O_ITER dest, FTOR match) { F_ITER result = begin; for(; begin != end; ++begin) { if (match(*begin)) { *dest++ = *begin; } else { *result++ = *begin; } } return result; } ``` Edit: Maybe there is confusion in what is meant by a "pass". In the OP's solution, there is a call to remove\_copy\_if() and a call to remove\_if(). Each of these will traverse the entirety of the original container. Then there is a call to erase(). This will traverse any elements that were removed from the original container. If my algorithm is used to copy the removed elements to a new container (using begin() the original container for the output iterator will not work, as dirkgently demonstrated), it will perform one pass, copying the removed elements to the new container by means of a back\_inserter or some such mechanism. An erase will still be required, just as with remove\_if(). One pass over the original container is eliminated, which I believe is what the OP was after.
With all due respect to Fred's hard work, let me add this: the `move_if` is no different than `remove_copy_if` at an abstract level. The only implementation level change is the `end()` iterator. You are still not getting any `erase()`. **The accepted answer does not `erase()` the matched elements -- part of the OP's problem statement.** **As for the OP's question: what you want is an in-place splice. This is possible for lists. However, with `vectors` this will not work. Read about when and how and why iterators are invalidated. You will have to take a two pass algorithm.** > `remove_copy_if` and other algorithms can only reorder the elements in the container, From SGI's documentation on [`remove_copy_if`](http://www.sgi.com/tech/stl/remove_copy_if.html): > This operation is stable, meaning that the relative order of the elements that are copied is the same as in the range [first, last). So no relative reordering takes place. Moreover, this is a copy, which means the elements from `Source` `vector` in your case, is being copied to the `Container vector`. > how can I call erase on the source container? You need to use a different algorithm, called [`remove_if`](http://www.sgi.com/tech/stl/remove_if.html): > `remove_if` removes from the range `[first, last)` every element `x` such that `pred(x)` is true. That is, `remove_if` returns an iterator `new_last` such that the range `[first, new_last)` contains no elements for which `pred` is true. The iterators in the range `[new_last, last)` are all still dereferenceable, but the elements that they point to are unspecified. `Remove_if` is stable, meaning that the relative order of elements that are not removed is unchanged. So, just change that `remove_copy_if` call to: ``` vector<string>::iterator new_last = remove_if(Strings.begin(), Strings.end(), Pred); ``` and you're all set. Just keep in mind, your `Strings vector`'s range is no longer that defined by the iterators `[first(), end())` but rather by `[first(), new_last)`. You can, if you want to, remove the remaining `[new_last, end())` by the following: ``` Strings.erase(new_last, Strings.end()); ``` Now, your `vector` has been shortened and your `end()` and `new_last` are the same (one past the last element), so you can use as always: ``` copy(Strings.begin(), Strings.end(), ostream_iterator(cout, "\")); ``` to get a print of the strings on your console (`stdout`).
Now to remove elements that match a predicate?
[ "", "c++", "stl", "" ]
I am looking for alternatives for my current box and Mac OS X seems very appealing. My main area of interest is C++ programming. Currently I'm using Eclipse + CDT and g++ for creating my software; sometimes it is KDevelop. I know that primary IDE for Mac is Xcode and primary language is Objective-C. I would like to avoid learning Objective-C if at all possible. I've also heard/read that there are some issues in accessing Mac OS X APIs from C++. Hence my question: what is the complete solution for developing/debugging/testing C++ applications that access all aspects of hardware (UI, sound, video/accelerated video, etc.) for Mac OS X? Edit: how does Xcode compare to the Eclipse+CDT combo? If this comparison is at all possible...
If you want to use C++ instead of Objective-C, and still want to avoid an intermediate layer of libraries (such as QT), you can use [Carbon](http://developer.apple.com/Carbon/). I would use XCode instead of Eclipse simply because Eclipse is way slower when dealing with hardcore C/C++ programming (compiling, debugging, testing). When I first started to program in Mac OS X, I was in the same page you are now. I thought it was better to stick to the language I knew (C++) and use an older library (Carbon). For some reason I don't remember now, I forced myself into Cocoa (Objective-C). Looking back, I think it was a good thing because: 1. Objective-C is not fundamentally different to C++ 2. Cocoa is better, faster and simpler than Carbon 3. iPhone Dev is exclusively Cocoa (Carbon is not supported)
You should **not** avoid learning Objective-C and Cocoa. It should in fact be the first thing you do. Unless you have a solid background in Smalltalk, you're unlikely to have been exposed to a large (set of) framework that is as well-designed.
Complete solution for writing Mac OS X application in C++
[ "", "c++", "xcode", "macos", "ide", "" ]
We have been using System.getProperties("user.dir") to get the location of a properties file. Now that it has been deployed on Tomcat(via servlet), the System call is giving the location as tomcat and not at the location at where the properties file exist. How can we call the the properties file dynamically? **Given:** * Tomcat is not the only way the app will be deployed * We have no control on where the app may be placed. * Relative paths will not work as that Vista is being used and Vista breaks relative paths. * This must work on all OS, including(but not limited to) Linux, XP and Vista. * **EDIT** I implied this, but in case I was not clear enough, I have no way of knowing the path String.
You must have a way of knowing the path of the property file which you can then wrap in a File and pass to the load() method of your properties object. If you run inside a Tomcat service you are not running as the user you installed it as,so you cannot derive the home directory. You most likely need to hardcode SOMETHING then. --- Edit: The property file is relative to the application. See <http://www.exampledepot.com/egs/java.lang/ClassOrigin.html> for an example of how to get to the file name for the bytecode for a given class. You should be able to continue from there. ``` Class cls = this.getClass(); ProtectionDomain pDomain = cls.getProtectionDomain(); CodeSource cSource = pDomain.getCodeSource(); URL loc = cSource.getLocation(); // file:/c:/almanac14/examples/ ``` You should be aware that some security managers disallow this.
Take a look at `ServletContext`'s [getResource](http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html#getResource(java.lang.String)) and [getResourceAsStream](http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html#getResourceAsStream(java.lang.String)) methods.
How a servlet can get the absolute path to a file outside of the servlet?
[ "", "java", "tomcat", "servlets", "filepath", "os-agnostic", "" ]