Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've been asked to implement some code that will update a row in a MS SQL Server database and then use a stored proc to insert the update in a history table. We can't add a stored proc to do this since we don't control the database. I know in stored procs you can do the update and then call execute on another stored proc. Can I set it up to do this in code using one SQL command?
Either run them both in the same statement (separate the separate commands by a semi-colon) or a use a transaction so you can rollback the first statement if the 2nd fails.
You don't really need a stored proc for this. The question really boils down to whether or not you have control over all the inserts. If in fact you have access to all the inserts, you can simply wrap an insert into datatable, and a insert into historytable in a single transasction. This will ensure that both are completed for 'success' to occur. However, when accessing to tables in sequence within a transaction you need to make sure you don't lock historytable then datatable, or else you could have a deadlock situation. However, if you do not have control over the inserts, you can add a trigger to certain db systems that will give you access to the data that are modified, inserted or deleted. It may or may not give you all the data you need, like who did the insert, update or delete, but it will tell you what changed.
Execute an insert and then log in one SQL command
[ "", "sql", "sql-server", "" ]
I need to make an ArrayList of ArrayLists thread safe. I also cannot have the client making changes to the collection. Will the unmodifiable wrapper make it thread safe or do I need two wrappers on the collection?
It depends. The wrapper will only prevent changes to the collection it wraps, not to the objects in the collection. If you have an ArrayList of ArrayLists, the global List as well as each of its element Lists need to be wrapped separately, and you may also have to do something for the contents of those lists. Finally, you have to make sure that the original list objects are not changed, since the wrapper only prevents changes through the wrapper reference, not to the original object. You do NOT need the synchronized wrapper in this case.
On a related topic - I've seen several replies suggesting using synchronized collection in order to achieve thread safety. Using synchronized version of a collection doesn't make it "thread safe" - although each operation (insert, count etc.) is protected by mutex when combining two operations there is no guarantee that they would execute atomically. For example the following code is not thread safe (even with a synchronized queue): ``` if(queue.Count > 0) { queue.Add(...); } ```
Does the unmodifiable wrapper for java collections make them thread safe?
[ "", "java", "multithreading", "collections", "unmodifiable", "" ]
I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far. I want to get them numerically ordered and I've come up with ``` select colname from table order by cast(replace(replace(colname,'Operator (',''),')','') as int) ``` which is very very ugly. Better suggestions?
It's that, InStr()/SubString(), changing Operator(1) to Operator(001), storing the n in Operator(n) separately, or creating a computed column that hides the ugly string manipulation. What you have seems fine.
If you really *have* to leave the data in the format you have - and adding a numeric sort order column is the better solution - then consider wrapping the text manipulation up in a user defined function. select colname from table order by dbo.udfSortOperator(colname) It's less ugly and gives you some abstraction. There's an additional overhead of the function call but on a table containing low thousands of rows in a not-too-heavily hit database server it's not a major concern. Make notes in the function to optomise later as required.
Force numerical order on a SQL Server 2005 varchar column, containing letters and numbers?
[ "", "sql", "sql-server", "sql-order-by", "" ]
I'm trying to make a two-column page using a div-based layout (no tables please!). Problem is, I can't grow the left div to match the height of the right one. My right div typically has a lot of content. Here's a paired down example of my template to illustrate the problem. ``` <div style="float:left; width: 150px; border: 1px solid;"> <ul> <li>nav1</li> <li>nav2</li> <li>nav3</li> <li>nav4</li> </ul> </div> <div style="float:left; width: 250px"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna .... </div> ```
Use jQuery for this problem; just call this function in your ready function: ``` function setHeight(){ var height = $(document).height(); //optionally, subtract some from the height $("#leftDiv").css("height", height + "px"); } ```
Your simplest answer lies in the next version of css (3), which currently no browser supports. For now you are relegated to calculating heights in javascript and setting them on the left side. If the navigation is so important to be positioned in such a way, run it along the top. you could also do a visual trick by moving the borders to the container and the bigger inner, and make it appear to be the same size. this makes it look the same, but it isn't. ``` <div style="border-left:solid 1px black;border-bottom:solid 1px black;"> <div style="float:left; width: 150px; border-top: 1px solid;"> <ul> <li>nav1</li> <li>nav2</li> <li>nav3</li> <li>nav4</li> </ul> </div> <div style="float:left; width: 250px; border:solid 1px black;border-bottom:0;"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna Lorem ipsum dolor sit amet, consectetur adipisicing elit, ... </div> <div style="clear:both;" ></div> </div> ```
On a two-column page, how can I grow the left div to the same height of the right div using CSS or Javascript?
[ "", "javascript", "html", "css", "" ]
I'm working on some production software, using C# on the .NET framework. I really would like to be able to use LINQ on the project. I believe it requires .NET version 3.5 (correct me if I'm wrong). This application is a commercial software app, required to run on a client's work PC. Is it reasonable to assume they have .NET 3.5, or assume that they won't mind upgrading to the latest version? I just wanted to feel out what the consensus was as far as mandating framework upgrades to run apps.
To use LINQ, as you have said, you need to have .NET 3.5. Just to confirm this, the Wikipedia page for LINQ says: > Language Integrated Query (LINQ, > pronounced "link") is a Microsoft .NET > Framework component that adds native > data querying capabilities to .NET > languages using a syntax reminiscent > of SQL. Many of the concepts that LINQ > has introduced were originally tested > in Microsoft's Cω research project. > **LINQ was released as a part of .NET > Framework 3.5 on November 19, 2007**. Due to the fact that machines may have some of the previous versions of .NET already installed, you may find that this site, [Smallest Dot NET](http://www.hanselman.com/smallestdotnet/) by Scott Hanselman (Microsoft employee) is useful. It works out the smallest updates you need to get up to date (currently 3.5 SP1). As for whether it is reasonable to expect it on the client's machine, I guess it depends upon what you're creating. My feelings are: **Small low cost applications = PERHAPS NOT YET** A tiny application sold at low cost, perhaps targeting 3.5 is a little early and likely to reduce the size of your audience because of the annoyance factor. **Large commercial applications, with installers = YES** If it is a large commercial application (your baseline specifications are already WInXP or newer running on .NET 2.0), I don't think the customer would care. Put the redistributable on the installer disk! Remember that adopting any new technology should be done for a number of reasons. What is your need to use LINQ, is it something that would be tough to replicate? If LINQ gives you functionality you really need, your costs and timetable are likely to benefit from selecting it. Your company gain by being able to sell the product for less or increase their margins. One final option, as pointed out by [Nescio](https://stackoverflow.com/questions/106439/requiring-users-to-update-net#106442), if all you need is Linq to Objects (eg. you don't need Linq to SQL or Linq to XML) then [LinqBridge](http://www.albahari.com/nutshell/linqbridge.aspx) may be an option.
I would say that it isn't safe to assume they have .NET 3.5. Where as it is very, very unlikely they will have any problems when upgrading, changing anything always carries a risk. I know I wouldn't mind upgrading, but I am a developer. I think it's one of those things that could go either way, they either won't think twice about it and just upgrade, or they might make an issue out of it. I think it would depend on your customers, 'low-tech' clients may think twice as they may not fully understand it, which would make them nervous.
Requiring users to update .NET
[ "", "c#", ".net", "linq", "client-applications", "" ]
I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have: ``` <p height="30"> ``` I want to apply a `class="h30"` to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an `id` or `class`. Help?
I would highly recommend using something like jquery where adding classes is trivial: ``` $("#someId").addClass("newClass"); ``` so in your case: ``` $("p[height='30']").addClass("h30"); ``` so this selects all paragraph tags where the height attribute is 30 and adds the class h30 to it.
See: [getAttribute()](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-666EE0F9). Parameter is the name of the attribute (case insensitive). Return value is the value of the attribute (a string). Be sure to see the [Remarks](http://msdn.microsoft.com/en-us/library/ms536429(VS.85).aspx) in MSDN before dealing with IE...
Javascript - Applying class to an HTML tag given an attribute/value
[ "", "javascript", "html", "" ]
I'm trying to write a Wordpress plug-in that automatically posts a blog post at a certain time of day. For example, read a bunch of RSS feeds and post a daily digest of all new entries. There are plug-ins that do something similar to what I want, but many of them rely on a cron job for the automated scheduling. I'll do that if I have to, but I was hoping there was a better way. Getting a typical Wordpress user to add a cron job isn't exactly friendly. Is there a good way to schedule a task that runs from a Wordpress plug-in? It doesn't have to run at exactly the right time.
<http://codex.wordpress.org/Function_Reference/wp_schedule_event>
pseudo-cron is good but the two issues it has is 1, It requires someone to "hit" the blog to execute. Low volume sites will potentially have wide ranging execution times so don't be two specific about the time. 2, The processing happens before the page loads. So if teh execution time happens and you have lots of "cron" entries you potentially upset visitors by giving them a sub standard experience. Just my 2 cents :-)
Running a scheduled task in a Wordpress plug-in
[ "", "php", "wordpress", "" ]
I would like to be able to do such things as ``` var m1 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Pounds); var m2 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Liters); m1.ToKilograms(); m2.ToPounds(new Density(7.0, DensityType.PoundsPerGallon); ``` If there isn't something like this already, anybody interested in doing it as an os project?
Check out the [Measurement Unit Conversion Library](http://www.codeproject.com/KB/library/Measurement_Conversion.aspx) on The Code Project.
We actually built one in-house where I work. Unfortunately, it's not available for the public. This is actually a great project to work on and it's not that hard to do. If you plan on doing something by yourself, I suggest you read about [Quantity](http://en.wikipedia.org/wiki/Physical_quantity), [Dimension](http://en.wikipedia.org/wiki/Dimensional_analysis) and [Unit](http://en.wikipedia.org/wiki/Units_of_measurement) ([fundamental units](http://en.wikipedia.org/wiki/Fundamental_units)). These helped us understand the domain of the problem clearly and helped a lot in designing the library.
Does anyone know a library for working with quantity/unit of measure pairs?
[ "", "c#", ".net", "vb.net", "metric", "" ]
I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised. I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of?
(Apart from the observer pattern) you can also use [`call_user_func()`](http://php.net/manual/function.call-user-func.php) or [`call_user_func_array()`](http://php.net/manual/function.call-user-func-array.php). If you pass an `array(obj, methodname)` as first parameter it will invoked as `$obj->methodname()`. ``` <?php class Foo { public function bar($x) { echo $x; } } function xyz($cb) { $value = rand(1,100); call_user_func($cb, $value); } $foo = new Foo; xyz( array($foo, 'bar') ); ?> ```
How do you feel about using the [Observer](http://en.wikipedia.org/wiki/Observer_Pattern) pattern? If not, you can implement a true callback this way: ``` // This function uses a callback function. function doIt($callback) { $data = "this is my data"; $callback($data); } // This is a sample callback function for doIt(). function myCallback($data) { print 'Data is: ' . $data . "\n"; } // Call doIt() and pass our sample callback function's name. doIt('myCallback'); ``` Displays: Data is: this is my data
Something like a callback delegate function in php
[ "", "php", "oop", "" ]
I'm working on a command line application for Solaris, written in Java6. I'd like to be able to scroll through a history of previous commands using the up and down arrows like many Unix tools allow (shells, VIM command mode prompt, etc). Is there any standard way of achieving this, or do I have to roll my own?
Yes, use the [GNU readline](http://tiswww.case.edu/php/chet/readline/rltop.html) library.
I think you are looking for something like [JLine](http://jline.sourceforge.net/) but I've never used it so cannot attest to its quality. She can apparently deal with autocompletion and command line history, and the last release was recently (feb this year) so it's by no means dead.
Adding command recall to a Unix command line application
[ "", "java", "unix", "command-line", "command-prompt", "ledit", "" ]
What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form.
``` private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar == 'm') this.WindowState = FormWindowState.Minimized; } ```
``` FormName.WindowState = FormWindowState.Minimized; ```
Is there a way to programmatically minimize a window
[ "", "c#", ".net", "vb.net", "winforms", "" ]
So I have a function that looks something like this: ``` float function(){ float x = SomeValue; return x / SomeOtherValue; } ``` At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this: ``` float function(){ float x = SomeValue; cout << x; return x / SomeOtherValue; } ``` and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing? (If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.)
Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register). When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases. See the MSDN documentation on VC++ [floating point switches](http://msdn.microsoft.com/en-us/library/e7s85ffb(VS.80).aspx). You could try compiling with /fp:strict and seeing what happens.
Printing a value to cout should not change the value of the paramter in any way at all. However, I have seen similar behaviour, adding debugging statements causes a change in the value. In those cases, and probably this one as well my guess was that the additional statements were causing the compiler's optimizer to behave differently, so generate different code for your function. Adding the cout statement means that the vaue of x is used directly. Without it the optimizer could remove the variable, so changing the order of the calculation and therefore changing the answer.
Can cout alter variables somehow?
[ "", "c++", "floating-point", "cout", "cpu-registers", "floating-point-precision", "" ]
I have 2 time values which have the type `datetime.time`. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type `datetime.datetime` but not for `datetime.time`. So what is the best way to do this?
Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours. One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference. ``` t1, t2 = datetime.time(...), datetime.time(...) t1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond t2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond delta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms]) ``` It's a little lame, but it works.
Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using `datetime.datetime.combine`, then subtracting: ``` >>> import datetime >>> t1 = datetime.time(2,3,4) >>> t2 = datetime.time(18,20,59) >>> dummydate = datetime.date(2000,1,1) >>> datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1) datetime.timedelta(0, 58675) ```
What is the simplest way to find the difference between 2 times in python?
[ "", "python", "datetime", "time", "" ]
I want to use SQL Profiler to trace the queries executed agains my database, track performance, etc. However it seems that the SQL Profiler is only available in the Enterprise edition of SQL Server 2005. Is this the case indeed, and can I do something about it?
You don't need **any** SQL license to run the client tools (Management Studio, Profiler, etc). If your organization has a copy of the installation media for Developer, Standard, or Enterprise, you can install the client tools on your local machine under the same license. If you're working solo, I would recommend [purchasing](http://www.microsoft.com/products/info/product.aspx?view=22&pcid=f544888c-2638-48ed-9f0f-d814e8b93ca0&crumb=catpage&catid=cd1daedd-9465-4aef-a7bf-8f5cf09a4dc0#HowToBuy) SQL Developer edition, it's only $50.
If you are open to using third party profilers, I have used [xSQL Profiler](http://www.xsqlsoftware.com/Product/xSQL_Profiler.aspx) and it performed well enough.
SQL Profiler on SQL Server 2005 Professional Edition
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I would prefer that a console app would default to multithreaded debug. warning level 4. build browse information. no resource folder. Does anyone know of any technique that would allow me to create a console app, with my desired options, without manually setting it.
Yes, you can do that. What you want is to create your own project template. You can then select that template from the New Project wizard. I wasn't able to location documentation on how to create a project template in Visual Studio 6, but [this MSDN article](http://msdn.microsoft.com/en-us/library/ms247120(VS.80).aspx) explains the procedure for Visual Studio 2005. Hopefully you will find those instructions to sufficiently similar.
I have concluded this is impossible. The is support for custom appwizards for windows projects, but not console projectcs. This is where I did research. <http://www.codeproject.com/KB/cpp/genwiz.aspx?fid=15478&df=90&mpp=25&noise=3&> sort=Position&view=Quick&select=1266895 <http://msdn.microsoft.com/en-us/library/ms950410.aspx> <http://msdn.microsoft.com/en-us/library/aa300499(VS.60).aspx> The custom appwizard will accept windows projects as a base for the template, but not console projects. A message dialog appears that claims that the base project selected is not a c++ project.
Changing the default settings for a console application
[ "", "c++", "visual-studio", "visual-c++-6", "" ]
I have this line in a javascript block in a page: ``` res = foo('<%= @ruby_var %>'); ``` What is the best way to handle the case where `@ruby_var` has a single-quote in it? Else it will break the JavaScript code.
I think I'd use a ruby [JSON](http://json.org) library on @ruby\_var to get proper js syntax for the string and get rid of the '', fex.: ``` res = foo(<%= @ruby_var.to_json %>) ``` (after require "json"'ing, not entirely sure how to do that in the page or if the above syntax is correct as I havn't used that templating language) (on the other hand, if JSON ever changed to be incompatible with js that'd break, but since a decent amount of code uses eval() to eval json I doubt that'd happen anytime soon)
Rails has method specifically dedicated to this task found in [ActionView::Helpers::JavaScriptHelper](http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html) called [escape\_javascript](http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript). In your example, you would use the following: ``` res = foo('<%= escape_javascript @ruby_var %>'); ``` Or better yet, use the **j** shortcut: ``` res = foo('<%= j @ruby_var %>'); ```
Javascript with embedded Ruby: How to safely assign a ruby value to a javascript variable
[ "", "javascript", "ruby", "" ]
I'm writing a J2SE desktop application that requires one of its components to be pluggable. I've already defined the Java interface for this plugin. The user should be able to select at runtime (via the GUI) which implementation of this interface they want to use (e.g. in an initialisation dialog). I envisage each plugin being packaged as a JAR file containing the implementing class plus any helper classes it may require. What's the best technology for doing this type of thing in a desktop Java app?
After many tries for plugin-based Java architectures (what is precisely what you seem to look for), I finally found [JSPF](http://code.google.com/p/jspf/) to be the best solution for Java5 code. it do not have the huge needs of OSGI like solutions, but is instead rather easy to use.
OSGI is certainly a valid way to go. But, assuming you dont need to unload to reload the plugin, it might be using a hammer to crack a nut. You could use the classes in 'java.util.jar' to scan each JAR file in your plugins folder and then use a 'java.net.URLClassLoader' to load in the correct one.
Best technology for adding plugin support to a J2SE application?
[ "", "java", "plugins", "plugin-architecture", "" ]
I'm looking for a way of getting a **concurrent collection** in **C#** or at least a collection which supports a **concurrent enumerator**. Right now I'm getting an `InvalidOperationException` when the collection over which I'm iterating changes. I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way Code snippet: ``` foreach (String s in (List<String>) callingForm.Invoke(callingForm.delegateGetKillStrings)) { //do some jazz } ``` --edit-- I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well. ``` private void addKillString(String s) { lock (killStrings) { killStrings.Add(s); } } ```
Other than doing a deep-copy your best bet might be to lock the collection: ``` List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings); lock(theList.SyncRoot) { foreach(string s in theList) { // Do some Jazz } } ```
So I'm not quite sure what you're asking, but the Parallel Extensions team has put together some stuff that might fit the bill. See this blog post in particular, about [enumerating parallel collections](http://blogs.msdn.com/pfxteam/archive/2008/08/12/8852005.aspx). It also contains a link to download the Parallel CTP, and you can of course browse through the rest of the blog posts to get an idea of what the CTP is meant to do and how the programming model works.
Concurrent collections in C#
[ "", "c#", "concurrency", "" ]
Hey, I'm using [Levenshteins](http://en.wikipedia.org/wiki/Levenshtein_distance) algorithm to get distance between source and target string. also I have method which returns value from 0 to 1: ``` /// <summary> /// Gets the similarity between two strings. /// All relation scores are in the [0, 1] range, /// which means that if the score gets a maximum value (equal to 1) /// then the two string are absolutely similar /// </summary> /// <param name="string1">The string1.</param> /// <param name="string2">The string2.</param> /// <returns></returns> public static float CalculateSimilarity(String s1, String s2) { if ((s1 == null) || (s2 == null)) return 0.0f; float dis = LevenshteinDistance.Compute(s1, s2); float maxLen = s1.Length; if (maxLen < s2.Length) maxLen = s2.Length; if (maxLen == 0.0F) return 1.0F; else return 1.0F - dis / maxLen; } ``` but this for me is not enough. Because I need more complex way to match two sentences. For example I want automatically tag some music, I have original song names, and i have songs with trash, like *super, quality,* years like *2007, 2008,* etc..etc.. also some files have just <http://trash..thash..song_name_mp3.mp3>, other are normal. I want to create an algorithm which will work just more perfect than mine now.. Maybe anyone can help me? here is my current algo: ``` /// <summary> /// if we need to ignore this target. /// </summary> /// <param name="targetString">The target string.</param> /// <returns></returns> private bool doIgnore(String targetString) { if ((targetString != null) && (targetString != String.Empty)) { for (int i = 0; i < ignoreWordsList.Length; ++i) { //* if we found ignore word or target string matching some some special cases like years (Regex). if (targetString == ignoreWordsList[i] || (isMatchInSpecialCases(targetString))) return true; } } return false; } /// <summary> /// Removes the duplicates. /// </summary> /// <param name="list">The list.</param> private void removeDuplicates(List<String> list) { if ((list != null) && (list.Count > 0)) { for (int i = 0; i < list.Count - 1; ++i) { if (list[i] == list[i + 1]) { list.RemoveAt(i); --i; } } } } /// <summary> /// Does the fuzzy match. /// </summary> /// <param name="targetTitle">The target title.</param> /// <returns></returns> private TitleMatchResult doFuzzyMatch(String targetTitle) { TitleMatchResult matchResult = null; if (targetTitle != null && targetTitle != String.Empty) { try { //* change target title (string) to lower case. targetTitle = targetTitle.ToLower(); //* scores, we will select higher score at the end. Dictionary<Title, float> scores = new Dictionary<Title, float>(); //* do split special chars: '-', ' ', '.', ',', '?', '/', ':', ';', '%', '(', ')', '#', '\"', '\'', '!', '|', '^', '*', '[', ']', '{', '}', '=', '!', '+', '_' List<String> targetKeywords = new List<string>(targetTitle.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries)); //* remove all trash from keywords, like super, quality, etc.. targetKeywords.RemoveAll(delegate(String x) { return doIgnore(x); }); //* sort keywords. targetKeywords.Sort(); //* remove some duplicates. removeDuplicates(targetKeywords); //* go through all original titles. foreach (Title sourceTitle in titles) { float tempScore = 0f; //* split orig. title to keywords list. List<String> sourceKeywords = new List<string>(sourceTitle.Name.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries)); sourceKeywords.Sort(); removeDuplicates(sourceKeywords); //* go through all source ttl keywords. foreach (String keyw1 in sourceKeywords) { float max = float.MinValue; foreach (String keyw2 in targetKeywords) { float currentScore = StringMatching.StringMatching.CalculateSimilarity(keyw1.ToLower(), keyw2); if (currentScore > max) { max = currentScore; } } tempScore += max; } //* calculate average score. float averageScore = (tempScore / Math.Max(targetKeywords.Count, sourceKeywords.Count)); //* if average score is bigger than minimal score and target title is not in this source title ignore list. if (averageScore >= minimalScore && !sourceTitle.doIgnore(targetTitle)) { //* add score. scores.Add(sourceTitle, averageScore); } } //* choose biggest score. float maxi = float.MinValue; foreach (KeyValuePair<Title, float> kvp in scores) { if (kvp.Value > maxi) { maxi = kvp.Value; matchResult = new TitleMatchResult(maxi, kvp.Key, MatchTechnique.FuzzyLogic); } } } catch { } } //* return result. return matchResult; } ``` This works normally but just in some cases, a lot of titles which should match, does not match... I think I need some kind of formula to play with weights and etc, but i can't think of one.. Ideas? Suggestions? Algos? by the way I already know this topic (My colleague already posted it but we cannot come with a proper solution for this problem.): [Approximate string matching algorithms](https://stackoverflow.com/questions/49263/approximate-string-matching-algorithms)
Your problem here may be distinguishing between noise words and useful data: * Rolling\_Stones.Best\_of\_2003.Wild\_Horses.mp3 * Super.Quality.Wild\_Horses.mp3 * Tori\_Amos.Wild\_Horses.mp3 You may need to produce a dictionary of noise words to ignore. That seems clunky, but I'm not sure there's an algorithm that can distinguish between band/album names and noise.
Kind of old, but It might be useful to future visitors. If you're already using the Levenshtein algorithm and you need to go a little better, I describe some very effective heuristics in this solution: [Getting the closest string match](https://stackoverflow.com/questions/5859561/getting-the-closest-string-match/5859823#5859823) The key is that you come up with 3 or 4 (or [more](http://en.wikipedia.org/wiki/String_metric)) methods of gauging the similarity between your phrases (Levenshtein distance is just one method) - and then using real examples of strings you want to match as similar, you adjust the weightings and combinations of those heuristics until you get something that maximizes the number of positive matches. Then you use that formula for all future matches and you should see great results. If a user is involved in the process, it's also best if you provide an interface which allows the user to see additional matches that rank highly in similarity in case they disagree with the first choice. Here's an excerpt from the linked answer. If you end up wanting to use any of this code as is, I apologize in advance for having to convert VBA into C#. --- Simple, speedy, and a very useful metric. Using this, I created two separate metrics for evaluating the similarity of two strings. One I call "valuePhrase" and one I call "valueWords". valuePhrase is just the Levenshtein distance between the two phrases, and valueWords splits the string into individual words, based on delimiters such as spaces, dashes, and anything else you'd like, and compares each word to each other word, summing up the shortest Levenshtein distance connecting any two words. Essentially, it measures whether the information in one 'phrase' is really contained in another, just as a word-wise permutation. I spent a few days as a side project coming up with the most efficient way possible of splitting a string based on delimiters. valueWords, valuePhrase, and Split function: ``` Public Function valuePhrase#(ByRef S1$, ByRef S2$) valuePhrase = LevenshteinDistance(S1, S2) End Function Public Function valueWords#(ByRef S1$, ByRef S2$) Dim wordsS1$(), wordsS2$() wordsS1 = SplitMultiDelims(S1, " _-") wordsS2 = SplitMultiDelims(S2, " _-") Dim word1%, word2%, thisD#, wordbest# Dim wordsTotal# For word1 = LBound(wordsS1) To UBound(wordsS1) wordbest = Len(S2) For word2 = LBound(wordsS2) To UBound(wordsS2) thisD = LevenshteinDistance(wordsS1(word1), wordsS2(word2)) If thisD < wordbest Then wordbest = thisD If thisD = 0 Then GoTo foundbest Next word2 foundbest: wordsTotal = wordsTotal + wordbest Next word1 valueWords = wordsTotal End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' SplitMultiDelims ' This function splits Text into an array of substrings, each substring ' delimited by any character in DelimChars. Only a single character ' may be a delimiter between two substrings, but DelimChars may ' contain any number of delimiter characters. It returns a single element ' array containing all of text if DelimChars is empty, or a 1 or greater ' element array if the Text is successfully split into substrings. ' If IgnoreConsecutiveDelimiters is true, empty array elements will not occur. ' If Limit greater than 0, the function will only split Text into 'Limit' ' array elements or less. The last element will contain the rest of Text. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function SplitMultiDelims(ByRef Text As String, ByRef DelimChars As String, _ Optional ByVal IgnoreConsecutiveDelimiters As Boolean = False, _ Optional ByVal Limit As Long = -1) As String() Dim ElemStart As Long, N As Long, M As Long, Elements As Long Dim lDelims As Long, lText As Long Dim Arr() As String lText = Len(Text) lDelims = Len(DelimChars) If lDelims = 0 Or lText = 0 Or Limit = 1 Then ReDim Arr(0 To 0) Arr(0) = Text SplitMultiDelims = Arr Exit Function End If ReDim Arr(0 To IIf(Limit = -1, lText - 1, Limit)) Elements = 0: ElemStart = 1 For N = 1 To lText If InStr(DelimChars, Mid(Text, N, 1)) Then Arr(Elements) = Mid(Text, ElemStart, N - ElemStart) If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) > 0 Then Elements = Elements + 1 Else Elements = Elements + 1 End If ElemStart = N + 1 If Elements + 1 = Limit Then Exit For End If Next N 'Get the last token terminated by the end of the string into the array If ElemStart <= lText Then Arr(Elements) = Mid(Text, ElemStart) 'Since the end of string counts as the terminating delimiter, if the last character 'was also a delimiter, we treat the two as consecutive, and so ignore the last elemnent If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) = 0 Then Elements = Elements - 1 ReDim Preserve Arr(0 To Elements) 'Chop off unused array elements SplitMultiDelims = Arr End Function ``` **Measures of Similarity** Using these two metrics, and a third which simply computes the distance between two strings, I have a series of variables which I can run an optimization algorithm to achieve the greatest number of matches. Fuzzy string matching is, itself, a fuzzy science, and so by creating linearly independent metrics for measuring string similarity, and having a known set of strings we wish to match to each other, we can find the parameters that, for our specific styles of strings, give the best fuzzy match results. Initially, the goal of the metric was to have a low search value for for an exact match, and increasing search values for increasingly permuted measures. In an impractical case, this was fairly easy to define using a set of well defined permutations, and engineering the final formula such that they had increasing search values results as desired. ![enter image description here](https://i.stack.imgur.com/eGCtC.png) As you can see, the last two metrics, which are fuzzy string matching metrics, already have a natural tendency to give low scores to strings that are meant to match (down the diagonal). This is very good. **Application** To allow the optimization of fuzzy matching, I weight each metric. As such, every application of fuzzy string match can weight the parameters differently. The formula that defines the final score is a simply combination of the metrics and their weights: ``` value = Min(phraseWeight*phraseValue, wordsWeight*wordsValue)*minWeight + Max(phraseWeight*phraseValue, wordsWeight*wordsValue)*maxWeight + lengthWeight*lengthValue ``` Using an optimization algorithm (neural network is best here because it is a discrete, multi-dimentional problem), the goal is now to maximize the number of matches. I created a function that detects the number of correct matches of each set to each other, as can be seen in this final screenshot. A column or row gets a point if the lowest score is assigned the the string that was meant to be matched, and partial points are given if there is a tie for the lowest score, and the correct match is among the tied matched strings. I then optimized it. You can see that a green cell is the column that best matches the current row, and a blue square around the cell is the row that best matches the current column. The score in the bottom corner is roughly the number of successful matches and this is what we tell our optimization problem to maximize. ![enter image description here](https://i.stack.imgur.com/hsMtp.png)
Fuzzy text (sentences/titles) matching in C#
[ "", "c#", "algorithm", "string", "fuzzy-search", "" ]
I'm looking for a tool to generate a JavaScript stub from a WSDL. Although I usually prefer to use REST services with JSON or XML, there are some tools I am currently integrating that works only using SOAP. I already created a first version of the client in JavaScript but I'm parsing the SOAP envelope by hand and I doubt that my code can survive a service upgrade for example, seeing how complex the SOAP envelope specification is. So is there any tool to automatically generate fully SOAP compliant stubs for JavaScript from the WSDL so I can be more confident on the future of my client code. More: The web service I try to use is RPC encoded, not document literal.
I had to do this myself in the past and I found this [CodeProject article](http://www.codeproject.com/KB/ajax/JavaScriptSOAPClient.aspx). I changed it up some, but it gave me a good foundation to implement everything I needed. One of the main features it already has is generating the SOAP client based off the WSDL. It also has built in caching of the WSDL for multiple calls. This article also has a custom implementation of XmlHttpRequest for Ajax calls. This is the part that I didn't use. During that time, I think I was using [Prototype](http://www.prototypejs.org/) javascript library and modified the code in this article to use it's Ajax functions instead. I just felt more comfortable using Prototype for the ajax calls, because it was widely used and had been tested on all the browsers.
Apache CXF has tools that generate JavaScript clients that talk soap. Actually, any CXF service can have a javascript client autogenerated by doing a get to the URL with ?js appended. (just like ?wsld produces the wsdl) There are command line tools as well, but the dynamic generated stuff is kind of neat.
Generating JavaScript stubs from WSDL
[ "", "javascript", "soap", "wsdl", "" ]
The exact error is as follows > Could not load file or assembly 'Microsoft.SqlServer.Replication, > Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' > or one of its dependencies. An attempt was made to load a program with > an incorrect format. I've recently started working on this project again after a two month move to another project. It worked perfectly before, and I've double checked all the references.
I've found the solution. I've recently upgraded my machine to Windows 2008 Server 64-bit. The SqlServer.Replication namespace was written for 32-bit platforms. All I needed to do to get it running again was to set the Target Platform in the Project Build Properties to X86.
The [answer by baldy](https://stackoverflow.com/a/41451/148412) below is correct, but you may also need to enable 32-bit applications in your AppPool. Source: <http://www.alexjamesbrown.com/uncategorized/could-not-load-file-or-assembly-chilkatdotnet2-or-one-of-its-dependencies-an-attempt-was-made-to-load-a-program-with-an-incorrect-format/> Whilst setting up an application to run on my local machine (running Vista 64bit) I encountered this error: > Could not load file or assembly `ChilkatDotNet2` or one of its > dependencies. An attempt was made to load a program with an incorrect > format. Obviously, the application uses [ChilKat components](http://www.chilkatsoft.com/), but it would seem that the version we are using, is only the 32bit version. To resolve this error, I set my app pool in IIS to allow 32bit applications. Open up IIS Manager, right click on the app pool, and select Advanced Settings (See below) ![enter image description here](https://i.stack.imgur.com/LQkqf.jpg) Then set "Enable 32-bit Applications" to True. ![enter image description here](https://i.stack.imgur.com/7ltqt.jpg) All done!
I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project
[ "", "c#", "sql-server", "replication", "" ]
What is a smart pointer and when should I use one?
**UPDATE** This answer is rather old, and so describes what was 'good' at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr), [`std::shared_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr) and [`std::weak_ptr`](http://en.cppreference.com/w/cpp/memory/weak_ptr). There was also [`std::auto_ptr`](http://en.cppreference.com/w/cpp/memory/auto_ptr). It was very much like a scoped pointer, except that it also had the "special" dangerous ability to be copied — which also unexpectedly transfers ownership. **It was deprecated in C++11 and removed in C++17**, so you shouldn't use it. ``` std::auto_ptr<MyObject> p1 (new MyObject()); std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership. // p1 gets set to empty! p2->DoSomething(); // Works. p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception. ``` --- **OLD ANSWER** A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way. Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you *really* do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory. With raw pointers, the programmer has to explicitly destroy the object when it is no longer useful. ``` // Need to create the object to achieve some goal MyObject* ptr = new MyObject(); ptr->DoSomething(); // Use the object in some way delete ptr; // Destroy the object. Done with it. // Wait, what if DoSomething() raises an exception...? ``` A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it. ``` SomeSmartPtr<MyObject> ptr(new MyObject()); ptr->DoSomething(); // Use the object in some way. // Destruction of the object happens, depending // on the policy the smart pointer class uses. // Destruction would happen even if DoSomething() // raises an exception ``` The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by [`boost::scoped_ptr`](http://www.boost.org/doc/libs/release/libs/smart_ptr/scoped_ptr.htm) or [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr). ``` void f() { { std::unique_ptr<MyObject> ptr(new MyObject()); ptr->DoSomethingUseful(); } // ptr goes out of scope -- // the MyObject is automatically destroyed. // ptr->Oops(); // Compile error: "ptr" not defined // since it is no longer in scope. } ``` Note that `std::unique_ptr` instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call. `std::unique_ptr`s are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed. A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last "reference" to the object is destroyed, the object is deleted. This policy is implemented by [`boost::shared_ptr`](http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm) and [`std::shared_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr). ``` void f() { typedef std::shared_ptr<MyObject> MyObjectPtr; // nice short alias MyObjectPtr p1; // Empty { MyObjectPtr p2(new MyObject()); // There is now one "reference" to the created object p1 = p2; // Copy the pointer. // There are now two references to the object. } // p2 is destroyed, leaving one reference to the object. } // p1 is destroyed, leaving a reference count of zero. // The object is deleted. ``` Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object. There is one drawback to reference counted pointers — the possibility of creating a dangling reference: ``` // Create the smart pointer on the heap MyObjectPtr* pp = new MyObjectPtr(new MyObject()) // Hmm, we forgot to destroy the smart pointer, // because of that, the object is never destroyed! ``` Another possibility is creating circular references: ``` struct Owner { std::shared_ptr<Owner> other; }; std::shared_ptr<Owner> p1 (new Owner()); std::shared_ptr<Owner> p2 (new Owner()); p1->other = p2; // p1 references p2 p2->other = p1; // p2 references p1 // Oops, the reference count of of p1 and p2 never goes to zero! // The objects are never destroyed! ``` To work around this problem, both Boost and C++11 have defined a `weak_ptr` to define a weak (uncounted) reference to a `shared_ptr`.
Here's a simple answer for these days of modern C++ (C++11 and later): * **"What is a smart pointer?"** It's a type whose values can be used like pointers, but which provides the additional feature of automatic memory management: When a smart pointer is no longer in use, the memory it points to is deallocated (see also [the more detailed definition on Wikipedia](http://en.wikipedia.org/wiki/Smart_pointer)). * **"When should I use one?"** Well, you are often better off avoiding the user of pointers altogether, smart or otherwise. Having said that - smart pointers may be useful in code which involves tracking the ownership of a piece of memory, allocating or de-allocating; the smart pointer often saves you the need to do these things explicitly. * **"But which smart pointer should I use in which of those cases?"** + Use [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr) when you want your object to live just as long as a single owning reference to it lives. For example, use it for a pointer to memory which gets allocated on entering some scope and de-allocated on exiting the scope. + Use [`std::shared_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr) when you do want to refer to your object from multiple places - and do not want your object to be de-allocated until all these references are themselves gone. + Use [`std::weak_ptr`](http://en.cppreference.com/w/cpp/memory/weak_ptr) when you do want to refer to your object from multiple places - for those references for which it's ok to ignore and deallocate (so they'll just note the object is gone when you try to dereference). + There is a [proposal](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2530r0.pdf) to add [hazard pointers](https://en.wikipedia.org/wiki/Hazard_pointer) to C++26, but for now you don't have them. + Don't use the `boost::` smart pointers or `std::auto_ptr` except in special cases which you can read up on if you must. * **"Hey, I didn't ask which one to use!"** Ah, but you really wanted to, admit it. * **"So when should I use regular pointers then?"** Mostly in code that is oblivious to memory ownership. This would typically be in functions which get a pointer from someplace else and do not allocate nor de-allocate, and do not store a copy of the pointer which outlasts their execution.
What is a smart pointer and when should I use one?
[ "", "c++", "pointers", "c++11", "smart-pointers", "c++-faq", "" ]
I have a button that I would like to disable when the form submits to prevent the user submitting multiple times. I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled. How do I disable the button when the form successfully submits not just when the user clicks? This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible.
Give this a whirl: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Threading; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Identify button as a "disabled-when-clicked" button... WebHelpers.DisableButtonOnClick( buttonTest, "showPleaseWait" ); } protected void buttonTest_Click( object sender, EventArgs e ) { // Emulate a server-side process to demo the disabled button during // postback. Thread.Sleep( 5000 ); } } using System; using System.Web; using System.Web.UI.WebControls; using System.Text; public class WebHelpers { // // Disable button with no secondary JavaScript function call. // public static void DisableButtonOnClick( Button ButtonControl ) { DisableButtonOnClick( ButtonControl, string.Empty ); } // // Disable button with a JavaScript function call. // public static void DisableButtonOnClick( Button ButtonControl, string ClientFunction ) { StringBuilder sb = new StringBuilder( 128 ); // If the page has ASP.NET validators on it, this code ensures the // page validates before continuing. sb.Append( "if ( typeof( Page_ClientValidate ) == 'function' ) { " ); sb.Append( "if ( ! Page_ClientValidate() ) { return false; } } " ); // Disable this button. sb.Append( "this.disabled = true;" ); // If a secondary JavaScript function has been provided, and if it can be found, // call it. Note the name of the JavaScript function to call should be passed without // parens. if ( ! String.IsNullOrEmpty( ClientFunction ) ) { sb.AppendFormat( "if ( typeof( {0} ) == 'function' ) {{ {0}() }};", ClientFunction ); } // GetPostBackEventReference() obtains a reference to a client-side script function // that causes the server to post back to the page (ie this causes the server-side part // of the "click" to be performed). sb.Append( ButtonControl.Page.ClientScript.GetPostBackEventReference( ButtonControl ) + ";" ); // Add the JavaScript created a code to be executed when the button is clicked. ButtonControl.Attributes.Add( "onclick", sb.ToString() ); } } ```
I'm not a huge fan of writing all that javascript in the code-behind. Here is what my final solution looks like. Button: ``` <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="doSubmit(this)" /> ``` Javascript: ``` <script type="text/javascript"><!-- function doSubmit(btnSubmit) { if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) { return false; } btnSubmit.disabled = 'disabled'; btnSubmit.value = 'Processing. This may take several minutes...'; <%= ClientScript.GetPostBackEventReference(btnSubmit, string.Empty) %>; } //--> </script> ```
Disable button on form submission
[ "", "asp.net", "javascript", "webforms", "" ]
The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments. Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhere. Thanks, ``` int foo(void) { unsigned int fooUnsigned = 0xffffffff; int fooSigned = fooUnsigned; // no warning if (fooSigned < fooUnsigned) // warning { return 0; } return fooSigned; } ``` Update: Quamrana is right, this is controlled by warning 4365 which appears to be off by default, even at W4. However you can explicitly enable it for a given warning level like so; ``` #pragma warning (4 : 4365) ``` Which results in; ``` warning C4365: 'initializing' : conversion from 'unsigned int' to 'int', signed/unsigned mismatch ```
You need to enable warning 4365 to catch the assignment. That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does.
You can change the level of any specific warning by using /W[level][code]. So in this case /W34365 will make warning 4365 into a level 3 warning. If you do this a lot you might find it useful to put these options in a text file and use the @[file] option to simplify the command line.
Make VS compiler catch signed/unsigned assignments?
[ "", "c++", "c", "visual-studio", "" ]
I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?
[Ponder](http://billyquith.github.io/ponder/) is a C++ reflection library, in answer to this question. I considered the options and decided to make my own since I couldn't find one that ticked all my boxes. Although there are great answers to this question, I don't want to use tonnes of macros, or rely on Boost. Boost is a great library, but there are lots of small bespoke C++0x projects out that are simpler and have faster compile times. There are also advantages to being able to decorate a class externally, like wrapping a C++ library that doesn't (yet?) support C++11. It is fork of CAMP, using C++11, that *no longer requires Boost*.
What you need to do is have the preprocessor generate reflection data about the fields. This data can be stored as nested classes. First, to make it easier and cleaner to write it in the preprocessor we will use typed expression. A typed expression is just an expression that puts the type in parenthesis. So instead of writing `int x` you will write `(int) x`. Here are some handy macros to help with typed expressions: ``` #define REM(...) __VA_ARGS__ #define EAT(...) // Retrieve the type #define TYPEOF(x) DETAIL_TYPEOF(DETAIL_TYPEOF_PROBE x,) #define DETAIL_TYPEOF(...) DETAIL_TYPEOF_HEAD(__VA_ARGS__) #define DETAIL_TYPEOF_HEAD(x, ...) REM x #define DETAIL_TYPEOF_PROBE(...) (__VA_ARGS__), // Strip off the type #define STRIP(x) EAT x // Show the type without parenthesis #define PAIR(x) REM x ``` Next, we define a `REFLECTABLE` macro to generate the data about each field(plus the field itself). This macro will be called like this: ``` REFLECTABLE ( (const char *) name, (int) age ) ``` So using [Boost.PP](http://www.boost.org/doc/libs/1_49_0/libs/preprocessor/doc/index.html) we iterate over each argument and generate the data like this: ``` // A helper metafunction for adding const to a type template<class M, class T> struct make_const { typedef T type; }; template<class M, class T> struct make_const<const M, T> { typedef typename boost::add_const<T>::type type; }; #define REFLECTABLE(...) \ static const int fields_n = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__); \ friend struct reflector; \ template<int N, class Self> \ struct field_data {}; \ BOOST_PP_SEQ_FOR_EACH_I(REFLECT_EACH, data, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) #define REFLECT_EACH(r, data, i, x) \ PAIR(x); \ template<class Self> \ struct field_data<i, Self> \ { \ Self & self; \ field_data(Self & self) : self(self) {} \ \ typename make_const<Self, TYPEOF(x)>::type & get() \ { \ return self.STRIP(x); \ }\ typename boost::add_const<TYPEOF(x)>::type & get() const \ { \ return self.STRIP(x); \ }\ const char * name() const \ {\ return BOOST_PP_STRINGIZE(STRIP(x)); \ } \ }; \ ``` What this does is generate a constant `fields_n` that is number of reflectable fields in the class. Then it specializes the `field_data` for each field. It also friends the `reflector` class, this is so it can access the fields even when they are private: ``` struct reflector { //Get field_data at index N template<int N, class T> static typename T::template field_data<N, T> get_field_data(T& x) { return typename T::template field_data<N, T>(x); } // Get the number of fields template<class T> struct fields { static const int n = T::fields_n; }; }; ``` Now to iterate over the fields we use the visitor pattern. We create an MPL range from 0 to the number of fields, and access the field data at that index. Then it passes the field data on to the user-provided visitor: ``` struct field_visitor { template<class C, class Visitor, class I> void operator()(C& c, Visitor v, I) { v(reflector::get_field_data<I::value>(c)); } }; template<class C, class Visitor> void visit_each(C & c, Visitor v) { typedef boost::mpl::range_c<int,0,reflector::fields<C>::n> range; boost::mpl::for_each<range>(boost::bind<void>(field_visitor(), boost::ref(c), v, _1)); } ``` Now for the moment of truth we put it all together. Here is how we can define a `Person` class that is reflectable: ``` struct Person { Person(const char *name, int age) : name(name), age(age) { } private: REFLECTABLE ( (const char *) name, (int) age ) }; ``` Here is a generalized `print_fields` function using the reflection data to iterate over the fields: ``` struct print_visitor { template<class FieldData> void operator()(FieldData f) { std::cout << f.name() << "=" << f.get() << std::endl; } }; template<class T> void print_fields(T & x) { visit_each(x, print_visitor()); } ``` An example of using the `print_fields` with the reflectable `Person` class: ``` int main() { Person p("Tom", 82); print_fields(p); return 0; } ``` Which outputs: ``` name=Tom age=82 ``` And voila, we have just implemented reflection in C++, in under 100 lines of code.
How can I add reflection to a C++ application?
[ "", "c++", "reflection", "templates", "sfinae", "" ]
I am looking for a drop-down JavaScript menu. It should be the simplest and most elegant accessible menu that works in IE6 and Firefox 2 also. It would be fine if it worked on an unnumbered list (`ul`) so the user can use the page without JavaScript support. Which one do you recommend and where can I find the code to such a menu?
I think the jquery superfish menu is fantastic and easy to use: <http://users.tpg.com.au/j_birch/plugins/superfish/> Javascript is **not required**, and it is based on simple valid ul unorder lists.
[A List Apart - Dropdowns](https://alistapart.com/article/dropdowns/) I'd use a css-only solution like the above so the user still gets dropdown menus even with javascript disabled.
Best Javascript drop-down menu?
[ "", "javascript", "menu", "dhtml", "" ]
How do I get an element or element list by it's tag name. Take for example that I want all elements from `<h1></h1>`. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
document.getElementsByTagName('a') returns an array. Look here for more information: <http://web.archive.org/web/20120511135043/https://developer.mozilla.org/en/DOM/element.getElementsByTagName> Amendment: If you want a real array, you should use something like `Array.from(document.getElementsByTagName('a'))`, or these days you'd probably want `Array.from(document.querySelectorAll('a'))`. Maybe polyfill `Array.from()` if your browser does not support it yet. I can recommend <https://polyfill.io/v2/docs/> very much (not affiliated in any way)
Use `$$()` and pass in a CSS selector. Read the [Prototype API documentation for `$$()`](http://www.prototypejs.org/api/utility/dollar-dollar) This gives you more power beyond just tag names. You can select by class, parent/child relationships, etc. It supports more CSS selectors than the common browser can be expected to.
Prototype get by tag function
[ "", "javascript", "prototypejs", "" ]
What does the `volatile` keyword do? In C++ what problem does it solve? In my case, I have never knowingly needed it.
`volatile` is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to. I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this: ``` void waitForSemaphore() { volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/ while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED); } ``` Without `volatile`, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.
`volatile` is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the `volatile` keyword to ensure that such accesses aren't optimised away by the compiler.
Why does volatile exist?
[ "", "c++", "volatile", "c++-faq", "" ]
For example, if passed the following: ``` a = [] ``` How do I check to see if `a` is empty?
``` if not a: print("List is empty") ``` Using the [implicit booleanness](https://docs.python.org/library/stdtypes.html#truth-value-testing) of the empty `list` is quite Pythonic.
The Pythonic way to do it is from the [PEP 8 style guide](https://www.python.org/dev/peps/pep-0008). > For sequences, (strings, lists, tuples), use the fact that empty sequences are false: > > ``` > # Correct: > if not seq: > if seq: > > # Wrong: > if len(seq): > if not len(seq): > ```
How do I check if a list is empty?
[ "", "python", "list", "" ]
I need to extract data from a .mpp file on the network and combine it with other data from several different databases. The application can be written in Perl, VB6, VB.net or C# but must be easily scheduled from a Windows based server. What would you recommend to extract the MS Project data with no user intervention? Is there any ODBC drivers available for MS Project? Are there any modules (for Perl, VB, VB.net or C#) for opening a .mpp and reading activity data?
I would recommend using MPXJ ([mpxj.sf.net](http://mpxj.sf.net)) to extract data from Microsoft Project files. Don't be put off by the fact that it was originally a Java library - the current release of MPXJ includes native .net dlls as well as the original Java JAR file, thanks to the magic of IKVM. Disclaimer: I maintain MPXJ.
MPP does have its own object model that can be used to access data in it. The info should be available here: <http://msdn.microsoft.com/en-us/office/aa905469.aspx>
How would you extract data from a MS Project .mpp file?
[ "", "c#", "vb.net", "perl", "vb6", "project-management", "" ]
What is the fastest way of transferring few thousand rows of data from one DataTable to another? Would be great to see some sample code snippets. Edit: I need to explain a bit more. There is a filtering condition for copying the rows. So, a plain Copy() will not work.
You can't copy the whole table, you need to copy one rows. From <http://support.microsoft.com/kb/308909> (sample code if you follow the link) "How to Copy DataRows Between DataTables Before you use the ImportRow method, you must ensure that the target table has the identical structure as the source table. This sample uses the Clone method of DataTable class to copy the structure of the DataTable, including all DataTable schemas, relations, and constraints. This sample uses the Products table that is included with the Microsoft SQL Server Northwind database. The first five rows are copied from the Products table to another table that is created in memory."
What is wrong with [DataTable.Copy](http://msdn.microsoft.com/en-us/library/system.data.datatable.copy.aspx)?
Copying data from one DataTable to another
[ "", "c#", "ado.net", "" ]
User [kokos](https://stackoverflow.com/users/1065/kokos) answered the wonderful *[Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)* question by mentioning the `using` keyword. Can you elaborate on that? What are the uses of `using`?
The reason for the `using` statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens. As in *[Understanding the 'using' statement in C# (codeproject)](https://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C)* and *[Using objects that implement IDisposable (microsoft)](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects)*, the C# compiler converts ``` using (MyResource myRes = new MyResource()) { myRes.DoSomething(); } ``` to ``` { // Limits scope of myRes MyResource myRes= new MyResource(); try { myRes.DoSomething(); } finally { // Check for a null resource. if (myRes != null) // Call the object's Dispose method. ((IDisposable)myRes).Dispose(); } } ``` C# 8 introduces a new syntax, named "[using declarations](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations)": > A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope. So the equivalent code of above would be: ``` using var myRes = new MyResource(); myRes.DoSomething(); ``` And when control leaves the containing scope (usually a method, but it can also be a code block), `myRes` will be disposed.
Since a lot of people still do: ``` using (System.IO.StreamReader r = new System.IO.StreamReader("")) using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) { //code } ``` I guess a lot of people still don't know that you can do: ``` using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) { //code } ```
What are the uses of "using" in C#?
[ "", "c#", "using", "using-statement", "" ]
At work today, I came across the `volatile` keyword in Java. Not being very familiar with it, I found [this explanation](http://web.archive.org/web/20210221170926/https://www.ibm.com/developerworks/java/library/j-jtp06197/). Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?
`volatile` has semantics for memory visibility. Basically, the value of a `volatile` field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without `volatile`, readers could see some non-updated value. To answer your question: Yes, I use a `volatile` variable to control whether some code continues a loop. The loop tests the `volatile` value and continues if it is `true`. The condition can be set to `false` by calling a "stop" method. The loop sees `false` and terminates when it tests the value after the stop method completes execution. The book "[Java Concurrency in Practice](http://jcip.net)," which I highly recommend, gives a good explanation of `volatile`. This book is written by the same person who wrote the IBM article that is referenced in the question (in fact, he cites his book at the bottom of that article). My use of `volatile` is what his article calls the "pattern 1 status flag." If you want to learn more about how [`volatile`](http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3.1.4) works under the hood, read up on [the Java memory model](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html). If you want to go beyond that level, check out a good computer architecture book like [Hennessy & Patterson](https://www.elsevier.com/books/computer-architecture/hennessy/978-0-12-383872-8) and read about cache coherence and cache consistency.
*“… the volatile modifier guarantees that any thread that reads a field will see the most recently written value.”* **- Josh Bloch** If you are thinking about using `volatile`, read up on the package [`java.util.concurrent`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html) which deals with atomic behaviour. The Wikipedia post on a [Singleton Pattern](https://en.wikipedia.org/wiki/Singleton_pattern#Lazy_initialization) shows volatile in use.
What is the volatile keyword useful for?
[ "", "java", "multithreading", "keyword", "volatile", "" ]
I would like to serialize and deserialize objects without having to worry about the entire class graph. Flexibility is key. I would like to be able to serialize any object passed to me without complete attributes needed throughout the entire object graph. > That means that Binary Serialization > is not an option as it only works with > the other .NET Platforms. I would > also like something readable by a > person, and thus decipherable by a > management program and other > interpreters. I've found problems using the DataContract, JSON, and XML Serializers. * Most of these errors seem to center around Serialization of Lists/Dictionaries (i.e. [XML Serializable Generic Dictionary](http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx)). * "Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer." Please base your answers on actual experiences and not theory or reading of an article.
Have you considered serializing to JSON instead of XML? [Json.NET](http://james.newtonking.com/projects/json-net.aspx) has a really powerful and flexible serializer that has no problems with Hashtables/generic dictionaries and doesn't require any particular attributes. I know because I wrote it :) It gives you heaps of control through various options on the serializer and it allows you to override how a type is serialized by creating a JsonConverter for it. In my opinion JSON is more human readable than XML and Json.NET gives the option to write nicely formatted JSON. Finally the project is open source so you can step into the code and make modifications if you need to.
If I recall it works something like this with a property: ``` [XmlArray("Foo")] [XmlArrayItem("Bar")] public List<BarClass> FooBars { get; set; } ``` If you serialized this you'd get something like: ``` <Foo> <Bar /> <Bar /> </Foo> ``` Of course, I should probably defer to the experts. Here's more info from MS: <http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx> Let me know if that works out for you.
What is the most flexible serialization for .NET objects, yet simple to implement?
[ "", "c#", ".net", "serialization", "" ]
I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality: The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database. Although I am mainly interested in doing this in php, I also have some Java implementation ideas for this. I believe it could also help if the answer was as much language-agnostic as possible.
This is the LibraryThing founder. We have nothing to offer here, so I hope my comments will not seem self-serving. First, the comment about Amazon, ASINs and ISBN numbers is wrong in a number of ways. In almost every circumstance where a book has an ISBN, the ASIN and the ISBN are the same. ISBNs are not now 13 digits. Rather, ISBNs can be either 10 or 13. Ten-digit ISBNs can be expressed as 13-digit ones starting with 978, which means every ISBN currently in existence has both a 10- and a 13-digit form. There are all sorts of libraries available for converting between ISBN10 and ISBN13. Basically, you add 978 to the front and recalculate the checksum digit at the end. ISBN13 was invented because publishers were running out of ISBNs. In the near future, when 979-based ISBN13s start being used, they will not have an ISBN10 equivalent. To my knowledge, there are no published books with 979-based ISBNs, but they are coming soon. Anyway, the long and short of it is that Amazon uses the ISBN10 form for all 978 ISBN10s. In any case, whether or not Amazon uses ten or thirteen-digit ASINs, you can search Amazon by either just fine. Personally, I wouldn't put ISBN DB at the top of your list. ISBN DB mines from a number of sources, but it's not as comprehensive as Amazon or Google. Rather, I'd look into Amazon—including the various international Amazons—and then the new Google Book Data API and, after that, the OpenLibrary API. For non-English books, there are other options, like Ozone for Russian books. If you care about the highest-quality data, or if you have any books published before about 1970, you will want to look into data from libraries, available by Z39.50 protocol and usually in MARC format, or, with a few libraries in Dublin Core, using the SRU/SRW protocol. MARC format is, to a modern programmer, pretty strange stuff. But, once you get it, it's also better data and includes useful fields like the LCCN, DDC, LCC, and LCSH. LibraryThing runs off a homemade Python library that queries some 680 libraries and converts the many flavors of MARC into Amazon-compatible XML, with extras. We are currently reluctant to release the code, but maybe releasing a service soon.
Google has it's own [API for Google Books](https://developers.google.com/books/docs/v1/reference/) that let's you query the Google Book database easily. The protocol is JSON based and you can view the technical information about it [here](https://developers.google.com/books/docs/v1/using?hl=en#WorkingVolumes). You essentially just have to request the following URL : > <https://www.googleapis.com/books/v1/volumes?q=isbn:YOUR_ISBN_HERE> This will return you the information about the book in a JSON format.
How to fetch a Book Title from an ISBN number?
[ "", "php", "language-agnostic", "" ]
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var? For example I rather lazily used var in questionable circumstances, e.g.:- ``` foreach(var item in someList) { // ... } // Type of 'item' not clear. var something = someObject.SomeProperty; // Type of 'something' not clear. var something = someMethod(); // Type of 'something' not clear. ``` More legitimate uses of var are as follows:- ``` var l = new List<string>(); // Obvious what l will be. var s = new SomeClass(); // Obvious what s will be. ``` Interestingly LINQ seems to be a bit of a grey area, e.g.:- ``` var results = from r in dataContext.SomeTable select r; // Not *entirely clear* what results will be here. ``` It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is. It's even worse when it comes to LINQ to objects, e.g.:- ``` var results = from item in someList where item != 3 select item; ``` This is no better than the equivilent foreach(var item in someList) { // ... } equivilent. There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type. `var` *does* maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
I still think `var` can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this: ``` var orders = cust.Orders; ``` I don't care if Customer.Orders is `IEnumerable<Order>`, `ObservableCollection<Order>` or `BindingList<Order>` - all I want is to keep that list in memory to iterate over it or get its count or something later on. Contrast the above declaration with: ``` ObservableCollection<Order> orders = cust.Orders; ``` To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from `ObservableCollection<Order>` to `IList<Order>`) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
I use `var` extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim. Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically *not* interested in the type a variable has. `var` takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn't actually be interested in the type of the variable but rather in what a variable *does*. This is why Microsoft also calls type inference “duck typing.” So, what does a variable do when I declare it using `var`? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense. If I am using a `var` declared variable and get confused what the variable is there for, there's something fundamentally wrong with my code. `var` is not the cause, it only makes the symptoms visible. Don't blame the messenger. Now, the C# team has released a coding guideline stating that `var` should *only* be used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to `var`). Well, screw that. As long as the C# team doesn't give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it's pure baloney. (Sorry; I've got no link to the guideline in question.) Actually, there are some (superficially) [good explanations](http://www.devx.com/codemag/Article/37010/0/page/2) on why you shouldn't use `var` but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that `var` makes it hard to search for places where `MyType` is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere).
Use of var keyword in C#
[ "", "c#", "type-inference", "var", "" ]
I am using URLDownloadToFile to retrieve a file from a website. Subsequent calls return the original file rather than an updated version. I assume it is retrieving a cached version.
Call DeleteUrlCacheEntry with the same URL just prior to calling URLDownloadToFile. You will need to link against Wininet.lib
Yes, it is pulling a cached version of the file by default. To avoid the cache file completely, pass an IBindStatusCallback object in the lpfnCB parameter of URLDownloadToFile(). In your implemented IBindStatusCallback::GetBindInfo() method, include the BINDF\_GETNEWESTVERSION flag, and optionally also the BINDF\_NOWRITECACHE flag, in the value you return via the grfBINDF parameter. If you want the cache file, if present, to be updated instead of skippe, specify the BINDF\_RESYNCHRONIZE flag instead.
How can I prevent URLDownloadToFile from retrieving from the cache?
[ "", "c++", "winapi", "wininet", "" ]
Hello again ladies and gents! OK, following on from my other question on [ASP.NET Web Service Results, Proxy Classes and Type Conversion](https://stackoverflow.com/questions/6681/aspnet-web-service-results-proxy-classes-and-type-conversion). I've come to a part in my project where I need to get my thinking cap on. Basically, we have a large, complex custom object that needs to be returned from a Web Service and consumed in the client application. Now, based on the previous discussion, we know this is going to then take the form of the proxy class(es) as the return type. To overcome this, we need to basically copy the properties from one to the other. In this case, that is something that I would really, really, *really!* like to avoid! So, it got me thinking, **how else could we do this?** My current thoughts are to enable the object for complete serialization to XML and then return the XML as a string from the Web Service. We then de-serialize at the client. This will mean a fair bit of attribute decorating, but at least the code at both endpoints will be light, namely by just using the .NET XML Serializer. ## What are your thoughts on this?
The .Net XML (de)serialisation is pretty nicely implemented. At first thought, I don't think this is a bad idea at all. If the two applications import the same C# class(es) definition(s), then this is a relatively nice way of getting copy-constructor behaviour for free. If the class structure changes, then everything will work when both sides get the new class definition, without needing to make any additional changes on the web-service consumption/construction side. There's a slight overhead in marshalling and demarshalling the XML, but that is probably dwarved by the overhead of the remote web service call. .Net XML serialisation is well understood by most programmers and should produce an easy to maintain solution.
I'm loving `JSON` for this kind of thing. I just finished a POC drop-things type portal for my company using `jQuery` to contact web services with script service enabled. The messages are lightweight and parsing etc is pretty much handled. The `jQuery ajax` stuff I read was here (loving it!) : [jquery ajax article](http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/)
Large, Complex Objects as a Web Service Result
[ "", "c#", "asp.net", "xml", "web-services", "serialization", "" ]
I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid. Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.
The node label editing is performed with a text box and when that text box loses focus the change in name will be committed as the new label for the node. So if the 'Save' button you are clicking on takes the focus then it will cause the update automatically because the text box will lose focus. If the 'Save' button does not take focus then need to handle a click event for the 'Save' button and ask the tree to end any current label editing. If does not have a method/property you can call to request label editing finish so you have two choices. If the tree view has the focus then put the focus somewhere else. Alternatively turn off/on again label editing... ``` treeView.LabelEdit = false; treeView.LabelEdit = true; ```
I'll accept the answer even though it's not really documented: does it or does it not have such a method? You actually didn't answer to this, just passed the question back to me. Meanwhile found the same hack-ish solution with forcing the focus to some other control (not very elegant but works), even though it's a bit harder for me since I use a TreeView as part of a UserControl.
Hot to commit changes for a TreeView while editing a node (C#)?
[ "", "c#", "treeview", "commit", "editing", "" ]
I'm kind of interested in getting some feedback about this technique I picked up from somewhere. I use this when a function can either succeed or fail, but you'd like to get more information about why it failed. A standard way to do this same thing would be with exception handling, but I often find it a bit over the top for this sort of thing, plus PHP4 does not offer this. Basically the technique involves returning true for success, and *something* which *equates* to false for failure. Here's an example to show what I mean: ``` define ('DUPLICATE_USERNAME', false); define ('DATABASE_ERROR', 0); define ('INSUFFICIENT_DETAILS', 0.0); define ('OK', true); function createUser($username) { // create the user and return the appropriate constant from the above } ``` The beauty of this is that in your calling code, if you don't care WHY the user creation failed, you can write simple and readable code: ``` if (createUser('fred')) { // yay, it worked! } else { // aww, it didn't work. } ``` If you particularly want to check why it didn't work (for logging, display to the user, or do whatever), use identity comparison with === ``` $status = createUser('fred'); if ($status) { // yay, it worked! } else if ($status === DUPLICATE_USERNAME) { // tell the user about it and get them to try again. } else { // aww, it didn't work. log it and show a generic error message? whatever. } ``` The way I see it, the benefits of this are that it is a normal expectation that a successful execution of a function like that would return true, and failure return false. The downside is that you can only have `7 "error" return values: false, 0, 0.0, "0", null, "", and (object) null.` If you forget to use identity checking you could get your program flow all wrong. Someone else has told me that using constants like an `enum` where they all equate to false is `"ick"`. --- So, to restate the question: how acceptable is a practise like this? Would you recommend a different way to achieve the same thing?
I agree with the others who have stated that this is a little on the WTFy side. If it's clearly documented functionality, then it's less of an issue, but I think it'd be safer to take an alternate route of returning 0 for success and integers for error codes. If you don't like that idea or the idea of a global last error variable, consider redefining your function as: ``` function createUser($username, &$error) ``` Then you can use: ``` if (createUser('fred', $error)) { echo 'success'; } else { echo $error; } ``` Inside createUser, just populate $error with any error you encounter and it'll be accessible outside of the function scope due to the reference.
As long as it's documented and contracted, and not too WTFy, then there shouldn't be a problem. Then again, I would recommend using exceptions for something like this. It makes more sense. If you can use PHP5, then that would be the way to go. Otherwise you don't have much choice.
Multiple return values to indicate success/failure.
[ "", "php", "" ]
I have a Java program that loads thirdparty class files (classes I did not write) and executes them. These classes often use `java.util.Random`, which by default generates random starting seed values every time it gets instantiated. For reasons of reproducability, I want to give these classes the same starting seed every time, changing it only at my discretion. Here are some of the obvious solutions, and why they don't work: 1. Use a different Random class in the thirdparty classfiles. The problem here is I only load the class files, and cannot modify the source. 2. Use a custom classloader to load our own Random class instead of the JVM's version. This approach will not work because Java does not allow classloaders to override classes in the `java` package. 3. Swap out the rt.jar's `java.util.Random` implementation for our own, or putting files into trusted locations for the JVM. These approaches require the user of the application messing with the JVM install on their machine, and are no good. 4. Adding a custom `java.util.Random` class to the bootclasspath. While this would technically work, for this particular application, it is impractical because this application is intended for end users to run from an IDE. I want to make running the app convenient for users, which means forcing them to set their bootclasspath is a pain. I can't hide this in a script, because it's intended to be run from an IDE like Eclipse (for easy debugging.) So how can I do this?
Consider modifying the third party libraries to have them use a seen for their Random instances. Though you do not have the source code, you can probably edit the bytecode to do it. One helpful toolkit for doing such is [ASM](http://asm.objectweb.org/).
Your option 2 will actually work, with the following directions. You will need ( as anjab said ) to change the bootstrap class path . In the command line of the program you need to add the following: java -Xbootclasspath/p:C:\your\random\_impl.jar YourProgram Assuming you're on Windown machine or the path for that matter in any OS. That option adds the classes in jar files before the rt.jar are loaded. So your Random will be loaded before the rt.jar Random class does. The usage is displayed by typing : ``` java -X ``` It displays all the X(tra) features de JVM has. It may by not available on other VM implementations such as JRockit or other but it is there on Sun JVM. -Xbootclasspath/p: prepend in front of bootstrap class path I've use this approach in an application where the default ORB class should be replaced with others ORB implementation. ORB class is part of the Java Core and never had any problem. Good luck.
How can I give java.util.Random a specific seed in thirdparty classes?
[ "", "java", "random", "jvm", "classloader", "" ]
In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, `static int MYINT = 3;` causes the serialVersionUID to change. In this example, it makes sense because different versions of the class would get different initial values. Why does any initialization change the serialVersionUID? For example, `static String MYSTRING = System.getProperty("foo");` also causes the serialVersionUID to change. To be specific, my question is why does initialization with a method cause the serialVersionUID to change. The problem I hit is that I added a new static field that was initialized with a system property value (getProperty). That change caused a serialization exception on a remote call.
You can find some information about that in the [bug 4365406](https://bugs.java.com/bugdatabase/view_bug?bug_id=4365406) and in the [algorithm for computing **serialVersionUID**](http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/class.html#4100). Basically, when changing the initialization of your `static` member with `System.getProperty()`, the compiler introduces a new `static` property in your class referencing the `System` class (I assume that the `System` class was previously unreferenced in your class), and since this property introduced by the compiler is not private, it takes part in the `serialVersionUID` computation. **Morality**: always use explicit `serialVersionUID`, you'll save some CPU cycles and some headaches :)
Automatic serialVersionUID is calculated based on members of a class. These can be shown for a class file using the javap tool in the Sun JDK. In the case mentioned in the question, the member that is added/removed is the static initialiser. This appears as ()V in class files. The contents of the method can be disassembled using javap -c. You should be able to make out the System.getProperty("foo") call and assignment to MYSTRING. However an assignment with a string literal (or any compile-time constant as defined by the Java Language Specification) is supported directly by the class file, so removing the need for a static initialiser. A common case for code targeting J2SE 1.4 (use -source 1.4 -target 1.4) or earlier is static fields to old Class instances which appear as class literals in source code (MyClass.class). The Class instance is looked up on demand with Class.forName, and the stored in a static field. It is this static field that disrupts the serialVersionUID. From J2SE 5.0, a variant of the ldc opcode gives direct support for class literals, removing the need for the synthetic field. Again, all this can be shown with javap -c.
Java serialization with static initialization
[ "", "java", "serialization", "" ]
I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the string are the same, and the middle part that differs is an integer, then compare based on the numeric values of those integers. For example, I want the following strings to end up in order they're shown: * aaa * bbb 3 ccc * bbb 12 ccc * ccc 11 * ddd * eee 3 ddd jpeg2000 eee * eee 12 ddd jpeg2000 eee As you can see, there might be other integers in the string, so I can't just use regular expressions to break out any integer. I'm thinking of just walking the strings from the beginning until I find a bit that doesn't match, then walking in from the end until I find a bit that doesn't match, and then comparing the bit in the middle to the regular expression "[0-9]+", and if it compares, then doing a numeric comparison, otherwise doing a lexical comparison. Is there a better way? **Update** I don't think I can guarantee that the other numbers in the string, the ones that may match, don't have spaces around them, or that the ones that differ do have spaces.
[The Alphanum Algorithm](https://web.archive.org/web/20210803201519/http://www.davekoelle.com/alphanum.html) From the website "People sort strings with numbers differently than software. Most sorting algorithms compare ASCII values, which produces an ordering that is inconsistent with human logic. Here's how to fix it." Edit: Here's a link to the [Java Comparator Implementation](https://web.archive.org/web/20210506213829/http://www.davekoelle.com/files/AlphanumComparator.java) from that site.
Interesting little challenge, I enjoyed solving it. Here is my take at the problem: ``` String[] strs = { "eee 5 ddd jpeg2001 eee", "eee 123 ddd jpeg2000 eee", "ddd", "aaa 5 yy 6", "ccc 555", "bbb 3 ccc", "bbb 9 a", "", "eee 4 ddd jpeg2001 eee", "ccc 11", "bbb 12 ccc", "aaa 5 yy 22", "aaa", "eee 3 ddd jpeg2000 eee", "ccc 5", }; Pattern splitter = Pattern.compile("(\\d+|\\D+)"); public class InternalNumberComparator implements Comparator { public int compare(Object o1, Object o2) { // I deliberately use the Java 1.4 syntax, // all this can be improved with 1.5's generics String s1 = (String)o1, s2 = (String)o2; // We split each string as runs of number/non-number strings ArrayList sa1 = split(s1); ArrayList sa2 = split(s2); // Nothing or different structure if (sa1.size() == 0 || sa1.size() != sa2.size()) { // Just compare the original strings return s1.compareTo(s2); } int i = 0; String si1 = ""; String si2 = ""; // Compare beginning of string for (; i < sa1.size(); i++) { si1 = (String)sa1.get(i); si2 = (String)sa2.get(i); if (!si1.equals(si2)) break; // Until we find a difference } // No difference found? if (i == sa1.size()) return 0; // Same strings! // Try to convert the different run of characters to number int val1, val2; try { val1 = Integer.parseInt(si1); val2 = Integer.parseInt(si2); } catch (NumberFormatException e) { return s1.compareTo(s2); // Strings differ on a non-number } // Compare remainder of string for (i++; i < sa1.size(); i++) { si1 = (String)sa1.get(i); si2 = (String)sa2.get(i); if (!si1.equals(si2)) { return s1.compareTo(s2); // Strings differ } } // Here, the strings differ only on a number return val1 < val2 ? -1 : 1; } ArrayList split(String s) { ArrayList r = new ArrayList(); Matcher matcher = splitter.matcher(s); while (matcher.find()) { String m = matcher.group(1); r.add(m); } return r; } } Arrays.sort(strs, new InternalNumberComparator()); ``` This algorithm need much more testing, but it seems to behave rather nicely. [EDIT] I added some more comments to be clearer. I see there are much more answers than when I started to code this... But I hope I provided a good starting base and/or some ideas.
Sort on a string that may contain a number
[ "", "java", "algorithm", "string", "sorting", "comparison", "" ]
Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection. At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items?
I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that. ``` if (item is IEnumerable) { foreach (object o in (item as IEnumerable)) { } } else { // reflect over item } ```
I've tried to use a similar technique as Darren suggested, however just beware that not just collections implement IEnumerable. `string` for instance is also IEnumerable and will iterate over the characters. Here's a small function I'm using to determine if an object is a collection (which will be enumerable as well since ICollection is also IEnumerable). ``` public bool isCollection(object o) { return typeof(ICollection).IsAssignableFrom(o.GetType()) || typeof(ICollection<>).IsAssignableFrom(o.GetType()); } ```
Accessing a Collection Through Reflection
[ "", "c#", "reflection", "collections", "" ]
I came across [this article](http://www.ddj.com/cpp/184403758) written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code?
It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a `catch` block is simply not true in C++ because RAII is an established idiom. Resource handling in C++ *is* done by resource acquisition and garbage collection is done by implicit destructor calls. On the other hand, explicit `catch` blocks would bloat the code and introduce subtle errors because the code flow gets much more complex and resource handling has to be done explicitly. RAII (including `ScopeGuard`s) isn't an obscure technique in C++ but firmly established best-practice.
Yes. If there is one single piece of C++ code that I could recommend every C++ programmer spend 10 minutes learning, it is ScopeGuard (now part of the freely available [Loki library](http://loki-lib.sourceforge.net/)). I decided to try using a (slightly modified) version of ScopeGuard for a smallish Win32 GUI program I was working on. Win32 as you may know has many different types of resources that need to be closed in different ways (e.g. kernel handles are usually closed with `CloseHandle()`, GDI `BeginPaint()` needs to be paired with `EndPaint()`, etc.) I used ScopeGuard with all these resources, and also for allocating working buffers with `new` (e.g. for character set conversions to/from Unicode). **What amazed me was how much *shorter* the program was.** Basically, it's a win-win: your code gets shorter and more robust at the same time. Future code changes *can't leak anything*. They just can't. How cool is that?
Does ScopeGuard use really lead to better code?
[ "", "c++", "raii", "scopeguard", "" ]
I have an app that I've written in C#/WinForms ([my little app](http://www.thekbase.com "TheKBase")). To make it cross-platform, I'm thinking of redoing it in Adobe AIR. Are there any arguments in favor of WinForms as a cross-platform app? Is there a cross-platform future for Winforms (e.g., Mono, etc.)? Suggestions for cross-platform UI development? By cross-platform I mean, currently, Mac OSX, Windows and Linux. This question was [asked again and answered with better success](https://stackoverflow.com/questions/116468/winforms-for-mono-on-mac-linux-and-pc-redux).
> I'm thinking of redoing it in Adobe AIR Not having spent much time with AIR, my personal opinion is that it is best for bringing a webapp to the desktop and provide a shell to it or run your existing flash/flex project on the desktop. Btw, if you don't know ActionScript, I mean its details, quirks, etc, don't forget to factor in the time it will take googling for answers. > Are there any arguments in favor of WinForms as a cross-platform app? > Is there a cross-platform future for Winforms (e.g., Mono, etc.)? It's always hard to predict what will happen, but there is at least one project (Plastic SCM) I know of which uses Mono Winforms on Win, Mac and Linux, so it is certainly doable. However, they say they built most of their controls from the ground up (and claim they want to release them as open source, but not sure if or when), so you will need to put in some work to make things look "pretty". I played with Winforms on non-windows platforms and unfortunately, it isn't exactly "mature" (especially on Mac). So what you get out of the box may or may not be sufficient for your needs. If you decide a desktop app is not the best way to provide a cross-platform solution, you can always take your business logic written in C# and create either a full-blown webapp with ASP.NET or go with Silverlight, so many other options exist with C#.
As far as my experience in Flex/AIR/Flash actionscripting goes, Adobe AIR development environment and coding/debugging toolsets are far inferior to the Visual Studio and .NET SDK as of the moment. The UI toolsets are superior though. But as *you already have a working C# code*, porting it to ActionScript might requires a redesign due to ActionScript having a different way of thinking/programming, they use different primitive data types, for example, they use just a `Number` instead of `int float double` etc. and the debugging tools are quiet lacking compared to VS IMO. And I heard that [Mono's GtkSharp](http://www.mono-project.com/GtkSharp) is quiet a decent platform. But if you don't mind the coding/debugging tooling problems, then AIR is a great platform. I like how Adobe integrates the Flash experience into it e.g. you can start an installation of AIR application via a button click in a flash movieclip, that kind of integration.
Making a C#/Winform application cross-platform - should I use AIR, Mono, or something else?
[ "", "c#", "winforms", "cross-platform", "" ]
The Interface Segregation Principle (ISP) says that many client specific interfaces are better than one general purpose interface. Why is this important?
ISP states that: > Clients should not be forced to depend > on methods that they do not use. ISP relates to important characteristics - [cohesion](http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29) and [coupling](http://en.wikipedia.org/wiki/Coupling_%28computer_science%29). Ideally your components must be highly tailored. It improves code robustness and maintainability. Enforcing ISP gives you following bonuses: * High [cohesion](http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29) - better understandability, robustness * Low [coupling](http://en.wikipedia.org/wiki/Coupling_%28computer_science%29) - better maintainability, high resistance to changes If you want to learn more about software design principles, get a copy of [Agile Software Development, Principles, Patterns, and Practices](https://rads.stackoverflow.com/amzn/click/com/0135974445) book.
The interface segregation is the “I” on the SOLID principle, before digging too deep with the first, let’s explain what’s does the latter mean. SOLID can be considered a set of best practices and recommendations made by experts (meaning they have been proved before) in order to provide a reliable foundation in how we design applications. These practices strive to make easier to maintain, extend, adapt and scale our applications. **Why should I care about SOLID programming?** First of all, you have to realize you are not going to be forever where you are. If we use standards and well known architectures, we can be sure that our code will be easy to maintain by other developers that come after us, and I’m sure you wouldn’t want to deal with the task of fixing a code that didn’t applied any known methodology as it would be very hard to understand it. **The interface segregation principle.** Know that we know what the SOLID principles are we can get into more detail about the Interface Segregation principle, but what exactly does the interface segregation says? > “Clients should not be forced to implement unnecessary methods which > they will not use” This means that sometimes we tend to make interfaces with a lot of methods, which can be good to an extent, however this can easily abused, and we can end up with classes that implement empty or useless methods which of course adds extra code and burden to our apps. Imagine you are declaring a lot of methods in single interface, if you like visual aids a class that is implementing an interface but that is really needing a couple of methods of it would look like this: ![enter image description here](https://i.stack.imgur.com/V6p8i.png) In the other hand, if you properly apply the interface segregation and split your interface in smaller subsets you can me sure to implement those that are only needed: ![enter image description here](https://i.stack.imgur.com/M0eWu.png) See! Is way better! Enforcing this principle will allow you to have low coupling which aids to a better maintainability and high resistance to changes. So you can really leverage the usage of interfaces and implementing the methods when you really should. Now let’s review a less abstract example, say you declared an interface called Reportable ``` public interface Reportable { void printPDF(); void printWord(); void printExcel(); void printPPT(); void printHTML(); } ``` And you have a client that will only to export some data in Excel format, you can implement the interface, but would you only have to implement the excel method? The answer is no, you will have to code the implementation for all the methods even if you are not going to use them, this can cause a lot of junk code hence making the code hard to maintain.. **Remember keep it simple and don’t repeat yourself and you will find that you are already using this principle without knowing.**
What is the reasoning behind the Interface Segregation Principle?
[ "", "java", "oop", "solid-principles", "design-principles", "interface-segregation-principle", "" ]
I'm porting old VB6 code that uses the Winsock control to C#. I haven't done any socket programming and I wonder if anyone has a good reference/tutorial/howto that I can use to start getting up to speed. I'm appealing to the hive mind while I proceed with my generally unproductive googling. I'm using UDP, not TCP at this time.
The August 2005 MSDN Magazine had an article about System.Net.Sockets and WinSock: <http://msdn.microsoft.com/en-us/magazine/cc300760.aspx>
* I recommend the asynchronous model for most applications, especially if you want performance or applications that don't hang as soon there is a network problem. For this the MSDN articles on [Socket.BeginConnect](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.beginconnect.aspx) and [Socket.BeginReceive](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.beginreceive.aspx) are good places to start. * The following link is not .NET, but many of the recommendations still hold: <http://tangentsoft.net/wskfaq/articles/lame-list.html>
What is a good tutorial/howto on .net / c# socket programming
[ "", "c#", "sockets", "network-programming", "winsock", "" ]
Are there any good database schema comparison tools out there that support Sybase SQL Anywhere version 10? I've seen a litany of them for SQL Server, a few for MySQL and Oracle, but nothing that supports SQL Anywhere correctly. I tried using DB Solo, but it turned all my non-unique indexes into unique ones, and I didn't see any options to change that.
If you are willing to download SQL Anywhere Version 11, and Compare It!, check out the comparison technique shown here: <http://sqlanywhere.blogspot.com/2008/08/comparing-database-schemas.html> You don't have to upgrade your SQL Anywhere Version 10 database.
The new kid on the block is [Qwerybuilder](http://www.werysoft.com/Features.aspx). It supports SQL Server, Sybase ASE, Sybase SQL Anywhere and Oracle. I've used it successfully with SQL Anywhere to track schema changes.
Any good SQL Anywhere database schema comparison tools?
[ "", "sql", "comparison", "schema", "sqlanywhere", "" ]
For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client? Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I was on a PC, so I grabbed the windows version from here: <http://gnuwin32.sourceforge.net/packages/wget.htm>.
If you have a Linux system available to you use [wget](http://www.gnu.org/software/wget/): ``` wget -k -K -E -r -l 10 -p -N -F -nH http://website.com/ ``` Options * -k : convert links to relative * -K : keep an original versions of files without the conversions made by wget * -E : rename html files to .html (if they don’t already have an htm(l) extension) * -r : recursive… of course we want to make a recursive copy * -l 10 : the maximum level of recursion. if you have a really big website you may need to put a higher number, but 10 levels should be enough. * -p : download all necessary files for each page (css, js, images) * -N : Turn on time-stamping. * -F : When input is read from a file, force it to be treated as an HTML file. * -nH : By default, wget put files in a directory named after the site’s hostname. This will disabled creating of those hostname directories and put everything in the current directory. Source: [Jean-Pascal Houde's weblog](http://blog.jphoude.qc.ca/2007/10/16/creating-static-copy-of-a-dynamic-website/)
build your site, then use a mirroring tool like [wget](http://www.gnu.org/software/wget/) or [lwp-mirror](http://search.cpan.org/dist/libwww-perl/bin/lwp-mirror) to grab a static copy
How can I create a site in php and have it generate a static version?
[ "", "php", "html", "wget", "" ]
I have three unordered lists that have been created as Scriptaculous Sortables so that the user can drag items within the lists and also between them: ``` var lists = ["pageitems","rowitems","columnitems"]; Sortable.create("pageitems", { dropOnEmpty: true, containment: lists, constraint: false }); Sortable.create("rowitems", { dropOnEmpty: true, containment: lists, constraint: false }); Sortable.create("columnitems", { dropOnEmpty: true, containment: lists, constraint: false }); ``` How can I make it so that if the user drags all the items out of a list, they're able to put them back again? At the moment it won't allow items to be dragged onto an empty list.
Maybe the empty list has no height, and therefore no droppable area available. If that's the case, perhaps you just need to set a minimum height, or some padding on the block.
add dropOnEmpty:true to the options parameters.
Can't Drag Items Onto An Empty List Using Scriptaculous Sortables
[ "", "javascript", "drag-and-drop", "scriptaculous", "" ]
I need to enumerate though generic IList<> of objects. The contents of the list may change, as in being added or removed by other threads, and this will kill my enumeration with a "Collection was modified; enumeration operation may not execute." What is a good way of doing threadsafe foreach on a IList<>? prefferably without cloning the entire list. It is not possible to clone the actual objects referenced by the list.
Cloning the list is the easiest and best way, because it ensures your list won't change out from under you. If the list is simply too large to clone, consider putting a lock around it that must be taken before reading/writing to it.
There is no such operation. The best you can do is ``` lock(collection){ foreach (object o in collection){ ... } } ```
Threadsafe foreach enumeration of lists
[ "", "c#", "multithreading", "" ]
I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program?
Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding. I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather create an anonymous type and use that rather than declare a whole new type that will never be used or known outside of the scope of my method. For instance: ``` var query = from item in database.Items // ... select new { Id = item.Id, Name = item.Name }; return query.ToDictionary(item => item.Id, item => item.Name); ``` Nobody cares about `a, the anonymous type. It's there so you don't have to declare another class.
From LINQ in action (page 76 section 2.6.3): > ... anonymous types [are] a great tool for quick and simple temporary results. We don't need to declare classes to hold temporary results thanks to temporary types. basically they're useful to hold information in the local scope temporarily. Anything more requires the use of reflection and can become quite a problem. The example they give in the above-quoted book is in writing to console the id, name, and amount of memory taken up by each running process. They create an anonymous type, add it to a list (all one statement) and then use ObjectDumper to output it. Therefore the code no longer needs a separately declared class to hold the id, name and memory used but its all declared implicitly bringing the line count down to 4: ``` var pl = new List<Object>(); foreach(var p in Process.GetProcesses()) pl.Add(new {p.Id, p.ProcessName, Memory=p.WorkingSet64}); ObjectDumper.Write(pl); ```
How should anonymous types be used in C#?
[ "", "c#", "anonymous-types", "" ]
In C#, what is the difference (if any) between these two lines of code? ``` tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick); ``` and ``` tmrMain.Elapsed += tmrMain_Tick; ``` Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?
I did this ``` static void Hook1() { someEvent += new EventHandler( Program_someEvent ); } static void Hook2() { someEvent += Program_someEvent; } ``` And then ran ildasm over the code. The generated MSIL was exactly the same. So to answer your question, yes they are the same thing. The compiler is just inferring that you want `someEvent += new EventHandler( Program_someEvent );` -- You can see it creating the new `EventHandler` object in both cases in the MSIL
It used to be (.NET 1.x days) that the long form was the only way to do it. In both cases you are newing up a delegate to point to the Program\_someEvent method.
Difference between wiring events with and without "new"
[ "", "c#", "events", "syntax", "delegates", "" ]
What method do I call to get the name of a class?
``` In [1]: class Test: ...: pass ...: In [2]: Test.__name__ Out[2]: 'Test' ```
It's not a method, it's a field. The field is called `__name__`. `class.__name__` will give the name of the class as a string. `object.__class__.__name__` will give the name of the class of an object.
How do I get the string with name of a class?
[ "", "python", "" ]
Why does the use of temp tables with a SELECT statement improve the logical I/O count? Wouldn't it increase the amount of hits to a database instead of decreasing it. Is this because the 'problem' is broken down into sections? I'd like to know what's going on behind the scenes.
There's no general answer. It depends on how the temp table is being used. The temp table may reduce IO by caching rows created after a complex filter/join that are used multiple times later in the batch. This way, the DB can avoid hitting the base tables multiple times when only a subset of the records are needed. The temp table may increase IO by storing records that are never used later in the query, or by taking up a lot of space in the engine's cache that could have been better used by other data. Creating a temp table to use all of its contents once is slower than including the temp's query in the main query because the query optimizer can't see past the temp table and it forces a (probably) unnecessary [spool](http://msdn.microsoft.com/en-us/library/ms181032.aspx) of the data instead of allowing it to stream from the source tables.
I'm going to assume by temp tables you mean a sub-select in a WHERE clause. (This is referred to as a semijoin operation and you can usually see that in the text execution plan for your query.) When the query optimizer encounter a sub-select/temp table, it makes some assumptions about what to do with that data. Essentially, the optimizer will create an execution plan that performs a join on the sub-select's result set, reducing the number of rows that need to be read from the other tables. Since there are less rows, the query engine is able to read less pages from disk/memory and reduce the amount of I/O required.
Temp tables and SQL SELECT performance
[ "", "sql", "performance", "" ]
I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers. I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers.
In most browsers, this can be achieved using CSS: ``` *.unselectable { -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; /* Introduced in IE 10. See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/ */ -ms-user-select: none; user-select: none; } ``` For IE < 10 and Opera, you will need to use the `unselectable` attribute of the element you wish to be unselectable. You can set this using an attribute in HTML: ``` <div id="foo" unselectable="on" class="unselectable">...</div> ``` Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the `<div>`. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants: ``` function makeUnselectable(node) { if (node.nodeType == 1) { node.setAttribute("unselectable", "on"); } var child = node.firstChild; while (child) { makeUnselectable(child); child = child.nextSibling; } } makeUnselectable(document.getElementById("foo")); ```
``` <script type="text/javascript"> /*********************************************** * Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com) * This notice MUST stay intact for legal use * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code ***********************************************/ function disableSelection(target){ if (typeof target.onselectstart!="undefined") //IE route target.onselectstart=function(){return false} else if (typeof target.style.MozUserSelect!="undefined") //Firefox route target.style.MozUserSelect="none" else //All other route (ie: Opera) target.onmousedown=function(){return false} target.style.cursor = "default" } //Sample usages //disableSelection(document.body) //Disable text selection on entire body //disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv" </script> ``` **EDIT** Code apparently comes from <http://www.dynamicdrive.com>
Is there a way to make text unselectable on an HTML page?
[ "", "javascript", "html", "css", "cross-browser", "textselection", "" ]
I'm using the After Effects CS3 Javascript API to dynamically create and change text layers in a composition. Or at least I'm trying to because I can't seem to find the right property to change to alter the actual text of the TextLayer object.
Hmm, must read docs harder next time. ``` var theComposition = app.project.item(1); var theTextLayer = theComposition.layers[1]; theTextLayer.property("Source Text").setValue("This text is from code"); ```
I'm not an expert with After Effects, but I have messed around with it. I think [reading this](http://library.creativecow.net/articles/ebberts_dan/ae6_exp.php) might help you out.
Programmatically change the text of a TextLayer in After Effects
[ "", "javascript", "after-effects", "" ]
I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces. **Example**: ``` Project = Tully.Saps.Data Folder = DataAccess/Interfaces Namespace = Tully.Saps.Data.DataAccess.Interfaces Folder = DataAccess/MbNetRepositories Namespace = Tully.Saps.Data.DataAccess.MbNetRepositories ``` **Question**: Is it best to leave the namespace alone and add the using clause to the classes that access it or change the namespace to Tully.Saps.Data for everything in this project?
Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent with other projects, et cetera).
Leave it. It's one great example of how your IDE is dictating your coding style.
Namespaces in C#
[ "", "c#", "" ]
I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but **not** in the parent class. Essentially, I am trying to accomplish the following: ``` class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = classmethod(foo.meth1) ```
I'm also not entirely sure what the exact behaviour you want is, but assuming its that you want bar.meth1(42) to be equivalent to foo.meth1 being a classmethod of bar (with "self" being the class), then you can acheive this with: ``` def convert_to_classmethod(method): return classmethod(method.im_func) class bar(foo): meth1 = convert_to_classmethod(foo.meth1) ``` The problem with classmethod(foo.meth1) is that foo.meth1 has already been converted to a method, with a special meaning for the first parameter. You need to undo this and look at the underlying function object, reinterpreting what "self" means. I'd also caution that this is a pretty odd thing to do, and thus liable to cause confusion to anyone reading your code. You are probably better off thinking through a different solution to your problem.
What are you trying to accomplish? If I saw such a construct in live Python code, I would consider beating the original programmer.
Decorating a parent class method
[ "", "python", "oop", "inheritance", "" ]
Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown? See the example below: ``` try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows(); // if currently executing an exception, exit the program, // otherwise just let the exception thrown by the function // above propagate } ``` or is ignoring one of the exceptions the only thing you can do? In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.
Set a flag variable, then check for it in the finally clause, like so: ``` boolean exceptionThrown = true; try { mightThrowAnException(); exceptionThrown = false; } finally { if (exceptionThrown) { // Whatever you want to do } } ```
If you find yourself doing this, then you might have a problem with your design. The idea of a "finally" block is that you want something done regardless of how the method exits. Seems to me like you don't need a finally block at all, and should just use the try-catch blocks: ``` try { doSomethingDangerous(); // can throw exception onSuccess(); } catch (Exception ex) { onFailure(); } ```
Fail fast finally clause in Java
[ "", "java", "exception", "fault-tolerance", "" ]
I'm looking for a tool that will reverse engineer Java into a sequence diagram BUT also provides the ability to filter out calls to certain libraries. For example, the Netbeans IDE does a fantastic job of this but it includes all calls to String or Integer which clutter up the diagram to the point it is unusable. Any help is greatly appreciated!!!!!!!
I think [jtracert](http://code.google.com/p/jtracert/) is what you are looking for. It generates a sequence diagram from a running Java program. Also, because its output is a text description of the diagram (in the formats of several popular SD tools), you can use grep to filter for only the classes you are interested in.
Try [MaintainJ](http://maintainj.com). MaintainJ generates sequence diagrams at runtime for a use case. It provides [multiple ways to filter out unwanted calls](http://maintainj.com/userGuide.jsp?param=faq#filtergetset). Yes, filtering out unwanted calls is the most important feature needed in sequence diagram generating tools. Besides, MaintainJ provides a neat interface to explore the diagram and search for calls in one use case or across use cases. Check the [demo video](http://maintainj.com/userGuide.jsp?param=overviewDemo) to get a quick overview. I am the author of MaintainJ, by the way.
Sequence Diagram Reverse Engineering
[ "", "java", "uml", "reverse-engineering", "sequence-diagram", "" ]
The Visual Studio refactoring support for C# is quite good nowadays (though not half as good as some Java IDE's I've seen already) but I'm really missing C++ support. I have seen [Refactor!](http://www.devexpress.com/Products/Visual_Studio_Add-in/RefactorCPP/index.xml) and am currently trying it out, but maybe one of you guys know a better tool or plugin? --- I've been working with [Visual Assist X](http://www.wholetomato.com/) now for a week or two and got totally addicted. Thanks for the tip, I'll try to convince my boss to get me a license at work too. --- I've been bughunting for a few days since Visual Assist X kept messing up my Visual Studio after a few specific refactorings, It took me (and customer support) a week to hunt down but let's say for now that Visual Assist X is not a good combination with [ClipX](http://bluemars.org/clipx/).
Visual Assist X by Whole Tomato software is not free, but it's absolutely worth the money if you use Visual Studio for C++. <http://www.wholetomato.com/>
I have tried Refactor!, as its features seemed promising, as did its testing with a simple testing project, but it failed to work with our real project at all - a lots of CPU activity, sometimes even frozen VS IDE, Refactoring UI not appearing at all for most of the code. We are using Visual Assist X instead. While it does not offer than many refactorings and it seems to me somewhat more complicated to use, it works.
Good refactoring support for C++
[ "", "c++", "visual-studio", "refactoring", "" ]
Say I have several JavaScript includes in a page: ``` <script type="text/javascript" src="/js/script0.js"></script> <script type="text/javascript" src="/js/script1.js"></script> <script type="text/javascript" src="/js/script2.js"></script> <script type="text/javascript" src="/js/script3.js"></script> <script type="text/javascript" src="/js/script4.js"></script> ``` Is there a way i can tell if any of those weren't found (404) without having to manually check each one? I guess i'm looking for an online tool or something similar. Any ideas?
If you get the [Firebug](https://addons.mozilla.org/en-US/firefox/addon/1843 "Firebug") firefox plugin and enable the consoles it should tell you when there are errors retrieving resources in the console.
I don't use other browsers enough to know where to find a similar feature in them, but Safari has an *Activity* window that displays all of the included files for a given web page and which ones were unable to be retrieved.
Find Missing Javascript Includes in Website
[ "", "javascript", "include", "" ]
I am trying to do something I've done a million times and it's not working, can anyone tell me why? I have a table for people who sent in resumes, and it has their email address in it... I want to find out if any of these people have NOT signed up on the web site. The aspnet\_Membership table has all the people who ARE signed up on the web site. There are 9472 job seekers, with unique email addresses. This query produces 1793 results: ``` select j.email from jobseeker j join aspnet_Membership m on j.email = m.email ``` This suggests that there should be 7679 (9472-1793) emails of people who are not signed up on the web site. Since 1793 of them DID match, I would expect the rest of them DON'T match... but when I do the query for that, I get nothing! Why is this query giving me nothing??? ``` select j.email from jobseeker j where j.email not in (select email from aspnet_Membership) ``` I don't know how that could be not working - it basically says "show me all the emails which are IN the jobseeker table, but NOT IN the aspnet\_Membership table...
We had a very similar problem recently where the subquery was returning null values sometimes. Then, the in statement treats null in a weird way, I think always matching the value, so if you change your query to: ``` select j.email from jobseeker j where j.email not in (select email from aspnet_Membership where email is not null) ``` it may work....
You could have a lot of duplicates out there. I'm not seeing the query error off the top of my head, but you might try writing it this way: ``` SELECT j.email FROM jobseeker j LEFT JOIN aspnet_Membership m ON m.email = j.email WHERE m.email IS NULL ``` You might also throw a GROUP BY or DISTINCT in there to get rid of duplicates.
Finding missing emails in SQL Server
[ "", "sql", "join", "anti-join", "" ]
I have an exe with an `App.Config` file. Now I want to create a wrapper dll around the exe in order to consume some of the functionalities. The question is how can I access the app.config property in the exe from the wrapper dll? Maybe I should be a little bit more in my questions, I have the following app.config content with the exe: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="myKey" value="myValue"/> </appSettings> </configuration> ``` The question is how to how to get "myValue" out from the wrapper dll? --- thanks for your solution. Actually my initial concept was to avoid XML file reading method or LINQ or whatever. My preferred solution was to use the [configuration manager libraries and the like](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx). I'll appreciate any help that uses the classes that are normally associated with accessing app.config properties.
After some testing, I found a way to do this. 1. Add the App.Config file to the test project. Use "Add as a link" option. 2. Use `System.Configuration.ConfigurationManager.AppSettings["myKey"]` to access the value.
The [ConfigurationManager.OpenMappedExeConfiguration Method](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openmappedexeconfiguration(VS.80).aspx) will allow you to do this. Sample from the MSDN page: ``` static void GetMappedExeConfigurationSections() { // Get the machine.config file. ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); // You may want to map to your own exe.comfig file here. fileMap.ExeConfigFilename = @"C:\test\ConfigurationManager.exe.config"; System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); // Loop to get the sections. Display basic information. Console.WriteLine("Name, Allow Definition"); int i = 0; foreach (ConfigurationSection section in config.Sections) { Console.WriteLine( section.SectionInformation.Name + "\t" + section.SectionInformation.AllowExeDefinition); i += 1; } Console.WriteLine("[Total number of sections: {0}]", i); // Display machine.config path. Console.WriteLine("[File path: {0}]", config.FilePath); } ``` --- EDIT: This should output the "myKey" value: ``` ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = @"C:\test\ConfigurationManager.exe.config"; System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); Console.WriteLine(config.AppSettings.Settings["MyKey"].Value); ```
Get the App.Config of another Exe
[ "", "c#", ".net", "configuration-files", "appsettings", "system.configuration", "" ]
I have an Eclipse RCP app running on Java 6. When I try to run the product configuration from within Eclipse, it silently terminates almost immediately. No error is reported in the console. I've tried setting breakpoints in the IApplication and in the Activator, and neither are reached. I know I don't have much specific information here, but can anyone give me any pointers on where I might start looking to diagnose the problem?
Have you checked the logs in runtime/.metadata folder?, Also make sure to validate all plugins in the runtime. Having them as a dependency doesn't necessarily mean they are added to the runtime. This is probably the biggest gotcha when launching an rcp app.
I wasn't able to locate the runtime/.metadata folder, but [this very helpful post](http://www.eclipsezone.com/eclipse/forums/t99010.rhtml) directed me to add -consoleLog and -noExit to my runtime arguments, which dumped the errors to the console. Configuration problems.
Eclipse RCP app fails to start
[ "", "java", "eclipse", "rcp", "" ]
I have an application that sends the customer to another site to handle the payments. The other site, outside of the customer, calls a page on our server to let us know what the status is of the payment. The called page checks the parameters that are given by the payment application and checks to see whether the transaction is known to us. It then updates the database to reflect the status. This is all done without any interaction with the customer. I have personally chosen to implement this functionality as a JSP since it is easier to just drop a file in the file system than to compile and package the file and then to add an entry into a configuration file. Considering the functionality of the page I would presume that a servlet would be the preferred option. The question(s) are:- Is my presumption correct? - Is there a real reason to use a servlet over a JSP? - What are those reasons?
A JSP is compiled to a servlet the first time it is run. That means that there's no real runtime difference between them. However, most have a tradition to use servlets for controllers and JSPs for views. Since controllers are just java classes you can get full tool support (code completion etc.) from all IDEs. That gives better quality and faster development times compared to JSPs. Some more advanced IDE's (IntelliJ IDEA springs to mind) have great JSP support, rendering that argument obsolete. If you're making your own framework or just making it with simple JSPs, then you should feel free to continue to use JSPs. There's no performance difference and if you feel JSPs are easier to write, then by all means continue.
JSPs: To present data to the user. No business logic should be here, and certainly no database access. Servlets: To handle input from a form or specific URL. Usually people will use a library like Struts/Spring on top of Servlets to clear up the programming. Regardless the servlet should just validate the data that has come in, and then pass it onto a backend business layer implementation (which you can code test cases against). It should then put the resulting values on the request or session, and call a JSP to display them. Model: A data model that holds your structured data that the website handles. The servlet may take the arguments, put them into the model and then call the business layer. The model can then interface with back-end DAOs (or Hibernate) to access the database. Any non-trivial project should implement a MVC structure. It is, of course, overkill for trivial functionality. In your case I would implement a servlet that called a DAO to update the status, etc, or whatever is required.
When do you use a JSP and when a Servlet?
[ "", "java", "jsp", "servlets", "" ]
I am looking for some JavaScript plugin (preferably jQuery) to be able to scroll through an image, in the same way that [Google Maps](http://maps.google.com) works. I can make the image draggable but then I see the whole image while dragging even if the parent div is `overflow:hidden`. Any help would be greatly appreciated!
I may be a little late to the party, but I was just looking for the same thing. What I stumbled upon is [scrollview](http://code.google.com/p/jquery-scrollview/) for jquery, it works perfect and does exactly this google maps-like drag-to-scroll for overflowed divs.
(I'm super late to this now dead party, but hey, I found this page via a search so...) Scrollview plugin suggested by mooware didn't work for me. However **Dragscrollable** did: <http://plugins.jquery.com/project/Dragscrollable> [Try out the demonstration](http://hitconsultants.com/dragscroll_scrollsync/scrollpane.html)
Google Maps style scrolling anyone?
[ "", "javascript", "jquery", "ajax", "" ]
Let's say I have the following HTML: ``` <table id="foo"> <th class="sortasc">Header</th> </table> <table id="bar"> <th class="sortasc">Header</th> </table> ``` I know that I can do the following to get all of the **th** elements that have class="sortasc" ``` $$('th.sortasc').each() ``` However that gives me the **th** elements from both table *foo* and table *bar*. How can I tell it to give me just the th elements from table *foo*?
table#foo th.sortasc
This is how you'd do it with straight-up JS: ``` var table = document.getElementById('tableId'); var headers = table.getElementsByTagName('th'); var headersIWant = []; for (var i = 0; i < headers.length; i++) { if ((' ' + headers[i].className + ' ').indexOf(' sortasc ') >= 0) { headersIWant.push(headers[i]); } } return headersIWant; ```
How do I select all <th> elements of class "sortasc" within a table with a specific id?
[ "", "javascript", "prototypejs", "" ]
I decided to try <http://www.screwturn.eu/> wiki as a code snippet storage utility. So far I am very impressed, but what irkes me is that when I copy paste my code that I want to save, '<'s and '[' (<http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Character_references>) invariably screw up the output as the wiki interprets them as either wiki or HTML tags. Does anyone know a way around this? Or failing that, know of a simple utility that would take C++ code and convert it to HTML safe code?
Surround your code in <nowiki> .. </nowiki> tags.
You can use the **@@...@@** tag to escape the code and automatically wrap it in **PRE** tags.
Converting C++ code to HTML safe
[ "", "c++", "wiki", "" ]
I don't want to take the time to learn Obj-C. I've spent 7+ years doing web application programming. Shouldn't there be a way to use the WebView and just write the whole app in javascript, pulling the files right from the resources of the project?
I found the answer after searching around. Here's what I have done: 1. Create a new project in XCode. I think I used the view-based app. 2. Drag a WebView object onto your interface and resize. 3. Inside of your WebViewController.m (or similarly named file, depending on the name of your view), in the viewDidLoad method: ``` NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; NSData *htmlData = [NSData dataWithContentsOfFile:filePath]; if (htmlData) { NSBundle *bundle = [NSBundle mainBundle]; NSString *path = [bundle bundlePath]; NSString *fullPath = [NSBundle pathForResource:@"index" ofType:@"html" inDirectory:path]; [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fullPath]]]; } ``` 4. Now any files you have added as resources to the project are available for use in your web app. I've got an index.html file including javascript and css and image files with no problems. The only limitation I've found so far is that I can't create new folders so all the files clutter up the resources folder. 5. Trick: make sure you've added the file as a resource in XCode or the file won't be available. I've been adding an empty file in XCode, then dragging my file on top in the finder. That's been working for me. Note: I realize that Obj-C must not be that hard to learn. But since I already have this app existing in JS and I know it works in Safari this is a much faster dev cycle for me. Some day I'm sure I'll have to break down and learn Obj-C. A few other resources I found helpful: Calling Obj-C from javascript: [calling objective-c from javascript](http://tetontech.wordpress.com/2008/08/14/calling-objective-c-from-javascript-in-an-iphone-uiwebview/) Calling javascript from Obj-C: [iphone app development for web hackers](http://dominiek.com/articles/2008/7/19/iphone-app-development-for-web-hackers) Reading files from application bundle: [uiwebview](http://iphoneincubator.com/blog/tag/uiwebview)
Check out PhoneGap at <http://www.phonegap.com> they claim it allows you to embed JavaScript, HTML and CSS into a native iPhone app.
How can I write an iPhone app entirely in JavaScript without making it just a web app?
[ "", "javascript", "ios", "objective-c", "" ]
I am working with a large Java web application from a commercial vendor. I've received a patch from the vendor in the form of a new .class file that is supposed to resolve an issue we're having with the software. In the past, applying patches from this vendor have caused new and completely unrelated problems to arise, so I want to understand the change being made even before applying it to a test instance. I've got the two .class files side by side, the one extracted from the currently running version and the updated one from the vendor. [JAD](http://www.kpdus.com/jad.html) and [JReversePro](http://jreversepro.blogspot.com/) both decompile and disassemble (respectively) the two versions to the same output. However, the .class files are different sizes and I see differences in the output of `od -x`, so they're definitely not identical. What other steps could I take to determine the difference between the two files? --- Conclusion: Thanks for the great responses. Since `javap -c` output is also identical for the two class files, I am going to conclude that Davr's right and the vendor sent me a placebo. While I'm accepting Davr's answer for that reason, it was Chris Marshall and John Meagher who turned me on to javap, so thanks to all three of you.
It's possible that they just compiled it with a new version of the java compiler, or with different optimization settings etc, so that the functionality is the same, and the code is the same, but the output bytecode is slightly different.
If you are looking for API level differences the [javap](http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javap.html) tool can be a big help. It will output the method signatures and those can be output to a plain text files and compared using normal diff tools.
Finding differences between versions of a Java class file
[ "", "java", "decompiling", "" ]
Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003)
The following query replace each and every `a` character with a `b` character. ``` UPDATE YourTable SET Column1 = REPLACE(Column1,'a','b') WHERE Column1 LIKE '%a%' ``` This will not work on SQL server 2003.
like so: ``` BEGIN TRANSACTION; UPDATE table_name SET column_name=REPLACE(column_name,'text_to_find','replace_with_this'); COMMIT TRANSACTION; ``` Example: Replaces <script... with <a ... to eliminate javascript vulnerabilities ``` BEGIN TRANSACTION; UPDATE testdb SET title=REPLACE(title,'script','a'); COMMIT TRANSACTION; ```
How do I do a simple 'Find and Replace" in MsSQL?
[ "", "sql", "sql-server", "" ]
Anybody know of a way to copy a file from path A to path B and suppressing the Windows file system cache? Typical use is copying a large file from a USB drive, or server to your local machine. Windows seems to swap everything out if the file is really big, e.g. 2GiB. Prefer example in C#, but I'm guessing this would be a Win32 call of some sort if possible.
Even more important, there are FILE\_FLAG\_WRITE\_THROUGH and FILE\_FLAG\_NO\_BUFFERING. MSDN has a nice article on them both: <http://support.microsoft.com/kb/99794>
In C# I have found something like this to work, this can be changed to copy directly to destination file: ``` public static byte[] ReadAllBytesUnbuffered(string filePath) { const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000; var fileInfo = new FileInfo(filePath); long fileLength = fileInfo.Length; int bufferSize = (int)Math.Min(fileLength, int.MaxValue / 2); bufferSize += ((bufferSize + 1023) & ~1023) - bufferSize; using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, bufferSize, FileFlagNoBuffering | FileOptions.SequentialScan)) { long length = stream.Length; if (length > 0x7fffffffL) { throw new IOException("File too long over 2GB"); } int offset = 0; int count = (int)length; var buffer = new byte[count]; while (count > 0) { int bytesRead = stream.Read(buffer, offset, count); if (bytesRead == 0) { throw new EndOfStreamException("Read beyond end of file EOF"); } offset += bytesRead; count -= bytesRead; } return buffer; } } ```
Copy a file without using the windows file cache
[ "", "c#", "windows", "winapi", "filesystems", "file-copying", "" ]
I'd like know what people think about using RAISERROR in stored procedures to pass back user messages (i.e. business related messages, not error messages) to the application. Some of the senior developers in my firm have been using this method and catching the SqlException in our C# code to pick up the messages and display them to the user. I am not happy with this method and would like to know how other people deal with these types of user messages from stored procs.
I've done this, but it was usually to pass along business "error" messages, essentially a data configuration had to be in place that couldn't be enforced with standard FK constraints for whatever reason. If they are actually "errors", I don't have much of a problem with it. If it's inserting a record and using RAISERROR to throw ("You have successfully registered for XYZ!"), then you've got a problem. If that was the case, I'd probably come up with a team/department/company development standard for using out parameters.
Using RAISERROR like this is really not a good idea. It's just like using Exceptions as flow control logic, which is generally frowned upon. Why not use an OUT parameter instead? That's exactly what they are for. I can't think of a database or a client API that doesn't support OUT parameters.
Stored Procs - Best way to pass messages back to user application
[ "", "sql", "sql-server", "t-sql", "raiserror", "" ]
How can you determine the performance consequences of your PHP code if you are not familiar with the internals? Are there ways to figure out how your code is being executed (besides simply load testing it)? I am looking for things like memory usage, the execution time for algorithms. Perhaps Joel would say, "learn C, then read the internals", but I really don't have time to learn C right now (though I'd love to, actually).
Use the [Xdebug](http://www.xdebug.org/) extension to profile PHP code.
If you're not familiar with valgrind or similar, then to add to @Jordi Bunster's answer... When you've had profiling on in Xdebug, you can open the dumped profile files in KCacheGrind or WinCacheGrind to get a graphical view of what is taking the time in your code. Fortunately the xdebug documentation also explains this in detail as well as how to interpret the results: <http://xdebug.org/docs/profiler>
Determining the performance consequences of PHP code
[ "", "php", "performance", "" ]
There doesn't seem to be a dictionary.AddRange() method. Does anyone know a better way to copy the items to another dictionary without using a foreach loop. I'm using the System.Collections.Generic.Dictionary. This is for .NET 2.0.
There's nothing wrong with a for/foreach loop. That's all a hypothetical AddRange method would do anyway. The only extra concern I'd have is with memory allocation behaviour, because adding a large number of entries could cause multiple reallocations and re-hashes. There's no way to increase the capacity of an existing Dictionary by a given amount. You might be better off allocating a new Dictionary with sufficient capacity for both current ones, but you'd still need a loop to load at least one of them.
There's the `Dictionary` constructor that takes another `Dictionary`. You'll have to cast it `IDictionary`, but there is an `Add()` overload that takes `KeyValuePair<TKey, TValue>`. You're still using foreach, though.
What's the fastest way to copy the values and keys from one dictionary into another in C#?
[ "", "c#", "dictionary", "copy", "foreach", "" ]
Are there any good recommendations anyone can provide for a good Javascript editor on Windows? I currently use combinations of FireBug and TextPad but would hate to miss out on the party if there are better options out there. Thanks.
In case you're a .Net programmer: VS 2008 has pretty great JS support including [intellisense](http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx) on dynamically added methods/properties and comfortable [debugging](http://weblogs.asp.net/scottgu/archive/2007/07/19/vs-2008-javascript-debugging.aspx).
I know [jsight](https://stackoverflow.com/questions/26897/recommendations-for-javascript-editor-on-windows#26905) already mentioned this, but [**Aptana Studio**](http://aptana.com/) really is a great, free editor for JavaScript if you find yourself doing a lot of work with it - it has great support for most of the well-known libraries. If it were not for the fact that I work with C# in addition to JavaScript, I would use Aptana for all of my work.
Recommendations for Javascript Editor on Windows?
[ "", "javascript", "editor", "" ]
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation? Or will I have to make my own custom shortcuts to setup the context properly?
In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own [context processor](http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors). From the docs: > A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.
There is **no need** to write a context processor for the user object if you already have the [`"django.core.context_processors.auth"`](https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates) in [`TEMPLATE_CONTEXT_PROCESSORS`](https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATE_CONTEXT_PROCESSORS) **and** if you're using [`RequestContext`](https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext) in your views. if you are using django 1.4 or latest the module has been moved to `django.contrib.auth.context_processors.auth`
Always including the user in the django template context
[ "", "python", "django", "authentication", "session", "cookies", "" ]
I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, *not* a source code file -- but embed that file in the executable file like a resource. (This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if it were for Windows.) Is there any simple way to do it, or will it effectively require me to write my own resource system for Linux? (Easily possible, but it would take a lot longer.)
You can use objcopy to bind the contents of the file to a symbol your program can use. See, for instance, [here](http://www.linuxjournal.com/content/embedding-file-executable-aka-hello-world-version-5967) for more information.
Use macros. Technically that file would be *source code* file but it wouldn't look like this. Example: ``` //queries.incl - SQL queries Q(SELECT * FROM Users) Q(INSERT [a] INTO Accounts) //source.cpp #define Q(query) #query, char * queries[] = { #include "queries.incl" }; #undef Q ``` Later on you could do all sorts of other processing on that file by the same file, say you'd want to have array and a hash map of them, you could redefine Q to do another job and be done with it.
Embed data in a C++ program
[ "", "c++", "linux", "sqlite", "" ]
It's known that you should declare events that take as parameters `(object sender, EventArgs args)`. Why?
This allows the consuming developer the ability to write a single event handler for multiple events, regardless of sender or event. **Edit:** Why would you need a different pattern? You can inherit EventArgs to provide any amount of data, and changing the pattern is only going to serve to confuse and frustrate any developer that is forced to consume this new pattern.
Actually this is debatable whether or not this is the best practice way to do events. There is the school of thought that as events are intended to decouple two segments of code, the fact that the event handler gets the sender, and has to know what type to cast the sender into in order to do anything with it is an anti-pattern.
Why should events in C# take (sender, EventArgs)?
[ "", "c#", ".net", "events", "" ]
Is there a framework that can be used to enable a C# Windows Service to automatically check for a newer version and upgrade itself? I can certainly write code to accomplish this, but I am looking for a framework that has already been implemented and (most importantly) tested. [edit] Here is a link to a similar question with links to modern projects that help accomplish this: [Auto-update library for .NET?](https://stackoverflow.com/questions/691663/auto-update-library-for-net)
The only way to unload types is to destroy the appdomain. To do this would require separation of your hosting layer from your executing service code - this is pretty complex. (sort of like doing keyhole surgery) May be easier to either a) run a batch task or b) in-service detect updates then launch a seperate process that stops the service, updates assemblies etc. then restarts it. If you're interested in the former, the MSDN patterns and practices folk wrote an app updater block that you adapt to your service. <https://web.archive.org/web/20080506103749/http://msdn.microsoft.com/en-us/library/ms978574.aspx>
I've had good experiences with [Google Omaha](https://github.com/google/omaha) for updating Windows Services. It can generally be used to update any Windows application but there is a [tutorial](https://omaha-consulting.com/update-windows-service) for using it to update a Windows Service. In comparison to other update frameworks, Omaha is more complex, but also the most powerful. This is because Google (and now also Microsoft) use it to update their browsers on billions of PCs. However, once it's set up and you understand the basics, it is a very nice experience.
I want my C# Windows Service to automatically update itself
[ "", "c#", "windows-services", "upgrade", "" ]
A common task in programs I've been working on lately is modifying a text file in some way. (Hey, I'm on Linux. Everything's a file. And I do large-scale system admin.) But the file the code modifies may not exist on my desktop box. And I probably don't want to modify it if it IS on my desktop. I've read about unit testing in Dive Into Python, and it's pretty clear what I want to do when testing an app that converts decimal to Roman Numerals (the example in DintoP). The testing is nicely self-contained. You don't need to verify that the program PRINTS the right thing, you just need to verify that the functions are returning the right output to a given input. In my case, however, we need to test that the program is modifying its environment correctly. Here's what I've come up with: 1) Create the "original" file in a standard location, perhaps /tmp. 2) Run the function that modifies the file, passing it the path to the file in /tmp. 3) Verify that the file in /tmp was changed correctly; pass/fail unit test accordingly. This seems kludgy to me. (Gets even kludgier if you want to verify that backup copies of the file are created properly, etc.) Has anyone come up with a better way?
You're talking about testing too much at once. If you start trying to attack a testing problem by saying "Let's verify that it modifies its environment correctly", you're doomed to failure. Environments have dozens, maybe even millions of potential variations. Instead, look at the pieces ("units") of your program. For example, are you going to have a function that determines where the files are that have to be written? What are the inputs to that function? Perhaps an environment variable, perhaps some values read from a config file? Test that function, and don't actually do anything that modifies the filesystem. Don't pass it "realistic" values, pass it values that are easy to verify against. Make a temporary directory, populate it with files in your test's `setUp` method. Then test the code that writes the files. Just make sure it's writing the right contents file contents. Don't even write to a real filesystem! You don't need to make "fake" file objects for this, just use Python's handy `StringIO` modules; they're "real" implementations of the "file" interface, they're just not the ones that your program is actually going to be writing to. Ultimately you will have to test the final, everything-is-actually-hooked-up-for-real top-level function that passes the real environment variable and the real config file and puts everything together. But don't worry about that to get started. For one thing, you will start picking up tricks as you write individual tests for smaller functions and creating test mocks, fakes, and stubs will become second nature to you. For another: even if you can't quite figure out how to test that one function call, you will have a very high level of confidence that everything which it is calling works perfectly. Also, you'll notice that test-driven development forces you to make your APIs clearer and more flexible. For example: it's much easier to test something that calls an `open()` method on an object that came from somewhere abstract, than to test something that calls `os.open` on a string that you pass it. The `open` method is flexible; it can be faked, it can be implemented differently, but a string is a string and `os.open` doesn't give you any leeway to catch what methods are called on it. You can also build testing tools to make repetitive tasks easy. For example, twisted provides facilities for creating temporary files for testing [built right into its testing tool](http://twistedmatrix.com/documents/8.1.0/api/twisted.trial.unittest.TestCase.html#mktemp). It's not uncommon for testing tools or larger projects with their own test libraries to have functionality like this.
You have two levels of testing. 1. Filtering and Modifying content. These are "low-level" operations that don't really require physical file I/O. These are the tests, decision-making, alternatives, etc. The "Logic" of the application. 2. File system operations. Create, copy, rename, delete, backup. Sorry, but those are proper file system operations that -- well -- require a proper file system for testing. For this kind of testing, we often use a "Mock" object. You can design a "FileSystemOperations" class that embodies the various file system operations. You test this to be sure it does basic read, write, copy, rename, etc. There's no real logic in this. Just methods that invoke file system operations. You can then create a MockFileSystem which dummies out the various operations. You can use this Mock object to test your other classes. In some cases, all of your file system operations are in the os module. If that's the case, you can create a MockOS module with mock version of the operations you actually use. Put your MockOS module on the `PYTHONPATH` and you can conceal the real OS module. For production operations you use your well-tested "Logic" classes plus your FileSystemOperations class (or the real OS module.)
Unit Testing File Modifications
[ "", "python", "linux", "unit-testing", "" ]
It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam. The web is littered with similar, yet still slightly different implementations of this type of solution. Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)? Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution?
As toolkit mentions above, Apache Commons IO is the way to go, specifically [FileUtils](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html).[copyFile()](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#copyFile(java.io.File,%20java.io.File)); it handles all the heavy lifting for you. And as a postscript, note that recent versions of FileUtils (such as the 2.0.1 release) have added the use of NIO for copying files; [NIO can significantly increase file-copying performance](http://www.javalobby.org/java/forums/t17036.html), in a large part because the NIO routines defer copying directly to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer. So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils.
I would avoid the use of a mega api like apache commons. This is a simplistic operation and its built into the JDK in the new NIO package. It was kind of already linked to in a previous answer, but the key method in the NIO api are the new functions "transferTo" and "transferFrom". <http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html#transferTo(long,%20long,%20java.nio.channels.WritableByteChannel)> One of the linked articles shows a great way on how to integrate this function into your code, using the transferFrom: ``` public static void copyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if(source != null) { source.close(); } if(destination != null) { destination.close(); } } } ``` Learning NIO can be a little tricky, so you might want to just trust in this mechanic before going off and trying to learn NIO overnight. From personal experience it can be a very hard thing to learn if you don't have the experience and were introduced to IO via the java.io streams.
Standard concise way to copy a file in Java?
[ "", "java", "file", "copy", "" ]
I'm converting an application to use Java 1.5 and have found the following method: ``` /** * Compare two Comparables, treat nulls as -infinity. * @param o1 * @param o2 * @return -1 if o1&lt;o2, 0 if o1==o2, 1 if o1&gt;o2 */ protected static int nullCompare(Comparable o1, Comparable o2) { if (o1 == null) { if (o2 == null) { return 0; } else { return -1; } } else if (o2 == null) { return 1; } else { return o1.compareTo(o2); } } ``` Ideally I would like to make the method take two Comparables of the same type, is it possible to convert this and how? I thought the following would do the trick: ``` protected static <T extends Comparable> int nullCompare(T o1, T o2) { ``` but it has failed to get rid of a warning in IntelliJ "Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'" on the line: ``` return o1.compareTo(o2); ```
Change it to: ``` protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) { ``` You need that because Comparable is itself a generic type.
Here's an odd case: ``` static class A { ... } static class B extends A implements Comparable<A> { public int compareTo(A o) { return ...; } } ``` Luckily code like the one above is rare, but nullCompare() will not support comparison of Bs unless it is stated that Comparable may apply to T *or any superclass thereof*: ``` protected static <T extends Comparable<? super T>> int nullCompare(T o1, T o2) { ``` Even though most people will never benefit from the above tweak, it may come in handy when designing APIs for exported libraries.
Can I convert the following code to use generics?
[ "", "java", "generics", "comparison", "" ]
Can anybody recommend a reliable and decently documented code highlighter for WordPress 2.6.1? I have tried Code Snippet by Roman Roan and Developer Formatter by Gilberto Saraiva. But they don't seem to work as described in the documentation and are mangling the code snippets instead of prettifying them.
I use [WP-Syntax](http://wordpress.org/extend/plugins/wp-syntax/) and it's worked very well for me. It's supported every language I've thrown at it so far, and the colors can be customized for a particular theme (though the defaults look just fine too)
You should also checkout [syntaxhighlighter](http://code.google.com/p/syntaxhighlighter/) from Google Code.
Seeking code highlighter recommendation for WordPress
[ "", "php", "wordpress", "codehighlighter", "geshi", "" ]
Say I have a `Textbox` nested within a `TabControl`. When the form loads, I would like to focus on that `Textbox` (by default the focus is set to the `TabControl`). Simply calling `textbox1.focus()` in the `Load` event of the form does not appear to work. I have been able to focus it by doing the following: ``` private void frmMainLoad(object sender, EventArgs e) { foreach (TabPage tab in this.tabControl1.TabPages) { this.tabControl1.SelectedTab = tab; } } ``` **My question is:** Is there a more elegant way to do this?
The following is the solution: ``` private void frmMainLoad(object sender, EventArgs e) { ActiveControl = textBox1; } ``` The better question would however be why... I'm not entirely sure what the answer to that one is. Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure.
Try putting it in the `Form_Shown()` event. Because it's in a container, putting in the Form\_Load or even the Form() constructor won't work.
Winforms c# - Set focus to first child control of TabPage
[ "", "c#", ".net", "winforms", "focus", "" ]
Is there a way? I need all types that implement a specific interface to have a parameterless constructor, can it be done? I am developing the base code for other developers in my company to use in a specific project. There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface). The interface will be internal to the assembly If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration...
[Juan Manuel said:](https://stackoverflow.com/questions/26903/how-can-you-require-a-constructor-with-no-parameters-for-types-implementing-an#27386) > that's one of the reasons I don't understand why it cannot be a part of the contract in the interface It's an indirect mechanism. The generic allows you to "cheat" and send type information along with the interface. The critical thing to remember here is that the constraint isn't on the interface that you are working with directly. It's not a constraint on the interface itself, but on some other type that will "ride along" on the interface. This is the best explanation I can offer, I'm afraid. By way of illustration of this fact, I'll point out a hole that I have noticed in aku's code. It's possible to write a class that would compile fine but fail at runtime when you try to instantiate it: ``` public class Something : ITest<String> { private Something() { } } ``` Something derives from ITest<T>, but implements no parameterless constructor. It will compile fine, because String does implement a parameterless constructor. Again, the constraint is on T, and therefore String, rather than ITest or Something. Since the constraint on T is satisfied, this will compile. But it will fail at runtime. To prevent **some** instances of this problem, you need to add another constraint to T, as below: ``` public interface ITest<T> where T : ITest<T>, new() { } ``` Note the new constraint: T : ITest<T>. This constraint specifies that what you pass into the argument parameter of ITest<T> **must** also **derive** from ITest<T>. Even so this will not prevent **all** cases of the hole. The code below will compile fine, because A has a parameterless constructor. But since B's parameterless constructor is private, instantiating B with your process will fail at runtime. ``` public class A : ITest<A> { } public class B : ITest<A> { private B() { } } ```
Not to be too blunt, but you've misunderstood the purpose of interfaces. An interface means that several people can implement it in their own classes, and then pass instances of those classes to other classes to be used. Creation creates an unnecessary strong coupling. It sounds like you really need some kind of registration system, either to have people register instances of usable classes that implement the interface, or of factories that can create said items upon request.
How can you require a constructor with no parameters for types implementing an interface?
[ "", "c#", ".net", "constructor", "interface", "oop", "" ]
What GUI should use to run my JUnit tests, and how exactly do I do that? My entire background is in .NET, so I'm used to just firing up my NUnit gui and running my unit tests. If the lights are green, I'm clean. Now, I have to write some Java code and want to run something similar using JUnit. The JUnit documentation is nice and clear about adding the attributes necessary to create tests, but its pretty lean on how to fire up a runner and see the results of those tests.
Eclipse is by-far the best I've used. Couple JUnit with a [code coverage](http://www.eclemma.org/) plug-in and Eclipse will probably be the best unit-tester.
JUnit stopped having graphical runners following the release of JUnit 4. If you do have an earlier version of JUnit you can use a graphical test runner by entering on the command line[1]: ``` java junit.swingui.TestRunner [optional TestClass] ``` With the optional test class the specified tests will run straight away. Without it you can enter the class into the GUI. The benefits of running your tests this way is that you don't have the overhead of an entire IDE (if you're not already running one). However, if you're already working in an IDE such as Eclipse, the integration is excellent and is a lot less hassle to get the test running. If you do have JUnit 4, and really don't want to use an IDE to run the tests, or want textual feedback, you can run the text UI test runner. In a similar vein as earlier, this can be done by entering on the command line[1]: ``` java junit.textui.TestRunner [TestClass] ``` Though in this case the TestClass is not optional, for obvious reasons. [1] assuming you're in the correct working directory and the classpath has been setup, which may be out of scope for this answer
What GUI should I run with JUnit(similar to NUnit gui)
[ "", "java", "ide", "junit", "" ]
I have read about JavaFX, and like all new technologies I wanted to get my hands "dirty" with it. However, although it talks of multiplatform support, I can't find specifics on this. What platforms support a JavaFX application? All those with Java SE? ME? Does it depend upon the APIs in JavaFX that I use?
JavaFX has three planned distributions. * JavaFX Desktop will run on Windows, Mac, ~~Linux, and Solaris~~ at FCS and will require Java SE. Support for Linux and Solaris will be forthcoming. * JavaFX TV and JavaFX Mobile have no announce target platforms. Also unannounced is whether they will run on ME or SE, and if ME which profiles. One important platform distinction is that JavaFX Desktop will support Swing components while JavaFX Mobile will not (only scene graph for graphics). JavaFX TV the least publicly concrete of the three at this time.
From what I can see JavaFX is a whole new runtime and compiler so is not a subset of Java. Sun will support it on mobile phones and on the desktop. OS-wise it is currently released for Windows/Mac but Solaris/Linux are in the works.
What platforms JavaFX is/will be supported on?
[ "", "java", "javafx", "" ]
this kind of follows on from another [question](https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app) of mine. Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to **test** it? I am thinking of creating a method which just spawns lots of [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx)'s or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc. Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me :) ### Edit Following [ajmastrean's](https://stackoverflow.com/questions/41568/whats-the-best-way-to-test-a-method-from-multiple-threads#41572) post: I am using a console app to test with Debug.Asserts :) --- ## Update I originally rolled with using [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this. I then followed up on [ajmastrean](https://stackoverflow.com/questions/41568/whats-the-best-way-to-unit-test-from-multiple-threads#41589)'s post and realised I should really be using the [Thread](http://msdn.microsoft.com/en-us/library/system.threading.thread(VS.80).aspx) class for working with concurrent operations. I will now refactor using this method (albeit a different approach).
In .NET, `ThreadPool` threads won't return without setting up `ManualResetEvent`s or `AutoResetEvent`s. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such. Something I have found that works is 1. Create an array of threads. 2. Setup the `ThreadStart` method of each thread. 3. Start each thread. 4. Join on all threads (blocks the current thread until all other threads complete or abort) ``` public static void MultiThreadedTest() { Thread[] threads = new Thread[count]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(DoSomeWork()); } foreach(Thread thread in threads) { thread.Start(); } foreach(Thread thread in threads) { thread.Join(); } } ```
@ajmastrean, since unit test result must be predictable we need to synchronize threads somehow. I can't see a simple way to do it without using events. I found that `ThreadPool.QueueUserWorkItem` gives me an easy way to test such use cases ``` ThreadPool.QueueUserWorkItem(x => { File.Open(fileName, FileMode.Open); event1.Set(); // Start 2nd tread; event2.WaitOne(); // Blocking the file; }); ThreadPool.QueueUserWorkItem(x => { try { event1.WaitOne(); // Waiting until 1st thread open file File.Delete(fileName); // Simulating conflict } catch (IOException e) { Debug.Write("File access denied"); } }); ```
Whats the best way to unit test from multiple threads?
[ "", "c#", "multithreading", "unit-testing", "testing", "" ]
I have a form element that contains multiple lines of inputs. Think of each line as attributes of a new object that I want to create in my web application. And, I want to be able to create multiple new objects in one HTTP POST. I'm using Javascript's built-in cloneNode(true) method to clone each line. The problem is that each input-line also has a removal link attached to its onclick-event: ``` // prototype based <div class="input-line"> <input .../> <a href="#" onclick="$(this).up().remove();"> Remove </a> </div> ``` When the cloned input-line's removal link is clicked, it also removes any input-lines that were cloned from the same dom object. Is it possible to rebind the "this" object to the proper anchor tag after using cloneNode(true) on the above DOM element?
Don't put handler on each link (this really should be a button, BTW). Use [event bubbling](http://www.quirksmode.org/js/events_order.html) to handle *all* buttons with one handler: ``` formObject.onclick = function(e) { e=e||event; // IE sucks var target = e.target||e.srcElement; // and sucks again // target is the element that has been clicked if (target && target.className=='remove') { target.parentNode.parentNode.removeChild(target.parentNode); return false; // stop event from bubbling elsewhere } } ``` + ``` <div> <input…> <button type=button class=remove>Remove without JS handler!</button> </div> ```
You could try cloning using the innerHTML method, or a mix: ``` var newItem = $(item).cloneNode(false); newItem.innerHTML = $(item).innerHTML; ``` Also: I think cloneNode doesn't clone events, registered with addEventListener. But IE's attachEvent events *are* cloned. But I might be wrong.
How to Maintain Correct Javascript Event After Using cloneNode(true)
[ "", "javascript", "events", "dom", "prototypejs", "clonenode", "" ]
Intel's [Threading Building Blocks (TBB)](http://www.threadingbuildingblocks.org/) open source library looks really interesting. Even though there's even an [O'Reilly Book](http://oreilly.com/catalog/9780596514808/) about the subject I don't hear about a lot of people using it. I'm interested in using it for some multi-level parallel applications (MPI + threads) in Unix (Mac, Linux, etc.) environments. For what it's worth, I'm interested in high performance computing / numerical methods kinds of applications. Does anyone have experiences with TBB? Does it work well? Is it fairly portable (including GCC and other compilers)? Does the paradigm work well for programs you've written? Are there other libraries I should look into?
I've introduced it into our code base because we needed a bettor malloc to use when we moved to a 16 core machine. With 8 and under it wasn't a significant issue. It has worked well for us. We plan on using the fine grained concurrent containers next. Ideally we can make use of the real meat of the product, but that requires rethinking how we build our code. I really like the ideas in TBB, but it's not easy to retrofit onto a code base. You can't think of TBB as another threading library. They have a whole new model that really sits on top of threads and abstracts the threads away. You learn to think in task, parallel\_for type operations and pipelines. If I were to build a new project I would probably try to model it in this fashion. We work in Visual Studio and it works just fine. It was originally written for linux/pthreads so it runs just fine over there also.
# Portability TBB is portable. It supports Intel and AMD (i.e. x86) processors, IBM PowerPC and POWER processors, ARM processors, and possibly others. If you look in the [build directory](https://github.com/01org/tbb/tree/tbb_2018/build), you can see all the configurations the build system support, which include a wide range of operating systems (Linux, Windows, Android, MacOS, iOS, FreeBSD, AIX, etc.) and compilers (GCC, Intel, Clang/LLVM, IBM XL, etc.). I have not tried TBB with the PGI C++ compiler and know that it does not work with the Cray C++ compiler (as of 2017). A few years ago, I was part of the effort to port TBB to IBM Blue Gene systems. Static linking was a challenge, but is now addressed by the [big\_iron.inc](https://github.com/jeffhammond/tbb/blob/cray-compiler/build/big_iron.inc) build system helper. The other issues were supporting relatively ancient versions of GCC (4.1 and 4.4) and ensuring the PowerPC atomics were working. I expect that porting to any currently unsupported architecture would be relatively straightforward on platforms that provide or are compatible with GCC and POSIX. # Usage in community codes I am aware of at least two HPC application frameworks that uses TBB: * [MOOSE](http://mooseframework.org/) * [MADNESS](https://github.com/m-a-d-n-e-s-s/madness) I do not know how MOOSE uses TBB, but MADNESS uses TBB for its task queue and memory allocator. # Performance versus other threading models I have personally used TBB in the [Parallel Research Kernels](https://github.com/ParRes/Kernels) project, within which I have compared TBB to OpenMP, OpenCL, Kokkos, RAJA, C++17 Parallel STL, and other models. See the [C++ subdirectory](https://github.com/ParRes/Kernels/tree/master/Cxx11) for details. The following figure shows the relative performance of the aforementioned models on an Intel Xeon Phi 7250 processor (the details aren't important - all models used the same settings). As you can see, TBB does quite well except for smaller problem sizes, where the overhead of adaptive scheduling is more relevant. TBB has tuning knobs that will affect these results. [![PRK stencil](https://i.stack.imgur.com/MVd5j.png)](https://i.stack.imgur.com/MVd5j.png) Full disclosure: I work for Intel in a research/pathfinding capacity.
Any experiences with Intel's Threading Building Blocks?
[ "", "c++", "multithreading", "intel", "tbb", "" ]
Our design has one jvm that is a jboss/webapp (read/write) that is used to maintain the data via hibernate (using jpa) to the db. The model has 10-15 persistent classes with 3-5 levels of depth in the relationships. We then have a separate jvm that is the server using this data. As it is running continuously we just have one long db session (read only). There is currently no intra-jvm cache involved - so we manually signal one jvm from the other. Now when the webapp changes some data, it signals the server to reload the changed data. What we have found is that we need to tell hibernate to purge the data and then reload it. Just doing a fetch/merge with the db does not do the job - mainly in respect of the objects several layers down the hierarchy. Any thoughts on whether there is anything fundamentally wrong with this design or if anyone is doing this and has had better luck with working with hibernate on the reloads. Thanks, Chris
A Hibernate session loads all data it reads from the DB into what they call the *first-level cache*. Once a row is loaded from the DB, any subsequent fetches for a row with the same PK will return the data from this cache. Furthermore, Hibernate gaurentees reference equality for objects with the same PK in a single Session. From what I understand, your read-only server application never closes its Hibernate session. So when the DB gets updated by the read-write application, the Session on read-only server is unaware of the change. Effectively, your read-only application is loading an in-memory copy of the database and using that copy, which gets stale in due course. The simplest and best course of action I can suggest is to close and open Sessions as needed. This sidesteps the whole problem. Hibernate Sessions are intended to be a window for a short-lived interaction with the DB. I agree that there is a performance gain by not reloading the object-graph again and again; but you need to measure it and convince yourself that it is worth the pains. Another option is to close and reopen the Session periodically. This ensures that the read-only application works with data not older than a given time interval. But there definitely is a window where the read-only application works with stale data (although the design guarantees that it gets the up-to-date data eventually). This might be permissible in many applications - you need to evaluate your situation. The third option is to use a *second level cache* implementation, and use short-lived Sessions. There are various caching packages that work with Hibernate with relative merits and demerits.
Chris, I'm a little confused about your circumstances. If I understand correctly, you have a both a web app (read/write) a standalone application (read-only?) using Hibernate to access a shared database. The changes you make with the web app aren't visible to the standalone app. Is that right? If so, have you considered using a different second-level cache implementation? I'm wondering if you might be able to use a clustered cache that is shared by both the web application and the standalone application. I believe that SwarmCache, which is integrated with Hibernate, will allow this, but I haven't tried it myself. In general, though, you should know that the contents of a given cache will never be aware of activity by another application (that's why I suggest having both apps share a cache). Good luck!
How to maintain Hibernate cache consistency running two Java applications?
[ "", "java", "hibernate", "caching", "" ]
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++. How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?
Namespaces are packages essentially. They can be used like this: ``` namespace MyNamespace { class MyClass { }; } ``` Then in code: ``` MyNamespace::MyClass* pClass = new MyNamespace::MyClass(); ``` Or, if you want to always use a specific namespace, you can do this: ``` using namespace MyNamespace; MyClass* pClass = new MyClass(); ``` **Edit:** Following what [bernhardrusch](https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41624) has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed). And as you asked [below](https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615), you can use as many namespaces as you like.
To avoid saying everything Mark Ingram already said a little tip for using namespaces: Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (\*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level. I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure. Sometimes namespaces are used in bigger C++ projects to hide implementation details. Additional note to the using directive: Some people prefer using "using" just for single elements: ``` using std::cout; using std::endl; ```
How do you properly use namespaces in C++?
[ "", "c++", "namespaces", "" ]
How do you ensure, that you can checkout the code into Eclipse or NetBeans and work there with it? Edit: If you not checking in ide-related files, you have to reconfigure buildpath, includes and all this stuff, each time you checkout the project. I don't know, if ant (especially an ant buildfile which is created/exported from eclipse) will work with an other ide seamlessly.
The smart ass answer is "by doing so" - unless you aren't working with multiple IDEs you don't know if you are really prepared for working with multiple IDEs. Honest. :) I always have seen multiple platforms as more cumbersome, as they may use different encoding standards (e.g. Windows may default to ISO-8859-1, Linux to UTF-8) - for me encoding has caused way more issues than IDEs. Some more pointers: * You might want to go with Maven (<http://maven.apache.org>), let it generate IDE specific files and never commit them to source control. * In order to be sure that you are generating the correct artefacts, you should have a dedicated server build your deliverables (e.g. cruisecontrol), either with the help of ant, maven or any other tool. These deliverables are the ones that are tested outside of development machines. Great way to make people aware that there is another world outside their own machine. * Prohibit any machine specific path to be contained in any IDE specific file found in source control. Always reference external libraries by logical path names, preferable containing their version (if you don't use maven)
We actually maintain a Netbeans and an Eclipse project for our code in SVN right now with no troubles at all. The Netbeans files don't step on the Eclipse files. We have our projects structured like this: ``` sample-project + bin + launches + lib + logs + nbproject + src + java .classpath .project build.xml ``` The biggest points seem to be: * Prohibit any absolute paths in the project files for either IDE. * Set the project files to output the class files to the same directory. * svn:ignore the private directory in the .nbproject directory. * svn:ignore the directory used for class file output from the IDEs and any other runtime generated directories like the logs directory above. * Have people using both consistently so that differences get resolved quickly. * Also maintain a build system independent of the IDEs such as cruisecontrol. * Use UTF-8 and correct any encoding issues immediately. We are developing on Fedora 9 32-bit and 64-bit, Vista, and WindowsXP and about half of the developers use one IDE or the other. A few use both and switch back and forth regularly.
How do you handle different Java IDEs and svn?
[ "", "java", "eclipse", "svn", "ide", "collaboration", "" ]
I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organizing classes.
A Python file is called a "module" and it's one way to organize your software so that it makes "sense". Another is a directory, called a "package". A module is a distinct thing that may have one or two dozen closely-related classes. The trick is that a module is something you'll import, and you need that import to be perfectly sensible to people who will read, maintain and extend your software. The rule is this: **a module is the unit of reuse**. You can't easily reuse a single class. You should be able to reuse a module without any difficulties. Everything in your library (and everything you download and add) is either a module or a package of modules. For example, you're working on something that reads spreadsheets, does some calculations and loads the results into a database. What do you want your main program to look like? ``` from ssReader import Reader from theCalcs import ACalc, AnotherCalc from theDB import Loader def main( sourceFileName ): rdr= Reader( sourceFileName ) c1= ACalc( options ) c2= AnotherCalc( options ) ldr= Loader( parameters ) for myObj in rdr.readAll(): c1.thisOp( myObj ) c2.thatOp( myObj ) ldr.laod( myObj ) ``` Think of the import as the way to organize your code in concepts or chunks. Exactly how many classes are in each import doesn't matter. What matters is the overall organization that you're portraying with your `import` statements.
Since there is no artificial limit, it really depends on what's comprehensible. If you have a bunch of fairly short, simple classes that are logically grouped together, toss in a bunch of 'em. If you have big, complex classes or classes that don't make sense as a group, go one file per class. Or pick something in between. Refactor as things change.
Possibilities for Python classes organized across files?
[ "", "python", "class", "project-structure", "" ]
I have a user interface in .net which needs to receive data from a server, on a request/reply/update model. The only constraint is to use Java only on the server box. What is the best approach to achieve this ? Is it by creating a Webservice in Java and then accessing it in .net, or should I create Java proxies and convert them in .net by using IKM ? Or do you have any better idea ? It can be HTTP based, used a direct socket connection, or any middleware.
I recommend the web service route. It offers a standard interface that can be consumed by other client platforms in the future. .NET clients interact with Java web services pretty well, though there are some gotchas. The best two technologies available for you for the .NET client are Microsoft Web Service Enhancements (WSE) and Windows Communication Foundation (WCF). WSE is an older technology that is no longer being updated by Microsoft, but still works great in Visual Studio 2005 and older. I find WSE to be a bit easier to get started with in terms of how you interface with basic services, but WCF has much more support for WS-\* protocols (security, trust, etc.). If your needs are basic and you're still using Visual Studio 2005 (.NET framework 2 or older), then go with WSE. If you like the cutting edge, or you anticipate more advanced security needs (doesn't sound like you will), then go with WCF. Please note that WSE will not work easily in Visual Studio 2008 and newer, and WCF will not work in Visual Studio 2005 and older. Going the web service route will mean that you will design to an interface that can be reused and will result in a more loosely coupled system when you're done than most of the other routes. The downside is primarily performance: xml serialization will be slower than binary over the wire, and web services do not handle large amounts of data well.
Write webservice in Java and access it in .net
What is the best way to make a .net client consume service from a Java server?
[ "", "java", ".net", "interop", "" ]
We put all of our unit tests in their own projects. We find that we have to make certain classes public instead of internal just for the unit tests. Is there anyway to avoid having to do this. What are the memory implication by making classes public instead of sealed?
If you're using .NET, the [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) assembly attribute allows you to create "friend" assemblies. These are specific strongly named assemblies that are allowed to access internal classes and members of the other assembly. Note, this should be used with discretion as it tightly couples the involved assemblies. A common use for InternalsVisibleTo is for unit testing projects. It's probably not a good choice for use in your actual application assemblies, for the reason stated above. **Example:** ``` [assembly: InternalsVisibleTo("NameAssemblyYouWantToPermitAccess")] namespace NameOfYourNameSpace { ```
Below are ways to use in **.NET Core** applications. 1. Add **AssemblyInfo.cs** file and add `[assembly: InternalsVisibleTo("AssemblytoVisible")]` 2. Add this in **.csproj** file *(the project which contains the Internal classes)* ``` <ItemGroup> <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo"> <_Parameter1>Test_Project_Name</_Parameter1> <!-- The name of the project that you want the Internal class to be visible To it --> </AssemblyAttribute> </ItemGroup> ``` For more information please follow <https://improveandrepeat.com/2019/12/how-to-test-your-internal-classes-in-c/>
Making code internal but available for unit testing from other projects
[ "", "c#", "unit-testing", "scope", "" ]