Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Does anyone have an idea why the ampersand was chosen as the way to denote references in C++? AFAIK (though I don't have the book near me), Stroustroup didn't explain that choice, which I find a little odd because the same symbol was already used for address-of in C.
Stroustrup was always very reluctant to introduce a new reserved symbol or name, so he probably used it to avoid making the feature look weird to users of C.
In addition to Earwicker's response which I generally agree with. I would also speculate that since & is the "address-of" operator, it is somewhat fitting. Since a reference in many ways is like passing by **address** instead of by **value**. In addition to that, taking the address of a variable is often referred to as "referencing" (Yes I know that references don't *have* to be implemented using pointers under the hood, I am referring to the way they conceptually work). This is just speculation though.
Why was the ampersand chosen as the symbol for references in C++?
[ "", "c++", "c", "reference", "history", "" ]
we have a J2EE web application usig Spring MVC. We have a new requirement for our web application where we have to remove certain pre-defined characters from the user input. For example, let's say that the application should remove '<' from all the user inputs. I have come up with 2 approaches to meet this requirement : 1. JSP Level : identify each and every jsp which allows user input and then remove the characters by client side processing. 2. Servlet Filter : Use a filter and intercept the request object. Here I can use 1 of the following 2 approaches : 2.1 : Override the request.getParameter method and write the character removal logic inside it. Whenever this method is called, it will return the filtered result. 2.2 : At the filter level, scan the parameter map and filter the required characters. Then write a setParameter method and set the new values in the request parameter map. Which approach do you suggest? Will the filter have any impact on the performance? If you can think of a better approach then please let me know.
You can do client-side filtering if you wish but **you absolutely should not rely on it.** Clients can turn off Javascript. They can also just post what they like when it comes down to it. Client-side validation is a convenience. It is no substitute for server-side validation. As for using servlet filters, I'm not sure I'm a big fan of that. It seems like (and I could be wrong here) you're trying to protect yourself from lazy, forgetful or just plain inept developers. Also if you allow HTML at any point (like this site does), you can't institute that sort of thing as a universal rule. This sort of thing should be handled where you do all your other validation. Put unit tests around it if you're really worried about it. Servlet filters just seems heavyhanded and possibly problematic for this. You're using Spring MVC. Are you using any particular validation framework behind Spring's validators? Whatever the case, IMHO this is the correct place to deal with this kind of problem and easily unit-testable [sic]. I think that's the right point for this kind of thing. All that being said, I don't see any technical reason why you couldn't do this with setParameter in a servlet filter if you really are so inclined towards that approach. I would certainly do that over overriding setParameter on the servlet request. Can you even do that? Even if you can I wouldn't.
I'd turn the issue about face. Is the issue that users are typing characters like < into the fields, or the fact that you aren't escaping them when you print them out again on a webpage?
How to remove pre-defined characters from user input in a J2EE web application?
[ "", "java", "web-applications", "servlet-filters", "" ]
I feel like I've seen this question asked before, but neither the SO search nor google is helping me... maybe I just don't know how to phrase the question. I need to count the number of events (in this case, logins) per day over a given time span so that I can make a graph of website usage. The query I have so far is this: ``` select count(userid) as numlogins, count(distinct userid) as numusers, convert(varchar, entryts, 101) as date from usagelog group by convert(varchar, entryts, 101) ``` This does most of what I need (I get a row per date as the output containing the total number of logins and the number of unique users on that date). The problem is that if no one logs in on a given date, there will not be a row in the dataset for that date. I want it to add in rows indicating zero logins for those dates. There are two approaches I can think of for solving this, and neither strikes me as very elegant. 1. Add a column to the result set that lists the number of days between the start of the period and the date of the current row. When I'm building my chart output, I'll keep track of this value and if the next row is not equal to the current row plus one, insert zeros into the chart for each of the missing days. 2. Create a "date" table that has all the dates in the period of interest and outer join against it. Sadly, the system I'm working on already has a table for this purpose that contains a row for every date far into the future... I don't like that, and I'd prefer to avoid using it, especially since that table is intended for another module of the system and would thus introduce a dependency on what I'm developing currently. Any better solutions or hints at better search terms for google? Thanks.
Frankly, I'd do this programmatically when building the final output. You're essentially trying to read something from the database which is not there (data for days that have no data). SQL isn't really meant for that sort of thing. If you really want to do that, though, a "date" table seems your best option. To make it a bit nicer, you could generate it on the fly, using i.e. your DB's date functions and a derived table.
I had to do exactly the same thing recently. This is how I did it in T-SQL ( YMMV on speed, but I've found it performant enough over a coupla million rows of event data): ``` DECLARE @DaysTable TABLE ( [Year] INT, [Day] INT ) DECLARE @StartDate DATETIME SET @StartDate = whatever WHILE (@StartDate <= GETDATE()) BEGIN INSERT INTO @DaysTable ( [Year], [Day] ) SELECT DATEPART(YEAR, @StartDate), DATEPART(DAYOFYEAR, @StartDate) SELECT @StartDate = DATEADD(DAY, 1, @StartDate) END -- This gives me a table of all days since whenever -- you could select @StartDate as the minimum date of your usage log) SELECT days.Year, days.Day, events.NumEvents FROM @DaysTable AS days LEFT JOIN ( SELECT COUNT(*) AS NumEvents DATEPART(YEAR, LogDate) AS [Year], DATEPART(DAYOFYEAR, LogDate) AS [Day] FROM LogData GROUP BY DATEPART(YEAR, LogDate), DATEPART(DAYOFYEAR, LogDate) ) AS events ON days.Year = events.Year AND days.Day = events.Day ```
SQL for counting events by date
[ "", "sql", "logging", "date", "" ]
Imagine these two classes: ``` class Part { public string Name { get; set;} public int Id { get; set; } } class MainClass { public Part APart { get; set;} } ``` How can I bind MainClass to a combo box on a WinForm, so it displays Part.Name (`DisplayMember = "Name";`) and the selected item of the combo sets the APart property of the MainClass without the need to handle any events on the dropdown. As far as I know, setting ValueMember of the ComboBox to "Id" means that it will try to set APart to a number (Id) which is not right. Hope this is clear enough!
What you're looking for is to have the `ValueMember` (= `ComboBox.SelectedItem`) be a reference to the object itself, while `DisplayMember` is a single property of the item, correct? As far as I know, there's no good way to do this without creating your own `ComboBox` and doing the binding yourself, due to the way `ValueMember` and `DisplayMember` work. But, here's a couple things you *can* try (assuming you have a collection of `Part`s somewhere): 1. Override the `ToString()` method of `Part` to return the `Name` property. Then set your `ComboBox`'s `ValueMember` to `"APart"` and leave `DisplayMember` null. (Untested, so no guarantees) 2. You can create a new property in Part to return a reference to itself. Set the 'ValueMember' to the new property and 'DisplayMember' to `"Name"`. It may feel like a bit of a hack, but it should work. 3. Do funny things with your `APart` getter and setter. You'll lose some strong-typing, but if you make `APart` an object and `MainClass` contains the collection of `Part`s, you can set it by `Id` (`int`) or `Part`. (Obviously you'll want to be setting it by Id when you bind the ComboBox to it.) ``` Part _APart; object APart { get {return _APart;} set { if(value is int) _APart = MyPartCollection.Where(p=>p.Id==value).Single(); else if(value is Part) _APart = value; else throw new ArgumentException("Invalid type for APart"); } } ```
create a backing class to hold the "information", and create properties for all the data. Then implement System.ComponentModel.INotifyPropertyChanged on that class, something like: ``` private String _SelectedPart = String.Empty; public String SelectedPart { get { return _SelectedPart; } set { if (_SelectedPart != value) { _SelectedPart = value; // helper method for handing the INotifyPropertyChanged event PropertyHasChanged(); } } } ``` Then create an "ObjectDataSource" for that class (Shift-Alt-D in VS2008 will bring that up while looking at a form), then click on your ComboBox and set the following properties: DataSource, set to the ObjectDataSource "BindingSource" you just created. DisplayMember, Set to the Name propertity of the List of parts ValueMember, Set to the ID member of the List of parts DataBindings.SelectedValue, set to the SelectedPart on the "BindingSource" you just created. I know the above sounds complex, and it might take a bit to find all the parts I just described (wish I could give a tutorial or screenshot), but really it is VERY fast to do once you get used to it. This is by the way, considered "data-binding" in .NET and there are a few good tutorials out there that can give your more information.
Dropdown binding in WinForms
[ "", "c#", ".net", "winforms", "data-binding", "" ]
I've got three tables ``` AUTHOR_TABLE ------------- AUTHOR_ID (PK) AUTHOR_NAME 1 me 2 you ARTICLE_AUTHOR_TABLE ------------- AUTHOR_ID ARTICLE_ID 1 100 2 101 EVENT_AUTHOR_TABLE ------------------------------------------ AUTHOR_ID EVENT_ID 1 200 1 201 ``` All I want is either ``` RESULTS ----------------------------------------- AUTHOR_ID AUTHOR_NAME SOURCE_TABLE ID 1 me article 100 2 you article 101 1 me event 200 1 me event 201 /* where SOURCE_TABLE would be either "EVENT" or "ARTICLE" */ ``` **EDIT I don't really want this** ``` RESULTS ----------------------------------------- AUTHOR_ID AUTHOR_NAME EVENT_ID ARTICLE_ID 1 me NULL 100 2 you NULL 101 1 me 200 NULL 1 me 201 NULL ``` Any pointers appreciated. THanks
``` SELECT at.author_id, at.author_name, 'article' AS source_table, aat.id FROM author_table at JOIN article_author_table aat ON at.author_id = aat.author_id UNION ALL SELECT at.author_id, at.author_name, 'event' AS source_table, eat.id FROM author_table at JOIN event_author_table eat ON at.author_id = eat.author_id ```
``` SELECT A.AUTHOR_ID, A.AUTHOR_NAME, EA.EVENT_ID, AA.ARTICLE_ID FROM AUTHOR_TABLE AS A LEFT JOIN ARTICLE_AUTHOR_TABLE AS AA ON AA.AUTHOR_ID = A.AUTHOR_ID LEFT JOIN EVENT_AUTHOR_TALBE AS EA ON EA.AUTHOR_ID = A.AUTHOR_ID ```
How do I join (merge?) several tables?
[ "", "sql", "sql-server", "join", "merge", "" ]
I have a series of Python tuples representing coordinates: ``` tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] ``` I want to create the following list: ``` l = [] for t in tuples: l[ t[0] ][ t[1] ] = something ``` I get an IndexError: list index out of range. My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't. The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. **Update**: I now know they can - see the accepted solution. Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2) Can anyone help?
What do you mean exactly by "but as far as I know dictionaries cannot be sorted by keys"? While this is not strictly the same as a "sorted dictionary", you *can* easily turn a dictionary into a list, sorted by the key, which seems to be what you're after: ``` >>> tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] >>> l = {} >>> for t in tuples: ... l[t] = "something" >>> sorted(l) # equivalent to sorted(l.keys()) [(0, 0), (0, 1), (1, 0), (1, 1), (2, 1)] >>> sorted(l.items()) # make a list of (key, value) tuples, and sort by key [((0, 0), 'something'), ((0, 1), 'something'), ((1, 0), 'something'), ((1, 1), 'something'), ((2, 1), 'something')] ``` (I turned `something` into the string "something" just to make the code work) To make use of this for your case however (if I understand it correctly, that is), you would still need to fill the dictionary with None values or something for every "empty" coordinate tuple)
No, you cannot create list with gaps. But you can create a dictionary with tuple keys: ``` tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] l = {} for t in tuples: l[t] = something ``` **Update:** Try using [NumPy](https://numpy.org/), it provides wide range of operations over matrices and array. Cite from free pfd on NumPy available on the site (3.4.3 Flat Iterator indexing): *"As mentioned previously, X.flat returns an iterator that will iterate over the entire array (in C-contiguous style with the last index varying the fastest"*. Looks like what you need.
Populate a list in python
[ "", "python", "list", "tuples", "" ]
As part of my application I have a function that receives a MethodInfo and need to do specific operations on it depending if that method is "Extension Method". I've checked the MethodInfo class and I could not find any *IsExtension* property or flag that shows that the method is extension. Does anyone knows how can I find that from the method's MethodInfo?
Based on [F# extension methods in C#](https://stackoverflow.com/questions/702256/f-extensions-in-c) it seems there is an attribute on the compiled form. So see if the method has this attribute: <http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx>
You can call the **IsDefined** method on the MethodInfo instance to find this out by checking to see if the **ExtensionAttribute** is applied to the method: ``` bool isExtension=someMethod.IsDefined(typeof(ExtensionAttribute),true); ```
Using reflection to check if a method is "Extension Method"
[ "", "c#", "reflection", "extension-methods", "methodinfo", "" ]
There are tons of GUI libraries for C/C++, but very few of them are based on the idea that opengl is a rather multiplatform graphics library. Is there any big disadvantage on using this OpenGL for building my own minimal GUI in a portable application? [Blender](http://www.blender.org) is doing that, and it seems that it works well for it. EDIT: The point of my question is not about using an external library or making my own. My main concern is about the use of libraries that use opengl as backend. [Agar](http://libagar.org), CEGUI or Blender's GUI for instance. Thanks.
Here's an oddball one that bit a large physics experiment I worked on: because an OpenGL GUI bypasses some of the usual graphics abstraction layers, it may defeat remote viewing applications. In the particular instance I'm thinking of we wanted to allow remote shift operations over VNC. Everything worked fine except for the one program (which we only needed about once per hour, but we *really needed*) that used an OpenGL interface. We had to delay until a remote version of the OpenGL interface could be prepared.
You're losing the native platforms capabilities for accessibility. For example on Windows most controls provide information to screen readers or other tools supporting accessibility impaired users. Basically unless you have a real reason to do this, you shouldn't.
What disadvantages could I have using OpenGL for GUI design in a desktop application?
[ "", "c++", "user-interface", "opengl", "" ]
Using Resharper 4.1, I have come across this interesting warning: "Access to a static member of a type via a derived type". Here is a code sample of where this occurs: ``` class A { public static void SomethingStatic() { //[do that thing you do...] } } class B : A { } class SampleUsage { public static void Usage() { B.SomethingStatic(); // <-- Resharper warning occurs here } } ``` Does anybody know what issues there are (if any) when making use of A's static members via B?
One place where it might be misleading is when the static is a factory method, e.g. the `WebRequest` class has a factory method `Create` which would allow this type of code to be written if accessed via a derived class. ``` var request = (FtpWebRequest)HttpWebRequest.Create("ftp://ftp.example.com"); ``` Here `request` is of type `FtpWebRequest` but it's confusing because it looks like it was created from an `HttpWebRequest` (a sibling class) even though the `Create` method is actually defined on `WebRequest` (the base class). The following code is identical in meaning, but is clearer: ``` var request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com"); ``` Ultimately there's no major problem accessing a static via a derived type, but code is often clearer by not doing so.
`B.SomethingStatic()` makes the statement that `SomethingStatic` is a member of `B`. This is not true. `SomethingStatic` is unequivocally a member of `A`. The fact that it's accessible unqualified to members of `B` (as if it were a member of `B`) is a matter of convenience. The fact that it's accessible when qualified with a `B` is, IMO, a mistake.
Using a class's static member on a derived type?
[ "", "c#", "static", "resharper", "" ]
I have a table with a smallint column that contains percentages as whole numbers (i.e., 50, 75, 85, etc.) When I divide this column by 100, as in ``` SELECT MY_COLUMN/100 AS PCT_AS_FRACTION FROM MY_TABLE ``` the result is rounded to the nearest whole number. For example, for a row that contains the number "50", I get zero as my result. I can duplicate this with a simple statement: ``` SELECT 50 / 100 AS TEST_VALUE ``` Why is that, and how can I get more precision in my result?
When you do integer division (integer divided by integer) you always get an integer answer. 50/100 = .50, which is 0 in integer-speak. Have you tried dividing MY\_COLUMN by 100.0?
Cast whole numbers. ``` SELECT (cast(50 AS float)/100) ```
Why does SQL Server round off results of dividing two integers?
[ "", "sql", "sql-server", "rounding", "" ]
What Java WebDAV client side library could you recommend?
Have you looked at [Jackrabbit's](https://jackrabbit.apache.org/jcr/components/jackrabbit-webdav-library.html)?
I've recently created one that is quite easy to use: <https://github.com/lookfirst/sardine>
Java WebDAV client side library
[ "", "java", "client-side", "webdav", "" ]
I want to compile multiple java files in my Application without restarting Weblogic and Tomcat. Otherwise, this takes a lot of time. For this I got one [Hotswap plugin in Eclipse](http://www.eclipse-plugins.info/eclipse/plugin_details.jsp?id=620), but this is not working in all the cases. It says it works for single file compile. Even if I use that it is not working in all the cases. Is there any other way that I can do this or is there any other plugin/script/software which can help me in this? If there are some open source ones, it will be very helpful. Thanks in Advance.
One thing is compiling the classes, but you also need the JAVA VM to reload the classes and use them, which is called hot-swapping. For the best available hot-swapping of classes you'll need something like [javarebel](http://www.zeroturnaround.com/javarebel/). It allows you to hot-reload a lot more [types of code-changes](http://www.zeroturnaround.com/javarebel/features/) than the regular SUN JVM. If you run your deployment in exploded-mode you're home free, and can test any code change in a second or so. We're fairly test-driven, so I only use javarebel in that short phase when I assemble the whole application, but it works really well.
The Java HotSpot VM does this automatically, but not in all cases... First, you must be running a "debug" session, not a "run" session. Next, some changes will force a restart. The basic idea is that if the interface to the class change (the method sigs, not an actual Java interface), the VM can't replace the class contents inline. You shouldn't need a plugin for this, just a recent-ish VM. This happens under several circumstances like * adding methods * removing methods * changing method signatures * changing the class hierarchy (superclasses, implemented interfaces) It can also happen if you introduce an error into the class. (For errors like mismatched curly braces) When you save a Java file, eclipse compiles it. If there is an error, eclipse inserts an exception throw to indicate that there is an unresolved compilation error. (It does this so when you run you don't just see the last successful compilation, making it obvious you have a compiler error)
How to compile single/multiple java files without server restart? Is there any Eclipse plugin for the same?
[ "", "java", "compilation", "eclipse-plugin", "" ]
I have a long stored procedure that does a lot of querying and generates a report. Since its a summary report, it calls a lot of other procs to get data. I am wondering if its possible to execute concurrent sql batches from with a proc in Sql server ... many thanks
No, SQL Server does not do concurrency in the sense I think you mean. How long does the code run for? Is is a problem? Edit, based on comment. 11-20 seconds for a big summary report isn't bad at all. If you submit the calls in parallel from the client, it may take the same or longer: if each query is fairly intense and is resource heavy, then you may max out the server by running them together and affect other processes. + then you have to assemble data in the final form in the client.
Your best bet is to report stuff like this from another database. Either based on transformations from your production database into an OLAP database (which will make the time delay go away), or at least a periodic (say, nighly) static snapshot (which will make the delay not matter - you can turn off locking because nothing will change). Side benefit: Report readers will be a lot happier with reports run five minutes apart that give the same answers. Or 12 hours apart. The benefit you will appreciate the most is that life will be simpler.
concurrent queries in T-SQL
[ "", "sql", "sql-server", "" ]
I am trying to databind a `DataGridView` to a list that contains a class with the following structure: ``` MyClass.SubClass.Property ``` When I step through the code, the `SubClass` is never requested. I don't get any errors, just don't see any data. Note that I can databind in an edit form with the same hierarchy.
[Law of Demeter](http://en.wikipedia.org/wiki/Principle_of_least_knowledge). Create a property on MyClass that exposes the SubClass.Property. Like so: ``` public class MyClass { private SubClass _mySubClass; public MyClass(SubClass subClass) { _mySubClass = subClass; } public PropertyType Property { get { return _subClass.Property;} } } ```
You can add a handler to DataBindingComplete event and fill the nested types there. Something like this: in form\_load: ``` dataGridView.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView_DataBindingComplete); ``` later in the code: ``` void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { foreach (DataGridViewRow row in dataGridView.Rows) { string consumerName = null; consumerName = ((Operations.Anomaly)row.DataBoundItem).Consumer.Name; row.Cells["Name"].Value = consumerName; } } ``` It isn't nice but works.
Winforms DataGridView databind to complex type / nested property
[ "", "c#", ".net", "data-binding", "datagridview", ".net-3.5", "" ]
What is the equivalent Scala constructor (to create an **immutable** `HashSet`) to the Java ``` new HashSet<T>(c) ``` where `c` is of type `Collection<? extends T>`?. All I can find in the `HashSet` *Object* is `apply`.
There are two parts to the answer. The first part is that Scala variable argument methods that take a T\* are a sugaring over methods taking Seq[T]. You tell Scala to treat a Seq[T] as a list of arguments instead of a single argument using "seq : \_\*". The second part is converting a Collection[T] to a Seq[T]. There's no general built in way to do in Scala's standard libraries just yet, but one very easy (if not necessarily efficient) way to do it is by calling toArray. Here's a complete example. ``` scala> val lst : java.util.Collection[String] = new java.util.ArrayList lst: java.util.Collection[String] = [] scala> lst add "hello" res0: Boolean = true scala> lst add "world" res1: Boolean = true scala> Set(lst.toArray : _*) res2: scala.collection.immutable.Set[java.lang.Object] = Set(hello, world) ``` Note the scala.Predef.Set and scala.collection.immutable.HashSet are synonyms.
The most concise way to do this is probably to use the `++` operator: ``` import scala.collection.immutable.HashSet val list = List(1,2,3) val set = HashSet() ++ list ```
Scala equivalent of new HashSet(Collection)
[ "", "java", "scala", "scala-collections", "" ]
How can one detect the search engine bots using php?
Here's a [Search Engine Directory of Spider names](http://www.searchenginedictionary.com/spider-names.shtml) Then you use `$_SERVER['HTTP_USER_AGENT'];` to check if the agent is said spider. ``` if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), "googlebot")) { // what to do } ```
I use the following code which seems to be working fine: ``` function _bot_detected() { return ( isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT']) ); } ``` update 16-06-2017 <https://support.google.com/webmasters/answer/1061943?hl=en> added **mediapartners**
how to detect search engine bots with php?
[ "", "php", "web-crawler", "bots", "" ]
In C# is there a way you can call a property of an object with a variable, something like this: ``` string fieldName = "FirstName"; Console.WriteLine(customer.&fieldName); ``` ## ANSWER: Excellent, thanks for the quick answers, this is what I was trying to do: ``` using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace TestLinqFieldIndex { class Program { static void Main(string[] args) { List<Customer> customers = new List<Customer>(); customers.Add(new Customer { ID = 1, FirstName = "Jim", LastName = "Smith" }); customers.Add(new Customer { ID = 2, FirstName = "Joe", LastName = "Douglas" }); customers.Add(new Customer { ID = 3, FirstName = "Jane", LastName = "Anders" }); var customer = (from c in customers where c.ID == 2 select c).SingleOrDefault(); string[] fieldNames = { "FirstName", "LastName" }; foreach (string fieldName in fieldNames) { Console.WriteLine("The value of {0} is {1}.", fieldName, customer.GetPropertyValue(fieldName)); } Console.ReadLine(); } } public class Customer { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string GetPropertyValue(string fieldName) { PropertyInfo prop = typeof(Customer).GetProperty(fieldName); return prop.GetValue(this, null).ToString(); } } } ```
You can do that using reflection. ``` PropertyInfo prop = typeof(Customer).GetProperty ("FirstName"); Console.WriteLine (prop.GetValue (customer, null)); ``` It is even possible to retrieve the value of a private property as well. To do that, you'll have to take a look at the overloaded `GetProperty` method that accepts bindingflags.
You can't do that out of the box; you'll have to use the `PropertyInfo` object and reflection: ``` Apple myApple = new Apple("Golden Delicious", Ripeness.Fresh); // ... var p = typeof(Apple).GetProperty("Variety"); Console.WriteLine(p.GetValue(myApple, null)); // "Golden Delicious" ``` Note that C# 4 will offer support for dynamic property access and other goodness. But I assume you don't want to wait that long. :)
How to call a property of an object with a variable in C# e.g. customer.&fieldName
[ "", "c#", "" ]
I am still trying to workout separation of function and how it applies to class creation and namespace inclusion. I have a custom class SoftwareComponent which when presented to the user will most often appear as a ListItem. Is creating a ToListItem method a good idea? I worry because I have now placed a dependency in the class which will require the inclusion of the System.Web.UI.WebControls namespace. ``` public ListItem ToListItem() { ListItem li = new ListItem(); li.Text = ComponentName + " (+" + ComponentCost + ")"; li.Selected = Selected; return li; } ``` My other inclination is to create a ListItem from the SoftwareComponent based on its properties outside of the class itself. Please provide any thoughts on which approach is more appropriate/better.
Could you not provide this additional method as an extension method? It seems to be better suited to being part of a utility class that can be included as a choice by creating a static method that provides this functionality rather than providing it on the main class as a first class method. ``` public static class SoftwareComponentExtensions { public static ListItem ToListItem(this SoftwareComponent component) { ListItem li = new ListItem(component.ComponentName + " (+" + component.ComponentCost + ")"); li.Selected = component.Selected; return li; } } ```
It sounds like SoftwareComponent is a domain object - an object that describes a "thing" in the world your application speaks in. I try to avoid making those domain objects depend on anything outside the domain - this could be the lower level (how is it stored? Is it serialized? Stored in a database) or at the UI level. I agree that it is difficult to do so, quite often you end up with separate hierarchies of classes to manage - ui classes, database mappings and so on. So depending on the size of the thing you build it is a tradeoff to include UI or database code in the domain objects or to keep stuff out. For the specific problem you've got have a look at C#3.5 extension methods. They are a sleight of hand of making static methods look like they are defined within a class -- as long as they don't access private/protected stuff (they only can access public methods like any other method) you can get away with them. I use them for stuff like you want to do (UI-Level "methods" for domain objects) that are defined elsewhere, however. But keep in mind, extension methods are nothing but syntactic sugar for you good old static methods in a static class.
Class Design C# Namespace Separation
[ "", "c#", "architecture", "class-design", "" ]
I'm using the click event on the TreeView to do some stuff when a node is clicked in the TreeView. I do this by getting the node that is click on by calling GetNodeAt() with the mouse coordinates, like this: ``` private void TreeView_Click(object sender, System.EventArgs e) { MouseEventArgs mouseEventArgs = e as MouseEventArgs; if (mouseEventArgs == null) return; // Get the node that is being clicked. TreeNode node = this.GetNodeAt(mouseEventArgs.X, mouseEventArgs.Y); // Do other stuff... } ``` However, the GetNodeAt() method only works when the click is on the node label, when the node image is clicked then GetNodeAt() returns null. This is a bit annoying since the node is actually selected when the image is clicked but I can't find out what node it is. Do anyone have any suggestions? Updated: I've gotten some suggestions to use SelectedNode instead. I can't since it's set after the Click event is fired. This actually in a control that inherits TreeView and what it does is fire it's own Clicked event but with the underlying data that the TreeNode represents instead of the TreeNode itself. Updated: Turns out that someone had overridden the GetNodeAt() method in our code which introduced this behavior, which I didn't realize. So the question is null and void and there is no problem with the GetNodeAt() method. Why someone would do this remains a mystery. :)
Have you tried the BeforeSelect or AfterSelect Events? You can get the selected node straight from the TreeViewCancelEventArgs, then use it in your Click Event. Edit: Additional Thought: The only problem I can see with this is that the BeforeSelect event actually fires ***after*** the Click and MouseClick Events. Another Edit: If you need an event that fires before Click, you can use NodeMouseClick - TreeNodeMouseClickEventArgs has a Node property.
Why not just use `TreeView.SelectedNode`?
C# TreeView.GetNodeAt() problem with clicking images
[ "", "c#", "winforms", "treeview", "click", "treenode", "" ]
Sorry for the nondescript title. I'll edit as we go along. I have a table `RateTable`: ``` | Code | Date | Rate | B001 2009-01-01 1.05 B001 2009-01-02 1.05 B001 2009-01-03 1.05 B001 2009-01-04 1.05 B001 2009-01-05 1.06 B001 2009-01-06 1.06 B001 2009-01-07 1.06 B001 2009-01-08 1.07 ``` There is an entry for each day, but the Rate rarely changes. Can I write a SQL query that will only return the rows in which a Rate change occurs? I'm using SQLServer
If I read this right, you aren't looking for modified rows, but rows where the rate changes from the previous date. This query or something like it should do it: ``` SELECT r1.Code, r1.Date, r1.Rate FROM RateTable r1 WHERE r1.Rate <> (SELECT TOP 1 Rate FROM RateTable WHERE Date < r1.Date ORDER BY Date DESC) ```
If your RDBMS supports analytic functions then the optimum method is almost certainly this: ``` select code, date, rate, last_rate from ( select code, date, rate, lag(rate) over (partition by code order by date) last_rate from ratetable ) my_tb where my_tb.rate != my_tb.last_rate ```
SQL: retrieve only the records whose value has changed
[ "", "sql", "sql-server", "" ]
Say I have a ``` struct SMyStruct { int MULT; int VAL; }; std::map<std::string, SMyStuct*> _idToMyStructMap; ``` Now I want to calculate total of all SMyStuct, where total is defined as MULT1 \*VAL1 + MULT2 \*VAL2 for each elements in the idToMyStructMap. Seems like accumulate function is a natural choice. Please suggest. thanks **No Boost please.... just an 'ld fashion stl**
``` typedef std::map< std::string, SMyStruct* > string_to_struct_t; int add_to_totals( int total, const string_to_struct_t::value_type& data ) { return total + data.second->MULT * data.second->VAL; } const int total = std::accumulate( _idToMyStructMap.begin(), _idToMyStructMap.end(), 0, add_to_totals ); ```
A variation on the theme would be to define operator+ for your struct, and then just use std::accumulate in its default mode. ``` int & operator+ (const int &lhs, const SMyStruct &rhs){ return lhs + (rhs.MULT * rhs.VALUE); } ``` Then: ``` std::accumulate(_idToMyStructMap.begin(), _idToMyStructMap.end(), 0); ``` Of course, if `operator+` makes sense in general for your struct, then you'd want to add overloads for using SMyStruct on the left as well, and/or make them templates so that you get functions for int, float, double, long, etc. all in one shot. As jalf mentioned in comments, if `operator+` (or this version of it) doesn't make sense in general for your struct, then the other solution is better.
accumulate the sum of elements in map, using value
[ "", "c++", "algorithm", "stl", "" ]
Consider these 2 examples... ``` $key = 'jim'; // example 1 if (isset($array[$key])) { // ... } // example 2 if (array_key_exists($key, $array)) { // ... } ``` I'm interested in knowing if either of these are better. I've always used the first, but have seen a lot of people use the second example on this site. So, which is better? Faster? Clearer intent?
`isset()` is faster, but it's not the same as `array_key_exists()`. `array_key_exists()` purely checks if the key exists, even if the value is `NULL`. Whereas `isset()` will return `false` if the key exists and value is `NULL`.
If you are interested in some tests I've done recently: <https://stackoverflow.com/a/21759158/520857> Summary: ``` | Method Name | Run time | Difference ========================================================================================= | NonExistant::noCheckingTest() | 0.86004090309143 | +18491.315775911% | NonExistant::emptyTest() | 0.0046701431274414 | +0.95346080503016% | NonExistant::isnullTest() | 0.88424181938171 | +19014.461681183% | NonExistant::issetTest() | 0.0046260356903076 | Fastest | NonExistant::arrayKeyExistsTest() | 1.9001779556274 | +209.73055713% ```
What's quicker and better to determine if an array key exists in PHP?
[ "", "php", "performance", "" ]
In case of integer overflows what is the result of `(unsigned int) * (int)` ? `unsigned` or `int`? What type does the array index operator (`operator[]`) take for `char*`: `int`, `unsigned int` or something else? I was auditing the following function, and suddenly this question arose. The function has a vulnerability at line 17. ``` // Create a character array and initialize it with init[] // repeatedly. The size of this character array is specified by // w*h. char *function4(unsigned int w, unsigned int h, char *init) { char *buf; int i; if (w*h > 4096) return (NULL); buf = (char *)malloc(4096+1); if (!buf) return (NULL); for (i=0; i<h; i++) memcpy(&buf[i*w], init, w); // line 17 buf[4096] = '\0'; return buf; } ``` Consider both `w` and `h` are very large unsigned integers. The multiplication at line 9 have a chance to pass the validation. Now the problem is at line 17. Multiply `int i` with `unsigned int w`: if the result is `int`, it is possible that the product is negative, resulting in accessing a position that is before `buf`. If the result is `unsigned int`, the product will always be positive, resulting in accessing a position that is after `buf`. It's hard to write code to justify this: `int` is too large. Does anyone has ideas on this? Is there any documentation that specifies the type of the product? I have searched for it, but so far haven't found anything. I suppose that as far as the vulnerability is concerned, whether `(unsigned int) * (int)` produces `unsigned int` or `int` doesn't matter, because in the compiled object file, they are just bytes. The following code works the same no matter the type of the product: ``` unsigned int x = 10; int y = -10; printf("%d\n", x * y); // print x * y in signed integer printf("%u\n", x * y); // print x * y in unsigned integer ``` Therefore, it does not matter what type the multiplication returns. It matters that whether the consumer function takes `int` or `unsigned`. The question here is **not** how bad the function is, or how to improve the function to make it better. The function undoubtedly has a vulnerability. The question is about the exact behavior of the function, based on the prescribed behavior from the standards.
To answer your question: the type of an expression multiplying an int and an unsigned int will be an unsigned int in C/C++. To answer your implied question, one decent way to deal with possible overflow in integer arithmetic is to use the "`IntSafe`" set of routines from Microsoft: <http://blogs.msdn.com/michael_howard/archive/2006/02/02/523392.aspx> It's available in the SDK and contains inline implementations so you can study what they're doing if you're on another platform.
do the w\*h calculation in long long, check if bigger than MAX\_UINT EDIT : alternative : if overflown (w\*h)/h != w (is this always the case ?! should be, right ?)
In case of integer overflows what is the result of (unsigned int) * (int) ? unsigned or int?
[ "", "c++", "c", "overflow", "buffer", "" ]
I am using std::queue for implementing JobQueue class. ( Basically this class process each job in FIFO manner). In one scenario, I want to clear the queue in one shot( delete all jobs from the queue). I don't see any clear method available in std::queue class. How do I efficiently implement the clear method for JobQueue class ? I have one simple solution of popping in a loop but I am looking for better ways. ``` //Clears the job queue void JobQueue ::clearJobs() { // I want to avoid pop in a loop while (!m_Queue.empty()) { m_Queue.pop(); } } ```
A common idiom for clearing standard containers is swapping with an empty version of the container: ``` void clear( std::queue<int> &q ) { std::queue<int> empty; std::swap( q, empty ); } ``` It is also the only way of actually clearing the memory held inside some containers (std::vector)
Yes - a bit of a misfeature of the queue class, IMHO. This is what I do: ``` #include <queue> using namespace std;; int main() { queue <int> q1; // stuff q1 = queue<int>(); } ```
How do I clear the std::queue efficiently?
[ "", "c++", "data-structures", "stl", "queue", "" ]
I have `MyClass<T>`. And then I have this `string s = "MyClass<AnotherClass>";`. How can I get Type from the string `s`? One way (ugly) is to parse out the "<" and ">" and do: ``` Type acType = Type.GetType("AnotherClass"); Type whatIwant = typeof (MyClass<>).MakeGenericType(acType); ``` But is there a cleaner way to get the final type without any parsing, etc.?
The [format for generics](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx) is the name, a ` character, the number of type parameters, followed by a comma-delimited list of the types in brackets: ``` Type.GetType("System.Collections.Generic.IEnumerable`1[System.String]"); ``` I'm not sure there's an easy way to convert from the C# syntax for generics to the kind of string the CLR wants. I started writing a quick regex to parse it out like you mentioned in the question, but realized that unless you give up the ability to have nested generics as type parameters the parsing will get very complicated.
Check out `Activator.CreateInstance` - you can call it with a type ``` Activator.CreateInstance(typeof(MyType)) ``` or with an assembly and type name as `string` ``` Activator.CreateInstance("myAssembly", "myType") ``` This will give you an instance of the type you need. If you need the `Type` rather than the instance, use the `Type.GetType()` method and the fully qualified name of the type you're interested in, e.g.: ``` string s = "System.Text.StringBuilder"; Type myClassType = Type.GetType(s); ``` That'll give you the `Type` in question.
How can I get generic Type from a string representation?
[ "", "c#", "reflection", "types", "" ]
For the reasons that I still do not understand ([see this SO question](https://stackoverflow.com/questions/275073/why-does-c-multidimensional-arrays-not-implement-ienumerablet)) multidimensional arrays in CLR do not implement `IEnumerable<T>`. So the following does not compile: ``` var m = new int[2,2] {{1, 2}, {3, 4}}; var q = from e in m select e; ``` Then how come that this **works just fine in VB.NET**? ``` Sub Main() Dim m(,) As Integer = {{1, 2}, {3, 4}} Dim q = From e In m Select e For Each i In q Console.WriteLine(i) Next End Sub ``` **Update:** The following code works because the C# compiler replaces the `foreach` with `for` loops to go through each dimension. ``` foreach(var e in m) Console.WriteLine(e); ``` becomes ``` int[,] numArray3 = new int[,] { { 2, 2 }, { 3, 3 } }; int upperBound = numArray3.GetUpperBound(0); int num4 = numArray3.GetUpperBound(1); for (int i = numArray3.GetLowerBound(0); i <= upperBound; i++) { for (int j = numArray3.GetLowerBound(1); j <= num4; j++) { int num = numArray3[i, j]; Console.WriteLine(num); } } ```
The query works in VB.Net because it gets transformed into ``` IEnumerable<object> q = m.Cast<object>().Select<object, object>(o => o); ``` This works because you can call `Cast<TResult>`() on `IEnumerable`, which `[*,*]` implements. The LINQ query doesn't work in C# because of the different approach the C# and VB.Net designers took. VB.Net takes a more hand holding approach and fixes your mistake and converts `IEnumerable` to `IEnumerable<object>` so it can be used. In C#, you can simulate this by using ``` var q = from e in m.Cast<object>() select e; ```
There are two reasons they don't implement it natively in C#: * There's more than one way you could do it. Do you want each 'cell', or do you want each 'row'? And how do you define 'row': [], IEnumerable, other? What if there are more than two dimensions? As soon as they pick one way, an army of developers will tell them they should have done it a different way. * Thanks to iterator blocks and the `yield` keyword, it just so easy to implement your own that's specific to your need at the time. Of course, that's a C# construct, but it's not *that* much harder in VB.
Multidimensional arrays do not implement IEnumerable<T>, or do they?
[ "", "c#", "vb.net", "arrays", "clr", "" ]
I need a method to run every so often that does some database processing. However, I may need it to be triggerable by an admin on the site. But I don't want this method being run more than once at the same time, as this could cause issues with the way it hits the database. For example, could I... Create a singleton class that runs the method on a timer, and instantiate it in the global.asax file. Then, since it's a singleton, I can call it from my normal .aspx pages and call the method whenever I want. I would probably need to use that "lock" feature of C# to check to see if the method is already running. I heard some talk lately that Singletons are "evil", but this seems like the perfect fit for it. What do you think? Thanks in advance.
Timers and locks (that are intended to synchronize access to the database) are a bad idea on the web; you may have zero, one or many app-pools on different servers. They may recycle at any time, and won't be spun up until needed. Basically, this won't prevent you hammering the db from multiple sources. Personally, I'd be tempted to either write a service to do this work (either db-polling, or via WCF etc), or use the db (a SP or similar) - set a flag in a table-row to say "in progress", do the work at the db, and clear the flag (duplicate attempts exit immediately while in progress).
I would do it this way 1. Build a normal ASP.NET page which does the processing 2. StealBorrow [LFSR Consultings](https://stackoverflow.com/users/33226/lfsr-consulting) idea for a flag in the DB which does the work of checking if the process is currently running 3. Use normal cronjob or windows task scheduler to call the web page on a regular basis. And [Singletons aren't evil](http://codebetter.com/blogs/jeremy.miller/archive/2005/08/04/130302.aspx) they just get abused easily.
How to implement a job that runs every hour but can also be triggered from .aspx pages?
[ "", "c#", "asp.net", "singleton", "timer", "global-asax", "" ]
I'm trying to grasp test driven development, and I'm wondering if those unit tests is fine. I have a interface which looks like this: ``` public interface IEntryRepository { IEnumerable<Entry> FetchAll(); Entry Fetch(int id); void Add(Entry entry); void Delete(Entry entry); } ``` And then this class which implements that interface: ``` public class EntryRepository : IEntryRepository { public List<Entry> Entries {get; set; } public EntryRepository() { Entries = new List<Entry>(); } public IEnumerable<Entry> FetchAll() { throw new NotImplementedException(); } public Entry Fetch(int id) { return Entries.SingleOrDefault(e => e.ID == id); } public void Add(Entry entry) { Entries.Add(entry); } public void Delete(Entry entry) { Entries.Remove(entry); } } ``` Theese are the unit tests I have written so far, are they fine or should I do something different? Should i be mocking the EntryRepository? ``` [TestClass] public class EntryRepositoryTests { private EntryRepository rep; public EntryRepositoryTests() { rep = new EntryRepository(); } [TestMethod] public void TestAddEntry() { Entry e = new Entry { ID = 1, Date = DateTime.Now, Task = "Testing" }; rep.Add(e); Assert.AreEqual(1, rep.Entries.Count, "Add entry failed"); } [TestMethod] public void TestRemoveEntry() { Entry e = new Entry { ID = 1, Date = DateTime.Now, Task = "Testing" }; rep.Add(e); rep.Delete(e); Assert.AreEqual(null, rep.Entries.SingleOrDefault(i => i.ID == 1), "Delete entry failed"); } [TestMethod] public void TestFetchEntry() { Entry e = new Entry { ID = 2, Date = DateTime.Now, Task = "Testing" }; rep.Add(e); Assert.AreEqual(2, rep.Fetch(2).ID, "Fetch entry failed"); } } ``` Thanks!
Just off the top of my head... Although your testing of add really only tests the framework: * You've got adding 1 item, that's good * what about adding LOTS of items (I mean, ridiculous amounts - for what value of n entries does the container add fail?) * what about adding no items? (null entry) * if you add items to the list, are they in a particular order? should they be? likewise with your fetch: * what happens in your fetch(x) if x > rep.Count ? * what happens if x < 0? * what happens if the rep is empty? * does x match performance requirements (what's it's algorithmic complexity? is it within range when there's just one entry and when there's a ridiculously large amount of entries? There's a good checklist in the book [Pragmatic Unit Testing](https://rads.stackoverflow.com/amzn/click/com/0974514020) (good book, highly recommended) * Are the results right? * Are all the boundary conditions CORRECT + Conform to an expected format + Ordered correctly + In a reasonable range + Does it Reference any external dependencies + Is the Cardinality correct? (right number of values) + does it complete in the correct amount of Time (real or relative) * Can you check inverse relationships * Can you cross check the results with another proven method * Can you force error conditions * Are performance characteristics within bounds
Here's some thoughts: **Positive** * You're Unit Testing! * You're following the convention Arrange, Act, Assert **Negative** * Where's the test to remove an entry when there's no entry? * Where's the test to fetch an entry when there's no entry? * What is supposed to happen when you add two entries and remove one? Which one should be left? * Should `Entries` be public. The fact that one of your asserts calls `rep.Entries.SingleOrDefault` suggests to me you're not constructing the class correctly. * Your test naming is a bit vague; typically a good pattern to follow is: `{MethodName}_{Context}_{Expected Behavior}` that remove the redundancy "test" redundancy. As a beginner to TDD I found the book [Test-Driven Development By Example](https://rads.stackoverflow.com/amzn/click/com/0321146530) to be a huge help. Second, Roy Osherove has some good [Test Review](http://weblogs.asp.net/rosherove/archive/2009/03/23/test-review-3-unity.aspx) video tutorials, check those out.
Are those unit tests fine?
[ "", "c#", ".net", "unit-testing", "tdd", "mocking", "" ]
My project **requires I use VB (5 or 6)\*** to store a date in an SQL Server database. The SQL datetime type includes the time, which I don't want. I'm also aware that VB's representation of a date doesn't mirror that of SQL Server. So, how can I store a date held in VB's date type in the SQL database, as the datetime at midnight on that date, for example? Edit: I need to use the date to select rows further down the line, so I can't get away with just truncating it on read. \*I know, I you were me, you wouldn't start from here. But given the constraints, any VB6/MS SQL fiends out there?
VB6 has a [`DateValue()`](http://www.vb6.us/tutorials/date-time-functions-visual-basic) function which returns the date portion of a Date/Time value, with the time portion "zeroed out". (Note: When the time portion of a date/time variable is "zeroed out", the time would be interpreted as 12:00 AM.)
SQL Server 2008 has [new date and time data types](http://msdn.microsoft.com/en-us/library/ms186724.aspx). There is the "Date" data type if you don't want to store the time component.
How do I store just a date in MS SQL from VB?
[ "", "sql", "sql-server", "datetime", "vb6", "" ]
I am currently using javax.imageio.ImageIO to write a PNG file. I would like to include a tEXt chunk (and indeed any of the chunks [listed here](http://en.wikipedia.org/wiki/Portable_Network_Graphics#Ancillary_chunks)), but can see no means of doing so. By the looks of com.sun.imageio.plugins.png.PNGMetadata it should be possible. I should be most grateful for any clues or answers. M.
The solution I struck upon after some decompilation, goes as follows ... ``` RenderedImage image = getMyImage(); Iterator<ImageWriter> iterator = ImageIO.getImageWritersBySuffix( "png" ); if(!iterator.hasNext()) throw new Error( "No image writer for PNG" ); ImageWriter imagewriter = iterator.next(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); imagewriter.setOutput( ImageIO.createImageOutputStream( bytes ) ); // Create & populate metadata PNGMetadata metadata = new PNGMetadata(); // see http://www.w3.org/TR/PNG-Chunks.html#C.tEXt for standardized keywords metadata.tEXt_keyword.add( "Title" ); metadata.tEXt_text.add( "Mandelbrot" ); metadata.tEXt_keyword.add( "Comment" ); metadata.tEXt_text.add( "..." ); metadata.tEXt_keyword.add( "MandelbrotCoords" ); // custom keyword metadata.tEXt_text.add( fractal.getCoords().toString() ); // Render the PNG to memory IIOImage iioImage = new IIOImage( image, null, null ); iioImage.setMetadata( metadata ); // Attach the metadata imagewriter.write( null, iioImage, null ); ```
We do this in the [JGraphX](https://github.com/jgraph/jgraphx) project. Download the source code and have a look in the com.mxgraph.util.png package, there you'll find three classes for encoding that we copied from the Apache Batik sources. An example of usage is in com.mxgraph.examples.swing.editor.EditorActions in the saveXmlPng method. Slightly edited the code looks like: ``` mxPngEncodeParam param = mxPngEncodeParam .getDefaultEncodeParam(image); param.setCompressedText(new String[] { "mxGraphModel", xml }); // Saves as a PNG file FileOutputStream outputStream = new FileOutputStream(new File( filename)); try { mxPngImageEncoder encoder = new mxPngImageEncoder(outputStream, param); if (image != null) { encoder.encode(image); } } finally { outputStream.close(); } ``` Where image is the BufferedImage that will form the .PNG and xml is the string we wish to place in the iTxt section. "mxGraphModel" is the key for that xml string (the section comprises some number of key/value pairs), obviously you replace that with your key. Also under com.mxgraph.util.png we've written a really simple class that extracts the iTxt without processing the whole image. You could apply the same idea for the tEXt chunk using mxPngEncodeParam.setText instead of setCompressedText(), but the compressed text section does allow for considerable larger text sections.
How can I save a PNG with a tEXt or iTXt chunk from Java?
[ "", "java", "text", "png", "javax.imageio", "" ]
I have a Java webapp using Hibernate and MySQL. If the site isn't used for a few days, the MySQL connection goes stale, and I am met with the following exception: ``` com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Connection.close() has already been called. Invalid operation in this state. ``` From experience using raw JDBC it is possible to configure the connection to attempt to recover from errors or stale connections, but I don't know how to do this using Hibernate. I am not explicitly calling close() anywhere (but I am betting Hibernate does somewhere deep down in its guts). Does anybody know what I should do?
What connection pool are you using? The [Hibernate suggestion](http://www.hibernate.org/117.html#A15) is not to use the built-in pooling, but use the application server datasource or something like [Commons DBCP](http://commons.apache.org/dbcp/) or [C3PO](http://sourceforge.net/projects/c3p0).
I had that problem. Using connection pooling (c3p0) made it go away. It is also a good idea in general to use some connection pooling.
How to avoid stale MySQL/Hibernate connections (MySQLNonTransientConnectionException)
[ "", "java", "mysql", "hibernate", "" ]
I am not using a pre-made shopping cart, I programming it myself. It works perfectly fine 99% of the time, but about once every couple months an order goes through for $0. I cannot figure out why. I make a test purchase with the same product and all the same info and I cannot get it to be $0 for me. I am not sure how to go about trouble shooting this, I do have a disclaimer saying that we do not honor erroneous prices. The client wants this to stop happening though. I am using PHP to do all of this. Since I cannot seem to duplicate the occurnace myself I am finding it hard to get to the bottom of the issue. Can anyone offer some advice on how to troubleshoot this? Thanks!!
Ultimately, you'll want to figure out why this is happening. Without seeing your code, I can't really help you out much with that. In the short term though, why not just add a sanity check at the end of the checkout process? ``` if ( $final_price < 1 ) { do_epic_fail(); // Show an error, whatever. } ```
I'd start by using some extensive order logging. Every click, every input, every sql query. Then when it happens again go through the logs of that order to see what happened. There are a couple of possibilities that spring to mind. One, you have a transient error in the queries to pull the item totals. Maybe when the query fails you just default to 0.00. For example, what happens when they type -1 for the quantity or put in some text like 'ABC' Alternatively you might have a sql injection issue where if the user puts something wrong in one of the fields it loads a zero value for price. Whatever it is will come to light with the right logging.
shopping cart sometimes makes sales for $0...how to troubleshoot?
[ "", "php", "shopping-cart", "" ]
My app needs to block sleep/hibernate mode. I have the code in place, but after successfully catching the **WM\_POWERBROADCAST** message, neither **PBT\_APMQUERYSUSPEND** nor **PBT\_APMQUERYSTANDBY** are being caught successfully. Interestingly, the **PBT\_APMRESUMECRITICAL** and **PBT\_APMRESUMEAUTOMATIC** messages *are* being caught by my app. Bottom line question: is there any reason why my app would fail to catch the standby/suspend messages, but succeed in catching the resume messages? This [Q&A](https://stackoverflow.com/questions/629240/prevent-windows-from-going-into-sleep-when-my-program-is-running) [stackoverflow.com] helped, btw, but again, the messages don't seem to be making it to my app. My code (w/ event logging code removed for brevity): ``` protected override void WndProc(ref System.Windows.Forms.Message m) { // Power status event triggered if (m.Msg == (int)NativeMethods.WindowMessage.WM_POWERBROADCAST) { // Machine is trying to enter suspended state if (m.WParam.ToInt32() == (int)NativeMethods.WindowMessage.PBT_APMQUERYSUSPEND || m.WParam.ToInt32() == (int)NativeMethods.WindowMessage.PBT_APMQUERYSTANDBY) { // Have perms to deny this message? if((m.LParam.ToInt32() & 0x1) != 0) { // If so, deny broadcast message m.Result = new IntPtr((int)NativeMethods.WindowMessage.BROADCAST_QUERY_DENY); } } return; // ?! } base.WndProc(ref m); } ```
It works now, for both XP and Vista. I created a stub winform app with the relevant code (could be cleaned up, obviously, but it conveys the point). ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace standbyTest { public partial class Form1 : Form { [DllImport("Kernel32.DLL", CharSet = CharSet.Auto, SetLastError = true)] protected static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE state); [Flags] public enum EXECUTION_STATE : uint { ES_CONTINUOUS = 0x80000000, ES_DISPLAY_REQUIRED = 2, ES_SYSTEM_REQUIRED = 1, ES_AWAYMODE_REQUIRED = 0x00000040 } public Form1() { if(Environment.OSVersion.Version.Major > 5) { // vista and above: block suspend mode SetThreadExecutionState(EXECUTION_STATE.ES_AWAYMODE_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS); } InitializeComponent(); //MessageBox.Show(string.Format("version: {0}", Environment.OSVersion.Version.Major.ToString() )); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); if(Environment.OSVersion.Version.Major > 5) { // Re-allow suspend mode SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS); } } protected override void WndProc(ref System.Windows.Forms.Message m) { // Power status event triggered if(m.Msg == (int)WindowMessage.WM_POWERBROADCAST) { // Machine is trying to enter suspended state if(m.WParam.ToInt32() == (int)WindowMessage.PBT_APMQUERYSUSPEND || m.WParam.ToInt32() == (int)WindowMessage.PBT_APMQUERYSTANDBY) { // Have perms to deny this message? if((m.LParam.ToInt32() & 0x1) != 0) { // If so, deny broadcast message m.Result = new IntPtr((int)WindowMessage.BROADCAST_QUERY_DENY); } } return; } base.WndProc(ref m); } } internal enum WindowMessage { /// <summary> /// Notify that machine power state is changing /// </summary> WM_POWERBROADCAST = 0x218, /// <summary> /// Message indicating that machine is trying to enter suspended state /// </summary> PBT_APMQUERYSUSPEND = 0x0, PBT_APMQUERYSTANDBY = 0x0001, /// <summary> /// Message to deny broadcast query /// </summary> BROADCAST_QUERY_DENY = 0x424D5144 } } ```
Try to subscribe the PowerModeChanged event: [How do I check when the computer is being put to sleep or wakes up?](https://stackoverflow.com/questions/1562474/how-do-i-check-when-the-computer-is-being-put-to-sleep-or-wakes-up)
Can't catch sleep/suspend messages (winXP)
[ "", "c#", "sleep-mode", "hibernate-mode", "" ]
What are situation when you want to use window.showModalDialog function? It seams that you can do exactly the same with window.open function and few parameters that remove some of the chrome (navigation, addressbar, etc...) When would you want to use window.showModalDialog and window.open?
Modal dialogs are dialogs that once opened by the parent, do not allow you to focus on the parent until the dialog is closed. One could use a modal dialog for a login form, edit form, etc where you want to have a popup for user interaction but not allow the user to return to the window that opened the popup. As a side note, I believe only Internet Explorer implementes `window.showModalDialog`, so that kind of limits your usage of it.
It has been a few years since this question was originally asked and things have changed a bit since then. `window.showModalDialog` is now officially [standardized as part of HTML5](http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dialogs-implemented-using-separate-documents) and is supported in IE, Firefox 3+, Chrome ([albeit buggy](http://code.google.com/p/chromium/issues/detail?id=16045)), and Safari 5.1+. Unfortunately `window.showModalDialog` is still plagued by a number of issues. * Modal dialogs are blocked as popups by default in Firefox, Chrome, and Safari. * The modal dialogs in Chrome are buggy and aren't truly modal - see <http://code.google.com/p/chromium/issues/detail?id=16045> & <http://code.google.com/p/chromium/issues/detail?id=42939>. * All browsers except Chrome block the user from interacting with the entire window (favorites, browser controls, other tabs, etc...) when a modal dialog is up. * They're a pain to debug because they halt JavaScript execution in the parent window while waiting for the modal dialog to complete. * No mobile browsers support `window.showModalDialog`. Therefore it's still not a good idea to use `window.showModalDialog`. If you need the window opened to be modal (i.e. the user cannot interact with the rest of the page until they deal with the dialog) I would suggest using [jQuery UI's dialog plugin](http://jqueryui.com/demos/dialog/). `window.open` will work for non modal windows but I would stick with jQuery UI's dialog because opening new windows tends to annoy users. If you're interested I write about this in more detail on my blog - <http://tjvantoll.com/2012/05/02/showmodaldialog-what-it-is-and-why-you-should-never-use-it/>.
window.showModalDialog vs. window.open
[ "", "javascript", "" ]
I have a silverlight app that I want to support plugin development for. I'm thinking that the plugin developer would create a dll and my main silverlight app would have some sort of config file that you would list the dll and type of the plugin, and the main app would detect, download, and load the dll for the plugin. Does this sound possible to do with silverlight? What would be the best approach?
Have a look at the Composite Application Library: <http://compositewpf.codeplex.com/> This frameworks helps you to create a moduled Silverlight application. Using this frameworks you could add new modules with ease when you are familiar with the framework.
Sounds like a feasible to me. I'd probably create a set of interfaces for my plugins and provide those in some kind of development package for plugin developers. As for loading assemblies dynamically at runtime in Silverlight, check out this link: [Silverlight - Dynamically Loading an Assembly](http://www.silverlightshow.net/items/Silverlight-Dynamically-Loading-an-Assembly.aspx)
What is the best way to support plugins with a Silverlight app?
[ "", "c#", ".net", "silverlight", "" ]
I have the following `ListView`: ``` <ListView Name="TrackListView"> <ListView.View> <GridView> <GridViewColumn Header="Title" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Name}"/> <GridViewColumn Header="Artist" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Artist.Name}" /> </GridView> </ListView.View> </ListView> ``` How can I attach an event to every bound item that will fire on double-clicking the item?
Found the solution from here: <http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/3d0eaa54-09a9-4c51-8677-8e90577e7bac/> --- XAML: ``` <UserControl.Resources> <Style x:Key="itemstyle" TargetType="{x:Type ListViewItem}"> <EventSetter Event="MouseDoubleClick" Handler="HandleDoubleClick" /> </Style> </UserControl.Resources> <ListView Name="TrackListView" ItemContainerStyle="{StaticResource itemstyle}"> <ListView.View> <GridView> <GridViewColumn Header="Title" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Name}"/> <GridViewColumn Header="Artist" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Artist.Name}" /> </GridView> </ListView.View> </ListView> ``` C#: ``` protected void HandleDoubleClick(object sender, MouseButtonEventArgs e) { var track = ((ListViewItem) sender).Content as Track; //Casting back to the binded Track } ```
No memory leaks *(no need to unsubscribe each item)*, works fine: XAML: ``` <ListView MouseDoubleClick="ListView_MouseDoubleClick" ItemsSource="{Binding TrackCollection}" /> ``` C#: ``` void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) { var item = ((FrameworkElement) e.OriginalSource).DataContext as Track; if (item != null) { MessageBox.Show("Item's Double Click handled!"); } } ```
WPF ListView: Attaching a double-click (on an item) event
[ "", "c#", "wpf", "xaml", "" ]
> **Possible Duplicate:** > [How do I calculate relative time?](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time) I want to format dates on my social web app much like Digg.com and other sites do. There, you see very friendly dates, such as: * just now * 3 minutes ago * one hour ago * 2 weeks ago * 6 months ago * etc Before I wrap my head around creating such a thing, does anyone know of any ready-to-go script for this where I simply insert a datestamp and a friendly date text is given based on how it related to the current time? PS: I need this in PHP, but pseudo-code or any other language is fine too.
This is a duplicate of this [question](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time). It has a flurry of code samples on how to accomplish this, in addition to the code this very site uses. I glanced at it and there seems to be a PHP implementation posted there too. In addition to all this, if are you using jQuery you can do this client-side with something like the [timeago](http://timeago.yarp.com/) plugin. It has the advantage of updating the text as time passes so if you load a page and it says "posted 5 minutes ago" and look again 5 minutes later, it says "posted 10 minutes ago"
Thanks all for the answers, and sorry for the duplicate question. I did not find the duplicate when I was looking for it because I did not really know what search terms to use. Anyways, I have my problem solved thanks to the PHP translation of the code used by stackoverflow. I made one tiny change in calculating the delta: ``` $delta = strtotime(gmdate("Y-m-d H:i:s", time())) - $time; ``` Since I am storing my dates in MySQL as timestamp in the GMT format, I have to use the same for calculating the CURRENT time. This makes for a timezone neutral comparison, which is exactly what is needed in my case.
How to create a friendly date format (for example "submitted 2 days ago")
[ "", "php", "date", "formatting", "" ]
A number of features were introduced into C# 3.0 which made me uneasy, such as object initializers, extension methods and implicitly typed variables. Now in C# 4.0 with things like the dynamic keyword I'm getting even more concerned. I know that each of these features **CAN** be used in appropriate ways **BUT** in my view they make it easier for developers to make bad coding decisions and therefore write worse code. It seems to me that Microsoft are trying to win market share by making the coding easy and undemanding. Personally I prefer a language that is rigorous and places more demands on my coding standards and forces me to structure things in an OOP way. Here are a few examples of my concerns for the features mentioned above: Object constructors can do important logic that is not exposed to the consumer. This is in the control of the object developer. Object initializers take this control away and allow the consumer to make the decisions about which fields to initialize. EDIT: I had not appreciated that you can mix constructor and initializer (my bad) but this starts to look messy to my mind and so I am still not convinced it is a step forward. Allowing developers to extend built-in types using extension methods allows all and sundry to start adding their favourite pet methods to the string class, which can end up with a bewildering array of options, or requires more policing of coding standards to weed these out. Allowing implicitly typed variables allows quick and dirty programming instead or properly OOP approaches, which can quickly become an unmanageable mess of vars all over your application. Are my worries justified?
Object initializers simply allow the client to set properties immediately after construction, no control is relinquished as the caller must still ensure all of the constructor arguments are satisfied. Personally I feel they add very little: ``` Person p1 = new Person("Fred"); p1.Age = 30; p1.Height = 123; Person p2 = new Person("Fred") { Age = 30; Height = 123; }; ``` I know a lot of people dislike the 'var' keyword. I can understand why as it is an openly inviting abuse, but I do not mind it providing the type is blindingly obvious: ``` var p1 = new Person("Fred"); Person p2 = GetPerson(); ``` In the second line above, the type is not obvious, despite the method name. I would use the type in this case. Extension methods -- I would use very sparingly but they are very useful for extending the .NET types with convenience methods, especially IEnumerable, ICollection and String. String.IsNullOrEmpty() as an extension method is very nice, as it can be called on null references. I do not think you need to worry, good developers will always use their tools with respect and bad developers will always find ways to misue their tools: limiting the toolset will not solve this problem.
You could limit the features of C# 3.0 your developers can use by writing the restrictions into your coding standards. Then when code is reviewed prior to check in, any code that breaches these rules should be spotted and the check in refused. One such case could well be extension methods. Obviously, your developers will want to use the new features - all developers do. However, if you've got good, well documented reasons why they shouldn't be used, good developers will follow them. You should also be open to revising these rules as new information comes to light. With VS 2008 you can specify which version of .NET you want to target (Right click over the solution and select Properties > Application). If you limit yourself to .NET 2.0 then you won't get any of the new features in .NET 3.5. Obviously this doesn't help if you want to use some of the features. However, I think your fears over `vars` are unwarranted. C# is still as strongly typed as ever. Declaring something as `var` simply tells the compiler to pick the best type for this variable. The variable can't change type it's always an `int` or `Person` or whatever. Personally I follow the same rules as Paul Ruane; if the type is clear from the syntax then use a `var`; if not name the type explicitly.
How do you deal with new features of C# so that they don't lead to poorly written code?
[ "", "c#", "coding-style", "" ]
I have a three projects in the solution WinSync. I have WinSyncGui, WinSyncLib and Setup. WinSyncGui requires files from WinSyncLib. How can I get it to include WinSyncLib in WinSyncGui? VS complains The type or namespace name 'WinSyncLib' could not be found (are you missing a using directive or an assembly reference?) I've set the dependencies so that WinSyncGui depends on WinSyncLib (so Lib is built first), but it's still not working.
You need to add WinSyncLib as a reference in your WinSyncGui project. [Adding a project reference.](http://msdn.microsoft.com/en-us/library/wkze6zky(VS.80).aspx)
Right click your project (WebSyncGui) and select Add Reference, Projects tab, and then select the project you need to reference.
Project Dependencies in Visual Studio
[ "", "c#", ".net", "visual-studio-2008", "dependencies", "" ]
I am self-studying a C# reference and it gives the following information: 1.21.4. Declaring Generic Parameters Generic parameters can be introduced in the declaration of classes, structs, interfaces, delegates (see the upcoming "Delegates" section), and methods. Other constructs, such as properties, cannot introduce a generic parameter, but can use a generic parameter. For example, the property Value uses T: ``` public struct Nullable<T> { public T Value {get;} } ``` First, I get an error trying to compile this saying that it must contain a body because it is neither abstract nor extern or that automatic parameters must have both get and set accessors. Second, assuming it is wrong and I correct it by adding "set;", I cannot seem to format a call to it successfully.
I'm not sure if you just picked a bad example for your struct name (since Nullable is a framework struct), but if not, the error is due to the fact that you have no set accessor in your property. Automatic properties (added in C# 3.0) need both a get and set property. So, if you change the code to: ``` public struct Nullable<T> { public T Value {get; set; } } ``` it should work. In this case, the error had nothing to do with generics. To create an instance, you could use: ``` Nullable<int> i = new Nullable<int>(); ``` This will make it compile. However, as both Jon and Cerebrus has pointed out, it's probably just an example to show the workings of generics.
That is just showing the API of `Nullable<T>` rather than the implementation. It's not meant to be compiled - `System.Nullable<T>` is part of the framework, you don't have to implement it yourself.
Need help understanding C# generics
[ "", "c#", "visual-studio", "" ]
C++ references have two properties: * They always point to the same object. * They can not be 0. Pointers are the opposite: * They can point to different objects. * They can be 0. Why is there no "non-nullable, reseatable reference or pointer" in C++? I can't think of a good reason why references shouldn't be reseatable. **Edit:** The question comes up often because I usually use references when I want to make sure that an "association" (I'm avoiding the words "reference" or "pointer" here) is never invalid. I don't think I ever thought "great that this ref always refers to the same object". If references were reseatable, one could still get the current behavior like this: ``` int i = 3; int& const j = i; ``` This is already legal C++, but meaningless. **I restate my question like this:** "What was the rationale behind the 'a reference *is* the object' design? Why was it considered useful to have references *always* be the same object, instead of only when declared as const?" Cheers, Felix
The reason that C++ does not allow you to rebind references is given in Stroustrup's "Design and Evolution of C++" : > It is not possible to change what a reference refers to after initialization. That is, once a C++ reference is initialized it cannot be made to refer to a different object later; it cannot be re-bound. I had in the past been bitten by Algol68 references where `r1=r2` can either assign through `r1` to the object referred to or assign a new reference value to `r1` (re-binding `r1`) depending on the type of `r2`. I wanted to avoid such problems in C++.
In C++, it is often said that "the reference *is* the object". In one sense, it is true: though references are handled as pointers when the source code is compiled, the reference is intended to signify an object that is not copied when a function is called. Since references are not directly addressable (for example, references have no address, & returns the address of the object), it would not semantically make sense to reassign them. Moreover, C++ already has pointers, which handles the semantics of re-setting.
Why are references not reseatable in C++
[ "", "c++", "pointers", "reference", "language-design", "" ]
My PHP script writes to a file so that it can create a jpg image. ``` fwrite($handle, $GLOBALS['HTTP_RAW_POST_DATA']); fclose($handle); print $newfile.'.jpg'; ``` I have put this script on a new server however the image never gets saved. The permission of the folder it saves to is 755 but it does not own it. Last time, I think I fixed the issue by changing the directory owner to apache as this is what PHP runs as. I can not do the same again because I am not root. Firstly., Is there another fix? Secondly, If I could change the owner of the directory like last time will this fix the issue? Thanks all for any help
1. change permissions of the folder to 777 (`rwxrwxrwx`) 2. from PHP create subdirectory with [mkdir](http://www.php.net/manual/en/function.mkdir.php) 3. change your directory permissions back to 755 (`rwxr-xr-x`) or even better 711 (`rwx--x--x`) 4. from now on save your images in the subdirectory, which is now owned by www-data (or whichever user Apache uses). BTW. you can reduce following code: ``` fopen($newfile.'.jpg','wb'); fwrite($handle, $GLOBALS['HTTP_RAW_POST_DATA']); fclose($handle); print $newfile.'.jpg'; ``` to: ``` file_put_contents($newfile.'.jpg', file_get_contents('php://input', FILE_BINARY), FILE_BINARY) ```
If you're not the owner, then yes, the directory being 755 is a problem. To break it down, 755 is: * user (owner) has read (4), write (2), and execute (1) * group has read (4) and execute (1) * others have read (4) and execute (1) Notice that **only** the owner has write privileges with 755. P.S. fopen should return an error if the open failed.
Write to Directory using PHP: Is this a permissions problem?
[ "", "php", "linux", "apache", "file", "permissions", "" ]
I'm writing a [microformats](http://microformats.org) parser in C# and am looking for some refactoring advice. This is probably the first "real" project I've attempted in C# for some time (I program almost exclusively in VB6 at my day job), so I have the feeling this question may become the first in a series ;-) Let me provide some background about what I have so far, so that my question will (hopefully) make sense. Right now, I have a single class, `MicroformatsParser`, doing all the work. It has an overloaded constructor that lets you pass a `System.Uri` or a `string` containing a URI: upon construction, it downloads the HTML document at the given URI and loads it into an `HtmlAgilityPack.HtmlDocument` for easy manipulation by the class. The basic API works like this (or will, once I finish the code...): ``` MicroformatsParser mp = new MicroformatsParser("http://microformats.org"); List<HCard> hcards = mp.GetAll<HCard>(); foreach(HCard hcard in hcards) { Console.WriteLine("Full Name: {0}", hcard.FullName); foreach(string email in hcard.EmailAddresses) Console.WriteLine("E-Mail Address: {0}", email); } ``` The use of generics here is intentional. I got my inspiration from the way that the the Microformats library in Firefox 3 works (and the Ruby `mofo` gem). The idea here is that the parser does the heavy lifting (finding the actual microformat content in the HTML), and the microformat classes themselves (`HCard` in the above example) basically provide the schema that tells the parser how to handle the data it finds. The code for the `HCard` class should make this clearer (note this is a not a complete implementation): ``` [ContainerName("vcard")] public class HCard { [PropertyName("fn")] public string FullName; [PropertyName("email")] public List<string> EmailAddresses; [PropertyName("adr")] public List<Address> Addresses; public HCard() { } } ``` The attributes here are used by the parser to determine how to populate an instance of the class with data from an HTML document. The parser does the following when you call `GetAll<T>()`: * Checks that the type `T` has a `ContainerName` attribute (and it's not blank) * Searches the HTML document for all nodes with a `class` attribute that matches the `ContainerName`. Call these the "container nodes". * For each container node: + Uses reflection to create an object of type `T`. + Get the public fields (a `MemberInfo[]`) for type `T` via reflection + For each field's `MemberInfo` - If the field has a `PropertyName` attribute * Get the value of the corresponding microformat property from the HTML * **Inject the value found in the HTML into the field (i.e. set the value of the field on the object of type `T` created in the first step)** * Add the object of type `T` to a `List<T>` + Return the `List<T>`, which now contains a bunch of microformat objects I'm trying to figure out a better way to implement the step in **bold**. The problem is that the `Type` of a given field in the microformat class determines not only what node to look for in the HTML, but also how to interpret the data. For example, going back to the `HCard` class I defined above, the `"email"` property is bound to the `EmailAddresses` field, which is a `List<string>`. After the parser finds all the `"email"` child nodes of the parent `"vcard"` node in the HTML, it has to put them in a `List<string>`. What's more, if I want my `HCard` to be able to return phone number information, I would probably want to be able to declare a new field of type `List<HCard.TelephoneNumber>` (which would have its own `ContainerName("tel")` attribute) to hold that information, because there can be multiple `"tel"` elements in the HTML, and the `"tel"` format has its own sub-properties. But now the parser needs to know how to put the telephone data into a `List<HCard.TelephoneNumber>`. The same problem applies to `Float`S, `DateTime`S, `List<Float>`S, `List<Integer>`S, etc. The obvious answer is to have the parser switch on the type of field, and do the appropriate conversions for each case, but I want to avoid a giant `switch` statement. Note that I'm not planning to make the parser support every possible `Type` in existence, but I will want it to handle most scalar types, and the `List<T>` versions of them, along with the ability to recognize other microformat classes (so that a microformat class can be composed from other microformat classes). Any advice on how best to handle this? Since the parser has to handle primitive data types, I don't think I can add polymorphism at the type level... My first thought was to use method overloading, so I would have a series of a `GetPropValue` overloads like `GetPropValue(HtmlNode node, ref string retrievedValue)`, `GetPropValue(HtmlNode, ref List<Float> retrievedValue)`, etc. but I'm wondering if there is a better approach to this problem.
Mehrdad's approach is basically the one I'd suggest to start with, but as the first step out of potentially more. You can use a simple `IDictionary<Type,Delegate>` (where each entry is actually from `T` to `Func<ParseContext,T>` - but that can't be expressed with generics) for single types (strings, primitives etc) but then you'll also want to check for lists, maps etc. You won't be able to do this using the map, because you'd have to have an entry for each type of list (i.e. a separate entry for `List<string>`, `List<int>` etc). Generics make this quite tricky - if you're happy to restrict yourself to *just* certain concrete types such as `List<T>` you'll make it easier for yourself (but less flexible). For instance, detecting `List<T>` is straightforward: ``` if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { // Handle lists // use type.GetGenericArguments() to work out the element type } ``` Detect whether a type implements `IList<T>` for some `T` (and then discovering `T`) can be a pain, especially as there could be multiple implementations, and the concrete type itself may or may not be generic. This effort could be worthwhile if you really need a very flexible library used by thousands of developers - but otherwise I'd keep it simple.
Instead of a large switch statement you can construct a dictionary that maps the string to a delegate and look it up when you want to parse using the appropriate method.
How would you refactor a "switch on Type" to be polymorphic if you don't control the types involved?
[ "", "c#", "generics", "oop", "reflection", "" ]
I would like to use Python 2.6's version of subprocess, because it allows the [Popen.terminate()](http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate) function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of `from __future__ import subprocess_module`?
I know this question has already been answered, but for what it's worth, I've used the `subprocess.py` that ships with Python 2.6 in Python 2.3 and it's worked fine. If you read the comments at the top of the file it says: > `# This module should remain compatible with Python 2.2, see PEP 291.`
There isn't really a great way to do it. subprocess is [implemented in python](http://svn.python.org/view/python/trunk/Lib/subprocess.py?rev=69620&view=markup) (as opposed to C) so you could conceivably copy the module somewhere and use it (hoping of course that it doesn't use any 2.6 goodness). On the other hand you could simply implement what subprocess claims to do and write a function that sends SIGTERM on \*nix and calls TerminateProcess on Windows. The following implementation has been tested on linux and in a Win XP vm, you'll need the [python Windows extensions](http://sourceforge.net/projects/pywin32/): ``` import sys def terminate(process): """ Kills a process, useful on 2.5 where subprocess.Popens don't have a terminate method. Used here because we're stuck on 2.5 and don't have Popen.terminate goodness. """ def terminate_win(process): import win32process return win32process.TerminateProcess(process._handle, -1) def terminate_nix(process): import os import signal return os.kill(process.pid, signal.SIGTERM) terminate_default = terminate_nix handlers = { "win32": terminate_win, "linux2": terminate_nix } return handlers.get(sys.platform, terminate_default)(process) ``` That way you only have to maintain the `terminate` code rather than the entire module.
Use Python 2.6 subprocess module in Python 2.5
[ "", "python", "subprocess", "python-2.5", "" ]
I currently have a method within my class that has to call other methods, some in the same object and others from other objects. ``` class MyClass { public function myMethod() { $var1 = $this->otherMethod1(); $var2 = $this->otherMethod2(); $var3 = $this->otherMethod3(); $otherObject = new OtherClass(); $var4 = $otherObject->someMethod(); # some processing goes on with these 4 variables # then the method returns something else return $var5; } } ``` I'm new to the whole TDD game, but some of what I *think* I understood to be key premises to more testable code are composition, loose coupling, with some strategy for Dependency Injection/Inversion of Control. How do I go about refactoring a method into something more testable in this particular situation? Do I pass the `$this` object reference to the method as a parameter, so that I can easily mock/stub the collaborating methods? Is this recommended or is it going overboard? ``` class MyClass { public function myMethod($self, $other) { # $self == $this $var1 = $self->otherMethod1(); $var2 = $self->otherMethod2(); $var3 = $self->otherMethod3(); $var4 = $other->someMethod(); # ... return $var5; } } ``` Also, it is obvious to me that dependencies are a pretty big deal with TDD, as one has to think about how to inject a stub/mock to the said method for tests. Do most TDDers use DI/IoC as a primary strategy for public dependencies? at which point does it become exaggerated? can you give some pointers to do this efficiently?
These are some good questions... let me first say that I do not really know JS at all, but I am a unit tester and have dealt with these issues. I first want to point out that JsUnit exists if you are not using it. I wouldn't worry too much about your method calling other methods within the same class... this is bound to happen. What worries me more is the creation of the other object, depending on how complicated it is. For example, if you are instantiating a class that does all kinds of operations over the network, that is too heavy for a simple unit test. What you would prefer to do is mock out the dependency on that class so that you can have the object produce the result you would expect to receive from its operations on the network, without incurring the overhead of going on the network: network failures, time, etc... Passing in the other object is a bit messy. What people typically do is have a factory method to instantiate the other object. The factory method can decide, based on whether or not you are testing (typically via a flag) whether or not to instantiate the real object or the mock. In fact, you may want to make the other object a member of you class, and within the constructor, call the factory, or make the decision right there whether or not to instantiate the mock or the real thing. Within the setup function or within your test cases you can set special conditions on the mock object so that it will return the proper value. Also, just make sure you have tests for your other functions in the same class... I hope this helps!
Looks like the whole idea of this class is not quite correct. In TDD your are testing classes, but not methods. If a method has it own responsibility and provides it's own (separate testable) functionality it should be moved to a separate class. Otherwise it just breaks the whole OOP encapsulation thing. Particularly it breaks the Single Responsibility Principle. In your case, I would extract the tested method into another class and injected `$var1`, `$var2`, `$var3` and `$other` as dependencies. The `$other` should be mocked, as well any object which tested class depends on. ``` class TestMyClass extends MyTestFrameworkUnitTestBase{ function testMyClass() { $myClass = new MyClass(); $myClass->setVar1('asdf'); $myClass->setVar2(23); $myClass->setVar3(78); $otherMock = getMockForClassOther(); $myClass->setOther($otherMock); $this->assertEquals('result', $myClass->myMethod()); } } ``` Basic rule I use is: If I want to test something, I should make it a class. This is not always true in PHP though. But it works in PHP in 90% of cases. (Based on my experience)
Refactoring a method having dependencies within the same object into something more testable (PHP)
[ "", "php", "unit-testing", "tdd", "dependency-injection", "inversion-of-control", "" ]
Is there a simple way to convert a bitmask in to an array index? ie. If i've got an enum ``` a = 0x01, b = 0x02, c = 0x04, d = 0x08, e = 0x10, etc ``` and I want to store releated data in an array, is there a simple way such that i can convert a to 0, b to 1, c to 2. etc? Many thanks
``` r = ln base 2 and programmatically, unsigned int v=yourEnumValue; unsigned r = 0; while (v >>= 1) { r++; } r is your answer ```
I'm not sure if this is what you're asking, but why don't you just take a 2-base log?
Bitmask to Array Index
[ "", "c++", "indexing", "bitmask", "" ]
I have a web service that returns me a JSON object that contains the string "Hello World". How do I pull this string out of the object? data = [object Object] Thanks Nick
You have to know how is your object, what members the object have. You could try something like ``` for(var e in data) alert(e + ' : ' + data[e]); ```
You can either use `eval`: ``` var foo = eval('(' + data + ')'); ``` But that is potentially dangerous, especially if you don't trust what is being sent from the server. Thus, the best way (and most secure way) to extract data from a JSON object is by using [Crockford's JSON library](http://www.json.org/js.html): ``` var foo = JSON.parse(data); ``` --- Btw, if you're using jQuery to query ASP.Net Web Services, be careful of the the `d.` issue (which is used as a container object). Thus to extract the returned object, you have to do: ``` var foo = JSON.parse(data); if (foo) { //Foo is not null foo = f.d; } ``` More information about this here: <http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/>
Pull string value out of JSON object
[ "", "asp.net", "javascript", "jquery", "web-services", "json", "" ]
I am working on a project for a client which needs an automatic login from a link click. I'm using a handshake page to do this with the following code: ``` $username = "admin"; $password = "blog"; $url = "http://wordpressblogURL/"; $cookie = "cookie.txt"; $postdata = "log=" . $username . "&pwd=" . $password . "&wp-submit=Log%20In&redirect_to=" . $url . "blog/wordpress/wp-admin/&testcookie=1"; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url . "blog/wordpress/wp-login.php"); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); curl_setopt ($ch, CURLOPT_TIMEOUT, 60); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 0); curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt ($ch, CURLOPT_REFERER, $url . "blog/wordpress/wp-login.php"); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); curl_setopt ($ch, CURLOPT_POST, 1); $result = curl_exec ($ch); curl_close($ch); echo $result; exit; ``` This works fine. It logs me in great. The problem is that I believe WordPress keys off of the URL. To elaborate, my handshake page (which logs me in) is in the "blog" directory and my WordPress application is in the "wordpress" directory which sits inside the "blog" directory. The URL in the browser says `..blog/handshake.php`. However, it has the Admin section of WordPress in the browser window. WordPress Admin links now do not function correctly, because the URL is in the `../blog` directory when it needs to be in the `..blog/wordpress/wp-admin` directory. Is there a way in [cURL](http://en.wikipedia.org/wiki/CURL) to make it so that the URL in the browser reflects the actual page? Should I be using FSockOPen instead?
Kalium got this right -- paths in the WordPress interface are relative, causing the administration interface to not work properly when accessed in this manner. Your approach is concerning in a few ways, so I'd like to make a few quick recommendations. Firstly, I would try to find a way to remove the `$username` and `$password` variables from being hard-coded. Think about how easy this is to break -- if the password is updated via the administration interface, for instance, the hard-coded value in your code will no longer be correct, and your "auto-login" will now fail. Furthermore, if someone somehow comprises the site and gains access to `handshake.php` -- well, now they've got the username and password for your blog. It looks like your WordPress installation rests on the same server as the handshake script you've written, given the path to `/blog` is relative (in your sample code). Accordingly, I'd suggest trying to mimic the session they validate against in your parent applications login. I've done this several times in the past -- just can't recall the specifics. So, for instance, your login script would not only set your login credentials, but also set the session keys required for WordPress authentication. This process will involve digging through a lot of WordPress's code, but thats the beauty of open source! Instead of using cURL and hard-coding values, try to simply integrate WordPress's authentication mechanism into your application's login mechanism. I'd start by looking at the source for `wp-login.php` and going from there. If all else fails and you're determined to not try to mesh your session authentication mechanism with that of WordPress, then you could immediately fix your problem (without fixing the more concerning aspects of your approach) with these changes to your code: First, add the following curl\_opt: ``` curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); // Enables session support ``` Then, add this after closing the cURL handler: ``` curl_close($ch); // Instead of echoing the result, redirect to the administration interface, now that the valid, authenticated session has been established header('location: blog/wordpress/wp-admin/'); die(); ``` So, in this less than ideal solution you'd use cURL to authenticate the user, and then rather than attempt to hijack the administration interface into that current page, redirect them to the regular administration interface. I hope this helps! Let me know if you need more help / the solution isn't clear.
Here is the code that worked for me: The key change is that I removed the parameter called "testcookie" from my post string. Note: add your website instead of "mywordpress" and username and password in the below code ``` $curl = curl_init(); //---------------- generic cURL settings start ---------------- $header = array( "Referer: https://mywordpress/wp-login.php", "Origin: https://mywordpress", "Content-Type: application/x-www-form-urlencoded", "Cache-Control: no-cache", "Pragma: no-cache", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15" ); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15'); curl_setopt($curl, CURLOPT_AUTOREFERER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_COOKIESESSION, true); curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookies.txt'); curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookies.txt'); //---------------- generic cURL settings end ---------------- $url = 'https://mywordpress/wp-login.php'; curl_setopt($curl, CURLOPT_URL, $url); $post = 'log=username&pwd=password&wp-submit=Log+In&redirect_to=https%3A%2F% mywordpress%2Fwp-admin%2F'; curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $post); $output = curl_exec($curl); curl_close ($curl); echo ($output) ```
PHP, cURL post to login to WordPress
[ "", "php", "wordpress", "curl", "" ]
What are differences between Actions and Commands in the context of Eclipse RCP? I know that they both contribute to the menu entries, but which one is better? And why? Of all the online resources I read, I could not get a firm understanding of the differences between both. I have not actually tried to use them, but just wanted to understand them to start with from higher level point of view. Thanks
Did you read the eclipse wiki [FAQ What is the difference between a command and an action?](http://wiki.eclipse.org/FAQ_What_is_the_difference_between_a_command_and_an_action%3F) > You probably already understand that Actions and Commands basically do the same thing: They cause a certain piece of code to be executed. They are triggered, mainly, from artificats within the user interface > > The main concern with **Actions** is that the **manifestation and the code is all stored in the Action**. > Although there is some separation in Action Delegates, they are still connected to the underlying action. Selection events are passed to Actions so that they can change their enabled state (programmatically) based on the current selection. This is not very elegant. Also to place an action on a certain workbench part you have to use several extension points. > > **Commands** pretty much solve all these issues. The basic idea is that **the Command is just the abstract idea of some code to be executed. The actual handling of the code is done by, well, handlers**. Handlers are activated by a certain state of the workbench. This state is queried by the platform core expressions. This means that we only need one global Save command which behaves differently based on which handler is currently active. ![properties of a command](https://i.stack.imgur.com/zyeAz.gif) This [article](http://blog.eclipse-tips.com/2009/01/commands-part-1-actions-vs-commands.html) details the differences **Actions**: * The **UI and handling are always tied**. There is no way you can separate each other * While Actions can be contributed to different parts of the workbench (popup menu/tool bar), all of them were **different extension points** and so you end up duplicating the XML in multiple places. The worst of it is that not all the extension points expect the same configuration. * Specifying Actions in multiple places is a **maintenance nightmare**. If you have to change the icon of an action, you need to change in all the places. * Another issue with duplicating Actions in plugin.xml is that **multiple instance of the same Actions will be created in the memory**. Commands involve more extension points, but: * Handler can be declared separately from a Command. This enables for **multiple handler declarations for the same command**. * The **activeWhen** for all the handlers are evaluated and the one that returns true for the most specific condition is selected. All these things are **done without even loading your handler in the memory. Even without loading your plugin**! * Defining the parameters is all about returning a map of display names & the ids. The name would be displayed in the key bindings page and the id would be used to invoke the command when the key sequence is pressed. * Define an IExecutionListener, which is merely an observer of the command execution so it can neither veto on it nor make any changes to the event
Just adding to VonC's excellent answer, commands might be a little overkill if your application is relatively small. They are relatively harder to setup, and they shine the most when you have multiple perspectives, editors and views. For something simple, I would go with actions.
Eclipse RCP: Actions VS Commands
[ "", "java", "eclipse", "command", "action", "rcp", "" ]
I have a list of events and each of them has a weekday registered. And now I'm trying to show all of these events, but ordered by the weekday name (monday, tuesday, wednesday...). How can I do this? I'm using LinqToSQL and Lambda Expressions. Thanks!!
``` public class Event { public string Day; } [Test] public void Te() { var dayIndex = new List<string> {"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"}; var list = new List<Event> {new Event(){Day = "saturday"}, new Event() {Day = "Monday"}, new Event() {Day = "Tuesday"}}; var sorted = list.OrderBy(e => dayIndex.IndexOf(e.Day.ToUpper())); foreach (var e in sorted) { Console.WriteLine(e.Day); } } ```
I know it is possible to sort a list using a custom class which implements IComparer(Of DateTime). So you'd create a class like this: ``` Public Class WeekDayComparer Implements IComparer(Of MyEvent) Public Function Compare(ByVal x As MyEvent, ByVal y As MyEvent) As Integer Implements System.Collections.Generic.IComparer(Of MyEvent).Compare Return GetDayOfWeekNumber(x.DayOfWeek).CompareTo(GetDayOfWeekNumber(y.DayOfWeek)) End Function Private Function GetDayOfWeekNumber(ByVal dayOfWeek As String) As Integer Select Case dayOfWeek.ToLower() Case "monday" Return 0 Case "tuesday" Return 1 Case "wednesday" Return 2 Case "thursday" Return 3 Case "friday" Return 4 Case "saturday" Return 5 Case "sunday" Return 6 Case Else Return 7 End Select End Function End Class ``` Then you'd take your list of objects and sort them using a your WeekDayComparer class. ``` events.Sort(New WeekDayComparer()) ``` This is VB, but easily converts to C#.
C# 3.0 - How can I order a list by week name starting on monday?
[ "", "c#", "linq-to-sql", "lambda", "" ]
I have a JTable with a set of uneditable cells and I want all the cells in a particular column to have a different mouse cursor displayed whilst the mouse is hovering over them. I am already using a custom renderer and setting the cursor on the renderer component doesn't seem to work (as it does for tooltips). It does seem to work for editors. Is this not possible in JTable when your cell is not being edited or am I missing something?
Add a MouseMotionListener to the JTable and then on mouseMoved() determine which column it is using JTable's columnAtPoint() and if it's the particular column you are after, setCursor() on the JTable.
Here is one way of changing the cursor at a particular column in JTable: ``` if(tblExamHistoryAll.columnAtPoint(evt.getPoint())==5) { setCursor(Cursor.HAND_CURSOR); } else { setCursor(0); } ```
Setting the mouse cursor for a particular JTable cell
[ "", "java", "swing", "jtable", "mouse-cursor", "tablecellrenderer", "" ]
I have what seems to be a simple problem that I can't solve myself. I have a WinForm app, with main method modified to accept command line arguments like this: ``` [STAThread] static void Main(String[] args) { int argCount = args.Length; } ``` This code works fine and argCount is equals to 2 when compiled in debug mode with the following execution line: program.exe -file test.txt. However as soon as I compile the program in release mode, argCount is now 1 with the same command line arguments. The only argument contains "-file test.txt". More than that it only happens if I run the compiled executable from obj/Release folder, but not from bin/Release. Unfortunately setup project takes executables from obj/Release so I can't change that. Is this a known issue and is there a way around this problem?
The command line processing should be the same, therefore something else is going on. When I try this: ``` class Program { [STAThread] static void Main(String[] args) { Console.WriteLine("Have {0} arguments", args.Length); for (int i = 0; i < args.Length; ++i) { Console.WriteLine("{0}: {1}", i, args[i]); } } } ``` and then it from the various locations I get 100% consistent results, the only way of getting arguments "merged" is to enclose them in quotes on the command line (which is specifically there to allow you do have arguments containing a space, see the last example below): ``` PS C:\...\bin\Debug> .\ConsoleApplication1.exe one two three Have 3 arguments 0: one 1: two 2: three PS C:\...\bin\Debug> pushd ..\release PS C:\...\bin\Release> .\ConsoleApplication1.exe one two three Have 3 arguments 0: one 1: two 2: three PS C:\...\bin\Release> pushd ..\..\obj\debug PS C:\...\obj\Debug> .\ConsoleApplication1.exe one two three Have 3 arguments 0: one 1: two 2: three PS C:\...\obj\Debug> pushd ..\release PS C:\...\obj\Release> .\ConsoleApplication1.exe one two three Have 3 arguments 0: one 1: two 2: three PS C:\...\obj\Release> .\ConsoleApplication1.exe -file test.txt Have 2 arguments 0: -file 1: test.txt PS C:\...\obj\Release> .\ConsoleApplication1.exe "-file test.txt" Have 1 arguments 0: -file test.txt ``` *Additional* While launching from a command prompt makes it easy to see what is being passed it can be hard to check when another application launches yours. However tools like [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx "Sysinternal") will show the command line used to start a program (double click on a process and look at the image tab).
This works for me from bin/Debug, bin/Release, obj/Debug and obj/Release: ``` static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { FormMain.Args = args; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } } public partial class FormMain: Form { public static string[] Args; public FormMain() { InitializeComponent(); } private void FormMain_Shown(object sender, EventArgs e) { foreach (string s in Args) { MessageBox.Show(s); } } } ```
C# Command Line arguments problem in Release build
[ "", "c#", ".net", "winforms", "" ]
Is there a way in Linq to do an OrderBy against a set of values (strings in this case) without knowing the order of the values? Consider this data: ``` A B A C B C D E ``` And these variables: string firstPref, secondPref, thirdPref; When the values are set like so: ``` firstPref = 'A'; secondPref = 'B'; thirdPref = 'C'; ``` Is it possible to order the data like so: ``` A A B B C C D E ```
If you put your preferences into a list, it might become easier. ``` List<String> data = new List<String> { "A","B","A","C","B","C","D","E" }; List<String> preferences = new List<String> { "A","B","C" }; IEnumerable<String> orderedData = data.OrderBy( item => preferences.IndexOf(item)); ``` This will put all items not appearing in `preferences` in front because `IndexOf()` returns `-1`. An ad hoc work around might be reversing `preferences` and order the result descending. This becomes quite ugly, but works. ``` IEnumerable<String> orderedData = data.OrderByDescending( item => Enumerable.Reverse(preferences).ToList().IndexOf(item)); ``` The solution becomes a bit nicer if you concat `preferences` and `data`. ``` IEnumerable<String> orderedData = data.OrderBy( item => preferences.Concat(data).ToList().IndexOf(item)); ``` I don't like `Concat()` and `ToList()` in there. But for the moment I have no really good way around that. I am looking for a nice trick to turn the `-1` of the first example into a big number.
In addition to @Daniel Brückner [answer](https://stackoverflow.com/a/728353) and problem defined at the end of it: > I don't like Concat() and ToList() in there. But for the moment I have no really >good way around that. I am looking for a nice trick to turn the -1 of the first >example into a big number. I think that the solution is to use a statement lambda instead of an expression lambda. ``` var data = new List<string> { "corge", "baz", "foo", "bar", "qux", "quux" }; var fixedOrder = new List<string> { "foo", "bar", "baz" }; data.OrderBy(d => { var index = fixedOrder.IndexOf(d); return index == -1 ? int.MaxValue : index; }); ``` The ordered data is: ``` foo bar baz corge qux quux ```
Linq OrderBy against specific values
[ "", "c#", "linq", "linq-to-objects", "" ]
Greetings Everyone, Trying to compile using g++ and need to link the standard f90 (or f77 even) libraries for some fortran source codes in my Makefile. I cant find the name of it anywhere. Makerfile: ``` products: SlowDynamic.exe SlowDynamic.exe: main.o SA.o mersenne.o CFE.o BCs.o EMatrix.o Numbering.o KMatrix.o Solve.o MA_57.o blas.o MA_57_Depend.o Metis.o g++ -L/usr/sfw/lib -R/usr/sfw/lib -lgcc_s -lstdc++ -o SlowDynamic.exe main.o \ SA.o mersenne.o CFE.o MA_57.o blas.o MA_57_Depend.o Metis.o\ BCs.o EMatrix.o Numbering.o KMatrix.o Solve.o main.o: main.cpp g++ -c -o main.o main.cpp SA.o: SA.cpp g++ -c -o SA.o SA.cpp mersenne.o: mersenne.cpp g++ -c -o mersenne.o mersenne.cpp CFE.o: CFE.c gcc -c -o CFE.o CFE.c MA_57.o: MA_57.f f77 -c -o MA_57.o MA_57.f blas.o: blas.f f77 -c -o blas.o blas.f MA_57_Depend.o: MA_57_Depend.f f77 -c -o MA_57_Depend.o MA_57_Depend.f Metis.o: Metis.f f77 -c -o Metis.o Metis.f BCs.o: BCs.c gcc -c -o BCs.o BCs.c EMatrix.o: EMatrix.c gcc -c -o EMatrix.o EMatrix.c Numbering.o: Numbering.c gcc -c -o Numbering.o Numbering.c KMatrix.o: KMatrix.c gcc -c -o KMatrix.o KMatrix.c Solve.o : Solve.c gcc -c -o Solve.o Solve.c clean: rm *.o Main.exe *.gpi ``` Compiler: ``` birch $ make mksh: Warning: newline is not last character in file Makefile Current working directory /u/f/osv20/Y4-UNIX/complete g++ -L/usr/sfw/lib -R/usr/sfw/lib -lgcc_s -o SlowDynamic.exe main.o \ SA.o mersenne.o CFE.o MA_57.o blas.o MA_57_Depend.o Metis.o\ BCs.o EMatrix.o Numbering.o KMatrix.o Solve.o Undefined first referenced symbol in file __f90_sfw_i4 MA_57.o __f90_sfw_ch MA_57.o __f90_sfw_r4 MA_57.o __f90_ifw_ch MA_57.o __f90_ifw_r4 MA_57.o __nintf MA_57.o __s_cmp blas.o __r_sign MA_57_Depend.o __f90_sifw MA_57.o __f90_ssfw MA_57.o __f90_stop blas.o __f90_esfw MA_57.o __f90_eifw MA_57.o ld: fatal: Symbol referencing errors. No output written to SlowDynamic.exe collect2: ld returned 1 exit status *** Error code 1 make: Fatal error: Command failed for target `SlowDynamic.exe' ``` Results for running 'f77 -v hello.f' ``` amos $ f77 -v hello.f NOTICE: Invoking /usr/bin/f90 -f77 -ftrap=%none -v hello.f ### command line files and options (expanded): ### -f77=%all -ftrap=%none -v hello.f -lf77compat ### f90: Note: NLSPATH = /opt/SUNWspro/prod/bin/../lib/locale/%L/LC_MESSAGES/%N.cat:/opt/SUNWspro/prod/bin/../../lib/locale/%L/LC_MESSAGES/%N.cat /opt/SUNWspro/prod/bin/f90comp -y-o -yhello.o -ev -y-ftrap=%none -m3 -dq -y-fbe -y/opt/SUNWspro/prod/bin/fbe -y-xarch=generic -y-s -H "/opt/SUNWspro/prod/bin/f90 -f77 -ftrap=%none -v " -y-xcache=generic -xcache=generic -I/opt/SUNWspro/prod/include/f95/v8 -p/opt/SUNWspro/prod/lib/modules -y-verbose -xall -xmemalign=8i -y-xmemalign=8i -f77=%all -y-xdbggen=no%stabs+dwarf2 -y-xdbggen=incl -xassume_control=optimize -y-xassume_control=optimize -iorounding=processor-defined -xhasc=yes hello.f hello.f: MAIN hellow: ### f90: Note: LD_LIBRARY_PATH = (null) ### f90: Note: LD_RUN_PATH = (null) ### f90: Note: LD_OPTIONS = (null) /usr/ccs/bin/ld -t -R/opt/SUNWspro/lib/sparc:/opt/SUNWspro/lib -o a.out /opt/SUNWspro/prod/lib/crti.o /opt/SUNWspro/prod/lib/crt1.o /opt/SUNWspro/prod/lib/misalign.o /opt/SUNWspro/prod/lib/values-xi.o -Y P,/opt/SUNWspro/lib/sparc:/opt/SUNWspro/prod/lib/sparc:/opt/SUNWspro/lib:/opt/SUNWspro/prod/lib:/usr/ccs/lib:/lib:/usr/lib hello.o -lf77compat -lfui -lfai -lfai2 -lfsumai -lfprodai -lfminlai -lfmaxlai -lfminvai -lfmaxvai -lfsu -lsunmath -Bdynamic -lmtsk -lm -lc /opt/SUNWspro/prod/lib/crtn.o rm hello.o ``` Results for running 'f90 -v hello.f' ``` amos $ f90 -v hello.f ### command line files and options (expanded): ### -v hello.f ### f90: Note: NLSPATH = /opt/SUNWspro/prod/bin/../lib/locale/%L/LC_MESSAGES/%N.cat:/opt/SUNWspro/prod/bin/../../lib/locale/%L/LC_MESSAGES/%N.cat /opt/SUNWspro/prod/bin/f90comp -y-o -yhello.o -ev -y-ftrap=common -m3 -dq -y-fbe -y/opt/SUNWspro/prod/bin/fbe -y-xarch=generic -y-s -H "/opt/SUNWspro/prod/bin/f90 -v " -y-xcache=generic -xcache=generic -I/opt/SUNWspro/prod/include/f95/v8 -p/opt/SUNWspro/prod/lib/modules -y-verbose -xall -xmemalign=8i -y-xmemalign=8i -y-xdbggen=no%stabs+dwarf2 -y-xdbggen=incl -xassume_control=optimize -y-xassume_control=optimize -iorounding=processor-defined -xhasc=yes hello.f ### f90: Note: LD_LIBRARY_PATH = (null) ### f90: Note: LD_RUN_PATH = (null) ### f90: Note: LD_OPTIONS = (null) /usr/ccs/bin/ld -t -R/opt/SUNWspro/lib/sparc:/opt/SUNWspro/lib -o a.out /opt/SUNWspro/prod/lib/crti.o /opt/SUNWspro/prod/lib/crt1.o /opt/SUNWspro/prod/lib/misalign.o /opt/SUNWspro/prod/lib/values-xi.o -Y P,/opt/SUNWspro/lib/sparc:/opt/SUNWspro/prod/lib/sparc:/opt/SUNWspro/lib:/opt/SUNWspro/prod/lib:/usr/ccs/lib:/lib:/usr/lib hello.o -lfui -lfai -lfai2 -lfsumai -lfprodai -lfminlai -lfmaxlai -lfminvai -lfmaxvai -lfsu -lsunmath -Bdynamic -lmtsk -lm -lc /opt/SUNWspro/prod/lib/crtn.o rm hello.o ``` Results for a successful compile using f77: ``` amos $ make mksh: Warning: newline is not last character in file Makefile Current working directory /u/f/osv20/Y4-UNIX/complete g++ -c -o main.o main.cpp In file included from main.cpp:16: SA.h:85:9: warning: no newline at end of file main.cpp:38:2: warning: no newline at end of file g++ -c -o SA.o SA.cpp In file included from SA.cpp:22: SA.h:85:9: warning: no newline at end of file In file included from SA.cpp:23: CFE.h:25:8: warning: no newline at end of file SA.cpp:468:4: warning: no newline at end of file g++ -c -o mersenne.o mersenne.cpp gcc -c -o CFE.o CFE.c In file included from BCs.h:9, from CFE.c:29: fg_types.h:38:7: warning: no newline at end of file In file included from CFE.c:29: BCs.h:15:84: warning: no newline at end of file In file included from CFE.c:32: KMatrix.h:12:171: warning: no newline at end of file In file included from CFE.c:34: Solve.h:9:91: warning: no newline at end of file CFE.c: In function `CFE': CFE.c:145: warning: `return' with a value, in function returning void gcc -c -o BCs.o BCs.c In file included from BCs.h:9, from BCs.c:9: fg_types.h:38:7: warning: no newline at end of file In file included from BCs.c:9: BCs.h:15:84: warning: no newline at end of file BCs.c:74:2: warning: no newline at end of file gcc -c -o EMatrix.o EMatrix.c In file included from EMatrix.h:9, from EMatrix.c:9: fg_types.h:38:7: warning: no newline at end of file EMatrix.c:78:2: warning: no newline at end of file gcc -c -o Numbering.o Numbering.c In file included from Numbering.h:8, from Numbering.c:8: fg_types.h:38:7: warning: no newline at end of file Numbering.c:144:3: warning: no newline at end of file gcc -c -o KMatrix.o KMatrix.c In file included from KMatrix.h:8, from KMatrix.c:9: fg_types.h:38:7: warning: no newline at end of file In file included from KMatrix.c:9: KMatrix.h:12:171: warning: no newline at end of file KMatrix.c:194:2: warning: no newline at end of file gcc -c -o Solve.o Solve.c In file included from Solve.c:8: Solve.h:9:91: warning: no newline at end of file Solve.c:95:2: warning: no newline at end of file f77 -c -o MA_57.o MA_57.f NOTICE: Invoking /usr/bin/f90 -f77 -ftrap=%none -c -o MA_57.o MA_57.f MA_57.f: ma57i: ma57a: ma57b: ma57c: ma57q: ma57r: ma57u: ma57s: ma57t: ma57d: ma57e: ma57g: ma57j: ma57k: ma57f: ma57l: ma57m: ma57n: ma57o: ma57p: ma57w: ma57x: ma57y: ma57v: ma57h: ma57z: f77 -c -o blas.o blas.f NOTICE: Invoking /usr/bin/f90 -f77 -ftrap=%none -c -o blas.o blas.f blas.f: sgemm: stpsv: isamax: xerbla: lsame: sgemv: f77 -c -o MA_57_Depend.o MA_57_Depend.f NOTICE: Invoking /usr/bin/f90 -f77 -ftrap=%none -c -o MA_57_Depend.o MA_57_Depend.f MA_57_Depend.f: mc47a: mc47b: mc71a: mc34a: mc59a: mc59b: mc59c: mc59d: mc59e: mc59f: ma27i: ma27a: ma27b: ma27c: ma27g: ma27h: ma27u: ma27j: ma27k: ma27l: ma27m: ma27n: ma27o: ma27p: ma27q: ma27r: mc64i: mc64a: mc64b: mc64d: mc64e: mc64f: mc64r: mc64s: mc64q: mc64u: mc64w: mc21a: mc21b: fd15a: f77 -c -o Metis.o Metis.f NOTICE: Invoking /usr/bin/f90 -f77 -ftrap=%none -c -o Metis.o Metis.f Metis.f: metis_nodend: f77 -L/usr/sfw/lib -R/usr/sfw/lib -lgcc_s -lstdc++ -o SlowDynamic.exe main.o \ SA.o mersenne.o CFE.o MA_57.o blas.o MA_57_Depend.o Metis.o\ BCs.o EMatrix.o Numbering.o KMatrix.o Solve.o NOTICE: Invoking /usr/bin/f90 -f77 -ftrap=%none -L/usr/sfw/lib -R/usr/sfw/lib -lgcc_s -lstdc++ -o SlowDynamic.exe main.o SA.o mersenne.o CFE.o MA_57.o blas.o MA_57_Depend.o Metis.o BCs.o EMatrix.o Numbering.o KMatrix.o Solve.o ```
What version of GCC are you using? The fortran compiler in GCC has changed completely over time (g77 vs gfortran) - so the correct answer is very dependent on exact versions. It's been a while since I needed to do this (and I used old g77 versions - so things may have changed) but I recall a couple of options at the time were: * Try link using g77 and include library -lstdc++ (and possibly -lm?) * Try link using g++ and include libraries -lg2c -lm (and possibly -lfrtbegin?) If using newer gfortran then -lgfortran should work if linking with g++ and -lstdc++ if linking with gfortran. You also want to make sure that the g++ and f77 commands in your makefile are running the commands that you expect them to be running (e.g. not accessing executables in unexpected directories or different/incompatible versions). EDIT: From your recent edits to your question you appear to be trying to link the SUN compiler's f77 with the GCC g++. I don't think this is possible. Try using GCC's g77 or gfortran instead of SUN f77.
Raugnar, I refer you to [my answer](https://stackoverflow.com/questions/662904/unix-symbol-referencing-error/662953#662953) to your previous question about unresolved symbols. Just run: ``` f77 -v something.f ``` on a standalone Fortran90 program and the compiler will reveal exactly which support libraries are linked in by default.
Standard F90 Library for Makefile
[ "", "c++", "makefile", "fortran", "" ]
**Original post: [How to access a timer from another class in C#](https://stackoverflow.com/questions/725413/how-to-access-a-timer-from-another-class-in-c)** I tried everything. -Event -Invoke can't be done,because Timers don't have InvokeRequired property. -Public/internal property Nothing worked,the code is being executed,the timer.Enabled property is being set to "true" ,but it doesn't Tick.If I call the event or just change the property from the form class in a NON-static method - it does tick and works. I never knew it would take me a day and probably more to acquire how to use a decent timer. If there's no way to do this,is there anything else I can use that works similiar to the timer(delay,enable/disable)?
You should use the Timer class from the System.Timers namespace, and not the WinForms Timer control, if you want multi-threading support. Check the MSDN documentation for the WinForms Timer control for more information: <http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx>
You don't need to check `InvokeRequired` on the Control iteself, you can check the property on the class e.g.: ``` if (this.InvokeRequired) { BeginInvoke(new MyDelegate(delegate() { timer.Enabled = true; })); } ```
How to enable a timer from a different thread/class
[ "", "c#", "winforms", "timer", "" ]
Can jquery ajax code call a **webservice** from another domain name or another website? Like this: ``` $.ajax({ type: "POST", url: "http://AnotherWebSite.com/WebService.asmx/HelloWorld", data: "{'name':'" + $('#price').val() + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert(msg); } }); ``` And how should I config this **webservice**?
you can use JSONP to make cross domain requests. with jquery you can make a jsonp request using the $.json function and specifying a callback in the url like so: ``` &callback=? ``` Actually, all you need is the question mark as the param value, the param name can be anything. Only catch, is that the server you are making the request to must support jsonp For more in depth information see this blog post about making jsonp work with the new york times json api: <http://notetodogself.blogspot.com/2009/02/using-jquery-with-nyt-json-api.html>
You need to use a JSONP call. Last two paragraphs on this [page](http://docs.jquery.com/Ajax/jQuery.ajax). Go over the basics.
can jquery ajax call external webservice?
[ "", "asp.net", "javascript", "jquery", "web-services", "" ]
I have a menubutton, which when clicked should display a menu containing a specific sequence of strings. Exactly what strings are in that sequence, we do not know until runtime, so the menu that pops up must be generated at that moment. Here's what I have: ``` class para_frame(Frame): def __init__(self, para=None, *args, **kwargs): # ... # menu button for adding tags that already exist in other para's self.add_tag_mb = Menubutton(self, text='Add tags...') # this menu needs to re-create itself every time it's clicked self.add_tag_menu = Menu(self.add_tag_mb, tearoff=0, postcommand = self.build_add_tag_menu) self.add_tag_mb['menu'] = self.add_tag_menu # ... def build_add_tag_menu(self): self.add_tag_menu.delete(0, END) # clear whatever was in the menu before all_tags = self.get_article().all_tags() # we don't want the menu to include tags that already in this para menu_tags = [tag for tag in all_tags if tag not in self.para.tags] if menu_tags: for tag in menu_tags: def new_command(): self.add_tag(tag) self.add_tag_menu.add_command(label = tag, command = new_command) else: self.add_tag_menu.add_command(label = "<No tags>") ``` The important part is the stuff under "if menu\_tags:" -- Suppose menu\_tags is the list ['stack', 'over', 'flow']. Then what I want to do is effectively this: ``` self.add_tag_menu.add_command(label = 'stack', command = add_tag_stack) self.add_tag_menu.add_command(label = 'over', command = add_tag_over) self.add_tag_menu.add_command(label = 'flow', command = add_tag_flow) ``` where add\_tag\_stack() is defined as: ``` def add_tag_stack(): self.add_tag('stack') ``` and so on. The problem is, the variable 'tag' takes on the value 'stack' and then the value 'over' and so on, and it doesn't get evaluated until new\_command is called, at which point the variable 'tag' is just 'flow'. So the tag that gets added is always the last one on the menu, no matter what the user clicks on. I was originally using a lambda, and I thought maybe explicitly defining the function as above might work better. Either way the problem occurs. I've tried using a copy of the variable 'tag' (either with "current\_tag = tag" or using the copy module) but that doesn't solve it. I'm not sure why. My mind is starting to wander towards things like "eval" but I'm hoping someone can think of a clever way that doesn't involve such horrible things. Much thanks! (In case it's relevant, Tkinter.\_\_version\_\_ returns '$Revision: 67083 $' and I'm using Python 2.6.1 on Windows XP.)
First of all, your problem doesn't have anything to do with Tkinter; it's best if you reduce it down to a simple piece of code demonstrating your problem, so you can experiment with it more easily. Here's a simplified version of what you're doing that I experimented with. I'm substituting a dict in place of the menu, to make it easy to write a small test case. ``` items = ["stack", "over", "flow"] map = { } for item in items: def new_command(): print(item) map[item] = new_command map["stack"]() map["over"]() map["flow"]() ``` Now, when we execute this, as you said, we get: ``` flow flow flow ``` The issue here is Python's notion of scope. In particular, the `for` statement does not introduce a new level of scope, nor a new binding for `item`; so it is updating the same `item` variable each time through the loop, and all of the `new_command()` functions are referring to that same item. What you need to do is introduce a new level of scope, with a new binding, for each of the `item`s. The easiest way to do that is to wrap it in a new function definition: ``` for item in items: def item_command(name): def new_command(): print(name) return new_command map[item] = item_command(item) ``` Now, if you substitute that into the preceding program, you get the desired result: ``` stack over flow ```
That kind of thing is quite a common problem in Tkinter, I think. Try this (at the appropriate point): ``` def new_command(tag=tag): self.add_tag(tag) ```
Dynamically creating a menu in Tkinter. (lambda expressions?)
[ "", "python", "lambda", "copy", "tkinter", "" ]
I have an object `x`. I'd like to copy it as object `y`, such that changes to `y` do not modify `x`. I realized that copying objects derived from built-in JavaScript objects will result in extra, unwanted properties. This isn't a problem, since I'm copying one of my own literal-constructed objects. How do I correctly clone a JavaScript object?
### 2022 update There's a new JS standard called [structured cloning](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone). It works in many browsers (see [Can I Use](https://caniuse.com/?search=structuredClone)). ``` const clone = structuredClone(object); ``` ## Old answer To do this for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object's prototype that should be left in the prototype and not copied to the new instance. If, for instance, you are adding a `clone` method to `Object.prototype`, as some answers depict, you will need to explicitly skip that attribute. But what if there are other additional methods added to `Object.prototype`, or other intermediate prototypes, that you don't know about? In that case, you will copy attributes you shouldn't, so you need to detect unforeseen, non-local attributes with the [`hasOwnProperty`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty "Mozilla JavaScript Reference: Object.hasOwnProperty") method. In addition to non-enumerable attributes, you'll encounter a tougher problem when you try to copy objects that have hidden properties. For example, `prototype` is a hidden property of a function. Also, an object's prototype is referenced with the attribute `__proto__`, which is also hidden, and will not be copied by a for/in loop iterating over the source object's attributes. I think `__proto__` might be specific to Firefox's JavaScript interpreter and it may be something different in other browsers, but you get the picture. Not everything is enumerable. You can copy a hidden attribute if you know its name, but I don't know of any way to discover it automatically. Yet another snag in the quest for an elegant solution is the problem of setting up the prototype inheritance correctly. If your source object's prototype is `Object`, then simply creating a new general object with `{}` will work, but if the source's prototype is some descendant of `Object`, then you are going to be missing the additional members from that prototype which you skipped using the `hasOwnProperty` filter, or which were in the prototype, but weren't enumerable in the first place. One solution might be to call the source object's `constructor` property to get the initial copy object and then copy over the attributes, but then you still will not get non-enumerable attributes. For example, a [`Date`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date "Mozilla JavaScript Reference: Date") object stores its data as a hidden member: ``` function clone(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; } return copy; } var d1 = new Date(); /* Executes function after 5 seconds. */ setTimeout(function(){ var d2 = clone(d1); alert("d1 = " + d1.toString() + "\nd2 = " + d2.toString()); }, 5000); ``` The date string for `d1` will be 5 seconds behind that of `d2`. A way to make one `Date` the same as another is by calling the `setTime` method, but that is specific to the `Date` class. I don't think there is a bullet-proof general solution to this problem, though I would be happy to be wrong! When I had to implement general deep copying I ended up compromising by assuming that I would only need to copy a plain `Object`, `Array`, `Date`, `String`, `Number`, or `Boolean`. The last 3 types are immutable, so I could perform a shallow copy and not worry about it changing. I further assumed that any elements contained in `Object` or `Array` would also be one of the 6 simple types in that list. This can be accomplished with code like the following: ``` function clone(obj) { var copy; // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } ``` The above function will work adequately for the 6 simple types I mentioned, as long as the data in the objects and arrays form a tree structure. That is, there isn't more than one reference to the same data in the object. For example: ``` // This would be cloneable: var tree = { "left" : { "left" : null, "right" : null, "data" : 3 }, "right" : null, "data" : 8 }; // This would kind-of work, but you would get 2 copies of the // inner node instead of 2 references to the same copy var directedAcylicGraph = { "left" : { "left" : null, "right" : null, "data" : 3 }, "data" : 8 }; directedAcyclicGraph["right"] = directedAcyclicGraph["left"]; // Cloning this would cause a stack overflow due to infinite recursion: var cyclicGraph = { "left" : { "left" : null, "right" : null, "data" : 3 }, "data" : 8 }; cyclicGraph["right"] = cyclicGraph; ``` It will not be able to handle any JavaScript object, but it may be sufficient for many purposes as long as you don't assume that it will just work for anything you throw at it.
If you do not use `Date`s, functions, undefined, regExp or Infinity within your object, a very simple one liner is `JSON.parse(JSON.stringify(object))`: ``` const a = { string: 'string', number: 123, bool: false, nul: null, date: new Date(), // stringified undef: undefined, // lost inf: Infinity, // forced to 'null' } console.log(a); console.log(typeof a.date); // Date object const clone = JSON.parse(JSON.stringify(a)); console.log(clone); console.log(typeof clone.date); // result of .toISOString() ``` This works for all kind of objects containing objects, arrays, strings, booleans and numbers. See also [this article about the structured clone algorithm of browsers](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm) which is used when posting messages to and from a worker. It also contains a function for deep cloning.
How do I correctly clone a JavaScript object?
[ "", "javascript", "clone", "javascript-objects", "" ]
I am currently using Microsoft's FOR XML PATH feature to pull data back from MS SQL Server in an XML format. I really like the feature but am always uncomfortable about using vendor specific functions. Do any of the other major database vendors have something similar? ## Edit Let me be more specific with type of features I'm looking for In MS SQL you can use this query ``` SELECT so.id AS '@Id', so.Code AS '@Code', cu.Code AS 'Customer/@Code', cu.Name AS 'Customer/@Name', (SELECT Item_Num AS '@Item', pa.Code AS '@PartCode' FROM tblSalesItem si LEFT JOIN tblPart pa ON pa.Id = si.Part_Id WHERE si.SalesOrder_ID = so.Id FOR XML PATH('SalesItem') , type) FROM tblSalesOrder so JOIN tblCustomer cu ON so.customer_id = cu.ID FOR XML PATH('SalesOrder'), ROOT('SalesOrders') ``` to generate this XML ``` <SalesOrders> <SalesOrder Id="13" Code="C1002 "> <Customer Code="ROBERTS " Name="Roberts Equipment Inc." /> <SalesItem Item="1" PartCode="FP-0001" /> <SalesItem Item="2" PartCode="FP-0003" /> </SalesOrder> <SalesOrder Id="15" Code="C1004 "> <Customer Code="EXBEL-LIFTS" Name="Exbel Lifts Inc." /> <SalesItem Item="1" /> </SalesOrder> </SalesOrders> ``` I can control the use of elements and attributes on a column by column basis. I can create attributes of elements to group related columns together. I can use sub-queries to generate nested elements. You can even use functions that return XML to generate trees that are arbitrary depth.
`FOR XML PATH` is not in the ANSI SQL-92 standard, so it will be up to the individual vendors. I do not know of any equivalent in Oracle or MySQL.
PostgreSQL 8.3 does not specifically have `FOR XML PATH`, but its XML functions (see [section 9.14 of the manual](http://www.postgresql.org/docs/8.3/static/functions-xml.html), particularly [9.14.3](http://www.postgresql.org/docs/8.3/static/functions-xml.html#FUNCTIONS-XML-MAPPING)) appear to provide very similar functionality.
Is there an equivalent to MS SQL 'FOR XML PATH' in other database products?
[ "", "sql", "xml", "" ]
What's the easiest way of storing a single number on a server so that any script can access it, using PHP? Currently, I have a number stored in a file, but this seems somewhat inelegant.
There's no right answer here, but most modern PHP systems for building web applications have some kind of Configuration object. This is often implemented as a singleton ``` //brain dead config object class NamespaceConfiguration { public static function getInstance() { if (!self::$instance instanceof self) { self::$instance = new self; } return self::$instance; } public static function set($key,$value){ //code to set $key/$value paid } public static function get($key){ //code to get a $value based on a $key } } $config = NamespaceConfiguration::getInstance(); $config->set('myNumber',42); .... function somewhereElse(){ $config = NamespaceConfiguration::getInstance(); $myNumber = $config->set('myNumber'); } ``` This class is loaded on every page requiest. This gives every developer a standard API to call when they want to get or set single configuration values, and allows a single developer to control the where of storage and the how of retrieval (which may be a flat file, XML file, memory cache, MySQL database, XML file stored in a MySQL Database, XML File stored in a MySQL Database that contains a node which points to a file that contains the value, etc.) The where and how of retrieval is going to depend on your application environment, although by using a configuration object you can create some efficiencies up front (storing already retrieved values in a property cache, pre-fetching certain values on instantiation, etc.)
Since your application probably already have some sort of include-file on the top "header.php" or simular, you could just create a constant/variable in that file, and all the files that include the header will also have access to the constant. This may help you to define the constant: <http://php.net/constant>
Constant server variables?
[ "", "php", "variables", "" ]
I can't get this CustomValidator working. In the <head>: ``` <script language="javascript" type="text/javascript"> function ValidateFile(sender, args){ alert("Hi"); args.IsValid = document.getElementById("fuFile").value != "" || document.getElementById("c101_c7").value != ""; } </script> ``` In the body: ``` <asp:FileUpload ID="fuFile" runat="server" size="70"/> <asp:TextBox ID="c101_c7" class="textbox" runat="server"/> <asp:CustomValidator ID="vldFile" runat="server" ClientValidationFunction="ValidateFile" ErrorMessage="You must either upload a file or provide a URL of a file."></asp:CustomValidator> ``` What should be in the args.IsValid if either the FileUpload or TextBox has to be filled in?
This works ``` document.getElementById("ctl00_ContentPlaceHolder1_fuFile").value ```
I find it helpful to actually let the code behind tell your JavaScript code what the client-side ID of the control is, since it's possible it's different than what you would think (based on what ASP .NET decides to do): ``` document.getElementById('<%=fuFile.ClientID %>'); ```
ASP.NET CustomValidator client side
[ "", ".net", "asp.net", "javascript", "validation", "" ]
I know there is a version of ASIO that is not included in the Boost namespace, but even then ASIO depends on Boost, but I'm wondering if there is a way to get ASIO to work without dependencies on Boost (because I cannot include Boost into the project, for too many reasons).
No, i don't believe so. ASIO has been using boost for as long as i have heard of it. I think they're very much interconnected. But you may be interested in a tool, [bcp](http://www.boost.org/doc/libs/1_38_0/tools/bcp/bcp.html), which lets you extract the minimal subset of boost required for the libraries that you want to use.
There is also a non-boost version of Asio: > Asio comes in two variants: (non-Boost) Asio and Boost.Asio. See: <http://think-async.com/Asio/>
Is there a way to get Asio working without Boost?
[ "", "c++", "boost", "boost-asio", "" ]
What is the difference, if any between the effects of the following snippets: ``` cout << "Some text" << s1 << "some more text\n"; cout << "Some text" + s1 + "some more text\n"; ```
The result of operator+ on strings is a new string. Therefore, in the example ``` cout << "Some text" + s1 + "some more text\n"; ``` two new strings are created (implies memory allocation) before the whole thing is written to cout. In your first example, everything is written directly to cout without unnecessary memory allocation.
Consider the following: ``` cout << "Some text" + " " + "some more text\n"; ``` It won't do what you think. Operator+ doesn't always mean concatenate. **Edit:** When applied to raw strings, operator+ doesn't concatenate - it adds the addresses of the pointers to the strings. The result is almost guaranteed to be nonsense, because it points to an area of memory that has no relationship to any of the original strings. With luck it will crash your program. **Edit 2:** Apparently it has been a very long time since I made this mistake. The results are so nonsensical that the compiler refuses to compile it.
Is there any difference between +-ing strings and <<-ing strings in c++?
[ "", "c++", "text", "concatenation", "cout", "" ]
Since there's no `button.PerformClick()` method in WPF, is there a way to click a WPF button programmatically?
WPF takes a slightly different approach than WinForms here. Instead of having the automation of a object built into the API, they have a separate class for each object that is responsible for automating it. In this case you need the `ButtonAutomationPeer` to accomplish this task. ``` ButtonAutomationPeer peer = new ButtonAutomationPeer(someButton); IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider; invokeProv.Invoke(); ``` [Here](http://joshsmithonwpf.wordpress.com/2007/03/09/how-to-programmatically-click-a-button/) is a blog post on the subject. Note: `IInvokeProvider` interface is defined in the `UIAutomationProvider` assembly.
Like JaredPar said you can refer to Josh Smith's article towards Automation. However if you look through comments to his article you will find more elegant way of raising events against WPF controls ``` someButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent)); ``` I personally prefer the one above instead of automation peers.
How to programmatically click a button in WPF?
[ "", "c#", ".net", "wpf", "button", "" ]
## Background I am using interface-based programming on a current project and have run into a problem when overloading operators (specifically the Equality and Inequality operators). --- ## Assumptions * I'm using C# 3.0, .NET 3.5 and Visual Studio 2008 UPDATE - The Following Assumption was False! * Requiring all comparisons to use Equals rather than operator== is not a viable solution, especially when passing your types to libraries (such as Collections). The reason I was concerned about requiring Equals to be used rather than operator== is that I could not find anywhere in the .NET guidelines that it stated it would use Equals rather than operator== or even suggest it. However, after re-reading [Guidelines for Overriding Equals and Operator==](http://msdn.microsoft.com/en-us/library/ms173147.aspx) I have found this: > By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types. and this [Equatable Interface](http://msdn.microsoft.com/en-us/library/ms131187.aspx) > The IEquatable interface is used by generic collection objects such as Dictionary, List, and LinkedList when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove. It should be implemented for any object that might be stored in a generic collection. --- ## Contraints * Any solution must not require casting the objects from their interfaces to their concrete types. --- ## Problem * When ever both sides of the operator== are an interface, no operator== overload method signature from the underlying concrete types will match and thus the default Object operator== method will be called. * When overloading an operator on a class, at least one of the parameters of the binary operator must be the containing type, otherwise a compiler error is generated (Error BC33021 <http://msdn.microsoft.com/en-us/library/watt39ff.aspx>) * It's not possible to specify implementation on an interface See Code and Output below demonstrating the issue. --- ## Question **How do you provide proper operator overloads for your classes when using interface-base programming?** --- ## References [== Operator (C# Reference)](http://msdn.microsoft.com/en-us/library/53k8ybth.aspx) For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. --- ## See Also --- ## Code ``` using System; namespace OperatorOverloadsWithInterfaces { public interface IAddress : IEquatable<IAddress> { string StreetName { get; set; } string City { get; set; } string State { get; set; } } public class Address : IAddress { private string _streetName; private string _city; private string _state; public Address(string city, string state, string streetName) { City = city; State = state; StreetName = streetName; } #region IAddress Members public virtual string StreetName { get { return _streetName; } set { _streetName = value; } } public virtual string City { get { return _city; } set { _city = value; } } public virtual string State { get { return _state; } set { _state = value; } } public static bool operator ==(Address lhs, Address rhs) { Console.WriteLine("Address operator== overload called."); // If both sides of the argument are the same instance or null, they are equal if (Object.ReferenceEquals(lhs, rhs)) { return true; } return lhs.Equals(rhs); } public static bool operator !=(Address lhs, Address rhs) { return !(lhs == rhs); } public override bool Equals(object obj) { // Use 'as' rather than a cast to get a null rather an exception // if the object isn't convertible Address address = obj as Address; return this.Equals(address); } public override int GetHashCode() { string composite = StreetName + City + State; return composite.GetHashCode(); } #endregion #region IEquatable<IAddress> Members public virtual bool Equals(IAddress other) { // Per MSDN documentation, x.Equals(null) should return false if ((object)other == null) { return false; } return ((this.City == other.City) && (this.State == other.State) && (this.StreetName == other.StreetName)); } #endregion } public class Program { static void Main(string[] args) { IAddress address1 = new Address("seattle", "washington", "Awesome St"); IAddress address2 = new Address("seattle", "washington", "Awesome St"); functionThatComparesAddresses(address1, address2); Console.Read(); } public static void functionThatComparesAddresses(IAddress address1, IAddress address2) { if (address1 == address2) { Console.WriteLine("Equal with the interfaces."); } if ((Address)address1 == address2) { Console.WriteLine("Equal with Left-hand side cast."); } if (address1 == (Address)address2) { Console.WriteLine("Equal with Right-hand side cast."); } if ((Address)address1 == (Address)address2) { Console.WriteLine("Equal with both sides cast."); } } } } ``` --- ## Output ``` Address operator== overload called Equal with both sides cast. ```
Short answer: I think your second assumption may be flawed. **`Equals()` is the right way to check for *semantic equality* of two objects, not `operator ==`.** --- Long answer: Overload resolution for operators is *performed at compile time, not run time*. Unless the compiler can definitively know the types of the objects it's applying an operator to, it won't compile. Since the compiler cannot be sure that an `IAddress` is going to be something that has an override for `==` defined, it falls back to the default `operator ==` implementation of `System.Object`. **To see this more clearly, try defining an `operator +` for `Address` and adding two `IAddress` instances.** Unless you explicitly cast to `Address`, it will fail to compile. Why? Because the compiler can't tell that a particular `IAddress` is an `Address`, and there is no default `operator +` implementation to fall back to in `System.Object`. --- Part of your frustration probably stems from the fact that `Object` implements an `operator ==`, and everything is an `Object`, so the compiler can successfully resolve operations like `a == b` for all types. When you overrode `==`, you expected to see the same behavior but didn't, and that's because the best match the compiler can find is the original `Object` implementation. > Requiring all comparisons to use Equals rather than operator== is not a viable solution, especially when passing your types to libraries (such as Collections). In my view, this is precisely what you should be doing. **`Equals()` is the right way to check for *semantic equality* of two objects.** Sometimes semantic equality is just reference equality, in which case you won't need to change anything. In other cases, as in your example, you'll override `Equals` when you need a stronger equality contract than reference equality. For example, you may want to consider two `Persons` equal if they have the same Social Security number, or two `Vehicles` equal if they have the same VIN. But `Equals()` and `operator ==` are not the same thing. Whenever you need to override `operator ==`, you should override `Equals()`, but almost never the other way around. `operator ==` is more of a syntactical convenience. Some CLR languages (e.g. Visual Basic.NET) don't even permit you to override the equality operator.
We ran into the same problem, and found an excellent solution: ReSharper custom patterns. We configured ALL of our users to use a common global pattern catalog in addition to their own, and placed it into SVN so that it can be versioned and updated for everyone. The catalog included all patterns known to be wrong in our system: `$i1$ == $i2$` (where i1 and i2 are *expressions* of our interface type, or derived. the replace pattern is `$i1$.Equals($i2$)` and the severity is "Show as error". Similarly we have `$i1$ != $i2$` Hope this helps. P.S. Global catalogs is the feature in ReSharper 6.1 (EAP), will be marked as final very soon. **Update**: I filed a [ReSharper Issue](http://youtrack.jetbrains.net/issue/RSRP-286954) to mark all interface '==' a warning unless it is comparing to null. Please vote if you think it is a worthy feature. **Update2**: ReSharper also has [CannotApplyEqualityOperator] attribute that can help.
Operator Overloading with Interface-Based Programming in C#
[ "", "c#", ".net", "operator-overloading", "equals", "" ]
I'm working on a mobile web app that needs to work in IE Mobile. I've narrowed down a JavaScript error I'm getting to IE Mobile not supporting the '`className`' property (IE4 engine...). I'm trying to find an alternative that works across all browsers with minimal code changes (I already have a few libraries that use '`className`'). The easiest approach I could think of would be to modify IE's element prototype to include className (if it doesn't have it), the problem is that I don't know what the alternative to '`className`' is in IE Mobile. I've tried this: ``` element.className = element.class; ``` Which obviously doesn't work because `class` is a keyword in JavaScript and my JS compressor doesn't like it, and it's probably not valid anyway. Other than using 'setAttribute()' everywhere I need to modify an element's class, is there any property I can use that is the equivalent to className?
While you can't avoid using `setAttribute()`, you can take a line out of the jQuery playbook and use a helper procedure with an optional parameter. This code is untested, but ought to work: ``` var className = function (obj, value) { if (value !== undefined) { return obj.setAttribute ('class', value); } return obj.getAttribute ('class'); }; // Use as alert (className (element)); className (element, "foo"); alert (className (element)); ```
No attribute, no. I'm afraid you're stuck with getAttribute() and setAttribute().
Alternative to 'className' in JavaScript for IE Mobile?
[ "", "javascript", "ie-mobile", "" ]
I currently have a Gridview that displays TypeID , Name , Description. I would like to display the actual type name instead of the TypeID in the gridview. I created this function that takes in the ID and returns the Name but I am having trouble using it. There are 15-20 different types so How do I convert the TypeID to a Type Name so that it is displayed when the Gridview is rendered. ``` protected string GetGenericTypeByID(int genericTypeID) { string genericTypeName; GenericType.Generic_TypeDataTable genericTypeNameDS = new GenericType.Generic_TypeDataTable(); genericTypeNameDS = GenericBO.Get_GenericTypeByID(genericTypeID); genericTypeName = genericTypeNameDS[0]["Generic_Type_Name"].ToString(); return genericTypeName; } ``` I thought I would be able to use the function in the ItemTemplate but it seems to be harder that I thought ``` <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("GetGenericTypeByID("Generic_Type_ID")")%>'></asp:Label> </ItemTemplate> ``` Thanks to Everyone who helped me solve this problem. I ended up using the method below and it works perfectly. GetGenericTypeByID( Convert.ToInt32(Eval("Generic\_Type\_ID")))
You've got the 'bind/eval' and method call inside out. See [Using Method inside a DataGrid or GridView TemplateField](http://yasserzaid.wordpress.com/2009/03/12/using-method-inside-a-datagrid-or-gridview-templatefield/) ``` <asp:TemplateField HeaderText=”Name”> <ItemTemplate> <a href='<%# FormatUrl(Eval(”email1″).ToString())%>'><%# Eval(”fname”) %>,&nbsp;<%# Eval(”lname”) %></a> </ItemTemplate> ``` With the 'FormatUrl' function being: ``` public string FormatUrl(string email) { return “mailto:” + email; } ```
Are you limited to a label tag? If not, Expanding on David HAust's answer try the following: ``` <ItemTemplate> <%#GetGenericTypeByID(Eval(Generic_Type_ID))%> </ItemTemplate> ```
Convert Gridview column from ID to String in ItemTemplate
[ "", "c#", "asp.net", "gridview", "controls", "" ]
I am just getting to grips with the concept of a UserControl. I've created a UserControl to group together a number of controls that were being duplicated on individual pages of a TabControl. Some of these controls are text fields that require validation, and when validation is unsuccessful I need to display an error message. However the place where I want to display the error message is on the status bar on the main form. What is the best way to handle validation/error display in this situation?
**To handle validation do one of these:** * Validate with a method inside the user control * Have your user control have a [`delegate`](http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx) property (e.g. `ValidationHandler`) that can handle the validation (this would allow you to have a class with a bunch of validators that you could assign to your controls) `public delegate void Validator(...)` `public Validator ValidationHandler { get; set; }` * Have your user control generate a validation request [`event`](http://msdn.microsoft.com/en-us/library/awbftdfh.aspx) (e.g. `ValidationRequested`) `public event EventHandler<ValidationEventArgs> ValidationRequested` **To notify the system that an error has occurred do one of these:** * Use an [`event`](http://msdn.microsoft.com/en-us/library/awbftdfh.aspx) that interested parties can subscribe to (e.g. `ValidationFailed`) * If the object that performs the validation (via the `delegate` or `event`) is also the one that you want to generate the error message from, it can raise the error message itself. **EDIT:** Since you've said you would validate inside your control, the code for a ValidationFailed event might look like: ``` // In your user control public class ValidationFailedEventArgs : EventArgs { public ValidationFailedEventArgs(string message) { this.Message = message; } public string Message { get; set; } } private EventHandler<ValidationFailedEventArgs> _validationFailed; public event EventHandler<ValidationFailedEventArgs> ValidationFailed { add { _validationFailed += value; } remove { _validationFailed -= value; } } protected void OnValidationFailed(ValidationFailedEventArgs e) { if(_validationFailed != null) _validationFailed(this, e); } private void YourValidator() { if(!valid) { ValidationFailedEventArgs args = new ValidationFailedEventArgs("Your Message"); OnValidationFailed(args); } } // In your main form: userControl.ValidationFailed += new EventHandler<ValidationFailedEventArgs>(userControl_ValidationFailed); // ... private void userControl_ValidationFailed(object sender, ValidationFailedEventArgs e) { statusBar.Text = e.Message; } ```
If you're doing the validation in the UserControl, you can have it offer a public ValidationFailed event and include the message in the EventArgs. The parent control could then subscribe to the ValidationFailed event and update the status bar.
Passing information back from a UserControl
[ "", "c#", "winforms", "validation", "" ]
Is it possible to lazily instantiate a final field? The following code does not compile: ``` public class Test{ private final Connection conn; public Connection getConnection(){ if(conn==null){ conn = new Connection(); } return conn; } } ``` Is there an alternative?
Here's one way you can do it using Memoisation (with Callables): Class Memo: ``` public class Memo<T> { private T result; private final Callable<T> callable; private boolean established; public Memo(final Callable<T> callable) { this.callable = callable; } public T get() { if (!established) { try { result = callable.call(); established = true; } catch (Exception e) { throw new RuntimeException("Failed to get value of memo", e); } } return result; } } ``` Now we can create a final conn! ``` private final Memo<Connection> conn = new Memo<Connection>( new Callable<Connection>() { public Connection call() throws Exception { return new Connection(); } }); public Connection getConnection() { return conn.get(); } ``` [Source](http://fahdshariff.blogspot.com/2011/05/lazily-instantiate-final-field.html)
No. The point of a final field is that it's set once, during construction, and will never change thereafter. How could the compiler or the VM know anything useful about `conn` in your case? How would it know that only that property should be able to set it, and not some other method? Perhaps if you explained what you want the semantics to be, we could come up with an alterative. You could potentially have a "provider" interface representing a way to fetch a value, and then a `MemoizingProvider` which proxies to another provider, but only once, caching the value otherwise. That wouldn't be able to have a final field for the cached value either, but at least it would only be in one place.
Lazily instantiate a final field
[ "", "java", "final", "" ]
I've recently started creating my own annotations and to sport TDD/BDD, I'd want to unit test my annotations to create a clear specification for them. However since annotations are basically merely fancy interfaces which to my knowledge can't be really instantiated directly, is there any way short of reflection to unit test an annotation?
It's not something I would usually write tests for, but you could simply create a set of test classes which use and abuse the annotation, to test that it is storing its member values, that it has the correct defaults etc. This will only work on Runtime annotations that are specfied on the correct targets of course. In my experience, annotations themselves are rarely interesting enough to warrant unit tests - it is usually the code which uses them that needs testing. But then I'm not from the 100% code coverage school of thought :-)
Annotations have some impact (otherwise, it would be pointless to use them). So don't test the annotation presence but the effect it should have.
Can Java annotations be unit tested?
[ "", "java", "tdd", "annotations", "bdd", "" ]
I'm developing a system that allows developers to upload custom groovy scripts and freemarker templates. I can provide a certain level of security at a very high level with the default Java security infrastructure - i.e. prevent code from accessing the filesystem or network, however I have a need to restrict access to specific methods. My plan was to modify the Groovy and Freemarker runtimes to read Annotations that would either whitelist or blacklist certain methods, however this would force me to maintain a forked version of their code, which is not desirable. All I essentially need to be able to do is prevent the execution of specific methods when called from Groovy or Freemarker. I've considered a hack that would look at the call stack, but this would be a massive speed hit (and it quite messy). Does anyone have any other ideas for implementing this?
You can do it by subclassing the GroovyClassLoader and enforcing your constraints within an AST Visitor. THis post explains how to do it: <http://hamletdarcy.blogspot.com/2009/01/groovy-compile-time-meta-magic.html> Also, the code referenced there is in the samples folder of Groovy 1.6 installer.
You should have a look at the project [groovy-sandbox](http://groovy-sandbox.kohsuke.org/) from kohsuke. Have also a look to his [blog post here](http://kohsuke.org/2012/04/27/groovy-secureastcustomizer-is-harmful/) on this topic and what is solution is addressing: sandboxing, but performance drawback.
Sandboxing Java / Groovy / Freemarker Code - Preventing execution of specific methods
[ "", "java", "security", "groovy", "sandbox", "freemarker", "" ]
I'm trying to create am immutable type (class) in C++, I made it so that all methods "aka member functions" don't modify the object and return a new instance instead. I'm running across a bunch of issues, but they all revolve around the reference types in C++. One example is when passing parameters of the same class type by reference: ``` Imm Imm::someOp( const Imm& p_im ) const { ... p_im = p_im.someOtherOp(); //error, p_im is const, can't modify it! ... } ``` The error is caused by passing the value by reference. If instead, I was passing the reference by value, then the error line above would not be an error! Consider a Java/C# example ``` class Imm { ... Imm someOp( Imm p_im ) { .... p_im = p_im.someOtherOp(); //ok, you're not modifying the //original object, just changing the local reference .... } .... } ``` How can I do something like this in C++? I know I can use pointers but then I run into the whole memory management mess. I don't want to worry about who owns references to objects. Ideally I'd like to design the class to be like immutable strings in python; you can use them without ever noticing or even knowing that they're immutable, and they just behave as you expect; they just work. **EDIT** Of course I can get around it by passing-by-value or by using a temp variable (which is what I'm doing currently). What I'm asking about is "how to pass references by value in C++" I'm expecting the answer to revolve around something in the STL, I'm currently looking into smart\_ptr family of templates. **UPDATE** Thanks for the responses, I realize there's no escape from pointers. (see my [other question](https://stackoverflow.com/questions/653211/stl-class-for-reference-counted-pointers), which is really a follow up on this one)
In Java and C#, you are not really dealing with a reference - they are more like handles or pointers. A reference in C++ is really another name for the original object, not a pointer to it (although it may be implemented with a pointer). When you assign a value to a reference, you are assigning to the object itself. There is confusion in that to initialize a reference you can use the `=` character, but it is an initialization, not an assignment. ``` Imm im, im2, im3; Imm &imr = im; // initialize a reference to im imr = im2; // assign im2 to imr (changes the value of im as well) Imm *imp = &im; // initialize a pointer to the address of im imp = &im3; // assign the address of im3 to imp (im is unnaffected); (*imp) = im2; // assign im2 to imp (modifies im3 as well). ``` If you specifically want to pass "references by value" then you are essentially asking for a contradition in terms. References, by definition are passed by reference. As pointed out elsewhere, you can pass a pointer by value, or else a straight value. If you really want, you can hold onto a reference in a class and pass that around by value: ``` struct ImmRef { Imm &Ref; ImmRef(Imm &ref) : Ref(ref) {} }; ``` Note also that a const applied to a reference is making the referred to object constant, not the reference. References are always const.
Isn't assignment, by definition, not a constant operation? You look like you're trying to assign something to a const reference, which totally defeats the idea of a const reference. I think you may be looking for a pointer instead of a reference.
How to pass references by value in C++?
[ "", "c++", "reference", "constants", "immutability", "" ]
Given multiple (x,y) ordered pairs, I want to compare distances between each one of them. So pretend I have a list of ordered pairs: ``` pairs = [a,b,c,d,e,f] ``` I have a function that takes two ordered pairs and find the distance between them: ``` def distance(a,b): from math import sqrt as sqrt from math import pow as pow d1 = pow((a[0] - b[0]),2) d2 = pow((a[1] - b[1]),2) distance = sqrt(d1 + d2) return distance ``` How can I use this function to compare every ordered pair to every other ordered pair, ultimately finding the two ordered-pairs with the greatest distance between them? Psuedopsuedocode: ``` distance(a,b) distance(a,c) ... distance(e,f) ``` Any help would be tremendously appreciated.
``` try: from itertools import combinations except ImportError: def combinations(l, n): if n != 2: raise Exception('This placeholder only good for n=2') for i in range(len(l)): for j in range(i+1, len(l)): yield l[i], l[j] coords_list = [(0,0), (3,4), (6,8)] def distance(p1, p2): return ( ( p2[0]-p1[0] ) ** 2 + ( p2[1]-p1[1] )**2 ) ** 0.5 largest_distance, (p1, p2) = max([ (distance(p1,p2), (p1, p2)) for (p1,p2) in combinations(coords_list, 2) ]) print largest_distance, p1, p2 ```
in python 2.6, you can use itertools.permutations ``` import itertools perms = itertools.permutations(pairs, 2) distances = (distance(*p) for p in perms) ``` or ``` import itertools combs = itertools.combinations(pairs, 2) distances = (distance(*c) for c in combs) ```
Python "round robin"
[ "", "python", "iteration", "round-robin", "" ]
In my Tomcat logs (catalina) I am getting the following error preventing my application from starting up: ``` SEVERE: Error listenerStart 24-Mar-2009 13:23:10 org.apache.catalina.core.StandardContext start SEVERE: Context [/exampleA] startup failed due to previous errors ``` I do not know why I am getting this. In my web.xml I have the following ``` <listener> <listener-class> uk.co.a.listener.SessionListener </listener-class> </listener> <listener> <listener-class> uk.co.a.listener.SessionAttributeListener </listener-class> </listener> ``` When I comment out the listeners it starts up fine. The code for the listners are below: ``` public class SessionAttributeListener implements HttpSessionAttributeListener { static Log log = LogFactory.getLog(SessionAttributeListener.class.getName()); public void attributeAdded(HttpSessionBindingEvent hsbe) { log.debug("VALUE attributeAdded to THE SESSION:" + hsbe.getName()); } public void attributeRemoved(HttpSessionBindingEvent hsbe) { log.debug("VALUE attributeRemoved from THE SESSION:" + hsbe.getName()); } public void attributeReplaced(HttpSessionBindingEvent hsbe) { log.debug("VALUE attributeReplaced in THE SESSION:" + hsbe.getName()); } } ``` and ``` public class SessionListener implements HttpSessionListener { static Log log = LogFactory.getLog(SessionListener.class.getName()); private static int activeSessions = 0; public void sessionCreated(HttpSessionEvent evt) { activeSessions++; log.debug("No. of active sessions on:"+ new java.util.Date()+" : "+activeSessions); } public void sessionDestroyed (HttpSessionEvent evt) { activeSessions--; } } ``` Why is this not starting? Or where can I look for more information? **UPDATE** There only seems to be a problem with SessionAttributeListener from starting up. The SessionListener was not starting up because the <listener> were declared after the <servlet> **UPDATE** There was a problem with the JAR file used. The class for SessionAttributeListener was not included. When it was included the application started. **UPDATE** The AttributeListener does not seem to be running. When it is used the code fails. Is there a simple way to check if a listener is running?
re your update reading "The AttributeListener does not seem to be running. When it is used the code fails. Is there a simple way to check if a listener is running?" have you tried adding a static initialiser? something like ``` static { log.debug("static initialiser called"); } ``` that way the first time that the class is referenced you should get a log record.
Since I ended up finding my route to a solution elsewhere, I thought it would be useful to update this issue with that information. It's all to do with the underlying exception which causes the dreaded 'SEVERE: Error listenerStart' message not being logged anywhere, and how to configure the logging to produce the exception. From [here](http://www.java-tutorial.ch/java-server-faces/jsf-error-listener-start-error-using-tomcat) there is a very clear description of the logging issue and a solution. In my case I went for an even more cut down version, adding ``` org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/web-app].level = FINE org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/web-app].handlers = java.util.logging.ConsoleHandler ``` to the tomcat conf/logging.properties, and replacing /web-app with the appropriate web application context path. And magically the hidden exception appeared and told me the Java 6 runtime didn't want to know about code compiled by Java 7. Embarrassing, but easily fixed. This is applicable to Tomcat 7. Your mileage may vary.
Java Listener not starting Under Tomcat
[ "", "java", "tomcat", "listener", "" ]
My application is suspending on a line of code that appears to have nothing wrong with it, however my IDE appears to be suspending on that line with the error: > gdb/mi (24/03/09 13:36) (Exited. Signal 'SIGSEGV' received. Description: Segmentation fault.) The line of code simply calls a method which has no code in it. Isn't a segmentation fault when you have a null reference? If so, how can an empty method have a null reference? This piece of code, seems to be causing the issue: ``` #include <sys/socket.h> #define BUFFER_SIZE 256 char *buffer; buffer = (char*)GetSomePointer()->SomeStackMemoryString.c_str(); int writeResult = write(socketFD, buffer, BUFFER_SIZE); bzero(buffer, BUFFER_SIZE); int readResult = read(socketFD, buffer, BUFFER_SIZE); ``` When the line using the `read(...)` method is commented out, the problem goes away. ### Update: I have changed the question to point toward the actual problem, and I have removed all the irrelevant code - and I also [answered my own question](https://stackoverflow.com/questions/677444/why-is-my-c-code-causing-a-segmentation-fault-when-calling-an-empty-virtual-met/678933#678933) so that people reading this know specifically what the issue is, please read my answer before saying "you're a moron!".
Your code is bogus: buffer points to some random piece of memory. I'm not sure why the line with bzero is not failing. The correct code is: ``` char buffer[BUFFER_SIZE]; bzero(buffer, BUFFER_SIZE); int readResult = read(socketFD, buffer, BUFFER_SIZE); ``` or you can use calloc(1, BUFFER\_SIZE) to get some memory allocated (and zeroed out).
First, calling a method through a null pointer or reference is strictly speaking undefined behaviour. But it may succeed unless the call is virtual. Calling virtual methods virtually (through a pointer/reference, not from the derived class with Class::Method() way of invokation) always fails if the reference/pointer is null because virtual calls require access to vtable and accessing the vtable through a null pointer/reference is impossible. So you can't call an empty virtual method through a reference/pointer. To understand this you need to know more about how code is organized. For every non-inlined method there's a section of code segment containing the machine code implementing the method. When a call is done non-virtually (either from a derived class or a non-virtual method through a reference/pointer) the compiler knows exactly which method to call (no polymorphism). So it just inserts a call to an exact portion of code and passes *this* pointer as the first parameter there. In case of calling through null pointer *this* will be null too, but you don't care if your method is empty. When a call is done virtually (through a reference/pointer) the compiler doesn't know which exactly method to call, it only knows that there's a table of virtual methods and the address of the table is stored in the object. In order to find what method to call it's necessary to first dereference the pointer/reference, get to the table, get the address of method from it and only then call the method. Reading the table is done in runtime, not during compilation. If the pointer/reference is null you get segmentation fault at this point. This also explains why virtual calls can't be inlined. The compiler simply has no idea what code to inline when it's looking at the source during compilation.
Why is my C++ code causing a segmentation fault well after using the read(...) function?
[ "", "c++", "c", "memory-leaks", "segmentation-fault", "" ]
This is what I mean: ``` class mycalss { string myfunc() { string str="hello"; return str; } } ... static void main() { string str2; str2=myfunc(); ... ... } ``` In this case is there a risk that the garbage collector might delete the contents of str2 because str went out of scope?
No. The garbage detector will see that str2 has a reference to the data, and it won't be collected.
No, there's no risk here. The reference will be returned, and if the garbage collector runs it will be able to see the reference in `main`, so it won't free the string. Note that even when the string *is* eligible for garbage collection, it won't be freed immediately - only when the garbage collector next runs (or even later, depending on what generation it ends up in). Note that the garbage collector *can* collect objects which won't be used any more, even if there's a variable still in scope - so long as it knows that the variable won't be read again: ``` object x = new object(); Console.WriteLine(x); // Lots more code not touching x // The object could be collected at any time here ```
in c# when returning a string from a function does the memory get freed?
[ "", "c#", ".net", "clr", "" ]
I have a PHP application where I would like to certain objects to persist in the following manner: 1. The object must not exist in the $\_SESSION. Separate web browser windows must control separate instances of the object. 2. The end-user must not be able to modify the object by changing the content of the $\_REQUEST variable by hand (if this happens the request should be treated as corrupted). Is there a best-practices / proper way to do this? With PHP becoming more and more object oriented, I fear that I am reinventing a wheel. The grand purpose of this code is to allow the creation and manipulation of complex objects without using a database until they are to be committed, then I will use a proper transaction to commit them to the database in full. I want to make it so that my database contains only the complete invoice, or no invoice at all. My current method is as follows: ``` <?php include('encrypt.php'); include('invoice.class.php'); if(isset($_REQUEST['invoice'])) { $invoice = unserialize(decrypt(base64_decode($_REQUEST['invoice']))); if(!($invoice instanceOf invoice)) throw new exception('Something bad happened'); } else { // Some pages throw an exception if the $_REQUEST doesn't exist. $invoice = new invoice(); } if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'addLine') { $invoice->addLine(new invoiceLine($_REQUEST['description'], $_REQUEST['qty'], $_REQUEST['unitprice']); } ?> <form action="index.php" method="post"> <input type="text" name="qty" /> ... <input type="hidden" name="invoice" value="<?php echo(base64_encode(encrypt(serialize($invoice)))); ?>" /> </form> ```
You could also save state on the client, without cookies, using a simple hidden form input. As long as the the data (probably a serialized blob) is encrypted and signed, the user can't modify it without breaking their session. Steve Gibson uses this method for his custom e-commerce system. While his code isn't open source, he thoroughly explains ways to save state without storing sensitive data on the server or requiring cookie support in [Security Now Episode #109](http://www.grc.com/securitynow.htm), "GRC's eCommerce System".
Here's a trick: put it in a cookie! Neat algorithm: $data = serialize($object); $time = time(); $signature = sha1($serverSideSecret . $time . $data); $cookie = base64("$signature-$time-$data"); The benefit is that you a) can expire the cookie when you want because you are using the timestamp as part of the signature hash. b) can verify that the data hasn't been modified on the client side, because you can recreate the hash from the data segment in the cookie. Also, you don't have to store the entire object in the cookie if it will be too big. Just store the data you need on the server and use the data in the cookie as a key. I can't take credit for the algorithm, I learned it from Cal Henderson, of Flickr fame. Edit: If you find using cookies too complicated, just forget about them and store the data that would have gone in the cookie in a hidden form field.
What is the best way to persist an object using forms in PHP?
[ "", "php", "oop", "object", "persistence", "" ]
Do you know of any good online SQL Reference for DB2. I need it for someone who will be moving from Oracle to DB2
The manual perhaps? <http://www.ibm.com/support/docview.wss?rs=71&uid=swg27009554>
DB2 Information Center is a good place to start: DB2 V9.5: <https://publib.boulder.ibm.com/infocenter/db2luw/v9r5/index.jsp?topic=/com.ibm.db2.luw.sql.ref.doc/doc/c0004100.html> DB2 V9.1 <http://publib.boulder.ibm.com/infocenter/db2luw/v9/topic/com.ibm.db2.udb.admin.doc/doc/r0011049.htm>
Online SQL reference for DB2
[ "", "sql", "reference", "db2", "" ]
I've got a simple stored procedure that does an insert to a table with an identity primary key column. I need to get the key that was generated by the insert. I would prefer to use the standard JDBC getGeneratedKeys method but I'm not sure what the stored procedure needs to do/return to build that result set. My end goal is to do this from Hibernate. I also tried using the select identity generator but it always returns 0.
I've never tried the identity val local() function; in my own stored procedures, I just do a SELECT after the insert. But you can have a stored procedure return a result set: ``` create procedure proc1( IN in_val ) language sql dynamic result sets 1 BEGIN -- do insert BEGIN DECLARE c_out CURSOR WITH RETURN TO CLIENT FOR select max(key) as inserted_key from table where val = in_val FOR READ ONLY; OPEN c_out; END; END; ``` You can probably use identity val local replacing the select with "select identity val local() from sysibm.sysdummy1". I can't seem to get the underscores to work in markdown, but hopefully this is clear.
It is also possible to select from the insert: ``` SELECT pkey FROM FINAL TABLE (INSERT INTO tab(a, b, c, d) VALUES ... ) ```
How can I return the generated keys to JDBC from a DB2 stored procedure that does an insert?
[ "", "java", "jdbc", "db2", "" ]
I have a function declared like so: ``` template <typename T> T read(); ``` and defined like so: ``` template <typename T> T packetreader::read() { offset += sizeof(T); return *(T*)(buf+offset-sizeof(T)); } ``` However, when I try to use it in my main() function: ``` packetreader reader; reader.read<int>(); ``` I get the following error from g++: ``` g++ -o main main.o packet.o main.o: In function `main': main.cpp:(.text+0xcc): undefined reference to `int packetreader::read<int>()' collect2: ld returned 1 exit status make: *** [main] Error 1 ``` Can anyone point me into the right direction?
You need to use the `export` keyword. However, I don't think G++ has proper support, so you need to include the template function's definition in the header so the translation unit can use it. This is because the `<int>` 'version' of the template hasn't been created, only the `<typename T>` 'version.' An easy way is to `#include` the .cpp file. However, this can cause problems, e.g. when other functions are in the .cpp file. It will also likely increase the compile time. A clean way is to move your template functions into its own .cpp file, and include that in the header *or* use the `export` keyword and compile it separately. [More information on why you should try and put template function definitions in its header file (and ignore `export` altogether).](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1426.pdf)
The problem is that a function template is not a function. It's a template for creating functions as needed. So for a template to work, the compiler intuitively needs two pieces of information: The template itself, and the type that should be substituted into it. This is unlike a function call, which the compiler can generate as soon as it knows that the function exists. It doesn't need to know what the function does, just that it looks like `void Frobnicate(int, float)`, or whatever its signature is. When you declare the function template without defining it, you're only telling the compiler that such a template exists, but not what it looks like. That's not enough for the compiler to be able to instantiate it, it has to be able to see the full definition as well. The usual solution is to put the entire template in a header that can be included where needed.
C++ templates, undefined reference
[ "", "c++", "templates", "g++", "undefined-reference", "" ]
Is there a way to cast an instance of a class using a Type variable rather then an explicitly provided type? For example in my method below "this" is a derived type of "Node". I want the method to repeatedly try to get a value from GetNodeIntrinsicProperty() after which if it get's a null value it should cast itself as it's base type and try again. Basically, I want to call every implementation of GetNodeIntrinsicProperty() until I get a value. ``` public string GetIntrinsicProperty(String propertyKey) { //sets the original type value Type currType = this.GetType(); Node thisNode = this; String propertyValue; while (currType is Node) { //casts thisNode as CurrType thisNode = thisNode as currType; /*The live above gives me the following error * * Error 20 The type or namespace name 'currType' could not be found (are you missing a using directive or an assembly reference?) */ //trys to get the property with the current cast //GetNodeIntrinsicProperty() is defined seperately in each type propertyValue = thisNode.GetNodeIntrinsicProperty(propertyKey); if (propertyValue != null) { return propertyValue; } //sets CurrType to its base type currType = currType.BaseType; } return null; } ```
Ok, so first the answer to your question. I'm assuming you have some structure like this: ``` public class Node { public string GetIntrinsicProperty(String propertyKey) { //sets the original type value Type currType = this.GetType(); Node thisNode = this; String propertyValue; while (currType.IsSubclassOf(typeof(Node))) { MethodInfo mi = currType.GetMethod("GetIntrinsicProperty",BindingFlags.Instance | BindingFlags.Public,null,new Type[] {typeof(string)},null); if (mi.DeclaringType != typeof(Node)) { propertyValue = (string)mi.Invoke(this, new object[] { propertyKey }); if (propertyValue != null) { return propertyValue; } } //sets CurrType to its base type currType = currType.BaseType; } return null; } } public class OtherNode : Node { new public string GetIntrinsicProperty(string propertyKey) { return "OtherNode says Hi!"; } } public class TestNode : Node { } ``` The implementation of GetIntrinsicProperty above will do what you're asking, but I would suggest that it's wrong. You're forcing a child class to exactly replicate your signature and a developer to understand what you want. This is what virtual methods are for. If I'm understanding you correctly the proper way to do what you want is this: ``` public class Node { public virtual string GetIntrinsicProperty(String propertyKey) { switch(propertyKey) { case "NodeUnderstoodProp": return "I know! Call on me!"; default: return null; } } } public class OtherNode : Node { public override string GetIntrinsicProperty(string propertyKey) { switch (propertyKey) { case "OtherUnderstoodProp": return "I'm the OtherNode, and I know better, call on me!"; default: return base.GetIntrinsicProperty(propertyKey); } } } public class TestNode : Node { } static void Main(string[] args) { Node node = new OtherNode(); var prop1 = node.GetIntrinsicProperty("NodeUnderstoodProp"); var prop2 = node.GetIntrinsicProperty("OtherUnderstoodProp"); var prop3 = node.GetIntrinsicProperty("PropTooHard!"); node = new TestNode(); prop1 = node.GetIntrinsicProperty("NodeUnderstoodProp"); prop2 = node.GetIntrinsicProperty("OtherUnderstoodProp"); prop3 = node.GetIntrinsicProperty("PropTooHard!"); } ``` The idea of virtual methods is that the type of your variable doesn't determine which implementation is called, but rather the run time type of the object determines it. As far as I can tell, the situation you're describing is one where you are trying do your own dispatch to the implementation of a method on the runtime type of the object. Pretty much the definition of a virtual method. If I didn't get the question right, please clarify. :)
Alright I took a step back and realized that what I'm really doing is trying to create a method that will return the value of a public property by passing the the property name. Rather then manually creating a relationship between a property in my class and a string that coincidentally has the same name I've figured that it's better to do that automatically. So here's what I'm doing now, and it seems to work. In addition, I don't have to worry about two classes trying to define duplicate property keys because a derived class already can't have a duplicate property name to one in its base class unless there is an explicit abstract/override relationship. ``` public HashSet<string> GetIntrinsicPropertyKeys() { Type t = this.GetType(); PropertyInfo[] properties = t.GetProperties(); HashSet<string> keys = new HashSet<string>(); foreach (PropertyInfo pNfo in properties) { keys.Add(pNfo.Name); } return keys; } public string GetIntrinsicProperty(string propertyKey) { HashSet<string> allowableKeys = this.GetIntrinsicPropertyKeys(); String returnValue = null; if (allowableKeys.Contains(propertyKey)) { Type t = this.GetType(); PropertyInfo prop = t.GetProperty(propertyKey); returnValue = (string)prop.GetValue(this, null); } return returnValue; } ```
Can I cast an instance of a class by a Type variable rather then an explicit type?
[ "", "c#", "casting", "" ]
I'm trying to use Java annotations, but can't seem to get my code to recognize that one exists. What am I doing wrong? ``` import java.lang.reflect.*; import java.lang.annotation.*; @interface MyAnnotation{} public class FooTest { @MyAnnotation public void doFoo() { } public static void main(String[] args) throws Exception { Method method = FooTest.class.getMethod( "doFoo" ); Annotation[] annotations = method.getAnnotations(); for( Annotation annotation : method.getAnnotations() ) System.out.println( "Annotation: " + annotation ); } } ```
You need to specify the annotation as being a Runtime annotation using the @Retention annotation on the annotation interface. i.e. ``` @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation{} ```
Short answer: you need to add @Retention(RetentionPolicy.RUNTIME) to your annotation definition. Explanation: Annotations are by default **not** kept by the compiler. They simply don't exist at runtime. This may sound silly at first, but there are lots of annotations that are only used by the compiler (@Override) or various source code analyzers (@Documentation, etc). If you want to actually USE the annotation via reflection like in your example, you'll need to let Java know that you want it to make a note of that annotation in the class file itself. That note looks like this: ``` @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation{} ``` For more information, check out the official docs[1](http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html) and especially note the bit about RetentionPolicy.
Java Annotations not working
[ "", "java", "annotations", "" ]
Two simple questions about generics. Are the following two function definitions the same? ``` FunctionA(Exception ex); FunctionB<T>(T ex) where T : Exception; ``` Are there advantages the Generic implementation (FunctionB) has over the normal implementation (FunctionA)?
See this question: [Difference between generic argument constrained to an interface and just using the interface](https://stackoverflow.com/questions/595260/difference-between-generic-argument-constrained-to-an-interface-and-just-using-th)
The following are effectively the same (in outcome): ``` catch (Exception e) { FunctionA(e); FunctionB(e); } ``` But it's not the same if you do this: ``` catch (ApplicationException e) { FunctionB(e); } catch (Exception e) { FunctionA(e); } ``` This is because FunctionB gets typed to ApplicationException at compile time, wheras the call to FunctionA will always downcast the parameter to Exception. Depending on your implementation of FunctionB, this may not matter, but there are cases where it can make a difference. I would say that as a rule of thumb, if you your method implementation does not need the generic implementation, then don't use it. Here are some examples of when it would matter: ``` public T AddSomeContextToThisException<T>(T ex) where T : Exception { ex.Data.Add("Some key", "Some context message"); return ex; } public T ThisIsABadIdeaForExceptionsButMaybeAGoodIdeaForOtherTypes<T>(T ex) where T : Exception, new() { // do something with ex return new T(); } ``` The following example needs some additional code for context, so see the code beneath it: ``` private readonly Bar bar = new Bar(); public void HandExceptionOffToSomethingThatNeedsToBeStronglyTyped<T>(T ex) where T : Exception { ICollection<T> exceptions = bar.GetCollectionOfExceptions<T>(); exceptions.Add(ex); // do other stuff } public class Bar { // value is object, because .net doesn't have covariance yet private Dictionary<Type, object> listsOfExceptions = new Dictionary<Type, object>(); public ICollection<T> GetCollectionOfExceptions<T>() { if (!listsOfExceptions.ContainsKey(typeof(T))) { listsOfExceptions.Add(typeof(T), new List<T>()); } return listsOfExceptions[typeof(T)] as List<T>; } } ```
Is FunctionA(Exception ex) the same as FunctionB<T>(T ex) where T : Exception?
[ "", "c#", "generics", "" ]
I am practicing for an exam, and found a sample problem that gets me totally lost. For the following code, find what the output is: ``` class Moe { public void print(Moe p) { System.out.println("Moe 1\n"); } } class Larry extends Moe { public void print(Moe p) { System.out.println("Larry 1\n"); } public void print(Larry l) { System.out.println("Larry 2\n"); } } class Curly extends Larry { public void print(Moe p) { System.out.println("Curly 1\n"); } public void print(Larry l) { System.out.println("Curly 2\n"); } public void print(Curly b) { System.out.println("Curly 3\n"); } } public class Overloading_Final_Exam { public static void main (String [] args) { Larry stooge1 = new Curly(); Moe stooge2 = new Larry(); Moe stooge3 = new Curly(); Curly stooge4 = new Curly(); Larry stooge5 = new Larry(); stooge1.print(new Moe()); ((Curly)stooge1).print(new Larry()); ((Larry)stooge2).print(new Moe()); stooge2.print(new Curly()); stooge3.print(new Curly()); stooge3.print(new Moe()); stooge3.print(new Larry()); ((Curly)stooge3).print(new Larry()); ((Curly)stooge3).print(new Curly()); stooge4.print(new Curly()); stooge4.print(new Moe()); stooge4.print(new Larry()); stooge5.print(new Curly()); stooge5.print(new Larry()); stooge5.print(new Moe()); } } ``` I had my ideas in mind, but then when I ran the java, I got something totally different: ``` Curly 1 Curly 2 Larry 1 Larry 1 Curly 1 Curly 1 Curly 1 Curly 2 Curly 3 Curly 3 Curly 1 Curly 2 Larry 2 Larry 2 Larry 1 ``` The first few ones are OK, but then I really don't understand. Anyone has a good explanation for this problem? Thanks
I would start by drawing a picture... ``` Moe - print(Moe) | Larry - print(Moe), print(Larry) | Curly - print(Moe), print(Larry), print(Curly) ``` Then I would keep track of the variables: * Larry - stooge1 -> Curly * Moe - stooge2 -> Larry * Moe - stooge3 -> Curly * Curly - stooge4 -> Curly * Larry - stooge5 -> Larry * `stooge1.print(new Moe())` + stooge1 -> Curly so calls Curly.print(Moe) * `((Curly)stooge1).print(new Larry());` + stooge1 -> Curly so calls Curly.print(new Larry()) * `((Larry)stooge2).print(new Moe());` + stooge2 -> Larry so calls Larry.print(new Moe()); * `stooge2.print(new Curly());` Ok, this is where it gets a bit trickier (sorry I stopped one before here) + stooge2 is declared to be a Moe. So when the compiler is looking at what to call it is going to call the print(Moe) method. Then at runtime it knows that stooge2 is a Larry so it calls the Larry.print(Moe) method. etc... Let me know if following that all the way through doesn't work out for you. (updated to clarify the next one) So the general rule is: * the compiler looks at the variable type to decide what method to call. * the runtime looks at the actual class that the variable is point at to decide where to get the method from. So when you have: ``` Moe stooge2 = new Larry(); stooge2.print(new Moe()); ``` the compiler says: * can Larry be assigned to stooge2? (yes as Larry is a subclass of Moe) * does Moe have a print(Moe) method? (yes) the runtime says: * I am supposed to call the print(Moe) method on this here object... stooge2 * stooge2 is point at a Larry. * I'll call the print(Moe) method in the Larry class. Once you have worked all that out try getting rid of some of the methods and see how that changes things.
Actually, this problem is not as simple as it seems, since Java is both static and dynamically bound. You have to understand where each is applied before you will understand all the results you are getting from this exercise. The General rule mentioned by TofuBeer is only correct in the dynamic binding case. In static binding, decisions are only made at compile time. Your example mixes the dynamic binding (when methods are overridden) and static binding (when methods are overloaded). Take a look [at this question](https://stackoverflow.com/questions/321864/java-dynamic-binding-and-method-overriding/322234#322234) for more details.
Java dynamic binding
[ "", "java", "binding", "overloading", "method-dispatch", "" ]
I have an array like this: ``` $array = [ 0 => 'Apple', 2 => 'Orange', 5 => 'Pear', 8 => 'Pear' ] ``` Is there a way to fill in the missing indexes with a default value (for example, an empty string or `null`)? I'd like to insert new elements into the array at the following keys: `1`, `3`, `4`, `6`, `7` My result should be: ``` [ 0 => 'Apple', 1 => '', 2 => 'Orange', 3 => '', 4 => '', 5 => 'Pear', 6 => '', 7 => '', 8 => 'Pear' ] ```
This should be faster for larger arrays. For smaller arrays any method will do. ``` $existingKeys = array_keys($array); //you can use any value instead of null $newKeys = array_fill_keys(range(min($existingKeys), max($existingKeys)), null); $array += $newKeys; //optional, probably not needed ksort($array); ```
``` for($i=0;i<count($array);++$i){ $array[$i] = isset($array[$i])? $array[$i] : ''; } ``` It just fills the missing keys with an empty string, though. Not sure if this suits you. **Edit** Just noticed Perr0\_hunter wrote pretty much the same thing before I did :P
Add elements to array which has gapped numeric keys to form an indexed array / list
[ "", "php", "arrays", "arraylist", "key", "default-value", "" ]
I want to have a library that will have a function in it that accepts an object for it's parameter. With this object I want to be able to call a specified function when X is finished. The function that will be called is to be specified by the caller, and X will be done and monitored by the library. How can I do this? For reference I'm using C# and .NET 3.5
Two options for you: 1. Have the function accept a [delegate](https://learn.microsoft.com/en-us/dotnet/api/system.delegate?view=netframework-4.8) ([`Action`](https://learn.microsoft.com/en-us/dotnet/api/system.action-1?view=netframework-4.8) for a callback that doesn't return anything, [`Func`](https://learn.microsoft.com/en-us/dotnet/api/system.func-2?view=netframework-4.8) for one that does) and use an anonymous delegate or Lambda Expression when calling it. 2. Use an interface ## Using a delegate/lambda ``` public static void DoWork(Action processAction) { // do work if (processAction != null) processAction(); } public static void Main() { // using anonymous delegate DoWork(delegate() { Console.WriteLine("Completed"); }); // using Lambda DoWork(() => Console.WriteLine("Completed")); } ``` If your callback needs to have something passed to it, you can use a type parameter on `Action`: ``` public static void DoWork(Action<string> processAction) { // do work if (processAction != null) processAction("this is the string"); } public static void Main() { // using anonymous delegate DoWork(delegate(string str) { Console.WriteLine(str); }); // using Lambda DoWork((str) => Console.WriteLine(str)); } ``` If it needs multiple arguments, you can add more type parameters to `Action`. If you need a return type, as mentioned use `Func` and make the return type the *last* type parameter (`Func<string, int>` is a function accepting a string and returning an int.) More about delegates [here](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/index?view=netframework-4.8). ## Using an interface ``` public interface IObjectWithX { void X(); } public class MyObjectWithX : IObjectWithX { public void X() { // do something } } public class ActionClass { public static void DoWork(IObjectWithX handlerObject) { // do work handlerObject.X(); } } public static void Main() { var obj = new MyObjectWithX() ActionClass.DoWork(obj); } ```
Sounds like a perfect recipe for delegates - in particular, callbacks with delegates are exactly how this is handled in the asynchronous pattern in .NET. The caller would usually pass you some state and a delegate, and you store both of them in whatever context you've got, then call the delegate passing it the state and whatever result you might have. You could either make the state just `object` or potentially use a generic delegate and take state of the appropriate type, e.g. ``` public delegate void Callback<T>(T state, OperationResult result) ``` Then: ``` public void DoSomeOperation(int otherParameterForWhateverReason, Callback<T> callback, T state) ``` As you're using .NET 3.5 you might want to use the existing `Func<...>` and `Action<...>` delegate types, but you *may* find it makes it clearer to declare your own. (The name may make it clearer what you're using it for.)
Callbacks in C#
[ "", "c#", ".net", "callback", "" ]
How do I list all tga files in a directory (non recursive) in Python?
If you are doing it based on file extension, you can do something like this: ``` import os directory = "C:/" extension = ".tga" list_of_files = [file for file in os.listdir(directory) if file.lower().endswith(extension)] ``` Obviously you can omit the lower() if you can garantee the case of the files. Also there is the excellent path.py (<http://pypi.python.org/pypi/path.py>) module. If you do not know the file extension you can use something like PIL (<http://www.pythonware.com/products/pil/>) to detect the file type by decoding the file.
``` import glob, os for filename in glob.glob(os.path.join(yourPath, "*.tga")) print(filename) ```
How do I list all tga files in a directory (non recursive) in Python?
[ "", "python", "" ]
I am looking for something like trim() but for within the bounds of a string. Users sometimes put 2, 3, 4, or more line returns after they type, I need to sanitize this input. Sample input ``` i like cats my cat is happy i love my cat hope you have a nice day ``` Desired output ``` i like cats my cat is happy i love my cat hope you have a nice day ``` I am not seeing anything built in, and a string replace would take many iterations of it to do the work. Before I whip up a small recursive string replace, I wanted to see what other suggestions you all had. I have an odd feeling there is a regex for this one as well.
Finally managed to get it, needs preg so you are using the PCRE version in php, and also needs a \n\n replacement string, in order to not wipe all line endings but one: ``` $body = preg_replace("/\n\n+/", "\n\n", $body); ``` Thanks for getting me on the right track.
``` function str_squeeze($body) { return preg_replace("/\n\n+/", "\n\n", $body); } ```
Remove excessive line returns
[ "", "php", "whitespace", "" ]
I am trying to iterate through the range(750, 765) and add the non-sequential numbers 769, 770, 774. If I try adding the numbers after the range function, it returns the range list, then the individual numbers: ``` >>> for x in range(750, 765), 769, 770, 774: print x ... [750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764] 769 770 774 ``` How can I get all the numbers in a single list?
Use the built-in + operator to append your non-sequential numbers to the range. ``` for x in range(750, 765) + [769, 770, 774]: print x ```
There are two ways to do it. ``` >>> for x in range(5, 7) + [8, 9]: print x ... 5 6 8 9 >>> import itertools >>> for x in itertools.chain(xrange(5, 7), [8, 9]): print x ... 5 6 8 9 ``` [itertools.chain()](http://docs.python.org/library/itertools.html#itertools.chain) is by far superior, since it allows you to use arbitrary iterables, rather than just lists and lists. It's also more efficient, not requiring list copying. And it lets you use xrange, which you should when looping.
How can I add non-sequential numbers to a range?
[ "", "python", "range", "" ]
I am having problems calling a URL from PHP code. I need to call a service using a query string from my PHP code. If I type the URL into a browser, it works ok, but if I use `file-get-contents()` to make the call, I get: > Warning: file-get-contents(http://.... ) failed to open stream: HTTP request failed! HTTP/1.1 202 Accepted in ... The code I am using is: ``` $query=file_get_contents('http://###.##.##.##/mp/get?mpsrc=http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv'); echo($query); ``` Like I said - call from the browser and it works fine. Any suggestions? I have also tried with another URL such as: ``` $query=file_get_contents('http://www.youtube.com/watch?v=XiFrfeJ8dKM'); ``` This works fine... could it be that the URL I need to call has a second `http://` in it?
Try using cURL. ``` <?php $curl_handle=curl_init(); curl_setopt($curl_handle, CURLOPT_URL,'http://###.##.##.##/mp/get?mpsrc=http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv'); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name'); $query = curl_exec($curl_handle); curl_close($curl_handle); ?> ```
Could this be your problem? > [Note: If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().](http://docs.php.net/file_get_contents)
PHP file_get_contents() returns "failed to open stream: HTTP request failed!"
[ "", "php", "query-string", "file-get-contents", "" ]
Is it possible in php to load a function, say from a external file to include in a class. I'm trying to create a loader for helper functions so that I could call: ``` $registry->helper->load('external_helper_function_file'); ``` after that it should be able call the function in file like this: ``` $registry->helper->function(); ``` Thanks for any help
Setting aside opinions it it's good OOP design. It's possible even with current version of PHP, although not as clean, as it can be with PHP5.3. ``` class Helper { /* ... */ function load($file) { include_once($file); } function __call($functionName, $args) { if(function_exists($functionName)) return call_user_func_array($functionName, $args); } } ```
ok, 1st, i agree that this is bad manners. also, in 5.3, you could use the new closure syntax with the \_\_call magic word to use operators as functions (JS style). now, if we want to supply a way of doing this you way, i can think of using create\_fnuction, mixed with the \_\_call magic. basically, you use a regex pattern to get convert the functions into compatible strings, and put themin a private member. than you use the \_\_call method to fetch them. i'm working on a small demo. ok, here is the class. i got the inspiration from a class i saw a few weeks ago that used closures to implement JS-style objects: ``` /** * supplies an interface with which you can load external functions into an existing object * * the functions supplied to this class will recive the classes referance as a first argument, and as * a second argument they will recive an array of supplied arguments. * * @author arieh glazer <arieh.glazer@gmail.com> * @license MIT like */ class Function_Loader{ /** * @param array holder of genarated functions * @access protected */ protected $_funcs = array(); /** * loads functions for an external file into the object * * a note- the file must not contain php tags. * * @param string $source a file's loaction * * @access public */ public function load($source){ $ptrn = '/function[\s]+([a-zA-Z0-9_-]*)[\s]*\((.*)\)[\s]*{([\w\s\D]+)}[\s]*/iU'; $source = file_get_contents($source); preg_match_all($ptrn,$source,$matches); $names = $matches[1]; $vars = $matches[2]; $funcs = $matches[3]; for ($i=0,$l=count($names);$i<$l;$i++){ $this->_funcs[$names[$i]] = create_function($vars[$i],$funcs[$i]); } } public function __call($name,$args){ if (isset($this->_funcs[$name])) $this->_funcs[$name]($this,$args); else throw new Exception("No Such Method $name"); } } ``` limitations- 1st, the source cannot have any php tags. 2nd, functions will always be public. 3rd- we can only mimic $this. what i did was to pass as a 1st argument $this, and the second is the array of arguments (which is a 4th limition). also, you will not be able to access non-public members and methods from within the class. an example for a source file: ``` function a($self,$arr=array()){ //assuming the object has a member called str echo $self->str; } ``` this was a fun exercise for me, but a bad practice all in all
Load functions dynamically into class from external file
[ "", "php", "class", "" ]
I've written a MnemonicsBuilder class for JLabels and AbstractButtons. I would like to write a convenience method `setMnemonics( JFrame f )` that will iterate through every child of the JFrame and select out the JLabels and AbstractButtons. How can I obtain access to everything contained in the JFrame? I've tried: ``` LinkedList<JLabel> harvestJLabels( Container c, LinkedList<JLabel> l ) { Component[] components = c.getComponents(); for( Component com : components ) { if( com instanceof JLabel ) { l.add( (JLabel) com ); } else if( com instanceof Container ) { l.addAll( harvestJLabels( (Container) com, l ) ); } } return l; } ``` In some situations, this works just fine. In others, it runs out of memory. What am I not thinking of? Is there a better way to search for child components? Is my recursion flawed? Is this not a picture of how things "Contain" other things in Swing - e.g., is Swing not a Rooted Tree? ``` JFrame | |\__JMenuBar | | | \__JMenu | | | \__JMenuItem | |\__JPanel | | | |\__JButton | | | |\__JLabel | | | |\__ ... JCheckBoxes, other AbstractButtons, etc. ```
Agree with Tom here... Your problem is that you're already passing the `List` to add the `JLabel`s down to your recursive method AND you're also returning it - thus adding the same items to your list more than once. In more politically correct terms - the `List` is your accumulator. Your method should instead look like this: ``` public void harvestJLabels(Container c, List<JLabel> l) { Component[] components = c.getComponents(); for(Component com : components) { if(com instanceof JLabel) { l.add((JLabel) com); } else if(com instanceof Container) { harvestJLabels((Container) com, l)); } } } ``` Then you can have a helper method to initiate this harvesting: ``` public List<JLabel> harvestJLabels(Container c) { List<JLabel> jLabels = new ArrayList<JLabel>(); harvestJLabels(c, jLabels); return jLabels; } ```
Here's your problem: ``` LinkedList<JLabel> harvestJLabels( Container c, LinkedList<JLabel> l ) { ... l.addAll( harvestJLabels( (Container) com, l ) ); ... return l; } ``` You only have a single list. You are appending a list to another list. Therefore you are adding a list to itself. That may work in some sense, but you are going to have a doubling of length (exponential growth). Either have a single `List` (usually there is no need to specify an algorithm in declarations) or create a new list instance each time the method is called. Avoid returning a reference you don't need to - it's just misleading. Also `ArrayList` would be more appropriate than `LinkedList`. `LinkedList` is almost always the wrong choice.
Iterate / recurse through Containers and Components to find objects of a given class?
[ "", "java", "swing", "recursion", "" ]
What is the name of the Command Line Compiler for a C/C++ program that target's Windows Mobile? I have Visual Studio 2008 Professional installed and I need to be able to compile a program from the command line. I've checked the project properties in Visual Studio and it shows me all of the parameters that are being passed to the compiler, but it doesn't show the name of the compiler itself.
The name of the command line C++ compiler is cl.exe The executable for windows ce is usually located at > %ProgramFiles%\Microsoft Visual Studio 9.0\VC\ce\bin\x86\_arm\cl.exe x86\_arm can be replaced with x86\_mips or x86\_sh depending on the particular architecture. Here's some further information on the Windows CE / Mobile Command Line Compiler: <http://msdn.microsoft.com/en-us/library/aa448630.aspx>
JaredPar has the answer about the actual location for `cl.exe`, but depending on what you need to do, you might want to look into invoking devenv from the command line - ``` Microsoft (R) Visual Studio Version 9.0.21022.8. Copyright (C) Microsoft Corp. All rights reserved. Use: devenv [solutionfile | projectfile | anyfile.ext] [switches] The first argument for devenv is usually a solution file or project file. You can also use any other file as the first argument if you want to have the file open automatically in an editor. When you enter a project file, the IDE looks for an .sln file with the same base name as the project file in the parent directory for the project file. If no such .sln file exists, then the IDE looks for a single .sln file that references the project. If no such single .sln file exists, then the IDE creates an unsaved solution with a default .sln file name that has the same base name as the project file. Command line builds: devenv solutionfile.sln /build [ solutionconfig ] [ /project projectnameorfile [ /projectconfig name ] ] etc... ``` The potential advantage that this gets you is that you can drive the compile from the command line, but it'll use the settings defined in the project/solution. That way you don't have to keep a makefile in sync with changes that are made to the project in the IDE.
Windows Mobile Command Line Compiler
[ "", "c++", "windows-mobile", "" ]
I do a rs.getTimestamp("datetime") in Java. In the database, this datetime is 2009/03/06 02:47:18 but the time is returned as 14:47:18 I'm not very knowledgeable about MySQL dates, so I would appreciate any explanation as to why this is happening.
It doesn't matter. Its not about MySQL or any database. This is the format Timestamp shows up by default, I believe. It doesn't mean it missed the date or something. You can always format the Timestamp returned by the method in any format in your code. Check out [java.text.SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html) class. Or for better, check out much more sophisticated [Joda Time](http://joda-time.sourceforge.net/).
Two things. First, I think we need sample code. What's going on is not at all clear from what you've given us. Context, usage, DB schema, and sample rows as well. Second, [ResultSet.getTimestamp()](http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getTimestamp(java.lang.String)) should be returning an object of type [Timestamp](http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Timestamp.html), rather than a String of any sort.
Java and MySQL date problem
[ "", "java", "mysql", "time", "" ]
I have a C++ function that I'd like to call using execvp(), due to the way my program is organized. Is this possible?
All of the exec variants including execvp() can only call complete programs visible in the filesystem. The good news is that if you want to call a function in your already loaded program, all you need is fork(). It will look something like this pseudo-code: ``` int pid = fork(); if (pid == 0) { // Call your function here. This is a new process and any // changes you make will not be reflected back into the parent // variables. Be careful with files and shared resources like // database connections. _exit(0); } else if (pid == -1) { // An error happened and the fork() failed. This is a very rare // error, but you must handle it. } else { // Wait for the child to finish. You can use a signal handler // to catch it later if the child will take a long time. waitpid(pid, ...); } ```
[excecvp()](http://linux.die.net/man/3/execvp) is meant ot start a program not a function. So you'll have to wrap that function into a compiled executable file and then have that file's main call your function.
Can I use execvp() on a function defined inside my program?
[ "", "c++", "function", "exec", "" ]
I'm working with some xml 'snippets' that form elements down the xml. I have the schema but I cannot validate these files because they are not complete xml documents. These snippets are wrapped with the necessary parent elements to form valid xml when they are used in other tools so I don't have much option in making them into valid xml or in changing the schema. Is it possible to validate an element, rather than the whole document? If not, what workarounds could be suggested? I'm working in C# with .NET 2.0 framework.
I had a similar problem where I could only validate parts of my XML document. I came up with this method here: ``` private void ValidateSubnode(XmlNode node, XmlSchema schema) { XmlTextReader reader = new XmlTextReader(node.OuterXml, XmlNodeType.Element, null); XmlReaderSettings settings = new XmlReaderSettings(); settings.ConformanceLevel = ConformanceLevel.Fragment; settings.Schemas.Add(schema); settings.ValidationType = ValidationType.Schema; settings.ValidationEventHandler += new ValidationEventHandler(XSDValidationEventHandler); using (XmlReader validationReader = XmlReader.Create(reader, settings)) { while (validationReader.Read()) { } } } private void XSDValidationEventHandler(object sender, ValidationEventArgs args) { errors.AppendFormat("XSD - Severity {0} - {1}", args.Severity.ToString(), args.Message); } ``` Basically, I pass it an XmlNode (which I select from the entire XmlDocument by means of .SelectSingleNode), and an XML schema which I load from an embedded resource XSD inside my app. Any validation errors that might occur are being stuffed into a "errors" string builder, which I then read out at the end, to see if there were any errors recorded, or not. Works for me - your mileage may vary :-)
There is a `XmlDocument.Validate` method that takes an `XmlNode` as argument an validates only this node. That may be what you're looking for ...
Validating xml nodes, not the entire document
[ "", "c#", "xml", ".net-2.0", "xsd", "xml-validation", "" ]
How to convert a string to integer using SQL query on SQL Server 2005?
You could use [CAST or CONVERT](http://msdn.microsoft.com/en-us/library/ms187928(SQL.90).aspx): ``` SELECT CAST(MyVarcharCol AS INT) FROM Table SELECT CONVERT(INT, MyVarcharCol) FROM Table ```
Starting with SQL Server 2012, you could use [TRY\_PARSE](https://learn.microsoft.com/en-us/sql/t-sql/functions/try-parse-transact-sql) or [TRY\_CONVERT](https://learn.microsoft.com/en-us/sql/t-sql/functions/try-convert-transact-sql). ``` SELECT TRY_PARSE(MyVarcharCol as int) SELECT TRY_CONVERT(int, MyVarcharCol) ```
Convert a string to int using sql query
[ "", "sql", "sql-server-2005", "" ]
I have a utility method and when irrelevant logic is removed from it, the simplified method would look like this: ``` public static <A extends Foo> List<A> getFooList(Class<A> clazz) { List<A> returnValue = new ArrayList<A>(); for(int i=0; i < 5; i++) { A object = clazz.newInstance(); returnValue.add(object); } return returnValue; } ``` The problem is, that if `clazz` is an inner class such as `Foo.Bar.class`, then the `newInstance()` method will not work even if `Bar` would be public, as it will throw a `java.lang.InstantiationException`. Is there a way to dynamically instantiate inner classes?
If it's genuinely an *inner* class instead of a *nested* (static) class, there's an implicit constructor parameter, which is the reference to the instance of the outer class. You can't use `Class.newInstance` at that stage - you have to get the appropriate constructor. Here's an example: ``` import java.lang.reflect.*; class Test { public static void main(String[] args) throws Exception { Class<Outer.Inner> clazz = Outer.Inner.class; Constructor<Outer.Inner> ctor = clazz.getConstructor(Outer.class); Outer outer = new Outer(); Outer.Inner instance = ctor.newInstance(outer); } } class Outer { class Inner { // getConstructor only returns a public constructor. If you need // non-public ones, use getDeclaredConstructors public Inner() {} } } ```
Something more generic: ``` public static <T> T createInstance(final Class<T> clazz) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { T instanceToReturn = null; Class< ? > enclosingClass = clazz.getEnclosingClass(); if (enclosingClass != null) { Object instanceOfEnclosingClass = createInstance(enclosingClass); Constructor<T> ctor = clazz.getConstructor(enclosingClass); if (ctor != null) { instanceToReturn = ctor.newInstance(instanceOfEnclosingClass); } } else { instanceToReturn = clazz.newInstance(); } return instanceToReturn; } ```
Instantiating an inner class
[ "", "java", "inner-classes", "" ]
I just inherited a 70k line PHP codebase that I now need to add enhancements onto. I've seen worse, at least this codebase uses an MVC architecture and is object oriented. However, there is no templating system and many classes are deprecated - only being called once. I think my method might be the following: 1. Find all the files on the live server that have not been touched in 48 hours and make them candidates for deletion (luckily there is a live server). 2. Implement a template system (Smarty) and try to find duplicate code in the templates. 3. Alot of the methods have copied and pasted code ... I don't know how much I want to mess with it. My questions are: Are there steps that I should take or you would take? What is your method for dealing with this? Are there tools to help find duplicate PHP code?
> Find all the files on the live server that have not been touched in 48 hours and make them candidates for deletion (luckily there is a live server) By "touched" I'm assuming you'll stat the file to see if it's been accessed by any part of the system. I'd go a month and a half on this rather than 48 hours. In older PHP code bases you'll often find there's a bunch of code lying around that gets called via a local cron job once a week or once a month, or a third party is calling it remotely as a pseudo-service on a regular basis. By waiting 6 weeks be more likely to catch any and all files that are being called. > Implement a template system (Smarty) and try to find duplicate code in the templates. Why? Serious question, is there a reason to implement a template system? (non-PHP savvy designers, developers who get you into trouble by including too much logic in the Views, or you're the one creating templates, and you know you work much faster in smarty than in PHP). If not, avoid it and just use PHP. Also, how realistic is it to implement a pure smarty template system? I'd give favorable odds that old PHP systems like this are going to have a ton of "business logic" mixed in with their views that can't be implemented in pure smarty, and if you allowed mixed PHP/Smarty your developers will use PHP everytime. > Alot of the methods have copied and pasted code ... I don't know how much I want to mess with it. I don't know of any code analysis tools that will do this out of the box, but it sould be possible to whip something up with the [tokenizer functions](https://www.php.net/manual/en/ref.tokenizer.php). ## What You Should Really Do I don't want to dissuade you or demoralize you, but why do you want to cleanup this code? Right now it's doing what's is supposed to do. Stupidly, but it's doing it. Every re-factoring project is going to put current, undocumented, possibly business critical functionality at risk and at the end of that work you have an application that's doing the exact same thing. It's 70k lines of what sounds like shoddy code that only you care about fixing, no mater what other people are telling you their priorities are. If their priority was clean code, their code would already be clean. One person can't change a culture. Unless there's a straight forward business case for that code to be cleaned (open sourcing the project as a business strategy?), that legacy code isn't going anywhere. Here's a different set of priorties to consider with legacy PHP applications 1. Is there a singleton database object or pair of objects that allows developers to easily setup seperate connections for read (slave) and write (master). Lot of legacy PHP applications will instantiate multiple connections to the same database in a single page call, which is a performance nightmare. 2. Is there a straight forward way for developers to avoid SQL injection? Give this to them for new code (parameterized SQL), and consider fixing legacy SQL to use this new method, but also consider security steps you can take on the network level. 3. Get a test framework of some kind wrapped around all the legacy code and treat it as a black-box. Use those tests to create a centralized API developers can use in place of the myriad function calls and copy/paste code they've been using. 4. Develop a centralized system for configuration values, most legacy PHP code is some awful combination of defines and class constants, which means any config changes mean a code push, which means potential DOOM. 5. Develop a lint that's hooked into the source control system to enforce code sanity for all new code, not [just for style](http://pear.php.net/package/PHP_CodeSniffer), but to make sure that business logic stays out of the view, that the SQL is being contructed in a safe way, that those old copy/paste libraries aren't being used, etc. 6. Develop a sane, trackable build and/or push system and stop people from hackin on code live in production
I don't know of any specific tools, but I have worked on re-factoring some fairly large PHP projects. I would recommend a templating system, either Smarty or a strict PHP system that is clearly explained to anybody working on the project. Take discrete, manageable sections and re-factor on a regular basis (e.g., this week, I'm going to re-write this). Don't bite off more than you can chew and don't plan to do a full rewrite. Also, I do regular code searches (I use Eclipse and search through the files in my project) on suspect functions and files. Some people are too scared to make big changes, but I would rather err on the bold side rather than accept messy and poorly organized code. Just be prepared to test, test, test!
Tools for cleaning garbage PHP
[ "", "php", "" ]
In a project I maintain, I see a lot of code like this for simple `get`/`set` methods ``` const int & MyClass::getFoo() { return m_foo; } void MyClass::setFoo(const int & foo) { m_foo = foo; } ``` What is the point in doing that instead of the following? ``` int MyClass::getFoo() { return m_foo; } // Removed 'const' and '&' void MyClass::setFoo(const int foo) { m_foo = foo; } // Removed '&' ``` Passing a reference to a primitive type should require the same (or more) effort as passing the type's value itself, right? It's just a number after all... Is this just some attempted micro-optimization or is there a true benefit?
The difference is that if you get that result into a reference yourself you can track the changes of the integer member variable in your own variable name without recalling the function. ``` const &int x = myObject.getFoo(); cout<<x<<endl; //... cout<<x<<endl;//x might have changed ``` It's probably not the best design choice, and it's very dangerous to return a reference (const or not), in case a variable that gets freed from scope is returned. So if you return a reference, be careful to be sure it is not a variable that goes out of scope. There is a slight difference for the modifier too, but again probably not something that is worth doing or that was intended. ``` void test1(int x) { cout<<x<<endl;//prints 1 } void test2(const int &x) { cout<<x<<endl;//prints 1 or something else possibly, another thread could have changed x } int main(int argc, char**argv) { int x = 1; test1(x); //... test2(x); return 0; } ``` So the end result is that you obtain changes even after the parameters are passed.
To me, passing a *const reference* for primitives is a mistake. Either you need to modify the value, and in that case you pass a *non-const reference*, or you just need to access the value and in that case you pass a *const*. *Const references* should only be used for complex classes, when copying objects could be a performance problem. In the case of primitives, unless you need to modify the value of the variable you shouldn't pass a *reference*. The reason is that *references* take more computation time than *non-references*, since with *references*, the program needs to look up in a table to find the *address* of the object. When this look-up time is shorter than the copying time, references are an improvement. Generally, *ints* and *addresses* have the same byte length in low-level implementations. So the time of copying an *int* as a return value for a function is equivalent to the time of copying an *address*. But in the case where an *int* is returned, no look up is performed, therefore performance is increased.
What is the use of passing const references to primitive types?
[ "", "c++", "reference", "constants", "primitive", "" ]