Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Alright here's the deal, I'm taking an intro to C++ class at my university and am having trouble figuring out how to change the extension of a file. First, what we are suppose to do is read in a .txt file and count words, sentences, vowels etc. Well I got this but the next step is what's troubling me. We are then suppose to create a new file using the same file name as the input file but with the extension .code instead of .txt (in that new file we are then to encode the string by adding random numbers to the ASCII code of each character if you were interested). Being a beginner in programming, I'm not quite sure how to do this. I'm using the following piece of code to at first get the input file:
```
cout << "Enter filename: ";
cin >> filename;
infile.open(filename.c_str());
```
I'm assuming to create a new file I'm going to be using something like:
```
outfile.open("test.code");
```
But I won't know what the file name is until the user enters it so I can't say "test.txt". So if anyone knows how to change that extenstion when I create a new file I would very much appreciate it! | There are several approaches to this.
You can take the super lazy approach, and have them enter in just the file name, and not the .txt extension. In which case you can append .txt to it to open the input file.
```
infile.open(filename + ".txt");
```
Then you just call
```
outfile.open(filename + ".code");
```
The next approach would be to take the entire filename including extension, and just append .code to it so you'd have test.txt.code.
It's a bit ambiguous if this is acceptable or not.
Finally, you can use `std::string` methods [`find`](http://en.cppreference.com/w/cpp/string/basic_string/find), and [`replace`](http://en.cppreference.com/w/cpp/string/basic_string/replace) to get the filename with no extension, and use that. | I occasionally ask myself this question and end up on this page, so for future reference, here is the single-line syntax:
```
string newfilename=filename.substr(0,filename.find_last_of('.'))+".code";
``` | How do you change the filename extension stored in a string in C++? | [
"",
"c++",
"encoding",
"file-extension",
""
] |
I have this regex code in python :
```
if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text):
print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups())
```
`text` is `{\fad(200,200)}Épisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03` and read from a file (don't know if that helps).
This returns the following:
```
(None, None)
```
When I change the regex in the print to `r"\{\\fad\((\d{1,4}),(\d{1,4})\)\}"`, it returns the correct values:
```
(200, 200)
```
Can anyone see why the conditional `fad|fade` matches the regex in the `re.search` but doesn't return the correct values of the groups in the print?
Thanks. | Put extra parens around the choice: `re.search(r"{(?:\\fad|fade)\((\d{1,4}),(\d{1,4})\)}", text).groups()`
Also, escaping `{}` braces isn't necessary, it just needlessly clutters your regexp. | The bracket is part of the or branch starting with fade, so it's looking for either "{fad" or "fade(...". You need to group the fad|fade part together. Try:
```
r"\{\\(?:fad|fade)\(\d{1,4},\d{1,4}\)\}"
```
**[Edit]**
The reason you do get into the if block is because the regex **is** matching, but only because it detects it starts with "{\fad". However, that part of the match contains no groups. You need to match with the part that defines the groups if you want to capture them. | Why doesn't the regex match when I add groups? | [
"",
"python",
"regex",
""
] |
I have a table, let's call it "a" that is used in a left join in a view that involves a lot of tables. However, I only want to return rows of "a" if they also join with another table "b". So the existing code looks like
```
SELECT ....
FROM main ...
...
LEFT JOIN a ON (main.col2 = a.col2)
```
but it's returning too many rows, specifically ones where a doesn't have a match in b. I tried
```
SELECT ...
FROM main ...
...
LEFT JOIN (
SELECT a.col1, a.col2
FROM a
JOIN b ON (a.col3 = b.col3)) ON (a.col2 = main.col2)
```
which gives me the correct results but unfortunately "EXPLAIN PLAN" tells that doing it this way ends up forcing a full table scan of both a and b, which is making things quite slow. One of my co-workers suggested another LEFT JOIN on b, but that doesn't work because it gives me the b row when it's present, but doesn't stop returning the rows from a that don't have a match in b.
Is there any way to put the main.col2 condition in the sub-SELECT, which would get rid of the full table scans? Or some other way to do what I want? | ```
SELECT ...
FROM ....
LEFT JOIN ( a INNER JOIN b ON .... ) ON ....
``` | 1. add a where (main.col2 = a.col2)
2. just do a join instead of a left join. | Restricting a LEFT JOIN | [
"",
"sql",
"oracle",
""
] |
Is there a c# command to include another web page - the equivelant of the php require?
I know how to do server side includes but was looking for something code based.
Thanks
> ---
Thanks for the answers all. I think I might need to explain further. I have several sub-pages that I will be loading during the use of the site using an xmlhttp request. Initially however, I need to load the starting sub-page before the user has interacted with the site. I could do this with js, but that would require more overhead in server calls from the client for the initial load. I already use master pages, but this is a little different. Since this is done serverside initally but must remain able to be refreshed clientside, I don't think I can make these pages into controls can I? I am pretty new to .Net so I may be making my life harder than I need to. | The way ASP.NET is structured, you shouldn't really need to do this. Code is compiled, so all of your classes and functions should be accessible simply by referencing the relevant assembly or namespace, without having to include individual code files.
You might be looking for user controls, which allow you to create fragments of markup with their corresponding code behind, and then reference these in your page. | I think what you may be looking for are [MasterPages](http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx) and [UserControls](http://msdn.microsoft.com/en-us/library/ms745025.aspx). A MasterPage allows you to define a basic template that is "filled in" by the implementing pages by having the implementing page add it's own content to the ContentPlaceHolders defined on the MasterPage. A UserControl is a re-usable piece of markup and associated code that you can reference from your mark up or add dynamically to the page being rendered in codebehind. | .Net include page - like php require | [
"",
"c#",
".net",
""
] |
I come from the land of Java, C#, etc. I am working on a javascript report engine for a web application I have. I am using jQuery, AJAX, etc. I am having difficulty making things work the way I feel they should - for instance, I have gone to what seems like too much trouble to make sure that when I make an AJAX call, my callback has access to the object's members. Those callback functions don't need to be that complicated, do they? I know I must be doing something wrong. Please point out what I could be doing better - let me know if the provided snippet is too much/too little/too terrible to look at.
What I'm trying to do:
* On page load, I have a select full of users.
* I create the reports (1 for now) and add them to a select box.
* When both a user and report are selected, I run the report.
* The report involves making a series of calls - getting practice serieses, leagues, and tournaments - for each league and tournament, it gets all of those serieses, and then for each series it grabs all games.
* It maintains a counter of the calls that are active, and when they have all completed the report is run and displayed to the user.
Code:
```
//Initializes the handlers and reports
function loadUI() {
loadReports();
$("#userSelect").change(updateRunButton);
$("#runReport").click(runReport);
updateRunButton();
return;
$("#userSelect").change(loadUserGames);
var user = $("#userSelect").val();
if(user) {
getUserGames(user);
}
}
//Creates reports and adds them to the select
function loadReports() {
var reportSelect = $("#reportSelect");
var report = new SpareReport();
engine.reports[report.name] = report;
reportSelect.append($("<option/>").text(report.name));
reportSelect.change(updateRunButton);
}
//The class that represents the 1 report we can run right now.
function SpareReport() {
this.name = "Spare Percentages";
this.activate = function() {
};
this.canRun = function() {
return true;
};
//Collects the data for the report. Initializes/resets the class variables,
//and initiates calls to retrieve all user practices, leagues, and tournaments.
this.run = function() {
var rC = $("#rC");
var user = engine.currentUser();
rC.html("<img src='/img/loading.gif' alt='Loading...'/> <span id='reportProgress'>Loading games...</span>");
this.pendingOperations = 3;
this.games = [];
$("#runReport").enabled = false;
$.ajaxSetup({"error":(function(report) {
return function(event, XMLHttpRequest, ajaxOptions, thrownError) {
report.ajaxError(event, XMLHttpRequest, ajaxOptions, thrownError);
};
})(this)});
$.getJSON("/api/leagues", {"user":user}, (function(report) {
return function(leagues) {
report.addSeriesGroup(leagues);
};
})(this));
$.getJSON("/api/tournaments", {"user":user}, (function(report) {
return function(tournaments) {
report.addSeriesGroup(tournaments);
};
})(this));
$.getJSON("/api/practices", {"user":user}, (function(report) {
return function(practices) {
report.addSerieses(practices);
};
})(this));
};
// Retrieves the serieses (group of IDs) for a series group, such as a league or
// tournament.
this.addSeriesGroup = function(seriesGroups) {
var report = this;
if(seriesGroups) {
$.each(seriesGroups, function(index, seriesGroup) {
report.pendingOperations += 1;
$.getJSON("/api/seriesgroup", {"group":seriesGroup.key}, (function(report) {
return function(serieses) {
report.addSerieses(serieses);
};
})(report));
});
}
this.pendingOperations -= 1;
this.tryFinishReport();
};
// Retrieves the actual serieses for a series group. Takes a set of
// series IDs and retrieves each series.
this.addSerieses = function(serieses) {
var report = this;
if(serieses) {
$.each(serieses, function(index, series) {
report.pendingOperations += 1;
$.getJSON("/api/series", {"series":series.key}, (function(report) {
return function(series) {
report.addSeries(series);
};
})(report));
});
}
this.pendingOperations -= 1;
this.tryFinishReport();
};
// Adds the games for the series to the list of games
this.addSeries = function(series) {
var report = this;
if(series && series.games) {
$.each(series.games, function(index, game) {
report.games.push(game);
});
}
this.pendingOperations -= 1;
this.tryFinishReport();
};
// Checks to see if all pending requests have completed - if so, runs the
// report.
this.tryFinishReport = function() {
if(this.pendingOperations > 0) {
return;
}
var progress = $("#reportProgress");
progress.text("Performing calculations...");
setTimeout((function(report) {
return function() {
report.finishReport();
};
})(this), 1);
}
// Performs report calculations and displays them to the user.
this.finishReport = function() {
var rC = $("#rC");
//snip a page of calculations/table generation
rC.html(html);
$("#rC table").addClass("tablesorter").attr("cellspacing", "1").tablesorter({"sortList":[[3,1]]});
};
// Handles errors (by ignoring them)
this.ajaxError = function(event, XMLHttpRequest, ajaxOptions, thrownError) {
this.pendingOperations -= 1;
};
return true;
}
// A class to track the state of the various controls. The "series set" stuff
// is for future functionality.
function ReportingEngine() {
this.seriesSet = [];
this.reports = {};
this.getSeriesSet = function() {
return this.seriesSet;
};
this.clearSeriesSet = function() {
this.seriesSet = [];
};
this.addGame = function(series) {
this.seriesSet.push(series);
};
this.currentUser = function() {
return $("#userSelect").val();
};
this.currentReport = function() {
reportName = $("#reportSelect").val();
if(reportName) {
return this.reports[reportName];
}
return null;
};
}
// Sets the enablement of the run button based on the selections to the inputs
function updateRunButton() {
var report = engine.currentReport();
var user = engine.currentUser();
setRunButtonEnablement(report != null && user != null);
}
function setRunButtonEnablement(enabled) {
if(enabled) {
$("#runReport").removeAttr("disabled");
} else {
$("#runReport").attr("disabled", "disabled");
}
}
var engine = new ReportingEngine();
$(document).ready( function() {
loadUI();
});
function runReport() {
var report = engine.currentReport();
if(report == null) {
updateRunButton();
return;
}
report.run();
}
```
I am about to start adding new reports, some of which will operate on only a subset of user's games. I am going to be trying to use subclasses (prototype?), but if I can't figure out how to simplify some of this... I don't know how to finish that sentence. Help! | ```
$.getJSON("/api/leagues", {"user":user}, (function(report) {
return function(leagues) {
report.addSeriesGroup(leagues);
};
})(this));
```
Can be written as:
```
var self = this;
$.getJSON("/api/leagues", {"user":user}, (function(leagues) {
self.addSeriesGroup(leagues);
});
```
The function-returning-function is more useful when you're inside a loop and want to bind to a variable that changes each time around the loop. | Provide "some" comments where necessary. | How can I make this javascript easier to read, maintain, and understand from an OO background? | [
"",
"javascript",
""
] |
I wish to extend a base class in C# with some additional functionality. I have existing code which returns an array of the base class objects (Account) which I need to convert into the extended version.
So I have the extended version:
```
class AccountXtra : Account
{
public int Period { get; set; }
public int Visitors { get; set; }
public string ContactName { get; set; }
}
```
All is good.
BUT how do I create a new instance of AccountXtra when I have a instance of Account?
I have tried:
```
//This doesn't work
AccountXtra newInstance = (AccountXtra)accountInstance;
//This also doesn't work
AccountXtra newInstance = new AccountXtra();
newInstance = accountInstance;
``` | You need to be generating new objects of the *derived* class now, not the base. Replace your old calls to `new Account` with `new AccountXtra`. Or, you need a constructor for `AccountXtra` that takes an `Account` object and makes a new derived-class version of it:
```
public AccountXtra(Account baseInstance) : this()
{
this.Field1 = baseInstance.Field1;
this.Field2 = baseInstance.Field2;
...
}
```
---
Explanation: You can't cast a base class to a derived class unless it is of the derived class type. This will work:
```
AccountXtra accountXtra = new AccountXtra();
Account xtraAsBase = (Account)accountXtra;
AccountXtra xtraCastBack = (AccountXtra)xtraCastAsBase;
```
But this will not:
```
Account Base = new Account();
AccountXtra baseAsDerived = (AccountXtra)Base; //Cast base to derived class
``` | > BUT how do I create a new instance of AccountXtra when I have a instance of Account?
That's going the wrong way - you need to have created the AccountXtra object which can then be treated everywhere as an Account object.
By the way, if you're not sure what type of objects you'll want to create in your list-creation code, you might want to read about [factory patterns](http://en.wikipedia.org/wiki/Factory_method_pattern).
Feel free to update your question with specific problems you're having. | Getting my head around an inheritance problem | [
"",
"c#",
"inheritance",
""
] |
I'm using the [jQuery datepicker](http://docs.jquery.com/UI/Datepicker) to select dates. It works fine, except there is 1 default behavior that I would like to change. When you select a day, the selected day is highlighted (which I like). The current day is also highlighted, but using a different css style (which I also like). However, if you select the current day, the highlighting because it is the current day supersedes it being selected... I would much prefer it being selected to supersede the current day highlight, which I feel would make it very clear that you have selected the current day.
Now, I feel I could probably update the css to solve my problem. However, I really don't want to tweak the out-of-the-box jQuery UI css, because I want to later add skins to my app. This means if I grab a bunch of the jQuery UI themes... I then have to make the same tweak on all of them (very undesirable).
I could probably update the actual Datepicker plugin to do this as well, but then I run into the issue that if I want to update my Datepicker later on... I need to remember to make this fix again.
Ideally, I could use some option built into the Datepicker to accomplish my goal, but as of yet none of the options seem to be right. I would settle for some kind of JavaScript hack, or css plopped into the page, but I'm at a loss for ideas right now. | Adding an additional CSS file to your page would definitely be the preferred method. It's easily managed and uses CSS the way it was intended to be used!
You would need to place your override CSS in the head tag after any previously loaded base jQuery CSS or any theme CSS files in order to override their values. (You could also increase the specificity of the default tag, referencing a class or ID in your specific instance.)
i.e.
```
<head>
<link href="base_jquery_css_file" rel="stylesheet"/>
<link href="theme_jquery_css_file" rel="stylesheet"/>
<link href="your_override_css" rel="stylesheet"/>
</head>
```
The "your\_override\_css" file would simply contain:
```
.ui-state-active, .ui-widget-content .ui-state-active {
/*any CSS styles you want overriden i.e.*/
border: 1px solid #999999;
background-color: #EEEEEE;
}
```
---
**Note from Mike:**
I ended up finding out that there is a td around the anchors that represent the days, and the td also has the "today" information... so despite there not being a cross-browser way to select an item that has multiple classes (that I've found), the following will work in this case, in a new file just as PHPexperts.ca describes:
```
.ui-datepicker-today .ui-state-active {
border: 1px solid #aaaaaa;
}
``` | Since it took me a while to figure out how to exactly replicate the "selected" style over top of the today style even with the answer from PHPexperts.ca, here's a bit more information that might make it a bit more straightforward if you're having trouble.
If you select a day other than "today", the style that you should copy for an identical look when "today" is selected is in the `a` tag and in the selector
`.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active`
This should be easy to find if you have Firefox with Firebug installed (select the date, reopen the datepicker, right click and select 'inspect element'.
For the jQuery UI theme 'UI darkness' the style to copy into your override css is
`.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active {
background:url("images/ui-bg_inset-soft_30_f58400_1x100.png") repeat-x scroll 50% 50% #F58400;
border:1px solid #FFAF0F;
color:#FFFFFF;
}`
If you change the theme, it looks like all 3 of these styles change. | jQuery UI Datepicker: don't highlight today when it is also selected | [
"",
"javascript",
"jquery",
"css",
"datepicker",
""
] |
I'm wondering if anyone can give me a good example of using pointers in C# in .Net and why you chose to use pointers? | This isn't really a question to specific to ASP.NET.
If you are going to use pointers in .NET, the predominant reason is that you have an interop scenario where it is going to be easier to use pointers in unsafe code instead of IntPtr instances.
The second most popular (and distant) reason is because you might actually have a performance gain in processing large amounts of data in unsafe code than in managed code. Image processing algorithms are a good example of this. | If you wanted to do some performant image processing for a web application, you might want to consider using pointers there. See *[Image Processing Basics in C#](http://www.codeproject.com/KB/recipes/ImageBasicCS.aspx)* on codeproject.com. | Uses of C# pointers in .Net | [
"",
"c#",
"pointers",
""
] |
Is there any way to get value of private static field from known class using reflection? | Yes.
```
Type type = typeof(TheClass);
FieldInfo info = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Static);
object value = info.GetValue(null);
```
This is for a field. For a property, change `type.GetField` to `type.GetProperty`. You can also access private methods in a similar fashion. | I suppose someone should ask whether this is a good idea or not? It creates a dependency on the private implementation of this static class. Private implementation is subject to change without any notice given to people using Reflection to access the private implementation.
If the two classes are meant to work together, consider making the field *internal* and adding the assembly of the cooperating class in an [assembly:InternalsVisibleTo] attribute. | How to get the value of a private static field from a class? | [
"",
"c#",
"reflection",
""
] |
I'm having trouble debugging my jbehave tests. I cannot get maven to start the jbehave tests and stop at a breakpoint. I have this in my pom:
```
<pluginManagement>
<plugins>
<plugin>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-maven-plugin</artifactId>
<version>2.0.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-maven-plugin</artifactId>
<executions>
<execution>
<id>run-scenarios-found</id>
<phase>test</phase>
<configuration>
<scenarioIncludes>
<scenarioInclude>**/scenario/**/*${test}.java</scenarioInclude>
</scenarioIncludes>
<scenarioExcludes>
<scenarioExclude>**/*Steps.java</scenarioExclude>
</scenarioExcludes>
</configuration>
<goals>
<goal>run-scenarios</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
```
and I have tried things like:
```
$ mvn -e -o -Dtest=MyTest -Dmaven.surefire.debug="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8787 -Xnoagent -Djava.compiler=NONE" clean test
```
and
```
$ export MVN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8787 -Xnoagent -Djava.compiler=NONE" ; mvn -Dtest=MyTest clean test
```
I can try to use [jsadebugd](http://java.sun.com/javase/6/docs/technotes/tools/share/jsadebugd.html), but I that will probably require immaculate timing to automate, so that sounds like a suboptimal solution, and I feel like the JBehave Maven plugin should provide this functionality. Clearly I have just not found the right piece of documetation yet. Any ideas how I go about this ? | The following worked for me:
export MAVEN\_OPTS="-Xdebug -Xrunjdwp:transport=dt\_socket,server=y,suspend=y,address=8787 -Xnoagent -Djava.compiler=NONE"
then start my mvn tests:
mvn install
(maven now hangs waiting for the debugger to connect)
Then start Eclipse in a remote debug session, pointing at local host, port 8787 (as above), with appropriate breakpoints set. | Wouldn't it be easier not to start the tests with maven, but rather in the IDE with JUnit? Then you can use the debugger directly? I normally do it so, that the CI server uses maven to execute JBehave, but in the IDE, I prefer a more direct way of execution. | Debugging JBehave scenarios | [
"",
"java",
"debugging",
"testing",
"bdd",
""
] |
We are programming a logging library that keeps itself in a .hpp file. We would like to include `<tr1/unordered_map>` (if the compiler supports TR1,) or the standard `<map>` otherwise. Is there a standard way of checking at compile time if tr1 is available or not?
I was thinking that the same way that the "`__cplusplus`" define symbol is present, there could have been defined a "`__cxx__tr1`" or something like that. I haven't seen that in the drafts for TR1, so I assume it is not present, but I wanted to ask first just in case.
As a note, if those defines don't exist, it wouldn't be a bad idea to include them in proposals themselves. | If you are using any configuration tools like autotools you may try to write a test like:
```
AC_CHECK_HEADER(tr1/unordered_map,[AC_DEFINE([HAVE_TR1],[],["Have tr1"])],[])
AC_CHECK_HEADER(unordered_map,[AC_DEFINE([HAVE_CXX0X],[],["Have C++0x"])],[])
```
And then use these defines in your code.
Generally speaking `__cplusplus` macro should give you standard version number, but there is no compiler that gives you 100% standard implementation... Thus write configure macros.
Unfortunately this is only quite reliable way to check such things unless you want to write 1001 `#ifdef` for each compiler (what boost does)
And then:
```
#include "config.h"
#ifdef HAVE_CXX0X
# include <unordered_map>
typedef std::unordered_map<foo,bar> my_map;
#elif HAVE_TR1
# include <tr1/unordered_map>
typedef std::tr1::unordered_map<foo,bar> my_map;
#else
# include <map>
typedef std::map<foo,bar> my_map;
#endif
``` | GCC-4.3 has:
```
#define __GXX_EXPERIMENTAL_CXX0X__ 1
```
But, this is obviously not standard. | How to check for TR1 while compiling? | [
"",
"c++",
"dictionary",
"unordered-map",
"tr1",
""
] |
Right now the library can translate this operation
```
Select * from List where name = k% order by desc
```
to
```
List.filter(function(x) { return x.first_char() == 'k' }).sort().reverse());
```
Whats the best hack to remove the () so that the developer can write statements like:
```
List.filter(fn(x) { return x.first_char == 'k' }).sort.reverse;
```
Naive approach:
```
maxfn = function() {this[0]..}; Array.prototype.max = maxfn();
```
But with this approach I can't access 'this'.
I wanted to add a syntactic sugar for
```
new Array("1","2","3")
```
to something like :)(suggestions needed)
```
_("1","2" ,"3")
```
like we have in scheme where list -> '
I tried to clone the arguments but failed.
Thanks. | For lists you can use [JSON](http://json.org) notation:
```
["1", "2", "3"]
``` | You can use JSON notation as suggested by RoBorg, if you control the list... However, there's no cross-browser way to treat a property as a method. Note: spidermonkey (firefox) does support using a getter (get method for a property). | How do I add syntactic sugar in my Javascript library? | [
"",
"javascript",
"syntactic-sugar",
""
] |
Aloha
Given a plug-in architecture (C# / .NET 3.5) with the plug-ins stored in the GAC, how can I list/load all dll's that contain types that implement my specific interface? In other words, I'd like to investigate which plug-ins for my application are installed on a machine, by looking in the GAC.
-Edoode | First a little clarification: a DLL cannot implement an interface. The DLL contains types that could implement a specific interface. Here's a [.NET wrapper](http://www.codeproject.com/KB/system/gacapi.aspx) around fusion.dll that allows you to enumerate all the assemblies in the GAC. Once you have loaded the assembly with [Assembly.Load](http://msdn.microsoft.com/en-us/library/ky3942xh.aspx) you can try to find all the types that implement the specific interface:
```
foreach (var type in assembly.GetTypes())
{
var myInterfaceType = typeof(IMyInterface);
if (type != myInterfaceType && myInterfaceType.IsAssignableFrom(type))
{
Console.WriteLine("{0} implements IMyInterface", type);
}
}
``` | To add to BFree's answer, I suggest that you could [load the assemblies for reflection only](http://msdn.microsoft.com/en-us/library/ms172331.aspx). This gives you enhanced security (the assemblies aren't able to execute at all) without appdomains, and flexibility (you can load assemblies that are for a different architecture). | List all DLL's implementing a specific interface from the GAC | [
"",
"c#",
"plugins",
"gac",
""
] |
With a JavaScript Array, I can reset it to an empty state with a single assignment:
```
array.length = 0;
```
This makes the Array "appear" empty and ready to reuse, and as far as I understand is a single "operation" - that is, constant time.
Is there a similar way to clear a JS Object? I know I can iterate its fields deleting them:
```
for (var prop in obj) { if (obj.hasOwnProperty(prop)) { delete obj[prop]; } }
```
but this has linear complexity.
I can also just throw the object away and create a new one:
```
obj = {};
```
But "promiscuous" creation of new objects leads to problems with Garbage Collection on IE6. ([As described here](http://ajaxian.com/archives/garbage-collection-in-ie6)) | The short answer to your question, I think, is no (you can just create a new object).
1. In this example, I believe setting the length to 0 still leaves all of the elements for garbage collection.
2. You could add this to Object.prototype if it's something you'd frequently use. Yes it's linear in complexity, but anything that doesn't do garbage collection later will be.
3. This is the best solution. I know it's not related to your question - but for how long do we need to continue supporting IE6? There are many campaigns to discontinue the usage of it.
Feel free to correct me if there's anything incorrect above. | Well, at the risk of making things too easy...
```
for (var member in myObject) delete myObject[member];
```
...would seem to be pretty effective in cleaning the object in one line of code with a minimum of scary brackets. All members will be truly deleted instead of left as garbage.
Obviously if you want to delete the object itself, you'll still have to do a separate delete() for that. | How to quickly clear a JavaScript Object? | [
"",
"javascript",
"performance",
""
] |
I have a standard Google Apps account. I have setup a custom domain through Google Apps. I am able to send and receive emails successfully through Google Apps when I use the Gmail interface. However, I want to send an email via code. In order to attempt this, I have been trying the following code:
```
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("someone@somewhere.example");
mailMessage.Subject = "Test";
mailMessage.Body = "<html><body>This is a test</body></html>";
mailMessage.IsBodyHtml = true;
// Create the credentials to login to the gmail account associated with my custom domain
string sendEmailsFrom = "emailAddress@mydomain.example";
string sendEmailsFromPassword = "password";
NetworkCredential cred = new NetworkCredential(sendEmailsFrom, sendEmailsFromPassword);
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.UseDefaultCredentials = false;
mailClient.Timeout = 20000;
mailClient.Credentials = cred;
mailClient.Send(mailMessage);
```
When the Send method is reached, an Exception is thrown that states:
> "The SMTP server requires a secure
> connection or the client was not
> authenticated. The server response
> was: 5.5.1 Authentication Required."
How do I send emails through my custom domain via Google? | There is no need to hardcode all SMTP settings in your code. Put them in web.config instead. This way you can encrypt these settings if needed and change them on the fly without recompiling your application.
```
<configuration>
<system.net>
<mailSettings>
<smtp from="example@domain.example" deliveryMethod="Network">
<network host="smtp.gmail.com" port="587"
userName="example@domain.example" password="password"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
```
End when you send email just enable SSL on your SmtpClient:
```
var message = new MailMessage("navin@php.net");
// here is an important part:
message.From = new MailAddress("example@domain.example", "Mailer");
// it's superfluous part here since from address is defined in .config file
// in my example. But since you don't use .config file, you will need it.
var client = new SmtpClient();
client.EnableSsl = true;
client.Send(message);
```
Make sure that you're sending email from the same email address with which you're trying to authenticate at Gmail.
*Note*: Starting with .NET 4.0 you can insert `enableSsl="true"` into `web.config` as opposed to setting it in code. | This is what I use in WPF 4
```
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("sender_email@domain.tld", "P@$$w0rD");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
MailAddress maFrom = new MailAddress("sender_email@domain.tld", "Sender's Name", Encoding.UTF8),
MailAddress maTo = new MailAddress("recipient_email@domain2.tld", "Recipient's Name", Encoding.UTF8);
MailMessage mmsg = new MailMessage(maFrom, maTo);
mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
mmsg.BodyEncoding = Encoding.UTF8;
mmsg.IsBodyHtml = true;
mmsg.Subject = "Some Other Text as Subject";
mmsg.SubjectEncoding = Encoding.UTF8;
client.Send(mmsg);
MessageBox.Show("Done");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), ex.Message);
//throw;
}
```
Watch for Firewalls and Anti-Viruses. These creepy things tend to block applications sending email.
I use McAfee Enterprise and I have to add the executable name (like Bazar.\* for both Bazar.exe and Bazar.vshost.exe) to be able to send emails... | Send Email via C# through Google Apps account | [
"",
"c#",
"smtp",
"google-apps",
""
] |
Why does [this WSDL file](http://services.fliqz.com/searchservice/20071001/service.svc?wsdl) generate an empty service proxy in VS2008?
If you look at the Reference.cs file generated, it's empty. Any ideas? | Have you read your error list? I got the following:
```
Custom tool warning: There was a validation error on a schema generated during export:
Source:
Line: 144 Column: 12
Validation Error: Wildcard '##any' allows element 'http://search.yahoo.com/mrss:text', and causes the content model to become ambiguous. A content model must be formed such that during validation of an element information item sequence, the particle contained directly, indirectly or implicitly therein with which to attempt to validate each item in the sequence in turn can be uniquely determined without examining the content or attributes of that item, and without any information about the items in the remainder of the sequence.
Custom tool warning: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.XmlSerializerMessageContractImporter
Error: Cannot import invalid schemas. Compilation on the XmlSchemaSet failed.
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://fliqz.com/services/search/20071001']/wsdl:portType[@name='IVideoSearchService']
Custom tool warning: Cannot import wsdl:binding
Detail: There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='http://fliqz.com/services/search/20071001']/wsdl:portType[@name='IVideoSearchService']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:binding[@name='basicHttpBinding_IVideoSearchService_20071001']
Custom tool warning: Cannot import wsdl:port
Detail: There was an error importing a wsdl:binding that the wsdl:port is dependent on.
XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:binding[@name='basicHttpBinding_IVideoSearchService_20071001']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:service[@name='VideoSearchService']/wsdl:port[@name='basicHttpBinding_IVideoSearchService_20071001']
Custom tool error: Failed to generate code for the service reference 'ServiceReference1'. Please check other error and warning messages for details.
```
**Edit:** I did some digging, and I came across the following links:
* [MSDN Question](http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/409d7bb0-3da0-4d66-bb8b-30f7204a6c9d)
* [Blog Entry](http://blogs.msdn.com/richardt/archive/2005/03/01/382208.aspx)
I tried following the instructions by ScottAnderson in the first link, but was unable to generate a client proxy with them. Perhaps you can have better luck.
It appears the *reason* this doesn't work is because Fliqz is using XmlSerializer rather than DataContract/MessageContract for its contract definitions, and WCF doesn't want to play nicely with them and generates inappropriate WSDL. If you could control the original contract, you could probably fix the issue and be on your way; unfortunately, you may be entirely out of luck.
If you can get the ServiceContract interface and the types it exposes, you might be able to generate your own client by hand. Judging by some of the class names I see in there, it appears that Fliqz is exposing internal objects in their contract, so I doubt you could, you know, call them up and ask them for a .dll you can reference.
You could try to write out the interface and data / message contract types yourself by analyzing the WSDL and XSDs. Looks like it'd be a lot of work, though.
Sorry I can't help more. This seems to be a combination of poor WCF legacy support and poor architecture/design on the part of Fliqz. | right click on service reference , cofigure , un-check “Reuse types in referenced assembles” and click OK. Try to Update Service Reference. This worked for me! | Why does this WSDL file generate an empty service proxy in VS2008? | [
"",
"c#",
"web-services",
"wsdl",
""
] |
I'm using BlazeDS to connect Flex with Java. I'm having trouble passing ArrayLists of custom objects from Flex to java.
I have two objects, one is called Category, the other Section. A Category has an ArrayList of Section objects. I can send an ArrayList of Category objects back and forth between Flex and Java, the problem is when I try to access the sections ArrayList of a Category object that has been returned to Java from Flex, I get the following error:
```
flex.messaging.MessageException: java.lang.ClassCastException : flex.messaging.io.amf.ASObject
```
For some reason I'm getting an ArrayList of ASObjects rather than my Section objects. I tried looking up how to explicitly type arrays in actionscript, but the only thing I could find was using a Vector object, which BlazeDS does not support. Is it possible to pass an ArrayList of Section objects within an ArrayList of Category objects, or do I have to find another way around? | Flex was actually sending back a flex.messaging.io.ArrayCollection object. Below is the code to convert this to an ArrayList of my java class:
```
public ArrayList<MyObject> convertArrayCollection(ArrayCollection array){
ArrayList<MyObject> myObjectArray = new ArrayList();
ASTranslator ast = new ASTranslator();
MyObject myObject;
ASObject aso;
for (int i=0;i< array.size(); i++){
myObject = new MyObject();
aso = new ASObject();
aso = (ASObject) array.get(i);
aso.setType("com.myPackage.MyObject");
myObject = (MyObject) ast.convert(aso, MyObject.class);
myObjectArray.add(myObject);
}
return myObjectArray;
}
``` | One of the most common complaints with AS3 is the lack of typed arrays. ArrayLists will only contain objects, you will have to cast the results yourself.
Here is an example of a Java and AS3 class that I would pass around.
In Java:
The top level class:
```
package mystuff;
public class StuffToSend
{
public List<Section> sections;
...
}
```
Sections class:
```
package mystuff;
public class Section
{
public List<Catagory> categories;
...
}
```
Category class:
```
package mystuff;
public class Category
{
...
}
```
In AS3:
```
package mystuff
{
[RemoteClass(alias="mystuff.StuffToSend")] // So AS3 knows which Java class to map
public class StuffToSend
{
public var sections:ArrayCollection;
...
}
}
package mystuff
{
[RemoteClass(alias="mystuff.Section")] // So AS3 knows which Java class to map
public class Section
{
public var categories:ArrayCollection;
...
}
}
package mystuff
{
[RemoteClass(alias="mystuff.Category")] // So AS3 knows which Java class to map
public class Category
{
...
}
}
```
You can learn more about remoteObjects here: [Data Access](http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_4.html) | BlazeDS and ArrayList of custom objects | [
"",
"java",
"apache-flex",
"actionscript-3",
"blazeds",
""
] |
Is there anyway I can incorporate a pretty large text file (about 700KBs) into the program itself, so I don't have to ship the text files together in the application directory ? This is the first time I'm trying to do something like this, and I have no idea where to start from.
Help is greatly appreciated (: | Depending on the platform that you are on, you will more than likely be able to embed the file in a resource container of some kind.
If you are programming on the Windows platform, then you might want to look into resource files. You can find a basic intro here:
<http://msdn.microsoft.com/en-us/library/y3sk7e6b.aspx>
With more detailed information here:
<http://msdn.microsoft.com/en-us/library/zabda143.aspx> | Have a look at the **`xxd`** command and its **`-include`** option. You will get a buffer and a length variable in a C formatted file. | Incorporating text files in applications? | [
"",
"c++",
"file",
"import",
"text-files",
""
] |
When I moved a program from a Mac to this Windows PC, the VC++ 2008 compiler is giving me errors for passing unsigned ints to the cmath pow() function. As I understand, this function is not overloaded to accept anything but floating-point numbers.
Is there some compiler flag/setting that will ignore these errors? Also does anyone know how to find the documentation on the VC++ compiler?
## Edit
This isn't a *warning*, it's an *error*. However, for me it's not an issue since my program is only dealing with numbers that come out as integers, so I don't care that they aren't floats. If it was just warnings I would move on with my life, but it's not letting me compile. Can I suppress errors somehow? Like I said, the errors aren't coming up on my Mac and the program is fine. | Regarding other answers here, it is not a good idea to tell the question author to turn off this warning. His code is broken - he's passing an unsigned int instead of a float. You should be telling him to fix his code!
> This isn't a warning, it's an error. However, for me it's not an issue since my
> program is only dealing with numbers that come out as integers, so I don't care that
> they aren't floats. If it was just warnings I would move on with my life, but it's not
> letting me compile. Can I suppress errors somehow? Like I said, the errors aren't
> coming up on my Mac and the program is fine.
Integers and floats use different representations internally. If you have the same number in an int and a float, the bit pattern inside the storage for them is *completely different*. You cannot *under any circumstances whatsoever* expect your code to work if you are passing an integer when you should be passing a float.
Furthermore, I assert your Mac code either is silently using an overloaded version of that function (e.g. you are on that platform compiling with C++) or you believe it works when in fact it is working by chance or is not actually working.
## Addendum
No compilers ever written has the ability to turn off errors.
A warning means *the compiler thinks you're making a mistake*.
An error means *the compiler doesn't know what to do*. | There are a couple of options:
In C, the solution is simply to cast the ints to doubles:
```
pow((double)i, (double)j)
```
In C++, you can do the same, although you should use a C++-style cast:
```
pow(static_cast<double>(i), static_cast<double>(j))
```
But a better idea is to use the overload C++ provides:
```
std::pow(static_cast<double>(i), j);
```
The base still has to be a floating-point value, but the exponent can be an int at least
The std:: prefix probably isn't necessary (most compilers make the function available in the global namespace as well).
Of course, to access the C++ versions of the function, you have to include the C++ version of the header.
So instead of `#include <math.h>` you need to `#include <cmath>`
C++ provides C++ versions of every C header, using this naming convention. If the C header is called `foo.h`, the C++ version will be `cfoo`. When you're writing in C++, you should always prefer these versions. | VC++ compiler and type conversion? | [
"",
"c++",
"visual-studio",
"compiler-construction",
"types",
"cmath",
""
] |
I use wxWidgets to create test tools at work. I have always created the GUI by creating the widgets in code. I haven't tried any of the tools available that help to do this. How do other users of wxWidgets typically create their interface? If you use a tool, which tool do you use? If you use a tool, what advantages and disadvantages do you think there are for using that tool? | I've used [wxFormBuilder](http://wxformbuilder.org/) for two reasons:
1. It's cross-platform and I needed something that would work on Linux.
2. I'm new to wxWidgets and I didn't want to spend lots of time futzing about with building the GUI.
I think it works quite well, and being familiar with similar GUI building tools (Borland C++ Builder, Jigloo for Java, Delphi) I found it easy to use.
If you stick with the paradigm of using wxFormBuilder to generate base classes, and then you make a class that inherits to layer your application specific logic on top, absolutely not hand-editing the C++ code wxFormBuilder generates, then it works well and you can easily update and modify your GUIs in wxFormBuilder again (and again...).
*Advantages:*
* Can generate your base GUIs quite quickly, in a visual manner, without having to constantly look up the documentation.
* Don't have to do as many code/compile/run cycles just to make sure your GUI is looking like what you expected.
* The base class/derived class paradigm can make a reasonably clean separation of your GUI and business logic code.
*Potential Disadvantages*
* *Disclaimer:* I've only used wxWidgets to create very simple, straight-forward GUIs, so haven't really pushed the tool to any limits.
* Potentially the base class/derived class paradigm could sometimes get in your way if you are doing something too sophisticated with your GUI (OTOH that could indicate that you may need to re-think your approach.)
* I had a situation where I needed a menu item when compiled for one operating system, but not when compiled for another. There is no logic in wxFormBuilder to support this. I ended up taking the short-cut of always creating the menu item and then having my derived class make it invisible if it was the wrong OS (not ideal.)
That's about it, I think. | What I find is that I often build the first cut at a GUI using a tool, and when it seems to be converging on the "final" form, I start to recode/refactor by hand.
Some of this depends on the tools, though, too. I'm not a big wxWidget fan. | What is the preferred method for creating a wxWidget application: using a GUI tool or procedurally in code? | [
"",
"c++",
"user-interface",
"wxwidgets",
"gui-designer",
""
] |
```
<?php
/* Copyright Date
--------------------------*/
function copyright_date($creation_year) {
$current_year = date('Y');
if ($creation_year == $current_year || $creation_year == '') {
echo $current_year;
}
else {
echo $creation_year . '-' . $current_year;
}
}
?>
```
If someone forgets to add the argument (the year the website was created), e.g.
```
<?php copyright_date(); ?>
```
instead of:
```
<?php copyright_date(2009); ?>
```
**how would I test to see if the argument was left blank?** In my if statement, that's what $creation\_year == '' is for, but since the argument isn't a string, it doesn't work. | Make `$creation_year` an optional argument with a default value of `NULL`.
```
function copyright_date($creation_year=NULL) {
```
Now inside the function just test if `$creation_year` is equal to `NULL`, which will happen when the function is called with no arguments. | Actually I think you MUST use [`func_num_args()`](https://www.php.net/manual/en/function.func-num-args.php). It's much more safer in practice.
```
function copyright_date($creation_year = NULL) {
if(!func_num_args()) {
// Nothing passed to the function
}
}
```
why? Because if you set a default value, let's say `function copyright_date($creation_year = NULL)` you wouldn't know if NULL is passed. Also `isset()` returns `true` if you set a default value. | If no arguments are provided in the function, how do I test to see if it is left blank? | [
"",
"php",
""
] |
I have multiple results sets coming back from a server request against a datasource. I want to organise these with a WinForms tabPage for each result set, on a single tabControl. I am displaying the data in a DataGridView, but want to avoid having a DataGridView instance on each tabPage - I'd rather intercept the "switching to new tab page" message, and load up the appropriate results set from my local cache. Is there an easy/obvious way to do this? | Create a tab control as usual and then put a DataGridView on top of it (be sure not to put it inside a tab page).
Subscribe to the SelectedIndexChanged event and reload the data when the event fires. | Why would you want to do this? You'd lose the designability per result set (unless they're all the same structure) and have to manage all of this yourself. | Tab control + DataGridView in WinForms | [
"",
"c#",
"winforms",
"user-interface",
""
] |
I would like to use a GroupTemplate to separate a list of items into groups. However, I need each Group to be numbered sequentially so I can link to them and implement some JS paging. I'm binding to an IEnumerable
Here's some pseudo code. I would like the output to look like this:
```
<a href="#group1">Go to Group 1<a>
<a href="#group2">Go to Group 2<a>
<a href="#group3">Go to Group 3<a>
<ul id="group1">
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
<ul id="group2">
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
<ul id="group3">
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
```
Is this easy to do in a ListView, using GroupTemplate and ItemTemplate?
```
<asp:ListView ID="lv" runat="server" GroupPlaceholderID="groupPlaceholder">
<LayoutTemplate>
<asp:PlaceHolder ID="groupPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate>
<GroupTemplate>
<ul id="<!-- group-n goes here -->">
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</ul>
</GroupTemplate>
<ItemTemplate>
<li>Item</li>
</ItemTemplate>
</asp:ListView>
```
I can get the number of groups to do the links at the top from the Datasource and basic math, but how do I get **id="groupN"** number into the template? | I don't think you can DataBind the id, so I'd probably either use a hidden field, have JQuery count them up, or use the CssClass. You can use `Container.DataItemIndex` to get your number.
Edit: By just changing the `ul` to be runat="server", ASP.NET will generate a unique id for you in it's infamous INamingContainer format. That will include an index as well, though it'll be something like `lv_ctrl0_group`, and is an implementation detail.
You could hook a handler to the `ul`'s Init event and append a number to it, making it something like `lv_ctrl0_group1`. I don't think you can get rid of the prepended INamingContainer stuff very easily, and this would probably break any IPostDataHandler controls.
```
<script runat="server">
void Group_Init(object sender, EventArgs e) {
((Control)sender).ID += groupId++.ToString();
}
int groupId = 0;
</script>
<asp:ListView id="lv" runat="server" GroupItemCount="3">
<LayoutTemplate>
<asp:PlaceHolder ID="groupPlaceHolder" runat="server" />
</LayoutTemplate>
<GroupTemplate>
<ul id="group" runat="server" oninit="Group_Init">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server"/>
</ul>
</GroupTemplate>
<ItemTemplate>
<li>Item</li>
</ItemTemplate>
</asp:ListView>
``` | In your aspx file:
```
<GroupTemplate>
<ul id='<%# "group"+GroupNumber %>'>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</ul>
</GroupTemplate>
```
In your code behind (assuming C#):
```
int _GroupNumber=0;
protected string GroupNumber
{
get { return (++_GroupNumber).ToString(); }
}
``` | Can I Number a GroupTemplate or ItemTemplate? | [
"",
"c#",
"asp.net",
"listview",
"paging",
""
] |
In Java 1.4, is there any better way of getting a Thread's ID than using `Thread.getName()`?
I mean, `getName()` in unit tests returns something like `"Thread-1"`, but in WebLogic 10 I get `"[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'.xml"`. | [Thread.getId](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getId()) (it can theoretically [overflow](https://stackoverflow.com/questions/591627/thread-getid-global-uniqueness-question), but it is defined not to and in practice will not).
1.5 is going through its End of Service Life period now, but if you are using old dusty-decks 1.4, then you can implement your own with [`ThreadLocal`](http://java.sun.com/javase/6/docs/api/java/lang/ThreadLocal.html). (Note, don't follow the Java SE 6 API docs too closely!) | Why do you need this? Because depending on your answer, there are several approaches.
First, understand that a thread's name is not guaranteed to be unique. Nor is identity hashcode.
If you truly want to associate a unique ID to a thread, you're going to need to do it yourself. Probably using an IdentityHashMap. However, that will introduce a strong reference that you don't want to have hanging around in a production app.
Edit: TofuBeer has solution that's probably better, although the docs note that thread IDs can be reused. | Get unique identifier of a Thread in Java 1.4 | [
"",
"java",
"multithreading",
"uniqueidentifier",
""
] |
I am trying to convert a generic collection (List) to a DataTable. I found the following code to help me do this:
```
// Sorry about indentation
public class CollectionHelper
{
private CollectionHelper()
{
}
// this is the method I have been using
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
table.Rows.Add(row);
}
return table;
}
public static DataTable CreateTable<T>()
{
Type entityType = typeof(T);
DataTable table = new DataTable(entityType.Name);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (PropertyDescriptor prop in properties)
{
// HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES
table.Columns.Add(prop.Name, prop.PropertyType);
}
return table;
}
}
```
My problem is that when I change one of the properties of MySimpleClass to a nullable type, I get the following error:
`DataSet does not support System.Nullable<>.`
How can I do this with Nullable properties/fields in my class? | Then presumably you'll need to lift them to the non-nullable form, using `Nullable.GetUnderlyingType`, and perhaps change a few `null` values to `DbNull.Value`...
Change the assignment to be:
```
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
```
and when adding the columns to be:
```
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
prop.PropertyType) ?? prop.PropertyType);
```
And it works. (`??` is the null-coalescing operator; it uses the first operand if it is non-null, else the second operand is evaluated and used) | Well. Since DataSet does not support nullable types, you'd have to check if the property is a generic type, get the generic definition of that type and then get the argument (which is the actual type) using, perhaps, `Nullable.GetUnderlyingType`. If the value is null, just use `DBNull.Value` in the DataSet. | .NET - Convert Generic Collection to DataTable | [
"",
"c#",
"generics",
"collections",
"datatable",
"nullable",
""
] |
I'm using the module pattern in Javascript to separate my public interface from the private implementation. To simplify what I'm doing, my code generates a chart. The chart consists of multiple parts (axises, labels, plot, legend, etc.) My code looks like:
```
var Graph = function() {
var private_data;
function draw_legend() { ... }
function draw_plot() { ... }
function helper_func() { ... }
...
return {
add_data: function(data) {
private_data = data;
},
draw: function() {
draw_legend()
draw_plot()
}
}
}
```
Some people advocate only testing the public interface of your classes, which makes sense, but I'd really like to get in some tests to test each of the components separately. If I screw up my draw\_legend() function, I'd like that test to fail, not a test for the public draw() function. Am I on the wrong track here?
I could separate each of the components in different classes, for example make a Legend class. But it seems silly to create a class for what's sometimes just 5-10 lines of code, and it would be uglier because I'd need to pass in a bunch of private state. And I wouldn't be able to test my helper functions. Should I do this anyway? Should I suck it up and only test the public draw()? Or is there some other solution? | There is no way to access inner functions (private) from an outer scope. If you want to test inner functions you might consider adding a public method for testing purposes only. If you are using some sort of a build environment, for example ant, you may pre-process the javascript file for production and remove those test functions.
Actually Javascript is an Object oriented language. It's just not a statitcally typed one. | My solution is just a little bit of hack. QUnit example:
At the top of Qunit test html I have declared:
```
var TEST_AVAILABLE = true;
```
In the testable class I have a fragment like this:
```
if(TEST_AVAILABLE){
this.test={
hasDraft:hasDraft,
isInterpIdIn:isInterpIdIn,
// other private methods
};
}
```
In the QUnit you could verify
```
test( "hello booth", function() {
var b = new Booth();
ok(b);
ok(b.test);
ok(!b.test.hasDraft());
});
``` | Testing private functions in javascript | [
"",
"javascript",
"unit-testing",
""
] |
I have a class "Class" which has a member std::list, I want to search that list/tree for an item, specifically an item with a specific name.
A basic representation of my class is as follows:
```
#include <list>
#include <string>
class Class {
std::string _name;
std::list<Class*> _members;
public:
Class(const std::string& name) : _name(name) {}
void addMember(Class* member) { _members.push_back(member); }
const std::string& name() const { return _name; }
const std::list members() const { return _members; }
Class* findItem(const std::string& name) const { ... }
};
```
I could just do something like this in Class::findItem:
```
Class* Class::findItem(const std::string& n) const {
std::list<Class>::const_iteratior i;
for(i=_members.begin(); i!=_members.end(); ++i)
if((*i)->name() == n) return *i;
for(i=_members.begin(); i!=_members.end(); ++i) {
Class* cls = (*i)->findItem(n);
if(cls) return cls;
}
return 0;
}
```
But, what I want to happen is for findItem() to return the "closest" item to the one searched from.
For instance, if this is my tree, with each letter representing one level in the list hierarchy, and each number representing the items "value". I want findItem(3) to return B(3), rather than C(3).
```
A(1)
|
----------------------------------
B(2) B(3)
| |
--------------------- -----
C(3) C(4) C(4)
| |
---------------- ----------
D(5) D(6) D(7) D(5) D(6)
``` | Use a [breadth-first search](http://en.wikipedia.org/wiki/Breadth-first_search). As you access a node that isn't equal to the query value, you push that node onto the back of the queue. Process nodes from the front of the queue first. The first match you find will be the one closest to the root.
```
Class* Class::findItem(const std::string& n) const {
std::list<Class>::const_iteratior i;
std::queue<Class*> q;
q.push(this);
while (!q.empty()) {
Class *c = q.front(); q.pop();
if (c->name() == n) return c;
for(i=c->_members.begin(); i!=c->_members.end(); ++i)
q.push(i);
}
return NULL;
}
``` | If you do it [breadth-first-search](http://en.wikipedia.org/wiki/Breadth-first_search) style, i.e. first look at all the Bs, then all the Cs, etc., your match node will automatically be the closest. | How can I recursively search a list of lists for an item, getting the "closest" match | [
"",
"c++",
"search",
"tree",
"graph-theory",
"breadth-first-search",
""
] |
I have an iframe and in order to access parent element I implemented following code:
```
window.parent.document.getElementById('parentPrice').innerHTML
```
How to get the same result using jquery?
**UPDATE**: Or how to access iFrame parent page using jquery? | To find in the parent of the iFrame use:
```
$('#parentPrice', window.parent.document).html();
```
The second parameter for the $() wrapper is the context in which to search. This defaults to document. | > how to access iFrame parent page using jquery
window.parent.document.
jQuery is a library on top of JavaScript, not a complete replacement for it. You don't have to replace every last JavaScript expression with something involving $. | how to access iFrame parent page using jquery? | [
"",
"javascript",
"jquery",
"iframe",
""
] |
I have a table with column ID that is identity one. Next I create new non-identity column new\_ID and update it with values from ID column + 1. Like this:
```
new_ID = ID + 1
```
Next I drop ID column and rename new\_ID to name 'ID'.
And how to set Identity on this new column 'ID'?
I would like to do this programmatically! | As far as I know, you have to create a temporary table with the ID field created as IDENTITY, then copy all the data from the original table. Finally, you drop the original table and rename the temporary one. This is an example with a table (named *TestTable*) that contains only one field, called ID (integer, non IDENTITY):
```
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_TestTable
(
ID int NOT NULL IDENTITY (1, 1)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT dbo.Tmp_TestTable ON
GO
IF EXISTS(SELECT * FROM dbo.TestTable)
EXEC('INSERT INTO dbo.Tmp_TestTable (ID)
SELECT ID FROM dbo.TestTable WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_TestTable OFF
GO
DROP TABLE dbo.TestTable
GO
EXECUTE sp_rename N'dbo.Tmp_TestTable', N'TestTable', 'OBJECT'
GO
COMMIT
``` | Looks like SQL Mobile supports altering a columns identity but on SQL Server 2005 didn't like the example from BOL.
So your options are to create a new temporary table with the identity column, then turn Identity Insert on:
```
Create Table Tmp_MyTable ( Id int identity....)
SET IDENTITY_INSERT dbo.Tmp_Category ON
INSERT Into Tmp_MyTable (...)
Select From MyTable ....
Drop Table myTable
EXECUTE sp_rename N'dbo.Tmp_MyTable', N'MyTable', 'OBJECT'
```
Additionally you can try and add the column as an identity column in the first place and then turn identity insert on. Then drop the original column. But I am not sure if this will work. | How to change programmatically non-identity column to identity one? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
"identity",
""
] |
I'm trying to import one of the GWT samples into Eclipse by following the instructions below. But when I browse to the directory containing the "Hello" sample and uncheck "Copy projects into workspace", the Finish button is grayed out, preventing me from completing the import. Any ideas why?
> -- Option A: Import your project into Eclipse (recommended) --
>
> If you use Eclipse, you can simply
> import the generated project into
> Eclipse. We've tested against Eclipse
> 3.3 and 3.4. Later versions will likely also work, earlier versions may
> not.
>
> In Eclipse, go to the File menu and
> choose:
>
> File -> Import... -> Existing
> Projects into Workspace
>
> Browse to the directory containing
> this file, select "Hello".
> Be sure to uncheck "Copy projects into workspace" if it is checked.
> Click Finish. | I had the same problem but found [this](http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/da884d3bcd5c950d/67ad4c450d8824d1?lnk=raot):
> I just tried this on Eclipse 3.4 1)
> Create a project named "Showcase"
> file > new > project
>
> 2) Import the Showcase files
> right-click on the project name
>
> > Import
> > File System
> > From Directory (browse to your eclipse samples installation)
> > Showcase (select the directory in the left panel)
> > Into folder (Showcase should be the default value)
>
> This will import the source into your
> workspace. Use build.xml to build the
> project. The build will fail as the
> gwt-servlet.jar is in a shared
> directory which doesn't get brought
> into the project via this method. | I also encountered this problem but got through it using following steps.
First open up a command prompt and go inside to the project folder using cd command.
then execute this command in there. Be sure to install apache ant before doing this.
```
ant eclipse.generate
```
this will generate .classpath and .project files
now you can import the project into the workspace just as normal way. file->import->general->existing project | No response in Eclipse: File ->Import->Existing Projects into Workspace | [
"",
"java",
"eclipse",
"gwt",
"import",
""
] |
I'm wondering if there is an enum type in some standard Java class library that defines symbolic constants for all of the valid HTTP response codes. It should support conversion to/from the corresponding integer values.
I'm debugging some Java code that uses `javax.ws.rs.core.Response.Status`. It works, but it only defines about half of the valid HTTP response codes. | I don't think there's one that's complete in the standard Java classes; **[`HttpURLConnection`](http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html)** is missing quite a few codes, like `HTTP 100/Continue`.
There's a complete list in the Apache HttpComponents, though:
[**`org.apache.http.HttpStatus`**](http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpStatus.html) (replaced [**`org.apache.commons.HttpClient.HttpStatus`**](http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpStatus.html) from Apache Http Client, which reached [end of life](http://hc.apache.org/httpclient-3.x/)) | Well, there are static constants of the exact integer values in the [HttpURLConnection](http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html) class | Does Java have a complete enum for HTTP response codes? | [
"",
"java",
"http",
""
] |
I have a couple of ActionMethods that queries the Controller.User for its role like this
```
bool isAdmin = User.IsInRole("admin");
```
acting conveniently on that condition.
I'm starting to make tests for these methods with code like this
```
[TestMethod]
public void HomeController_Index_Should_Return_Non_Null_ViewPage()
{
HomeController controller = new HomePostController();
ActionResult index = controller.Index();
Assert.IsNotNull(index);
}
```
and that Test Fails because Controller.User is not set.
Any idea? | You need to Mock the ControllerContext, HttpContextBase and finally IPrincipal to mock the user property on Controller. Using Moq (v2) something along the following lines should work.
```
[TestMethod]
public void HomeControllerReturnsIndexViewWhenUserIsAdmin() {
var homeController = new HomeController();
var userMock = new Mock<IPrincipal>();
userMock.Expect(p => p.IsInRole("admin")).Returns(true);
var contextMock = new Mock<HttpContextBase>();
contextMock.ExpectGet(ctx => ctx.User)
.Returns(userMock.Object);
var controllerContextMock = new Mock<ControllerContext>();
controllerContextMock.ExpectGet(con => con.HttpContext)
.Returns(contextMock.Object);
homeController.ControllerContext = controllerContextMock.Object;
var result = homeController.Index();
userMock.Verify(p => p.IsInRole("admin"));
Assert.AreEqual(((ViewResult)result).ViewName, "Index");
}
```
Testing the behaviour when the user isn't an admin is as simple as changing the expectation set on the userMock object to return false. | Using Moq version 3.1 (and NUnit):
```
[Test]
public void HomeController_Index_Should_Return_Non_Null_ViewPage()
{
// Assign:
var homeController = new HomeController();
Mock<ControllerContext> controllerContextMock = new Mock<ControllerContext>();
controllerContextMock.Setup(
x => x.HttpContext.User.IsInRole(It.Is<string>(s => s.Equals("admin")))
).Returns(true);
homeController.ControllerContext = controllerContextMock.Object;
// Act:
ActionResult index = homeController.Index();
// Assert:
Assert.IsNotNull(index);
// Place other asserts here...
controllerContextMock.Verify(
x => x.HttpContext.User.IsInRole(It.Is<string>(s => s.Equals("admin"))),
Times.Exactly(1),
"Must check if user is in role 'admin'");
}
```
Notice that there is no need to create mock for HttpContext, Moq supports nesting of properties when setting up the test. | How to mock Controller.User using moq | [
"",
"c#",
"asp.net-mvc",
"unit-testing",
"mocking",
"moq",
""
] |
Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element):
```
>>> a = ['1', '2', '3', '4']
>>> b = a[:a.index('2')+1] + ['2.4', '2.6'] + a[a.index('2'):]
>>> b
<<< ['1', '2', '2.4', '2.6', '3', '4']
``` | ```
>>> a = ['1', '2', '3', '4']
>>> a
['1', '2', '3', '4']
>>> i = a.index('2') + 1 # after the item '2'
>>> a[i:i] = ['2.4', '2.6']
>>> a
['1', '2', '2.4', '2.6', '3', '4']
>>>
``` | You can easily insert a single element using `list.insert(i, x)`, which Python defines as `s[i:i] = [x]`.
```
a = ['1', '2', '3', '4']
for elem in reversed(['2.4', '2.6']):
a.insert(a.index('2')+1, elem))
```
If you want to insert a list, you can make your own function that omits the []:
```
def iextend(lst, i, x):
lst[i:i] = x
a = ['1', '2', '3', '4']
iextend(a, a.index('2')+1, ['2.4', '2.6']
# a = ['1', '2', '2.4', '2.6', '3', '4']
``` | Simultaneously inserting and extending a list? | [
"",
"python",
""
] |
```
//here assembly is loaded
Assembly asm = Assembly.LoadFile(@"C:\Documents and Settings\E454930\Desktop\nunit_dll_hutt\for_hutt_proj\bin\Debug\for_hutt_proj.dll");
Type type = asm.GetType("for_hutt_proj.class1"); //returning null
object instance = Activator.CreateInstance(type);
```
This is what I did, can anyone see what the mistake is here?
Here type is returning null. What is a fully qualified name
here for\_hutt\_proj is my dll name and class1 is my type name | Looks fine... the only things I wonder is whether the casing of the type-name is correct. You could try:
```
Type type = asm.GetType("for_hutt_proj.class1", false, true);
```
which will do a case-insensitive search.
Also; is `for_hutt_proj` a *namespace* or an *outer-class*? i.e. if it is:
```
class for_hutt_proj {
class class1 {}
}
```
then this is `for_hutt_proj+class1` in terms of fully-qualified names. Namespaces remain as `.` - i.e.
```
namespace for_hutt_proj {
class class1 {}
}
``` | Seems fine. Try posting more info, and use formatting. | Type is returning null for a loaded assembly? | [
"",
"c#",
""
] |
I have created a DLL that will gather information from the AssemblyInfo.cs. In the class constructor I am using Reflection to get the top-most application that is running.
```
public class AppInfo()
{
public AppInfo()
{
System.Reflection.Assembly assembly =
System.Reflection.Assembly.GetEntryAssembly();
if (assembly == null)
assembly = System.Reflection.Assembly.GetCallingAssembly();
//code to gather needed information
}
}
```
How this is intended to be used is if I call this from any DLL in a given application, MyApp, that lets say the name will always be 'MyApp'. Retrieving that information is not a problem and it works great in Windows Services and Windows Applications. My question is this:
**How do I get the Assembly of the top-most Website?**
I have found a few articles and I can get the information in the Global.asax.cs by moving the AssemblyInfo.cs for the Website out of the App\_Code folder and into the root of the Website. Then by adding a compilerOption to the physical path of the AssemblyInfo.cs
```
<compiler
language="c#;cs;csharp"
extension=".cs"
compilerOptions="C:\Sandbox\MyWebSite\AssemblyInfo.cs"
type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
```
Using that I am able to retrieve information in the AssemblyInfo.cs for the Website through `System.Reflection.Assembly.GetExecutingAssembly()`. Now I can overload the constructor of my `AppInfo` class to accept an `Assembly` and retrieve information that way, but if another DLL that is used by `MyWebSite` creates a `new AppInfo()` I will get the assembly information of that DLL instead of the parent Website.
I know that if I was working with Web Apps instead of Web Sites I wouldn't have this issue, but for reasons I won't go into I am not able to use Web Apps. Any suggestions on how I can read information from the AssemblyInfo.cs of the Website I'm running in no matter what DLL I'm in?
**EDIT:** I need this to work for Web Sites, Windows Apps and Windows Services | If I understand you properly, the problem is that `Assembly.GetEntryAssembly()` returns null in a Website and `Assembly.GetCallingAssembly()` is returning the wrong thing because you've got a chain of calls resulting in the website not being the immediate caller. If that's the case, you could find the "Entry Assembly" using the stack trace & walking back up the calling frames. The stack will be full of references from System.Web, etc as the call will have originated from deep within IIS somewhere, but you should be able to pick out the assembly you're interested in by grabbing the lowest frame that you can positively identify as belonging to you. Note that this is pretty hacky, but I think it'll get you what you want...
```
var trace = new StackTrace();
Assembly entryAssembly = null;
foreach (var frame in trace.GetFrames())
{
var assembly = frame.GetMethod().DeclaringType.Assembly;
//check if the assembly is one you own & therefore could be your logical
//"entry assembly". You could do this by checking the prefix of the
//Assembly Name if you use some standardised naming convention, or perhaps
//looking at the AssemblyCompanyAttribute, etc
if ("assembly is one of mine")
{
entryAssembly = assembly;
}
}
```
Hopefully someone else will be able to come up with a less nasty way of doing it... but if you're really stuck, this might help. | AppDomains are created per website and then the bin\*.dll files are loaded into that Application's AppDomain. There is not a "Master Assembly" of the site, at least any that has any special meaning.
It is a process. [System.Web.Hosting.ProcessHost](http://msdn.microsoft.com/en-us/library/system.web.hosting.processhost.aspx) which creates a [System.Web.ApplicationHost](http://msdn.microsoft.com/en-us/library/system.web.hosting.applicationhost.aspx) through a combination of the [System.Web.Hosting.ApplicationManger](http://msdn.microsoft.com/en-us/library/system.web.hosting.applicationmanager.aspx) and [System.Web.Hosting.Environment](http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.aspx) which then creates a System.AppDomain for the application.
AppDomain is secured pretty well so unless you know how to get into an AppDomain, you're out of luck.
If you can update your question, someone may be able to help more.
You **MAY** be able to do this if security is not setup properly"
```
String binDir = Server.MapPath("/bin/");
Response.Write(String.Format("Bin dir:{0}<br/><br/>",binDir));
foreach (string file in Directory.GetFiles(binDir, "*.dll"))
{
Response.Write(String.Format("File:{0}<br/>", file));
try
{
Assembly assembly = Assembly.LoadFile(file);
object[] attrinutes = assembly.GetCustomAttributes(true);
foreach (var o in attrinutes)
{
//AssemblyCompanyAttribute is set in the AssemblyInfo.cs
if (o is AssemblyCompanyAttribute)
{
Response.Write(String.Format("Company Attribute: Company = {0}<br/>", ((AssemblyCompanyAttribute)o).Company));
continue;
}
Response.Write(String.Format("Attribute: {0}<br/>", o));
}
}
catch(Exception ex)
{
Response.Write(String.Format("Exception Reading File: {0} Exception: {1}",file,ex));
}
}
```
You are assuming alot here that the Master site is not compiled (has a App\_Code directory) and resides in the same Application Pool as your child site. Do you have needed access to do this? Is the master site a shared hosting site or something? | Accessing information in the AssemblyInfo.cs using Reflection in a Web Site | [
"",
"c#",
"asp.net",
"reflection",
"web",
"assemblies",
""
] |
I need an embedded database for one of our .net applications.
This database should support sql (Unlike Berkley).
Can anyone suggest any options. | The major options I can think of are:
* [SQLite](http://www.sqlite.org/)
* [SQL Server Compact](http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx) (Linq Support)
* [VistaDB](http://www.vistadb.com/) (Linq Support)
* [SharpHSQL](http://www.codeplex.com/sharphsql)
* [Embedded Firebird](http://www.firebirdsql.org/dotnetfirebird/embedded-firebird-documentation.html)
* [Blackfish SQL](http://www.codegear.com/products/blackfish) | I just wanted to chime in late here with more information on VistaDB.
Our SQL Syntax is very close with SQL Server syntax, and we include TSQL and CLR Stored Procs.
Runs in process with your application, and you only have to deploy 1 assembly for both 32 and 64 bit (100% managed code). You can't do this with SQL CE since you have different unmanaged assemblies that have to be deployed.
You can embed VistaDB with your app and even ILMERGE it, change the database name, etc to fully hide the engine from your users (some people are real big on this).
And yes it can also run on Mono since it is 100% managed code. There are still a few issues (including non-Intel Mono machines).
Full disclosure - I am the owner of the company | Embedded database for .net | [
"",
".net",
"sql",
"embedded-database",
""
] |
I was playing with recursive lambdas in C# and have found two approaches to do this on the web. One approach uses [fixed point combinator](http://en.wikipedia.org/wiki/Y_combinator) and the other does not. In the code below f1 is built using combinator, and f2 is defined directly. My question is, do we need fixed point combinators in C# or the language already provides all we need, so we can leave them alone?
```
class Program
{
static Func<T, T> F<T>(Func<Func<T,T>,Func<T,T>> f)
{
return x => f(F(f))(x);
}
static void Main(string[] args)
{
Func<Func<int,int>,Func<int,int>> f = fac => x => x == 0 ? 1 : x * fac(x - 1);
var f1 = F(f);
Console.WriteLine(f1(5));
Func<int, int> f2 = null;
f2 = x => x == 0 ? 1 : x * f2(x - 1);
Console.WriteLine(f2(5));
}
}
``` | As we can give a name to a method, that means that the language already has the necessary support for recursion built into it.
Note that the second method given in your question involves changing the value of a variable after it has been introduced, making it not "pure" functional programming.
Y-combinator is only necessary if your system of functional calculus doesn't have a built-in notion of a function that can refer to its own definition by name before the definition is completely defined. C# has two ways to do that directly: 1. initially defining the function variable as null and 2. declaring an ordinary named method (by far the preferred technique). | I think it can be rather elegant with an extra utility class called Recursive as follows:
```
public static class Recursive {
public static Func<R> Func<R>(
Func<Func<R>, Func<R>> f) {
return () => f(Func(f))(); }
public static Func<T1, R> Func<T1, R>(
Func<Func<T1, R>, Func<T1, R>> f) {
return x => f(Func(f))(x); }
public static Func<T1, T2, R> Func<T1, T2, R>(
Func<Func<T1, T2, R>, Func<T1, T2, R>> f) {
return (a1, a2) => f(Func(f))(a1, a2);
}
//And so on...
}
class Program {
static void Main(string[] args) {
Console.WriteLine(
Recursive.Func<int, int>(factorial =>
x => x == 0 ? 1 : factorial(x - 1) * x
)
(10)
);
Console.WriteLine(
Recursive.Func<int,int,int>(gcd =>
(x,y) =>
x == 0 ? y:
y == 0 ? x:
x > y ? gcd(x % y, y):
gcd(y % x, x)
)
(35,21)
);
}
}
``` | Do we need fixed point combinators in C#? | [
"",
"c#",
"functional-programming",
"lambda",
""
] |
I have a little control-panel, just a little application that I made. I would like to minimize/put the control-panel up/down with the systemicons, together with battery life, date, networks etc.
Anyone that can give me a clue, link to a tutorial or something to read? | As of Java 6, this is supported in the [`SystemTray`](http://docs.oracle.com/javase/7/docs/api/java/awt/SystemTray.html) and [`TrayIcon`](http://docs.oracle.com/javase/7/docs/api/java/awt/TrayIcon.html) classes. `SystemTray` has a pretty extensive example in its Javadocs:
```
TrayIcon trayIcon = null;
if (SystemTray.isSupported()) {
// get the SystemTray instance
SystemTray tray = SystemTray.getSystemTray();
// load an image
Image image = Toolkit.getDefaultToolkit().getImage("your_image/path_here.gif");
// create a action listener to listen for default action executed on the tray icon
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// execute default action of the application
// ...
}
};
// create a popup menu
PopupMenu popup = new PopupMenu();
// create menu item for the default action
MenuItem defaultItem = new MenuItem(...);
defaultItem.addActionListener(listener);
popup.add(defaultItem);
/// ... add other items
// construct a TrayIcon
trayIcon = new TrayIcon(image, "Tray Demo", popup);
// set the TrayIcon properties
trayIcon.addActionListener(listener);
// ...
// add the tray image
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
// ...
} else {
// disable tray option in your application or
// perform other actions
...
}
// ...
// some time later
// the application state has changed - update the image
if (trayIcon != null) {
trayIcon.setImage(updatedImage);
}
// ...
```
You could also check out [this article](http://www.oracle.com/technetwork/articles/javase/systemtray-139788.html), or [this tech tip](http://blogs.oracle.com/CoreJavaTechTips/entry/getting_to_know_system_tray). | **It's very simple**
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class SystemTrayDemo{
//start of main method
public static void main(String []args){
//checking for support
if(!SystemTray.isSupported()){
System.out.println("System tray is not supported !!! ");
return ;
}
//get the systemTray of the system
SystemTray systemTray = SystemTray.getSystemTray();
//get default toolkit
//Toolkit toolkit = Toolkit.getDefaultToolkit();
//get image
//Toolkit.getDefaultToolkit().getImage("src/resources/busylogo.jpg");
Image image = Toolkit.getDefaultToolkit().getImage("src/images/1.gif");
//popupmenu
PopupMenu trayPopupMenu = new PopupMenu();
//1t menuitem for popupmenu
MenuItem action = new MenuItem("Action");
action.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Action Clicked");
}
});
trayPopupMenu.add(action);
//2nd menuitem of popupmenu
MenuItem close = new MenuItem("Close");
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
trayPopupMenu.add(close);
//setting tray icon
TrayIcon trayIcon = new TrayIcon(image, "SystemTray Demo", trayPopupMenu);
//adjust to default size as per system recommendation
trayIcon.setImageAutoSize(true);
try{
systemTray.add(trayIcon);
}catch(AWTException awtException){
awtException.printStackTrace();
}
System.out.println("end of main");
}//end of main
}//end of class
```
Set appropriate **path** for image and then run the program. t.y. :) | How do I put a Java app in the system tray? | [
"",
"java",
"system-tray",
"minimize",
""
] |
I have a class `Bar` with a private field containing the reference type `Foo`. I would like to expose `Foo` in a public property, but I do not want the consumers of the property to be able to alter `Foo`... It should however be alterable internally by `Bar`, i.e. I can't make the field `readonly`.
So what I would like is:
```
private _Foo;
public Foo
{
get { return readonly _Foo; }
}
```
...which is of course not valid. I could just return a clone of `Foo` (assumming that it is `IClonable`), but this is not obvious to the consumer. Should I change the name of the property to `FooCopy`?? Should it be a `GetCopyOfFoo` method instead? What would you consider best practice? Thanks! | It sounds like you're after the equivalent of "const" from C++. This doesn't exist in C#. There's no way of indicating that consumers can't modify the properties of an object, but something else can (assuming the mutating members are public, of course).
You could return a clone of the Foo as suggested, or possibly a *view* onto the Foo, as [ReadOnlyCollection](http://msdn.microsoft.com/en-us/library/ms132474.aspx) does for collections. Of course if you could make `Foo` an immutable type, that would make life simpler...
Note that there's a big difference between making the *field* readonly and making the object itself immutable.
Currently, the type itself could change things in both ways. It could do:
```
_Foo = new Foo(...);
```
*or*
```
_Foo.SomeProperty = newValue;
```
If it only needs to be able to do the second, the field could be readonly but you still have the problem of people fetching the property being able to mutate the object. If it only needs to do the first, and actually `Foo` is either already immutable or could be made immutable, you can just provide a property which only has the "getter" and you'll be fine.
It's *very important* that you understand the difference between changing the value of the field (to make it refer to a different instance) and changing the contents of the object that the field refers to. | Unfortunately, there's no easy way around this in C# at the moment. You could extract the "read only part" of `Foo` in an interface and let your property return that instead of `Foo`. | How to make a reference type property "readonly" | [
"",
"c#",
"properties",
"encapsulation",
"readonly",
""
] |
I got a `list<list<string>>`
in `list[x][0]` are records from which I want to choose unique records thus such record wouldn't be in any other `list[x][0`], when I choose it, i'd like whole row `list[x]` to be chosen. I haven't found the appropriate exapmple for this in Linq, please help :(
**EDIT**
When Jon Skeet asks me to clarify, I can't deny ;-)
```
list<list<string>>
```
contains list of string table . Each of the string "table" contains several keys `list[x][several_items]` and I want to get unique records from list-> meaning FIRST item in that "table".
Thus:
```
item[0] = "2","3","1","3"
item[1] = "2","3","4","2"
item[3] = "10","2"
item[4]= "1","2"
```
-> unique would mean that I can derive rows `item[3] and item[4]` as unique. because first occurence of number/string is important.
If there are 2 or more records/rows (`item[x] of which first item (item[x][0])` exists more than once in the list, it's not unique.
First element of each list is important to determine uniqueness. Maybe it'd be easier if someone can help to find a way to find non-unique -> so from the above example the list I'd get only item[0] and item[1] | EDIT: I've updated the `UniqueBy` implementation at the bottom to be significantly more efficient, and only iterate through the source once.
If I've understood you correctly (the question is pretty unclear - it would really help if you could provide an example) this is what you want:
```
public static IEnumerable<T> OnlyUnique<T>(this IEnumerable<T> source)
{
// No error checking :)
HashSet<T> toReturn = new HashSet<T>();
HashSet<T> seen = new HashSet<T>();
foreach (T element in source)
{
if (seen.Add(element))
{
toReturn.Add(element);
}
else
{
toReturn.Remove(element);
}
}
// yield to get deferred execution
foreach (T element in toReturn)
{
yield return element;
}
}
```
EDIT: Okay, if you only care about the first element of the list for uniqueness, we need to change it somewhat:
```
public static IEnumerable<TElement> UniqueBy<TElement, TKey>
(this IEnumerable<TElement> source,
Func<TElement, TKey> keySelector)
{
var results = new LinkedList<TElement>();
// If we've seen a key 0 times, it won't be in here.
// If we've seen it once, it will be in as a node.
// If we've seen it more than once, it will be in as null.
var nodeMap = new Dictionary<TKey, LinkedListNode<TElement>>();
foreach (TElement element in source)
{
TKey key = keySelector(element);
LinkedListNode<TElement> currentNode;
if (nodeMap.TryGetValue(key, out currentNode))
{
// Seen it before. Remove if non-null
if (currentNode != null)
{
results.Remove(currentNode);
nodeMap[key] = null;
}
// Otherwise no action needed
}
else
{
LinkedListNode<TElement> node = results.AddLast(element);
nodeMap[key] = node;
}
}
foreach (TElement element in results)
{
yield return element;
}
}
```
You'd call it with:
```
list.UniqueBy(row => row[0])
``` | Something like this, perhaps?
I'm now fairly sure this would work for you, given your clarification :)
```
var mylist = new List<List<string>>() {
new List<string>() { "a", "b", "c" },
new List<string>() { "a", "d", "f" },
new List<string>() { "d", "asd" },
new List<string>() { "e", "asdf", "fgg" }
};
var unique = mylist.Where(t => mylist.Count(s => s[0] == t[0]) == 1);
```
`unique` now contains the "d" and "e" entries from above. | Any chance to get unique records using Linq (C#)? | [
"",
"c#",
"linq",
"unique",
""
] |
```
declare @test varchar(20)
set @test = 'VALUE'
exec('
select '+@test+'
')
```
This returns:
> Invalid column name 'VALUE'.
Is there an alternate method to display the variable value on the select statement? | cmsjr has a point about not needing exec for this. But assuming you're posting a simplified version of the problem and exec is a requirement:
There's no column named "value" because there's no table. If you just want it to print `value`, you need to encase it in quotes so it looks like a string literal inside the call to exec:
```
exec(' select ''' + @test + ''' ')
``` | The clean alternative is to use [sp\_executesql()](http://msdn.microsoft.com/en-us/library/ms188001.aspx) and its ability to deal with parameterized statements:
```
DECLARE @test VARCHAR(20)
DECLARE @stmt NVARCHAR(100)
DECLARE @parm NVARCHAR(100)
SET @stmt = N'SELECT @val' /* statement definition */
SET @parm = N'@val VARCHAR(20)' /* parameters definition */
SET @test = 'VALUE'
EXECUTE sp_executesql @stmt, @parm, @val = @test
```
Yields:
```
(no column name)
VALUE
``` | TSQL: Variable scope and EXEC() | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I know that Java has beautiful inbuilt support for the HashMaps or HashTables.
Does anybody have knowledge that what kind of hashing functions or techniques are employed by Java language?
Is it possible to tweak those functions to be able to make them more specific to one's application in order to improve performance and reducing access time?
Thanks a lot for reading! | Java allows you to override the `hashCode()` method for your Classes to use a hashing algorithm that is not only well suited to your application, but to your individual types:
```
public class Employee {
private int id;
// Default implementation might want to use "name" for as part of hashCode
private String name;
@Override
public int hashCode() {
// We know that ID is always unique, so don't use name in calculating
// the hash code.
return id;
}
}
``` | Just as a note, if you are going to override hashCode you should also override equals. | Hashing function used in Java Language | [
"",
"java",
"oop",
"hash",
"function",
""
] |
Overview:
I have three tables 1) subscribers, bios, and shirtsizes and i need to find the subscribers without a bio or shirtsizes
the tables are laid out such as
**subscribers**
```
| season_id | user_id |
```
**bio**
```
| bio_id | user_id |
```
**shirt sizes**
```
| bio_id | shirtsize |
```
And I need to find all users who do not have a bio or shirtsize, (if no bio; then no shirtsize via relation) for any given season.
I originally wrote a query like:
```
SELECT *
FROM subscribers s
LEFT JOIN bio b ON b.user_id = subscribers.user_id
LEFT JOIN shirtsizes ON shirtsize.bio_id = bio.bio_id
WHERE s.season_id = 185181 AND (bio.bio_id IS NULL OR shirtsize.size IS NULL);
```
but it is taking 10 seconds to complete now.
I am wondering how I can restructure the query (or possibly the problem) so that it will preform reasonably.
Here is the mysql explain: (ogu = subscribers, b = bio, tn = shirtshize)
```
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------------+--------+-------------+
| 1 | SIMPLE | ogu | ref | PRIMARY | PRIMARY | 4 | const | 133 | Using where |
| 1 | SIMPLE | b | index | NULL | PRIMARY | 8 | NULL | 187644 | Using index |
| 1 | SIMPLE | tn | ref | nid | nid | 4 | waka2.b.nid | 1 | Using where |
```
The above is pretty sanitized, here's the realz info:
```
mysql> DESCRIBE subscribers
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| subscribers | int(11) | NO | PRI | | |
| uid | int(11) | NO | PRI | | |
mysql> DESCRIBE bio;
+-------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| bio_id | int(10) unsigned | NO | PRI | 0 | |
| uid | int(10) unsigned | NO | PRI | 0 | |
mysql> DESCRIBE shirtsize;
+-------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| bio_id | int(10) unsigned | NO | PRI | 0 | |
| shirtsize | int(10) unsigned | NO | PRI | 0 | |
```
and the real query looks like:
```
SELECT ogu.nid, ogu.is_active, ogu.uid, b.nid AS bio_node, tn.nid AS size
FROM og_uid ogu
LEFT JOIN bio b ON b.uid = ogu.uid
LEFT JOIN term_node tn ON tn.nid = b.nid
WHERE ogu.nid = 185033 AND ogu.is_admin = 0
AND (b.nid IS NULL OR tn.tid IS NULL)
```
nid is season\_id or bio\_id (with a type);
term\_node is going to be the shirtsize | The query should be OK. I would run it through a query analyzer and refine the indexes on the tables. | Joins are one of the most expensive operations that you can perform on an SQL query. While it should be able to automatically optimize your query somewhat, maybe try restructuring it. First of all, I would instead of SELECT \*, be sure to specify which columns you need from which relations. This will speed things up quite a bit.
If you only need the user ID for example:
```
SELECT s.user_id
FROM subscribers s
LEFT JOIN bio b ON b.user_id = subscribers.user_id
LEFT JOIN shirtsizes ON shirtsize.bio_id = bio.bio_id
WHERE s.season_id = 185181 AND (bio.bio_id IS NULL OR shirtsize.size IS NULL);
```
That will allow the SQL database to restructure your query a little more efficiently on its own. | Left Joins are what I want but they are very slow? | [
"",
"sql",
"optimization",
"join",
""
] |
Is there anyway to call PHP script from a .Net application and pass in some parameters? | You can do it through a command line call
```
php your-file.php parameter1 parameter2
```
The parameters are available in the `$_SERVER['argv']` variable. | I've got interop with .NET and PHP using web services. You can output XML from both, which means you can call each way. | Call PHP script from .Net application | [
"",
".net",
"php",
""
] |
If I have a list like this:
`>>> data = [(1,2),(40,2),(9,80)]`
how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ? | List comprehensions save the day:
```
first = [x for (x,y) in data]
second = [y for (x,y) in data]
``` | The unzip operation is:
```
In [1]: data = [(1,2),(40,2),(9,80)]
In [2]: zip(*data)
Out[2]: [(1, 40, 9), (2, 2, 80)]
```
Edit: You can decompose the resulting list on assignment:
```
In [3]: first_elements, second_elements = zip(*data)
```
And if you really need lists as results:
```
In [4]: first_elements, second_elements = map(list, zip(*data))
```
To better understand why this works:
```
zip(*data)
```
is equivalent to
```
zip((1,2), (40,2), (9,80))
```
The two tuples in the result list are built from the first elements of zip()'s arguments and from the second elements of zip()'s arguments. | Extract array from list in python | [
"",
"python",
"arrays",
"list",
""
] |
I want a Web Service in C# that returns a Dictionary, according to a search:
```
Dictionary<int, string> GetValues(string search) {}
```
The Web Service compiles fine, however, when i try to reference it, i get the following error:
"is not supported because it implements IDictionary."
¿What can I do in order to get this working?, any ideas not involving return a DataTable? | [This article](http://msdn.microsoft.com/en-us/magazine/cc164135.aspx) has a method to serialize IDictionaries. Look for " I've noticed that XmlSerializer won't serialize objects that implement IDictionary by default. Is there any way around this?" about 2/3 the way down the page. | There's no "default" way to take a Dictionary and turn it into XML. You have to pick a way, and your web service's clients will have to be aware of that same way when they are using your service. If both client and server are .NET, then you can simply use the same code to serialize and deserialize Dictionaries to XML on both ends.
There's code to do this [in this blog post](http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx). This code uses the default serialization for the keys and values of the Dictionary, which is useful when you have non-string types for either. The code uses inheritance to do its thing (you have to use that subclass to store your values). You could also use a wrapper-type approach as done in the last item in [this article](http://msdn.microsoft.com/en-us/magazine/cc164135.aspx), but note that the code in that article just uses ToString, so you should combine it with the first article.
Because I agree with Joel about StackOverflow being the canonical source for everything, below is a copy of the code from the first link. If you notice any bugs, edit this answer!
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}
``` | How to Return Generic Dictionary in a WebService | [
"",
"c#",
"generics",
""
] |
I wrote a program that outputs a Python program that fills my [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) application with data. This program however is 23 MB large and my computer won't run it. Is there a solution for this?
Another possible solution to fill the database would be using a fixture. The problem is that I don't know the new primary keys yet... or I would have to use the old ones (which I don't prefer).
Any suggestions?
The reason for my path: I'm migrating a database that is very different from the new one, it also has many relations. The 23 MB program remembers all objects from the source database, that's why it's not easily cut in half. Maybe there is a better way to do this? I prefer using Django than using raw SQL. | In most cases, you can find a natural hierarchy to your objects. Sometimes there is some kind of "master" and all other objects have foreign key (FK) references to this master and to each other.
In this case, you can use an XML-like structure with each master object "containing" a lot of subsidiary objects. In this case, you insert the master first, and all the children have FK references to an existing object.
In some cases, however, there are relationships that can't be simple FK's to an existing object. In this case you have circular dependencies and you must (1) break this dependency temporarily and (2) recreate the dependency after the objects are loaded.
You do this by (a) defining your model to have an optional FK, (b) and having a temporary "natural key" reference. You'll load data without the proper FK (it's optional).
Then, after your data is loaded, you go back through a second pass and insert all of the missing FK references. Once this is done you can then modify your model to make the FK mandatory.
Program 1 - export from old database to simple flat-file. CSV format or JSON format or something simple.
```
for m in OldModel.objects.all():
aDict = { 'col1':m.col1, 'old_at_fk':m.fktoanothertable.id, 'old_id':id }
csvwriter.writerow( aDict )
```
Program 2 - read simple flat-file; build new database model objects.
```
# Pass 1 - raw load
for row in csv.reader:
new= NewModel.create( **row )
# Pass 2 - resolve FK's
for nm in NewModel.objects.all():
ref1= OtherModel.objects.get( old_id=nm.old_at_fk )
nm.properfk = ref1
nm.save()
``` | Your computer wouldn't run it because is a large program?
Maybe you should reference an external file, or files, with all the structure, and then dump it inside the database, instead of writing it inside your script/software... | Fill Django application with data using very large Python script | [
"",
"python",
"database",
"django",
"migration",
""
] |
What's the best technique for exiting from a constructor on an error condition in C++? In particular, this is an error opening a file.
Thanks for the responses. I'm throwing an exception. Here's the code (don't know if it's the *best* way to do it, but it's simple)
```
// Test to see if file is now open; die otherwise
if ( !file.is_open() ) {
cerr << "Failed to open file: " << m_filename << endl;
throw ("Failed to open file");
}
```
One think I like about C++ is you don't have to declare thrown exceptions on the method declarations. | The best suggestion is probably what parashift says. But read my caution note below as well please.
[See parashift FAQ 17.2](http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.2)
> [17.2] How can I handle a constructor
> that fails?
>
> Throw an exception.
>
> Constructors don't have a return type,
> so it's not possible to use return
> codes. The best way to signal
> constructor failure is therefore to
> throw an exception. If you don't have
> the option of using exceptions, the
> "least bad" work-around is to put the
> object into a "zombie" state by
> setting an internal status bit so the
> object acts sort of like it's dead
> even though it is technically still
> alive.
>
> The idea of a "zombie" object has a
> lot of down-side. You need to add a
> query ("inspector") member function to
> check this "zombie" bit so users of
> your class can find out if their
> object is truly alive, or if it's a
> zombie (i.e., a "living dead" object),
> and just about every place you
> construct one of your objects
> (including within a larger object or
> an array of objects) you need to check
> that status flag via an if statement.
> You'll also want to add an if to your
> other member functions: if the object
> is a zombie, do a no-op or perhaps
> something more obnoxious.
>
> In practice the "zombie" thing gets
> pretty ugly. Certainly you should
> prefer exceptions over zombie objects,
> but if you do not have the option of
> using exceptions, zombie objects might
> be the "least bad" alternative.
---
**A word of caution with throwing exceptions in a constructor:**
Be very careful though because if an exception is thrown in a constructor, the class's destructor is not called. So you need to be careful about destructing objects that you already constructed before the exception is thrown. The same warnings apply to exception handling in general, but it is maybe a little less obvious when dealing with a constructor.
```
class B
{
public:
B()
{
}
virtual ~B()
{
//called after D's constructor's exception is called
}
};
class D : public B
{
public:
D()
{
p = new char[1024];
throw std::exception("test");
}
~D()
{
delete[] p;
//never called, so p causes a memory leak
}
char *p;
};
int main(int argc, char **argv)
{
B *p;
try
{
p = new D();
}
catch(...)
{
}
return 0;
}
```
**Protected/Private constructors with CreateInstance method:**
Another way around this is to make your constructor private or protected and make a CreateInstance method that can return errors. | You can throw an exception, as others have mentioned, or you can also refactor your code so that your constructor can't fail. If, for example, you're working on a project where exceptions are disabled or disallowed, then the latter is your best option.
To make a constructor that can't fail, refactor the code that could potentially fail into an `init()` method, and have the constructor do as little work as possible, and then require all users of the class to call `init()` immediately after construction. If `init()` fails, you can return an error code. Make sure to document this in your class's documentation!
Of course, this is somewhat dangerous, since programmers might forget to call `init()`. The compiler can't enforce this, so tread carefully, and try to make your code fail-fast if `init()` is not called. | What's the best technique for exiting from a constructor on an error condition in C++ | [
"",
"c++",
"constructor",
""
] |
see also "[Any tools to check for duplicate VB.NET code?"](https://stackoverflow.com/questions/2266978/any-tools-to-check-for-duplicate-vb-net-code)
A friend of mine only has access to the Express editions of Visual Studio and I am trying to help him refactor to remove a lot of duplication. | You could take a look at [Simian](http://www.harukizaemon.com/simian/) or [DuplicateFinder](http://duplicatefinder.codeplex.com/). Neither have a dependency on the IDE, although you can [integrate](http://blogs.conchango.com/howardvanrooijen/archive/2006/02/08/2776.aspx) Simian [quite easily](http://blogs.conchango.com/howardvanrooijen/archive/2006/02/18/2888.aspx). | [Clone Detective](http://clonedetectivevs.codeplex.com/) appears as though it might work for you. I haven't used it before, but I stumbled across it on codeplex this week. | What are good tools for identifying potentially duplicated code for C# Express users? | [
"",
"c#",
"visual-studio",
"visual-studio-express",
""
] |
Does anyone have any good c# code (and regular expressions) that will parse a string and "linkify" any urls that may be in the string? | It's a pretty simple task you can acheive it with [Regex](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx) and a ready-to-go regular expression from:
* [http://regexlib.com/](http://regexlib.com/DisplayPatterns.aspx?cattabindex=1&categoryId=2)
Something like:
```
var html = Regex.Replace(html, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+" +
"\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?" +
"([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$",
"<a href=\"$1\">$1</a>");
```
You may also be interested not only in creating links but in shortening URLs. Here is a good article on this subject:
* [Resolve and shorten URLs in C#](http://madskristensen.net/post/resolve-and-shorten-urls-in-csharp)
**See also**:
* [Regular Expression Workbench](http://code.msdn.microsoft.com/RegexWorkbench) at MSDN
* [Converting a URL into a Link in C# Using Regular Expressions](http://rickyrosario.com/blog/converting-a-url-into-a-link-in-csharp-using-regular-expressions)
* [Regex to find URL within text and make them as link](http://weblogs.asp.net/farazshahkhan/archive/2008/08/09/regex-to-find-url-within-text-and-make-them-as-link.aspx)
* [Regex.Replace Method](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx) at MSDN
* [The Problem With URLs](https://blog.codinghorror.com/the-problem-with-urls/) by Jeff Atwood
* [Parsing URLs with Regular Expressions and the Regex Object](http://www.cambiaresearch.com/c4/890160aa-bc4e-40fc-ac36-c1031858c048/Parsing-URLs-with-Regular-Expressions-and-the-Regex-Object.aspx)
* [Format URLs in string to HTML Links in C#](http://snipplr.com/view/13286/format-urls-in-string-to-html-links-in-c/)
* [Automatically hyperlink URL and Email in ASP.NET Pages with C#](http://www.codeproject.com/KB/aspnet/Autohyperlink.aspx) | well, after a lot of research on this, and several attempts to fix times when
1. people enter in <http://www.sitename.com> and www.sitename.com in the same post
2. fixes to parenthisis like (<http://www.sitename.com>) and <http://msdn.microsoft.com/en-us/library/aa752574(vs.85).aspx>
3. long urls like: [http://www.amazon.com/gp/product/b000ads62g/ref=s9\_simz\_gw\_s3\_p74\_t1?pf\_rd\_m=atvpdkikx0der&pf\_rd\_s=center-2&pf\_rd\_r=04eezfszazqzs8xfm9yd&pf\_rd\_t=101&pf\_rd\_p=470938631&pf\_rd\_i=507846](https://rads.stackoverflow.com/amzn/click/com/b000ads62g)
we are now using this HtmlHelper extension... thought I would share and get any comments:
```
private static Regex regExHttpLinks = new Regex(@"(?<=\()\b(https?://|www\.)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|](?=\))|(?<=(?<wrap>[=~|_#]))\b(https?://|www\.)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|](?=\k<wrap>)|\b(https?://|www\.)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static string Format(this HtmlHelper htmlHelper, string html)
{
if (string.IsNullOrEmpty(html))
{
return html;
}
html = htmlHelper.Encode(html);
html = html.Replace(Environment.NewLine, "<br />");
// replace periods on numeric values that appear to be valid domain names
var periodReplacement = "[[[replace:period]]]";
html = Regex.Replace(html, @"(?<=\d)\.(?=\d)", periodReplacement);
// create links for matches
var linkMatches = regExHttpLinks.Matches(html);
for (int i = 0; i < linkMatches.Count; i++)
{
var temp = linkMatches[i].ToString();
if (!temp.Contains("://"))
{
temp = "http://" + temp;
}
html = html.Replace(linkMatches[i].ToString(), String.Format("<a href=\"{0}\" title=\"{0}\">{1}</a>", temp.Replace(".", periodReplacement).ToLower(), linkMatches[i].ToString().Replace(".", periodReplacement)));
}
// Clear out period replacement
html = html.Replace(periodReplacement, ".");
return html;
}
``` | C# code to linkify urls in a string | [
"",
"c#",
"asp.net",
"regex",
"linkify",
""
] |
I am selecting from a database of news articles, and I'd prefer to do it all in one query if possible. In the results, I need a sorting criteria that applies ONLY to the first result.
In my case, the first result must have an image, but the others should be sorted without caring about their image status.
Is this something I can do with some sort of conditionals or user variables in a MySQL query? | Even if you manage to find a query that looks like one query, it is going to be logicaly two queries. Have a look at [MySQL UNION](http://dev.mysql.com/doc/refman/5.0/en/union.html) if you really must make it one query (but it will still be 2 logical queries). You can union the image in the first with a limit of 1 and the rest in the second. | Something like this ensures an article with an image on the top.
```
SELECT
id,
title,
newsdate,
article
FROM
news
ORDER BY
CASE WHEN HasImage = 'Y' THEN 0 ELSE 1 END,
newsdate DESC
```
Unless you define "the first result" closer, of course. This query prefers articles with images, articles without will appear at the end.
Another variant (thanks to le dorfier, who deleted his answer for some reason) would be this:
```
SELECT
id,
title,
newsdate,
article
FROM
news
ORDER BY
CASE WHEN id = (
SELECT MIN(id) FROM news WHERE HasImage = 'Y'
) THEN 0 ELSE 1 END,
newsdate DESC
```
This sorts the earliest (assuming MIN(id) means "earliest") article with an image to the top. | changing sorting criteria after the first result | [
"",
"sql",
"mysql",
"sorting",
""
] |
### Duplicate:
> [Tool to read and display Java .class versions](https://stackoverflow.com/questions/27065/tool-to-read-and-display-java-class-versions)
If I have a compiled Java class, is there a way to tell from just the class file what its target version compatibility is? Specifically, I have a number of class files, compiled to Java 6, which are running under Java 5 and giving the the "Unrecognized version" error. I want to be able to look at a class file and find what its target version compatibility is without running the JVM. Any ideas? | I've found this on the net and it works.
> Every '.class' file starts off with
> the following:
>
> * Magic Number [4 bytes]
> * Version Information [4 bytes]
>
> A hexdump of a '.class' file compiled
> with each of the following options
> reveals:
>
> `javac -target 1.1` ==> `CA FE BA BE 00 03 00 2D`
> `javac -target 1.2` ==> `CA FE BA BE 00 00 00 2E`
> `javac -target 1.3` ==> `CA FE BA BE 00 00 00 2F`
> `javac -target 1.4` ==> `CA FE BA BE 00 00 00 30`
>
> Perhaps you could use this information
> to write your own '.class' file
> version checking utility, using Java,
> or perhaps a scripting or shell
> language ;) !
>
> I hope this helps.
>
> Anthony Borla
From: <http://bytes.com/groups/java/16603-how-determine-java-bytecode-version> | You can use the **javap** utility that comes with the standard JDK.
```
javap -verbose MyClass
Compiled from “MyClass.java”
public class MyClass extends java.lang.Object
SourceFile: “MyClass.java”
minor version: 3
major version: 45
``` | How can I find the target Java version for a compiled class? | [
"",
"java",
"compiler-construction",
""
] |
Is there a Java equivalent to [.NET Reflector](http://www.red-gate.com/products/reflector/)?
Edit: more specifically, decompiling is what I'm after. | From what little I know the functionality of .NET Reflector is available in pretty much all Java IDEs, including Eclipse. Just add a `jar` file to a projects and you can browse its classes just as you browse your own classes.
For the decompiler aspect (as opposed to the pure class browser) there are some alternatives as well. The JDK tool `javap` only decompiles to byte-code so it isn't really useful to get to the source code (but might help with getting an understanding of the code).
[JAD](http://en.wikipedia.org/wiki/JAD_%28JAva_Decompiler%29) is a pretty popular decompiler in the Java world and it produces compilable Java code most of the time (some bytecode sequences aren't easily translatable to valid Java 'though, so some corner cases exist). | See [How do I decompile Java class files?](https://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files) There's a link there to [JD-GUI](http://jd.benow.ca/), which seems to be about what you're looking for.
**Edit:** Also see [Open Java \*.Class Files](https://stackoverflow.com/questions/76314/open-java-class-files).
**Edit 2:** And [Best free Java .class viewer?](https://stackoverflow.com/questions/202586/best-free-java-class-viewer), which specifically mentions .NET Reflector. | Reflector for Java? | [
"",
"java",
".net",
"decompiling",
""
] |
I need to programmatically store data on the client side without having to transfer the data from the server on every page load. I considered generating a dynamic JavaScript file with the needed data for the current session of the user and make sure it is cached, but that seems really messy and there are a few drawbacks I can think of to such an approach.
How can I go about storing persistent data on the client side? | You may store data in `window.name`, which can hold up to 2MB of data (!).
```
/* on page 1 */
window.name = "Bla bla bla";
/* on page 2 */
alert(window.name); // alerts "Bla bla bla"
```
**Edit:** Also have a look at [this Ajaxian article](http://ajaxian.com/archives/whats-in-a-windowname) regarding this.
Note that other sites in the same tab/window does also have access to `window.name`, so you shouldn't store anything confidential here. | You can use the [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) ([`Window.localStorage`](https://developer.mozilla.org/en/docs/Web/API/Window/localStorage) or [`Window.sessionStorage`](https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage)). Check out [this article on html5doctor](http://html5doctor.com/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/) for a more in-depth explanation. The [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) is [supported by all modern browsers](http://caniuse.com/namevalue-storage) at this point.
> The read-only localStorage property allows you to access a Storage object for the Document's origin; **the stored data is saved across browser sessions**. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, **data stored in sessionStorage gets cleared when the page session ends** — that is, when the page is closed.
> <https://developer.mozilla.org/en/docs/Web/API/Window/localStorage>
As highlighted above:
* To store the data indefinitely (until the cache is cleared), use [`Window.localStorage`](https://developer.mozilla.org/en/docs/Web/API/Window/localStorage).
* To store the data until the window is closed, use [`Window.sessionStorage`](https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage).
There are two methods of setting and getting properties via the [`Window.localStorage`](https://developer.mozilla.org/en/docs/Web/API/Window/localStorage) and [`Window.sessionStorage`](https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage) API's:
1. Access the properties directly:
```
localStorage.name = 'ashes999';
console.log(localStorage.name); // ashes999
delete localStorage.name;
console.log(localStorage.name); // undefined
```
```
sessionStorage.name = 'ashes999';
console.log(sessionStorage.name); // ashes999
delete sessionStorage.name;
console.log(sessionStorage.name); // undefined
```
2. Use the [`Storage.setItem`](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem), [`Storage.getItem`](https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem), and [`Storage.removeItem`](https://developer.mozilla.org/en-US/docs/Web/API/Storage/removeItem) API methods.
```
localStorage.setItem('name', 'ashes999');
console.log(localStorage.getItem('name')); // ashes999
localStorage.removeItem('name');
console.log(localStorage.getItem('name')); // undefined
```
```
sessionStorage.setItem('name', 'ashes999');
console.log(sessionStorage.getItem('name')); // ashes999
sessionStorage.removeItem('name');
console.log(sessionStorage.getItem('name')); // undefined
```
### Caveats:
* Browsers may impose limitations on the storage capacity per origin of the [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API), but you should be safe up to 5MB.
* The Web Storage API is limited by the same origin policy.
* Access to Web Storage from third-party IFrames is denied if the user has disabled third-party cookies in Firefox | How to store persistent data client side | [
"",
"javascript",
"persistence",
"storage",
"client-side",
""
] |
Can I write a custom function that I can call when making mySQL queries eg.
My database table has fields 'filetype' and 'filename'. I want to perform a function on filename before returning the result.
```
$query = "SELECT filetype, MY_FUNCTION(filename) FROM table..";
$result = mysql_query($query);
return $result
```
SO $result now has the new values created by MY\_FUNCTION. The original database data will be unchanged.
OK - so it looks like User Defined Functions are the way to go... how do I write my own user defined function? Can I use PHP to write it? Where do I save the function or do I include it in my globals file?
Thanks! | ```
DELIMITER $$
CREATE FUNCTION MY_FUNCTION (FILENAME VARCHAR(255)) RETURNS VARCHAR(255)
DETERMINISTIC
NO SQL
BEGIN
RETURN SUBSTR(filename, 1, 20);
END
$$
DELIMITER ;
```
To create the function, you just paste its code (sililar to provided above) in your favorite query tool, like `mysql.exe`, `MySQL Query Browser`, `phpmysqladmin` etc.
You can write `UDF`'s both in `C` and in `SQL`. In the latter case, you don't need to have a compiler.
The function I provided as an example is an `SQL UDF`. It just returns first `20` characters of the filename.
You can use any `MySQL` functions in an `SQL UDF`. | Yes, this is called [User Defined Functions (UDF)](http://dev.mysql.com/doc/refman/5.0/en/adding-functions.html).
And here is a [good repository](http://www.mysqludf.org/) of already pre-build functions, so you can check if something fits your needs. | Can I write my own mySQL functions to use in mySQL queries? | [
"",
"php",
"mysql",
"function",
""
] |
Let's assume, for instance, an xHTML document as below:
```
<html>
<head>
</head>
<body>
<div id="wrapper">
<div id="sidebar"></div>
<div id="content"></div>
</div>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="./application.js"></script>
</html>
```
We'll be performing a GET AJAX request to a PHP script that will query a database and return a response to populate a `TABLE` element which will be formatted as a sortable grid via JavaScript.
Additionally, we want all of our JavaScript in one file that can easily be included as displayed above.
The options:
1. Have the PHP script return the `TABLE`
element populated with all of the
data. Use jQuery's `live()` function
to actively watch for new `TABLE`
elements in the DOM and apply the
sortable grid functionality when it
discovers them. This method allows us to manipulate the content retruned from the AJAX request in PHP and returns a completed semantic table to the parent document.
2. Insert the `TABLE` element into the script listed above, but leaving it's content empty. jQuery would immediately apply the sortable grid functionality once the document is ready, although no content would exist yet. The GET request would then return a JSON response that would populate the database.
Any other opinions / best practices / use cases you can share for this sort of thing? I am only discussing a `TABLE` here but we have been discussing the issue with a number of things: lightboxes, drop-down menus, etc.
Currently, we are not using jQuery's `live()` function nor do the DOM elements exist within the parent document. So, we are having to place small blocks of Javascript at the top of each of our individual Views. Although sloppy, this has allowed us to only load functionality when it is needed, but it is obviously difficult to maintain. | Its always best to load as much as is reasonable on the initial load. If your site/application requires that you add stuff dynamically via AJAX then I can see you dilemma.
From what I understand, you are wondering what the best/preferred practice would be to keep your JavaScript concise and in on file and not scattered throughout your page. You are saying that currently your scripts are scattered throughout your page because when you are loading in modules/views or whatever they have the js along with them so that when they load their script is run (long-winded, sorry). And, the problem is that you want specific events to be triggered (like instantiating a lightbox or sorting a table) when these views are loaded by using the one omnipotent super global js file.
So, if that sounds right, then here's what I'd do (for any views being loaded in dynamically)...
So, let's assume you have the code you provided:
```
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"z></script>
<script type="text/javascript" src="./application.js"></script>
</head>
<body>
<div id="wrapper">
<div id="sidebar"></div>
<div id="content"></div>
</div>
</body>
</html>
```
If you loaded some content into the '#content' div (say, a table) when the page is fully loaded, and then you wanted to sort that table without putting the script to do so in the HTML that is returned from AJAX, you could have the following code in you main ('./application.js') file:
```
$(function() {
load_table();
$('#content #my_table').live('table_loaded',function() {
$(this).sort(); // or whatever your sorting method is...
});
});
function load_table() {
$.get('mysite.php',{foo:bar,bar:foo},function(data) {
$('#content').html(data).find('#my_table').trigger('table_loaded');
});
}
```
This uses jquery custom events and the live() event. I haven't tested this out but it should work in theory.
**UPDATE:** I tested this and it works perfectly using jquery 1.3.2 :) | The **[jQuery jqGrid Plugin](http://www.trirand.com/blog/)** might fit the bill, loads data dynamically through ajax, can be integrated with any server-side technology, allows you to theme it with theme roller.
To update the table yourself you can issue a callback with most jquery ajax functions when the request completes. For example, if you have this in your document:
```
<div id="output">
<table>...</table>
</div>
```
You can load the result with the jquery [Ajax Load](http://docs.jquery.com/Ajax/load) function:
```
$('#output').load('results.php',{arg:'val'},updateSort);
function updateSort(){
$("#output > table").sort();
}
```
I usually take it a set further:
```
$('#output')
.html('<div class="centered_padded_msg_class">Loading data...</div>')
.load('results.php',{arg:'val'},updateSort);
function updateSort(){
$("#output > table").sort();
}
```
Best of luck, -Matt | Best Practice in Integrating JavaScript Actions w/ DOM | [
"",
"javascript",
"jquery",
""
] |
I've got a bookmarklet which loads jQuery and some other js libraries.
How do I:
* Wait until the javascript library I'm using is available/loaded. If I try to use the script before it has finished loading, like using the $ function with jQuery before it's loaded, an undefined exception is thrown.
* Insure that the bookmarklet I load won't be cached (without using a server header, or obviously, being that this is a javascript file: *a metatag*)
Is anyone aware if onload for dynamically added javascript works in IE? (to contradict this [post](http://answers.google.com/answers/threadview?id=595949))
What's the simplest solution, cleanest resolution to these issues? | It depends on how you are actually loading jQuery. If you are appending a script element to the page, you can use the same technique that jQuery uses to dynamically load a script.
**EDIT**: I did my homework and actually extracted a loadScript function from the jQuery code to use in your bookmarklet. It might actually be useful to many (including me).
```
function loadScript(url, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
// Attach handlers for all browsers
var done = false;
script.onload = script.onreadystatechange = function()
{
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
// Continue your code
callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
// Usage:
// This code loads jQuery and executes some code when jQuery is loaded
loadScript("https://code.jquery.com/jquery-latest.js", function()
{
$('my_element').hide();
});
``` | To answer your first question: Javascript is interpreted sequentially, so any following bookmarklet code will not execute until the library is loaded (assuming the library was interpreted successfully - no syntax errors).
To prevent the files from being cached, you can append a meaningless query string...
```
url = 'jquery.js?x=' + new Date().getTime();
``` | Bookmarklet wait until Javascript is loaded | [
"",
"javascript",
"jquery",
"bookmarklet",
""
] |
There is a simple way to get top N rows from any table:
```
SELECT TOP 10 * FROM MyTable ORDER BY MyColumn
```
Is there any efficient way to query M rows starting from row N
For example,
```
Id Value
1 a
2 b
3 c
4 d
5 e
6 f
```
And query like this
```
SELECT [3,2] * FROM MyTable ORDER BY MyColumn /* hypothetical syntax */
```
queries 2 rows starting from 3d row, i.e 3d and 4th rows are returned. | > **UPDATE** If you you are using SQL 2012 new syntax was added to make this really easy. See [Implement paging (skip / take) functionality with this query](https://stackoverflow.com/questions/13220743/implement-paging-skip-take-functionality-with-this-query)
I guess the most elegant is to use the ROW\_NUMBER function (available from MS SQL Server 2005):
```
WITH NumberedMyTable AS
(
SELECT
Id,
Value,
ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber
FROM
MyTable
)
SELECT
Id,
Value
FROM
NumberedMyTable
WHERE
RowNumber BETWEEN @From AND @To
``` | The problem with the suggestions in this thread and elsewhere on the web is that all the proposed solutions run in linear time with respect to the number of records. For example, consider a query like the following.
```
select *
from
(
select
Row_Number() over (order by ClusteredIndexField) as RowNumber,
*
from MyTable
) as PagedTable
where RowNumber between @LowestRowNumber and @HighestRowNumber;
```
When getting page 1, the query takes 0.577 seconds. However, when getting page 15,619, this same query takes over 2 minutes and 55 seconds.
We can greatly improve this by creating a record number, index cross-table as shown in the following query. The cross-table is called PagedTable and is non-persistent.
```
select *
from
(
select
Row_Number() over (order by Field1 asc, Field2 asc, Field3 asc) as RowNumber,
ClusteredIndexField
from MyTable
) as PagedTable
left join MyTable on MyTable.ClusteredIndexField = PagedTable.ClusteredIndexField
where RowNumber between @LowestRowNumber and @HighestRowNumber;
```
Like in the previous example, I tested this on a very wide table with 780,928 records. I used a page size of 50, which resulted in 15,619 pages.
The total time taken for page 1 (the first page) is 0.413 seconds. The total time taken for page 15,619 (the last page) is 0.987 seconds, merely twice times as long as page 1. These times were measured using SQL Server Profiler and the DBMS was SQL Server 2008 R2.
This solution works for any case when you are sorting your table by an index. The index does not have to be clustered or simple. In my case, the index was composed of three fields: varchar(50) asc, varchar(15) asc, numeric(19,0) asc. That the performance was excellent despite the cumbersome index just further demonstrates that this approach works.
However, it is critical that the order by clause in the Row\_Number windowing function corresponds to an index. Otherwise performance will degrade to the same level as the first example.
This approach does still require a linear operation to generate the non-persistent cross-table, but since that's just an index with a row number added, it happens very quickly. In my case it took 0.347 seconds, but my case had varchars that needed to be copied. A single numeric index would take far less time.
For all practical purposes, this design reduces the scaling of server-side paging from a linear operation to a logarithmic operation allowing the scaling of large tables. Below is the complete solution.
```
-- For a sproc, make these your input parameters
declare
@PageSize int = 50,
@Page int = 15619;
-- For a sproc, make these your output parameters
declare @RecordCount int = (select count(*) from MyTable);
declare @PageCount int = ceiling(convert(float, @RecordCount) / @PageSize);
declare @Offset int = (@Page - 1) * @PageSize;
declare @LowestRowNumber int = @Offset;
declare @HighestRowNumber int = @Offset + @PageSize - 1;
select
@RecordCount as RecordCount,
@PageCount as PageCount,
@Offset as Offset,
@LowestRowNumber as LowestRowNumber,
@HighestRowNumber as HighestRowNumber;
select *
from
(
select
Row_Number() over (order by Field1 asc, Field2 asc, Field3 asc) as RowNumber,
ClusteredIndexField
from MyTable
) as PagedTable
left join MyTable on MyTable.ClusteredIndexField = PagedTable.ClusteredIndexField
where RowNumber between @LowestRowNumber and @HighestRowNumber;
``` | How to get N rows starting from row M from sorted table in T-SQL | [
"",
"sql",
"t-sql",
""
] |
I have a data structure that looks like this:
```
typedef struct
{
unsigned short m_short1;
unsigned short m_short2;
unsigned char m_character;
} MyDataType;
```
I want to use boost::serialization to serialize this data structure, then use boost::asio to transmit it via TCP/IP, then have another application receive the data and de-serialize it using the same boost libraries.
[I'm trying to following boost::serialization tutorial](http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/tutorial.html), ([as some other SO questions have suggested](http://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c)) but the example is specifically for writing/reading to a file, not to a socket using boost::asio.
I'm pretty sure I've got the right tools for the job -- I just need help making them work together. Writing to a socket can't be that different from writing to a file, right?
Any suggestions are very much appreciated. Thanks! | For such simple structure, boost::serialization is overkill and huge overhead.
Do simpler:
```
vector<uint16_t> net(3,0);
net[0]=htons(data.m_short1);
net[1]=htons(data.m_short2);
net[2]=htons(data.character);
asio::async_write(socket,buffer((char*)&net.front(),6),callback);
vector<uint16_t> net(3,0);
asio::async_read(socket,buffer((char*)&net.front(),6),callback);
callback:
data.m_short1=ntohs(net[0]);
data.m_short2=ntohs(net[1]);
data.character=ntohs(net[2]);
```
And Save yourself HUGE overhead that boost::serialization has
And if you private protocol where computers with same order of bytes work (big/little)
that just send structure as is -- POD. | There is a good serialization [example](http://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/examples.html) in the asio documentation: [server.cpp](http://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/example/serialization/server.cpp), [stock.hpp](http://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/example/serialization/stock.hpp), [connection.hpp](https://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/example/serialization/connection.hpp).
Here's a snippet:
```
std::ostringstream archive_stream;
boost::archive::text_oarchive archive(archive_stream);
archive << your_struct;
outbound_data_ = archive_stream.str();
boost::asio::async_write(socket_,
boost::asio::buffer(outbound_data_), handler);
``` | Serialize and send a data structure using Boost? | [
"",
"c++",
"serialization",
"boost",
"boost-asio",
""
] |
I have child classes, each carries a different type of value along with other members. There may be a LongObject, IntObject, StringObject, etc.
I will be given a value, which can be a long, int, string, etc., and I have to create a LongObject, IntObject, StringObject, etc., respectively.
Would it be faster to overload a method as shown below (a) or just use a elseif as shown below (b)?
It may not be a noticeable performance difference. It may be that the overloaded methods are implemented in a similar manner to the if/else anyway. I don't know.
I can also hear some of you saying to just test it. Sure, I ought to. I would also like to know how this type of overloading is handled under the hood, if anyone knows.
Please let me know what you think.
Thanks,
jbu
a)
```
BaseObject getObject(long l)
{
return new LongObject(l);
}
BaseObject getObject(int i)
{
return new IntObject(i);
}
BaseObject getObject(String s)
{
return new StringObject(s);
}
...
```
b)
```
BaseObject getObject(Object x)
{
if(value is a long)
return new LongObject((Long)x);
else if(value is an int)
return new IntObject((Int)x);
else if(value is a String)
return new StringObject((String)x);
...
}
```
edit: I guess I didn't completely add all the details, some of you caught it. For both choices, I still have to get an object/value and from the value determine what type it is. Therefore, I still have to do an if/else of some sort to even use the overloaded methods. | There's a massive discrepancy here: overloads are chosen at *compile-time* whereas your "if (value is a long)" would be an *execution-time* test.
If you know the type at compile-time, I strongly suggest you use that information. If you don't, then the overloading option isn't really feasible anyway.
EDIT: The comment suggests I elaborate a bit about overloads being chosen at compile-time.
The compiler picks which method signature is called based on *compile-time* information about the arguments. This is unlike *overriding* where the method implementation to use is determined by the type of the actual target of the method.
Here's an example:
```
public class Test
{
public static void main(String[] args)
{
Object x = "I'm a string";
foo(x);
}
public static void foo(String x)
{
System.out.println("foo(String)");
}
public static void foo(Object x)
{
System.out.println("foo(Object)");
}
}
```
This prints `foo(Object)` because the compile-time type of `x` is `Object`, not `String`. The fact that the execution-time type of the object that `x` refers to is `String` doesn't mean that `foo(String)` is called. | The overloading solution is much faster (and better) because it is resolved at compile time.
Basically the compiler figure out which method to invoke when you pass a value to it. When you call getObject("abc"), the compiler will emit calls to method:
```
BaseObject getObject(String s)
{
return new StringObject(s);
}
```
rather than trying to go through your if ... else state and evaluate the object type (which is a slow activity) at run time. | Java: which is faster overloading or if/else | [
"",
"java",
"optimization",
"polymorphism",
"conditional-statements",
"overloading",
""
] |
From what I've ready you should be able to use the 'value' property of a file input field to get the currently set path of that field. But when I do this:
```
$('#fileinput').value()
```
I get 'undefined'. The ID of the field is set to "fileinput" I'm sure. Does anyone have any thoughts on why this might not be working for me?
And by the way, this works:
```
var d = document.getElementById('AttachmentFile');
alert(d.value);
```
So I guess this has something to do with the way jQuery works that I don't fully understand.
Thanks! | You need to use val rather than value.
```
$("#fileinput").val();
``` | In Chrome 8 the path is always 'C:\fakepath\' with the correct file name. | How to use jQuery to get the current value of a file input field | [
"",
"javascript",
"jquery",
"dom",
""
] |
What are current best-practices for systematic build numbering and version number management in Java projects? Specifically:
* How to manage build numbers systematically in a distributed development environment
* How to maintain version numbers in source / available to the runtime application
* How to properly integrate with source repository
* How to more automatically manage version numbers vs. repository tags
* How to integrate with continuous build infrastructure
There are quite a number of tools available, and ant (the build system we're using) has a task that will maintain a build number, but it's not clear how to manage this with multiple, concurrent developers using CVS, svn, or similar.
[EDIT]
Several good and helpful partial or specific answers have appeared below, so I'll summarize a few of them. It sounds to me like there is not really a strong "best practice" on this, rather a collection of overlapping ideas. Below, find my summaries and some resulting questions that folks might try to answer as follow-ups. [New to stackoverflow... please provide comments if I'm doing this wrong.]
* If you are using SVN, versioning of a specific checkout comes along for the ride. Build numbering can exploit this to create a unique build number that identifies the specific checkout/revision. [CVS, which we are using for legacy reasons, doesn't provide quite this level of insight... manual intervention with tags gets you part way there.]
* If you are using maven as your build system, there is support for producing a version number from the SCM, as well as a release module for automatically producing releases. [We can't use maven, for a variety of reasons, but this helps those who can. [Thanks to [marcelo-morales](https://stackoverflow.com/users/83674/marcelo-morales)]]
* If you are using [ant](http://ant.apache.org) as your build system, the following task description can help produce a Java .properties file capturing build information, which can then be folded into your build in a number of ways. [We expanded on this idea to include hudson-derived information, thanks [marty-lamb](https://stackoverflow.com/users/79194/marty-lamb)].
* Ant and maven (and hudson and cruise control) provide easy means for getting build numbers into a .properties file, or into a .txt/.html file. Is this "safe" enough to keep it from being tampered with intentionally or accidentally? Is it better to compile it into a "versioning" class at build time?
* Assertion: Build numbering should be defined/enacted in a continuous integration system like [hudson](http://hudson-ci.org/). [Thanks to [marcelo-morales](https://stackoverflow.com/users/83674/marcelo-morales)] We have taken this suggestion, but it does crack open the release engineering question: How does a release happen? Are there multiple buildnumbers in a release? Is there a meaningful relationship between buildnumbers from differing releases?
* Question: What is the objective behind a build number? Is it used for QA? How? Is it used primarily by developers to disambiguate between multiple builds during development, or more for QA to determine what build an end-user got? If the goal is reproducibility, in theory this is what a release version number should provide -- why doesn't it? (please answer this as a part of your answers below, it will help illuminate the choices you have made/suggested...)
* Question: Is there a place for build numbers in manual builds? Is this so problematic that EVERYONE should be using a CI solution?
* Question: Should build numbers be checked in to the SCM? If the goal is reliably and unambiguously identifying a particular build, how to cope with a variety of continuous or manual build systems that may crash/restart/etc...
* Question: Should a build number be short and sweet (i.e., monotonically increasing integer) so that it's easy to stick into file names for archival, easy to refer to in communication, etc... or should it be long and full of usernames, datestamps, machine names, etc?
* Question: Please provide details about how the assignment of build numbers fits into your larger automated release process. Yes, maven lovers, we know this is done and done, but not all of us have drunk the kool-aid quite yet...
I'd really like to flesh this out into a complete answer, at least for the concrete example of our cvs/ant/hudson setup, so someone could build a complete strategy based on this question. I'll mark as "The Answer" anyone who can give a soup-to-nuts description for this particular case (including cvs tagging scheme, relevant CI config items, and release procedure that folds the build number into the release such that it's programmatically accessible.) If you want to ask/answer for another particular configuration (say, svn/maven/cruise control) I'll link to the question from here. --JA
[EDIT 23 Oct 09]
I accepted the top-voted answer because I think it's a reasonable solution, while several of the other answers also include good ideas. If someone wants to take a crack at synthesizing some of these with [marty-lamb](https://stackoverflow.com/users/79194/marty-lamb)'s, I'll consider accepting a different one. The only concern I have with marty-lamb's is that it doesn't produce a reliably serialized build number -- it depends on a local clock at the builder's system to provide unambiguous build numbers, which isn't great.
[Edit Jul 10]
We now include a class like the below. This allows the version numbers to be compiled into the final executable. Different forms of the version info are emitted in logging data, long-term archived output products, and used to trace our (sometimes years-later) analysis of output products to a specific build.
```
public final class AppVersion
{
// SVN should fill this out with the latest tag when it's checked out.
private static final String APP_SVNURL_RAW =
"$HeadURL: svn+ssh://user@host/svnroot/app/trunk/src/AppVersion.java $";
private static final String APP_SVN_REVISION_RAW = "$Revision: 325 $";
private static final Pattern SVNBRANCH_PAT =
Pattern.compile("(branches|trunk|releases)\\/([\\w\\.\\-]+)\\/.*");
private static final String APP_SVNTAIL =
APP_SVNURL_RAW.replaceFirst(".*\\/svnroot\\/app\\/", "");
private static final String APP_BRANCHTAG;
private static final String APP_BRANCHTAG_NAME;
private static final String APP_SVNREVISION =
APP_SVN_REVISION_RAW.replaceAll("\\$Revision:\\s*","").replaceAll("\\s*\\$", "");
static {
Matcher m = SVNBRANCH_PAT.matcher(APP_SVNTAIL);
if (!m.matches()) {
APP_BRANCHTAG = "[Broken SVN Info]";
APP_BRANCHTAG_NAME = "[Broken SVN Info]";
} else {
APP_BRANCHTAG = m.group(1);
if (APP_BRANCHTAG.equals("trunk")) {
// this isn't necessary in this SO example, but it
// is since we don't call it trunk in the real case
APP_BRANCHTAG_NAME = "trunk";
} else {
APP_BRANCHTAG_NAME = m.group(2);
}
}
}
public static String tagOrBranchName()
{ return APP_BRANCHTAG_NAME; }
/** Answers a formatter String descriptor for the app version.
* @return version string */
public static String longStringVersion()
{ return "app "+tagOrBranchName()+" ("+
tagOrBranchName()+", svn revision="+svnRevision()+")"; }
public static String shortStringVersion()
{ return tagOrBranchName(); }
public static String svnVersion()
{ return APP_SVNURL_RAW; }
public static String svnRevision()
{ return APP_SVNREVISION; }
public static String svnBranchId()
{ return APP_BRANCHTAG + "/" + APP_BRANCHTAG_NAME; }
public static final String banner()
{
StringBuilder sb = new StringBuilder();
sb.append("\n----------------------------------------------------------------");
sb.append("\nApplication -- ");
sb.append(longStringVersion());
sb.append("\n----------------------------------------------------------------\n");
return sb.toString();
}
}
```
Leave comments if this deserves to become a wiki discussion. | For several of my projects I capture the subversion revision number, time, user who ran the build, and some system information, stuff them into a .properties file that gets included in the application jar, and read that jar at runtime.
The ant code looks like this:
```
<!-- software revision number -->
<property name="version" value="1.23"/>
<target name="buildinfo">
<tstamp>
<format property="builtat" pattern="MM/dd/yyyy hh:mm aa" timezone="America/New_York"/>
</tstamp>
<exec executable="svnversion" outputproperty="svnversion"/>
<exec executable="whoami" outputproperty="whoami"/>
<exec executable="uname" outputproperty="buildsystem"><arg value="-a"/></exec>
<propertyfile file="path/to/project.properties"
comment="This file is automatically generated - DO NOT EDIT">
<entry key="buildtime" value="${builtat}"/>
<entry key="build" value="${svnversion}"/>
<entry key="builder" value="${whoami}"/>
<entry key="version" value="${version}"/>
<entry key="system" value="${buildsystem}"/>
</propertyfile>
</target>
```
It's simple to extend this to include whatever information you might want to add. | Your *build.xml*
```
...
<property name="version" value="1.0"/>
...
<target name="jar" depends="compile">
<buildnumber file="build.num"/>
<manifest file="MANIFEST.MF">
...
<attribute name="Main-Class" value="MyClass"/>
<attribute name="Implementation-Version" value="${version}.${build.number}"/>
...
</manifest>
</target>
...
```
Your java code
```
String ver = MyClass.class.getPackage().getImplementationVersion();
``` | Build and Version Numbering for Java Projects (ant, cvs, hudson) | [
"",
"java",
"build",
"build-process",
"versioning",
""
] |
I'm using Postgres and I'm trying to write a query like this:
```
select count(*) from table where datasets = ARRAY[]
```
i.e. I want to know how many rows have an empty array for a certain column, but postgres doesn't like that:
```
select count(*) from super_eds where datasets = ARRAY[];
ERROR: syntax error at or near "]"
LINE 1: select count(*) from super_eds where datasets = ARRAY[];
^
``` | The syntax should be:
```
SELECT
COUNT(*)
FROM
table
WHERE
datasets = '{}'
```
You use quotes plus curly braces to show array literals. | If you find this question in 2020, like I did, the correct answer is
```
select count(*) from table where cardinality(datasets) = 0
```
`cardinality` was added in PostgreSQL 9.4, which is ~2015
<https://www.postgresql.org/docs/9.4/functions-array.html> | Postgres - How to check for an empty array | [
"",
"sql",
"arrays",
"postgresql",
""
] |
I've been using Jquery for some time now and I have a question concerning bad/good practices. Here is the deal. Lets say we have this HTML:
```
<span class="а_s_trigger" id="tekst1">text1</span>
<span class="а_s_trigger" id="video1">video1</span>
<div class="a_s_songvideo" id="showvideo1">
<object>
//video1
</object>
</div>
<div class="a_s_songtext" id="showtext1">
<p>
//text1
</p>
</div>
```
And the following jQuery function that triggers hide/show on click for an element that is either video or text.
```
$('.а_s_trigger')
.bind('mouseover',function(e) {
$(this).css({background:'#F3F3F3',cursor:'pointer'});
})
.bind('mouseout',function(e) {
$(this).css({background:'#E6E6E6'});
})
.bind('click',function(e) {
var id=$(this).attr('id');
var status=$(this).attr('id').toString().slice(0,5);
var index=$(this).attr('id').toString().slice(5,7);
var visibility=$('#showtext'+index).css('display');
if(status=='tekst1')
{
if(visibility=='block')
{
$('#showtext'+index).slideUp();
}
else if(visibility=='none')
{
$('#showtext'+index).slideDown();
}
}
else if(status=="video")
{
$('#showvideo'+index).toggle();
}
});
```
Everything is working fine but what bugs me is the way I select the element I need :
```
var id=this.id;
var status=$(this).attr('id').toString().slice(0,5);
var index=$(this).attr('id').toString().slice(5,7);
var visibility=$('#showtext'+index).css('display');
```
Is it OK to assign variables to strings in such manner?
I know that jQuery is all about selectors and the nice chaining functions like :
```
$(this).children().siblings().attr('id'); //and so on
```
Should I always try to select elements using the chain selectors or should I follow the principle "If it works don't change it!"? | I'm **a Class man**
```
$(".button"). //etc
```
To me its much easier and you can grab multiple elements, but if you have no problem with your way as you said
> If it works don't change it!" | I think conditionals make your code a bit cluttered and difficult to read. In my opinion you could encapsulate the status within the event handlers.
Add the status as classes to your elements.
```
<span class="а_s_trigger tekst" id="t_001">text1</span>
<span class="а_s_trigger video" id="v_001">video1</span>
```
Bind accordingly:
```
$('.а_s_trigger').bind('mouseover',function(e) {
$(this).css({background:'#F3F3F3',cursor:'pointer'});
}).bind('mouseout',function(e) {
$(this).css({background:'#E6E6E6'});
});
$('.а_s_trigger .tekst').bind('click',function(e) {
var index=this.id.toString().slice(2,6);
var $element = $('#showtext'+index);
var visibility=$element.css('display');
if(visibility=='block')
{
$element.slideUp();
}
else
{
$element.slideDown();
}});
$('.а_s_trigger .video').bind('click',function(e) {
var index=this.id.toString().slice(2,6);
$('#showvideo'+index).toggle;
});
```
EDIT:
The text handler could be substituted by (with a tiny performance penalty):
```
$('.а_s_trigger .tekst').bind('click',function(e) {
var index=this.id.toString().slice(2,6);
$('#showtext'+index + ':visible').slideUp();
$('#showtext'+index + ':hidden').slideDown();
});
``` | Is it considered a bad-practice to select distinct elements by catching their class/id in a string? | [
"",
"javascript",
"jquery",
"html",
"string",
""
] |
If I have a deeply immutable type (all members are readonly and if they are reference type members, then they also refer to objects that are deeply immutable).
I would like to implement a lazy initialized property on the type, like this:
```
private ReadOnlyCollection<SomeImmutableType> m_PropName = null;
public ReadOnlyCollection<SomeImmutableType> PropName
{
get
{
if(null == m_PropName)
{
ReadOnlyCollection<SomeImmutableType> temp = /* do lazy init */;
m_PropName = temp;
}
return m_PropName;
}
}
```
From what I can tell:
```
m_PropName = temp;
```
...is threadsafe. I'm not worried too much about two threads both racing to initialize at the same time, because it will be rare, both results would be identical from a logical perspective, and I'd rather not use a lock if I don't have to.
Will this work? What are the pros and cons?
**Edit:**
Thanks for your answers. I will probably move forward with using a lock. However, I'm surprised nobody brought up the possibility of the compiler realizing that the temp variable is unnecessary, and just assigning straight to m\_PropName. If that were the case, then a reading thread could possibly read an object that hasn't finished being constructed. Does the compiler prevent such a situation?
(Answers seem to indicate that the runtime won't allow this to happen.)
**Edit:**
So I've decided to go with an Interlocked CompareExchange method inspired by [this article by Joe Duffy](https://web.archive.org/web/20080216100813/http://www.bluebytesoftware.com/blog/2007/11/17/ImmutableTypesCanCopyTheWorldSafely.aspx).
Basically:
```
private ReadOnlyCollection<SomeImmutableType> m_PropName = null;
public ReadOnlyCollection<SomeImmutableType> PropName
{
get
{
if(null == m_PropName)
{
ReadOnlyCollection<SomeImmutableType> temp = /* do lazy init */;
System.Threading.Interlocked(ref m_PropName, temp, null);
}
return m_PropName;
}
}
```
This is supposed to ensure that all threads that call this method on this object instance will get a reference to the same object, so the == operator will work. It is possible to have wasted work, which is fine - it just makes this an optimistic algorithm.
As noted in some comments below, this depends on the .NET 2.0 memory model to work. Otherwise, m\_PropName should be declared volatile. | That will work. Writing to references in C# is guaranteed to be atomic, as described in section 5.5 of the [spec](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx).
This is still probably not a good way to do it, because your code will be more confusing to debug and read in exchange for a probably minor effect on performance.
Jon Skeet has a great [page](http://www.yoda.arachsys.com/csharp/singleton.html) on implementing singeltons in C#.
The general advice about small optimizations like these is not to do them unless a profiler tells you this code is a hotspot. Also, you should be wary of writing code that cannot be fully understood by most programmers without checking the spec.
EDIT: As noted in the comments, even though you say you don't mind if 2 versions of your object get created, that situation is so counter-intuitive that this approach should never be used. | I'd be interested to hear other answers to this, but I don't see a problem with it. The duplicate copy will be abandoned and gets GCed.
You need to make the field `volatile` though.
Regarding this:
> However, I'm surprised nobody brought
> up the possibility of the compiler
> realizing that the temp variable is
> unnecessary, and just assigning
> straight to m\_PropName. If that were
> the case, then a reading thread could
> possibly read an object that hasn't
> finished being constructed. Does the
> compiler prevent such a situation?
I considered mentioning it but it makes no difference. The new operator doesn't return a reference (and so the assignment to the field doesn't happen) until the constructor completes - this is guaranteed by the runtime, not the compiler.
However, the language/runtime does NOT really guarantee that other threads cannot see a partially constructed object - [it depends what the constructor does](http://incrediblejourneysintotheknown.blogspot.com/2009/03/readonly-fields-and-thread-safety.html).
**Update:**
The OP also wonders whether [this page has a helpful idea](http://blog.markrendle.net/post/Lazy-initialization-thread-safety-and-my-favourite-operator.aspx). Their final code snippet is an instance of [Double checked locking](http://en.wikipedia.org/wiki/Double_checked_locking_pattern) which is the classic example of an idea that thousands of people recommmend to each other without any idea of how to do it right. The problem is that SMP machines consist of several CPUs with their own memory caches. If they had to synchronise their caches every time there was a memory update, this would undo the benefits of having several CPUs. So they only synchronize at a "memory barrier", which occurs when a lock is taken out, or an interlocked operation occurs, or a `volatile` variable is accessed.
The usual order of events is:
* Coder discovers double-checked locking
* Coder discovers memory barriers
Between these two events, they release a lot of broken software.
Also, many people believe (as that guy does) that you can "eliminate locking" by using interlocked operations. But at runtime they are a memory barrier and so they cause all CPUs to stop and synchronize their caches. They have an advantage over locks in that they don't need to make a call into the OS kernel (they are "user code" only), but [they can kill performance just as much as any synchronization technique](http://www.bluebytesoftware.com/blog/2009/01/09/SomePerformanceImplicationsOfCASOperations.aspx).
Summary: threading code looks approximately 1000 x easier to write than it is. | Is a lock required with a lazy initialization on a deeply immutable type? | [
"",
"c#",
"lazy-loading",
"immutability",
"lock-free",
""
] |
I met a problem about HTML rendering.
In dir="rtl" document of IE7, when JavaScript tries to set focus to a DIV element(with oElement.focus() method), the rendering turns to mess. The context is very complicated, so I suppose the easiest fix is to make the DIV unfocusable?
Is there any way to make a DIV not be focused? | The `<div>` should not be capable of receiving focus unless you have added **tabIndex**.
If you have added `tabIndex`, you should remove it by
```
document.getElementById("yourElement").removeAttribute("tabIndex");
``` | **Additionally**, If you want to make a focussable element(form input elements etc.) as unfocussable. You can set :
```
tabIndex = "-1"
document.getElementById("yourElement").setAttribute("tabIndex", "-1");
``` | how to make a DIV unfocusable? | [
"",
"javascript",
"html",
"focus",
""
] |
I have some settings in my app.config which I intend to be 'global' - ie. any user can change them, and all users get the same setting.
But unless I change them to be user settings, they are read only.
Why is this?
And how should I go about persisting my app's global settings?
**Edit:**
This is actually a windows service application which runs as a service as LocalSystem. It can also be run manually by a local admin with argument "/config", which launches a windows form to edit configuration values.
So it will have write access to `%PROGRAMFILES%` in both situations.
The way I am accessing my settings is thusly:
```
Settings.Default.MySetting = MyNewValue;
```
And when MySetting is set to Application (in my project properties, Settings.settings), I get a compile-time error "MySetting is read only".
I am new to this stuff, and have not yet found a very good explanation of how it is supposed to be done. For example, why do I need to say 'Default', and what does that actually mean? I have no idea. If anyone can point me to an app.config usage tutorial, that would be really helpful. | The real complete answer:
The app.config settings are read-only because there are 2 types of settings:
1. Application Settings
2. User Settings
The first won't change unless the application publisher publishes a new version of it. The second is not stored in the app.config, but in a user.config file. In the abscence of this user.config file the app.config provides the default value.
If MySetting is a User Setting:
```
Settings.Default.MySetting = MyNewValue;
Settings.Default.Save();
```
It will create a `user.config` file at `[User Local Settings Application Data]\[company name]\[application].exe[hash string]\[version]` with the new settings, and those settings will prevail over the settings in the `app.config` file. | **Why:** Application settings are intended to be stored in the Application folder under Program Files where the user does not have write privileges.
**How:** There is no default support for "All Users" but you should be able to setup your own custom config file in a public folder or use a Database. | Why are application settings read-only in app.config? | [
"",
"c#",
".net",
"app-config",
""
] |
I have some (a bit more than a little) code where object values from a DataReader are assigned to business object properties. This code is quite untidy to look at with lots of null coalescing, parsing, etc. I was wondering how to implement a tidier means of converting the object values from the DataReader to the appropriate values for the object properties.
One option is to have discrete conversion functions for each data type, where the data types on my object properties are limited to a small set of CLR primitive types. I don't use nullable types, as then I'll just be moving the untidiness to where these values are used elsewhere.
My second option is to create an extension method for each of the four or so data types used, limited to the niche namespace in which these assignments take place. Something like this rather simplistic example:
```
public static void SafelyAssign(this string target, object value)
{
if (value is string)
{
target = (string)value ?? "";
}
else
{
target = value.ToString();
}
}
```
What other options do I have? | As an interim measure, I have created an extension method called `AssignObjectValue` on each of the five primitive types I assign to. This allows me to call the 'same' method on each assignment, regardless of the LHS type. I would have loved to be able to overload the `=` operator for this, but I'm happy for now. My code looks like something like this:
```
cDoc.DocType.AssignObjectValue(dr["DocType"]); // int
cDoc.DocID.AssignObjectValue(dr["docID"]);
cDoc.CustomerNo.AssignObjectValue(dr["customerNo"]); // string
cDoc.InvTitle.AssignObjectValue(dr["InvTitle"]);
cDoc.TaxPercent.AssignObjectValue(dr["taxPercent"]); // double
cDoc.TaxTypeID = GetTaxTypeIDForDocType(cDoc.DocType);
cDoc.Remarks.AssignObjectValue(dr["remarks"]);
cDoc.Cost.AssignObjectValue(dr["cost"]); // double
cDoc.InvDate.AssignObjectValue(dr["InvDate"]); // date
```
Which is more or less where I wanted to be. I will eventually be doing the assignments in a loop, based on a mapping dictionary, instead of explicitly in code, so I think my 'half' solution is not bad for the time invested in a temporary fix. | A solution I liked was adopted from the [CSLA.Net](http://www.lhotka.net/cslanet/Default.aspx) framework. Create a [SafeDataReader](http://www.lhotka.net/cslacvs/viewvc.cgi/branches/V3-5-x/cslacs/Csla/Data/SafeDataReader.cs?revision=3286&view=markup) which implements IDataReader. I will try and find a link but here's an example for how to get a safe int. This solution does not require the CSLA.Net framework, this is just how he solves the problem which I find really handy.
```
public class SafeDataReader : IDataReader, ISafeDataRecord
{
/// <summary>
/// Gets an integer from the datareader.
/// </summary>
/// <remarks>
/// Returns 0 for null.
/// </remarks>
public int GetInt32(string name)
{
return GetInt32(_dataReader.GetOrdinal(name));
}
/// <summary>
/// Gets an integer from the datareader.
/// </summary>
/// <remarks>
/// Returns 0 for null.
/// </remarks>
public int GetInt32(int i)
{
if (_dataReader.IsDBNull(i))
return 0;
else
return _dataReader.GetInt32(i);
}
public object this[string name]
{
get
{
object val = _dataReader[name];
if (DBNull.Value.Equals(val))
return null;
else
return val;
}
}
public Nullable<T> GetNullable<T>(string name) where T:struct
{
int index = _dataReader.GetOrdinal(name);
if (_dataReader.IsDBNull(index))
{
return null;
}
else
{
return new Nullable<T>((T)_dataReader[index]);
}
}
}
```
Edit: Ok so how do we use this safe data reader? So let's assume we have a cmd object which is all setup
```
using (SafeDataReader reader=new SafeDataReader(cmd.ExecuteDataReader())
{
//Assume MyColumn was null here, this will still work because
//since a string can be null
string myString=reader["MyColumn"];
//In this case myInt will be set to 0 if MyColumn is DBNull
int myInt=reader.GetInt("MyColumn");
}
```
You can also use the GetNullable method although, that is not part of his class, and I'm not sure where it came from, but it looks correct to me.
How portable is this? Well since it is implementing IDataReader it should be very portable; and should be able to be swapped in and out so long as the calling code doesn't expect DBNull.Value to be returned. | How to safely assign DB values to object properties? | [
"",
"c#",
".net",
""
] |
When I compile a c++ application I'm writing that makes use of hash\_map, I get this warning on g++ 4.3.2:
You are using the deprecated header . To eliminate this warning, use an ANSI-standard header file or use hte -Wno-deprecated compiler flag.
```
9> #include <ext/hash_map>
```
What include replaces this? I've searched for a while on google, and can't find anything except for people having similar problems, but no solution. | My very first Google hit for "[g++ hash\_map deprecated](http://www.google.com/search?q=g%2B%2B+hash_map+deprecated)" takes me to [a page](https://blueprints.launchpad.net/ember/+spec/ember-deprecated-cleanup) that includes a list of things to use instead of the deprecated headers and classes.
For `hash_map`, the list suggests using [`unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map), in the `unordered_map` header. The class is new for [TR1](http://en.wikipedia.org/wiki/Technical_Report_1). | I believe that that new data structure is called `unordered_map`
```
<tr1/unordered_map>
```
found in the `std::tr1` namespace. | How to get rid of g++ hash_map deprecation warning? | [
"",
"c++",
"g++",
"hashmap",
"deprecated",
""
] |
Though .htaccess, I want to redirect /page/var1/var2 to ./page.php?var1=var1&var2=var2. This is very easy BUT I want to make it so /page/var1 also redirects to ./page.php?var1=var1 (without having the var2). The only way I'm doing this is:
```
RewriteRule page/(.*)$ ./page.php?var1=$1
RewriteRule page/(.*)/(.*)$ ./page.php?var1=$1&var2=$2
```
As you can see it's very redundant, and I have a ton of lines like this, so it gets very messy. Any way to define "optional" parts? | The expression `.*` matches both `var1` and `var1/var2` thus the first rule is applied on both.
So you have to specify it that the first rule only matches `var1`. This can be done by replacing `.` (any character) by `[^/]` (any character except `/`). So try this:
```
RewriteRule ^page/([^/]+)$ ./page.php?var1=$1
RewriteRule ^page/([^/]+)/([^/]+)$ ./page.php?var1=$1&var2=$2
```
**Edit** You can also write this in one rule:
```
RewriteRule ^page/([^/]+)(/([^/]+))?$ ./page.php?var1=$1&var2=$3
``` | mod\_rewrite is not well suited to such heavy lifting, leave that to your PHP app.
```
RewriteRule page/(.*)$ ./page.php?vars=$1
```
and somewhere near the beginning of page.php:
```
<?php
$vars = explode('/',$_GET['vars']);
```
Voila, you have an array of your vars; now you could do some processing there to see what is required/optional for your app and react accordingly. | .htaccess Optional characters? | [
"",
"php",
"regex",
".htaccess",
""
] |
It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to `*args` and `**kwargs` when they're unrolled in the following manner:
```
items = [1,2,3,4,5,6]
def do_something(*items):
pass
```
I ask because, hypothetically, there might be cases where a list larger than 256 items gets unrolled as a set of `*args` or `**kwargs`. | In Python 3.7 and newer, there is no limit. This is the result of work done in [issue #27213](https://bugs.python.org/issue27213) and [issue #12844](https://bugs.python.org/issue12844); #27213 reworked the `CALL_FUNCTION*` family of opcodes for performance and simplicity (part of 3.6), freeing up the opcode argument to only encode a single argument count, and #12844 removed the compile-time check that prevented code with more arguments from being compiled.
So as of 3.7, with the [`EXTENDED_ARG()` opcode](https://docs.python.org/3/library/dis.html#opcode-EXTENDED_ARG), there is now *no limit at all* on how many arguments you can pass in using explicit arguments, save how many can be fitted onto the stack (so bound now by your memory):
```
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=7, micro=0, releaselevel='alpha', serial=2)
>>> def f(*args, **kwargs): pass
...
>>> exec("f({})".format(', '.join(map(str, range(256)))))
>>> exec("f({})".format(', '.join(map(str, range(2 ** 16)))))
```
Do note that lists, tuples and dictionaries are limited to [`sys.maxsize`](https://docs.python.org/3/library/sys.html#sys.maxsize) elements, so if the called function uses `*args` and/or `**kwargs` catch-all parameters then those *are* limited.
For the `*args` and `**kwargs` call syntax (expanding arguments) there are no limits other than the same `sys.maxint` size limits on Python standard types.
In versions before Python 3.7, CPython has a limit of 255 explicitly passed arguments in a call:
```
>>> def f(*args, **kwargs): pass
...
>>> exec("f({})".format(', '.join(map(str, range(256)))))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
SyntaxError: more than 255 arguments
```
This limitation is in place because until Python 3.5, the [`CALL_FUNCTION` opcode](https://docs.python.org/3.5/library/dis.html#opcode-CALL_FUNCTION) overloaded the opcode argument to encode both the number of positional and keyword arguments on the stack, each encoded in a single byte. | In Python 3.6 and before, the limit is due to how the compiled bytecode treats calling a function with position arguments and/or keyword arguments.
The bytecode op of concern is [`CALL_FUNCTION`](https://docs.python.org/3.5/library/dis.html#opcode-CALL_FUNCTION) which carries an `op_arg` that is 4 bytes in length, but on the two least significant bytes are used. Of those, the most significant byte represent the number of keyword arguments on the stack and the least significant byte the number of positional arguments on the stack. Therefore, you can have at most `0xFF == 255` keyword arguments or `0xFF == 255` positional arguments.
This limit does not apply to `*args` and `**kwargs` because calls with that grammar use the bytecode ops [`CALL_FUNCTION_VAR`](https://docs.python.org/3.5/library/dis.html#opcode-CALL_FUNCTION_VAR), [`CALL_FUNCTION_KW`](https://docs.python.org/3.5/library/dis.html#opcode-CALL_FUNCTION_KW), and [`CALL_FUNCTION_VAR_KW`](https://docs.python.org/3.5/library/dis.html#opcode-CALL_FUNCTION_VAR_KW) depending on the signature. For these opcodes, the stack consists of an iterable for the `*args` and a `dict` for the `**kwargs`. These items get passed directly to the receiver which unrolls them as needed. | What is a maximum number of arguments in a Python function? | [
"",
"python",
"function",
"arguments",
"language-features",
"limit",
""
] |
I need to convert 0.5 in base 10 to base 2 (0.1).
I have tried using
```
Double.doubleToRawLongBits(0.5)
```
and it returns `4602678819172646912` which I guess is in hex, but it does not make sense to me. | Multiply you number by 2^n, convert to an BigInteger, convert to *binary* String, add a decimal point at position n (from right to left).
Example (quick & ++dirty):
```
private static String convert(double number) {
int n = 10; // constant?
BigDecimal bd = new BigDecimal(number);
BigDecimal mult = new BigDecimal(2).pow(n);
bd = bd.multiply(mult);
BigInteger bi = bd.toBigInteger();
StringBuilder str = new StringBuilder(bi.toString(2));
while (str.length() < n+1) { // +1 for leading zero
str.insert(0, "0");
}
str.insert(str.length()-n, ".");
return str.toString();
}
``` | No. 4602678819172646912 is in dec, hex is 0x3fe0000000000000. To dismantle that:
```
3 | F | E | 0 ...
0 0 1 1 1 1 1 1 1 1 1 0 0 ...
s| exponent | mantissa
```
s is the sign bit, exponent is the exponent shifted by 2^9 (hence this exponent means -1), mantissa is the xxx part of the number 1.xxx (1. is implied). Therefore, this number is 1.000...\*2^-1, which is 0.5.
Note that this describes the "normal" numbers only, so no zeros, denormals, NaNs or infinities | How do I convert a decimal fraction to binary in Java? | [
"",
"java",
"binary",
"decimal",
""
] |
I'm developing a eclipse plugin rcp and I'm running into a NoClassDefFoundError
```
Exception in thread "Thread-7" java.lang.NoClassDefFoundError: org/jdom/input/SAXBuilder
at org.geonames.WebService.search(WebService.java:783)
at geo.GeocoderGeonames$SearchThread.run(GeocoderGeonames.java:119)
Caused by: java.lang.ClassNotFoundException: org.jdom.input.SAXBuilder
at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:483)
at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 2 more
```
The class that supposedly cannot be found is in a jar that I have added to the buildpath. I don't get any compile error etc only this exception when the running application enters the code where this class is needed...
Is there some other place I need to add the jar | After reading [this](http://www.eclipsezone.com/articles/eclipse-vms/) added the jar to the MANIFEST.MF, which solved the problem.
As I understand it, eclipse starts several classloaders which only sees what MANIFEST.MF tells them to see and ingnores the build path... | How are you running your plug-in? You may need to add the JAR to the class path in the VM arguments. | Class in buildpath-jar still not found | [
"",
"java",
"eclipse-rcp",
""
] |
I have a html text like this:
```
<xml ... >
```
and I want to convert it to something readable:
```
<xml ...>
```
Any easy (and fast) way to do it in Python? | ## Python >= 3.4
Official documentation for `HTMLParser`: [Python 3](https://docs.python.org/3/library/html.html#html.unescape)
```
>>> from html import unescape
>>> unescape('© €')
© €
```
## Python < 3.5
Official documentation for `HTMLParser`: [Python 3](https://docs.python.org/3/library/html.parser.html)
```
>>> from html.parser import HTMLParser
>>> pars = HTMLParser()
>>> pars.unescape('© €')
© €
```
Note: this was deprecated in the favor of `html.unescape()`.
## Python 2.7
Official documentation for `HTMLParser`: [Python 2.7](https://docs.python.org/2.7/library/htmlparser.html)
```
>>> import HTMLParser
>>> pars = HTMLParser.HTMLParser()
>>> pars.unescape('© €')
u'\xa9 \u20ac'
>>> print _
© €
``` | Modern Python 3 approach:
```
>>> import html
>>> html.unescape('© €')
© €
```
<https://docs.python.org/3/library/html.html> | Replace html entities with the corresponding utf-8 characters in Python 2.6 | [
"",
"python",
"html-entities",
"python-2.6",
""
] |
I have a value stored in a DB correlating to a monetary amount, say 10.0. I also have access to the Currency/CurrencyCode. How can I use NumberFormat/DecimalFormat/(other?) to format when I don't know the Locale? According to the docs it will pick a default locale which won't work with a foreign Currency. | The correct behavior, generally speaking, is to format the amount in the User's preferred locale, not the currency's typical locale. On the client side, you'll have the user's preference (Locale.getDefault()); if you are doing something on the web server side, use the Accept-Language or, preferably, the page content's locale to obtain the proper a locale.
The reasoning is this:
An English-US user will understand € 10,000,000.15 but not the suitable-for-Germany equivalent, € 10.000.000,15
The currency itself doesn't contain enough information to infer a suitable locale, anyway. | JasonTrue is correct, but you can override the currency of the NumberFormat's locale:
```
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
//the user may have selected a different currency than the default for their locale
Currency currency = Currency.getInstance("GBP");
numberFormat.setCurrency(currency);
numberFormat.format(amount);
``` | Java: Currency to Locale Mapping Possible? | [
"",
"java",
"formatting",
"currency",
""
] |
Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.
Has anybody done this? Any direction would be appreciated.
Using Python 2.5.4 and PyQt4 on Window XP Pro | It's pretty straightforward once you remember that there's no way to actually minimize to the [system tray](https://web.archive.org/web/20070114154431/http://blogs.msdn.com/oldnewthing/archive/2003/09/10/54831.aspx).
Instead, you fake it by doing this:
1. Catch the minimize event on your window
2. In the minimize event handler, create and show a QSystemTrayIcon
3. Also in the minimize event handler, call hide() or setVisible(false) on your window
4. Catch a click/double-click/menu item on your system tray icon
5. In your system tray icon event handler, call show() or setVisible(true) on your window, and optionally hide your tray icon. | Code helps, so here's something I wrote for an application, except for the closeEvent instead of the minimize event.
Notes:
"closeEvent(event)" is an overridden Qt event, so it must be put in the class that implements the window you want to hide.
"okayToClose()" is a function you might consider implementing (or a boolean flag you might want to store) since sometimes you actually want to exit the application instead of minimizing to systray.
There is also an example of how to show() your window again.
```
def __init__(self):
traySignal = "activated(QSystemTrayIcon::ActivationReason)"
QtCore.QObject.connect(self.trayIcon, QtCore.SIGNAL(traySignal), self.__icon_activated)
def closeEvent(self, event):
if self.okayToClose():
#user asked for exit
self.trayIcon.hide()
event.accept()
else:
#"minimize"
self.hide()
self.trayIcon.show() #thanks @mojo
event.ignore()
def __icon_activated(self, reason):
if reason == QtGui.QSystemTrayIcon.DoubleClick:
self.show()
``` | PyQt4 Minimize to Tray | [
"",
"python",
"pyqt4",
"system-tray",
"minimize",
""
] |
An interview question for a .NET 3.5 job is "What is the difference between an iterator and an enumerator"?
This is a core distinction to make, what with LINQ, etc.
Anyway, what is the difference? I can't seem to find a solid definition on the net. Make no mistake, I can find the meaning of the two terms but I get slightly different answers. What would be the best answer for an interview?
IMO an iterator "iterates" over a collection, and an enumerator provides the functionality to iterate, but this has to be called.
Also, using the yield keyword is said to save state. What exactly is this state? Is there an example of this benefit occurring? | Iterating means repeating some steps, while enumerating means going through all values in a collection of values. So enumerating usually requires some form of iteration.
In that way, enumerating is a special case of iterating where the step is getting a value from a collection.
Note the "usually" – enumerating may also be performed recursively, but recursion and iteration are so closely related that I would not care about this small difference.
You may also enumerate values you do not explicitly store in a collection. For example, you can enumerate the natural number, primes, or whatever but you would calculate these values during the enumeration and not retrieve them from a physical collection. You understand this case as enumerating a virtual collection with its values defined by some logic.
---
I assume Reed Copsey got the point. In C# there are two major ways to enumerate something.
1. Implement `Enumerable` and a class implementing `IEnumerator`
2. Implement an iterator with the `yield` statement
The first way is harder to implement and uses objects for enumerating. The second way is easier to implement and uses continuations. | In C# 2+, [iterators](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/iterators) are a way for the compiler to automatically generate the IEnumerable and/or IEnumerable<T> interfaces for you.
Without iterators, you would need to create a class implementing [IEnumerator](http://msdn.microsoft.com/en-us/library/78dfe2yb(VS.80).aspx), including Current, MoveNext, and Reset. This requires a fair amount of work. Normally, you would create a private class that implemtented IEnumerator<T> for your type, then yourClass.GetEnumerator() would construct that private class, and return it.
Iterators are a way for the compiler to automatically generate this for you, using a simple syntax (yield). This lets you implement GetEnumerator() directly in your class, without a second class (The IEnumerator) being specified by you. The construction of that class, with all of its members, is done for you.
Iterators are very developer friendly - things are done in a very efficient way, with much less effort.
When you use foreach, the two will behave identically (provided you write your custom IEnumerator correctly). Iterators just make life much simpler. | Distinction between iterator and enumerator | [
"",
"c#",
".net",
"iterator",
"generator",
"enumeration",
""
] |
Is it normal behavior for an ImageButton event to not fire if it can't find the image for it. For example, assume I have the following piece of code:
```
imageLink = new ImageButton();
imageLink.ImageUrl = "~/images/arrow.png";
```
If the page finds arrow.png, the image click works, but if it doesn't find it, it does not work.
These images are created dynamically and a CommandName, CommandArgument and Click Handler are assigned.
```
void imageLink_Click(object sender, ImageClickEventArgs e)
{
ImageButton button = (ImageButton)sender;
Detail oDetail = new Detail();
switch(button.CommandName)
{
case "Band":
oDetail.Band = button.CommandArgument;
break;
case "State":
oDetail.State = button.CommandArgument;
break;
}
Session["Page2"] = oDetail;
Response.Redirect("~/Page2.aspx");
}
``` | In some cases, it happens
Image button events are not firing sometime without image
Anybody know the exact reason behind this issue,
please post here | No, that is not normal. I just tested and even if you never set `ImageUrl` the button will still post back. Are you certain that the issue is not related to event handling? | ImageButton event does not fire if ImageButton does not have Image? | [
"",
"c#",
"asp.net",
""
] |
This is a follow up to a previous question which seems to have confused people so I'll purify it a bit. Here is some markup.
```
<div class="button width120 height30 iconLeft colorRed"></div>
<div class="button width180 height20 iconPlus colorBlue"></div>
<div class="button width200 height10 iconStar colorGreen"></div>
<div class="button width110 height60 iconBack colorOrange"></div>
```
The challenge is to fill in the code in the following.
```
$(".button").each(function(){
// Get the width from the class
// Get the height from the class
// Get the icon from the class
// Get the color from the class
});
```
Now, I know that you shouldn't use classes this way so I'm not looking for alternative ways of doing it, this is an experiment and I'm interested to know if it's possible to do it this way. | Something like:
```
$(".button").each(function(){
var classNames = $(this).attr('class').split(' ');
var width, height;
for(int i = 0; i < classNames.length; i++) {
var className = classNames[i];
if(className.indexOf('width') > -1) {
width = className.substring(5, className.length - 1);
} else if(className.indexOf('height') > -1) {
height = className.substring(6, className.length - 1);
} // etc. etc.
}
});
```
Or have I misunderstood what you were asking? | I found this answer which looks very robust...
```
$(".button").each(function(el){
classStr = el.className;
classes = classStr.split(' ');
// Loop through classes and find the one that starts with icon
});
``` | Programming Challenge using jQuery | [
"",
"javascript",
"jquery",
""
] |
this code using an OLEDB source will populate the OutputColumnCollection
below it, the code using a flatfile source will not populate the OutputColumnCollection.
## Why not?
```
Microsoft.SqlServer.Dts.Runtime.Application a = new Microsoft.SqlServer.Dts.Runtime.Application();
String SSISPackageFilePath;
SSISPackageFilePath = "Package Name";
Package pkg = new Package();
MainPipe dataFlow;
//oledb source
ConnectionManager conMgrSource = pkg.Connections.Add("OLEDB");
conMgrSource.ConnectionString = "Data Source=Steve;Initial Catalog=Scrambler;Provider=SQLNCLI.1;Integrated Security=SSPI;Auto Translate=False;";
// set the standardized name on source
conMgrSource.Name = "ConnectionSource";
ConnectionManager conMgrDestination = pkg.Connections.Add("OLEDB");
conMgrDestination.Name = "OLEDBConnectionDestination";
conMgrDestination.ConnectionString = "Data Source=server;Initial Catalog=Scrambler;Provider=SQLNCLI.1;Integrated Security=SSPI;Auto Translate=False;";
Executable exe = pkg.Executables.Add("DTS.Pipeline.1");
TaskHost th = exe as TaskHost;
th.Name = "DynamicDataFlowTask";
dataFlow = th.InnerObject as MainPipe;
IDTSComponentMetaDataCollection90 metadataCollection = dataFlow.ComponentMetaDataCollection;
IDTSComponentMetaData90 Source = dataFlow.ComponentMetaDataCollection.New();
Source.Name = "Source";
//sql server
//-------
Source.ComponentClassID = "DTSAdapter.OLEDBSource.1";
//-------
IDTSComponentMetaData90 OLEDBDestination = dataFlow.ComponentMetaDataCollection.New();
OLEDBDestination.Name = "OLEDBDestination";
OLEDBDestination.ComponentClassID = "DTSAdapter.OLEDBDestination.1";
// Get the design time instance of the component.
CManagedComponentWrapper InstanceSource = Source.Instantiate();
// Initialize the component
InstanceSource.ProvideComponentProperties();
// Specify the connection manager.
if (Source.RuntimeConnectionCollection.Count > 0)
{
Source.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(pkg.Connections["ConnectionSource"]);
Source.RuntimeConnectionCollection[0].ConnectionManagerID = pkg.Connections["ConnectionSource"].ID;
}
//sql server
InstanceSource.SetComponentProperty("OpenRowset", SourceTableNameInternal);
InstanceSource.SetComponentProperty("AccessMode", 0);
//reinitialize the component
InstanceSource.AcquireConnections(null);
InstanceSource.ReinitializeMetaData();
InstanceSource.ReleaseConnections();
// Get the design time instance of the component.
CManagedComponentWrapper InstanceDestination = OLEDBDestination.Instantiate();
// Initialize the component
InstanceDestination.ProvideComponentProperties();
// Specify the connection manager.
if (OLEDBDestination.RuntimeConnectionCollection.Count > 0)
{
OLEDBDestination.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(pkg.Connections["OLEDBConnectionDestination"]);
OLEDBDestination.RuntimeConnectionCollection[0].ConnectionManagerID = pkg.Connections["OLEDBConnectionDestination"].ID;
}
InstanceDestination.SetComponentProperty("OpenRowset", DestinationTableNameInternal);
InstanceDestination.SetComponentProperty("AccessMode", 0);
//reinitialize the component
InstanceDestination.AcquireConnections(null);
InstanceDestination.ReinitializeMetaData();
InstanceDestination.ReleaseConnections();
//map the columns
IDTSPath90 path = dataFlow.PathCollection.New();
path.AttachPathAndPropagateNotifications(**Source.OutputCollection[0]**, OLEDBDestination.InputCollection[0]);
```
---
// Source.OutPutCollection[0].OutputColumnCollection contains the columns of the data source. Below, the same code altered for a Flatfile source does not work.
---
```
Microsoft.SqlServer.Dts.Runtime.Application a = new Microsoft.SqlServer.Dts.Runtime.Application();
String SSISPackageFilePath;
SSISPackageFilePath = PackageNameInternal;
if (File.Exists(SSISPackageFilePath))
File.Delete(SSISPackageFilePath);
Package pkg = new Package();
MainPipe dataFlow;
// csv source
ConnectionManager conMgrSource = pkg.Connections.Add("FLATFILE");
conMgrSource.ConnectionString = @"c:\temp\test.txt";
conMgrSource.Properties["ColumnNamesInFirstDataRow"].SetValue(conMgrSource, true);
conMgrSource.Properties["FileUsageType"].SetValue(conMgrSource, Microsoft.SqlServer.Dts.Runtime.Wrapper.DTSFileConnectionUsageType.DTSFCU_FILEEXISTS);
conMgrSource.Properties["Format"].SetValue(conMgrSource, "Delimited");
conMgrSource.Properties["RowDelimiter"].SetValue(conMgrSource, "{CR}{LF}");
conMgrSource.Properties["HeaderRowDelimiter"].SetValue(conMgrSource, "{CR}{LF}");
// set the standardized name on source
conMgrSource.Name = "ConnectionSource";
ConnectionManager conMgrDestination = pkg.Connections.Add("OLEDB");
conMgrDestination.Name = "OLEDBConnectionDestination";
conMgrDestination.ConnectionString = "Data Source=server;Initial Catalog=Scrambler;Provider=SQLNCLI.1;Integrated Security=SSPI;Auto Translate=False;";
Executable exe = pkg.Executables.Add("DTS.Pipeline.1");
TaskHost th = exe as TaskHost;
th.Name = "DynamicDataFlowTask";
dataFlow = th.InnerObject as MainPipe;
IDTSComponentMetaDataCollection90 metadataCollection = dataFlow.ComponentMetaDataCollection;
IDTSComponentMetaData90 Source = dataFlow.ComponentMetaDataCollection.New();
Source.Name = "Source";
//csv
//-------
Source.ComponentClassID = "DTSAdapter.FlatFileSource.1";
// Get native flat file connection
// customize delimiters through the columns collection
//RuntimeWrapper.IDTSConnectionManagerFlatFile90 connectionFlatFile = conMgrSource.InnerObject as RuntimeWrapper.IDTSConnectionManagerFlatFile90;
//foreach (RuntimeWrapper.IDTSConnectionManagerFlatFileColumns90 col in connectionFlatFile.Columns)
//{
//
//}
//-------
IDTSComponentMetaData90 OLEDBDestination = dataFlow.ComponentMetaDataCollection.New();
OLEDBDestination.Name = "OLEDBDestination";
OLEDBDestination.ComponentClassID = "DTSAdapter.OLEDBDestination.1";
// Get the design time instance of the component.
CManagedComponentWrapper InstanceSource = Source.Instantiate();
// Initialize the component
InstanceSource.ProvideComponentProperties();
// Specify the connection manager.
if (Source.RuntimeConnectionCollection.Count > 0)
{
Source.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(pkg.Connections["ConnectionSource"]);
Source.RuntimeConnectionCollection[0].ConnectionManagerID = pkg.Connections["ConnectionSource"].ID;
}
//reinitialize the component
InstanceSource.AcquireConnections(null);
InstanceSource.ReinitializeMetaData();
InstanceSource.ReleaseConnections();
// Get the design time instance of the component.
CManagedComponentWrapper InstanceDestination = OLEDBDestination.Instantiate();
// Initialize the component
InstanceDestination.ProvideComponentProperties();
// Specify the connection manager.
if (OLEDBDestination.RuntimeConnectionCollection.Count > 0)
{
OLEDBDestination.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(pkg.Connections["OLEDBConnectionDestination"]);
OLEDBDestination.RuntimeConnectionCollection[0].ConnectionManagerID = pkg.Connections["OLEDBConnectionDestination"].ID;
}
//reinitialize the component
InstanceDestination.AcquireConnections(null);
InstanceDestination.ReinitializeMetaData();
InstanceDestination.ReleaseConnections();
//map the columns
IDTSPath90 path = dataFlow.PathCollection.New();
path.AttachPathAndPropagateNotifications(**Source.OutputCollection[0]**, OLEDBDestination.InputCollection[0]);
```
--- | You might have fixed this by now... :) If so let us know.
In the Flat File version the following lines after the destination connection assignement are missing. This may not help much (because your input columns are missing) but lets fix it and see what error are we getting....
```
InstanceDestination.SetComponentProperty("OpenRowset",
DestinationTableNameInternal);
InstanceDestination.SetComponentProperty("AccessMode", 0);
``` | I have had issues using SSIS with flat files for input and sql output because the data types didn't match. Check to make sure its not something simple like this first.
Also you didn't include very much information in your post about what is going wrong so its hard for me to tell if its a DB problem or what kind of errors your getting? Have you tried using the SSIS gui rather then programmatically doing this? | Programmatically derived Columns from flatfile source using SSIS DataFlowTask | [
"",
"c#",
"sql-server",
"vb.net",
"ssis",
""
] |
I have noticed a rather strange behaviour in IE.
I have a HTML form with a single input text field and a submit button
On Submit click I need to execute a client side JavaScript function that does the necessary.
Now when I want to prevent the postback in the text field (on enter key press).
I have added a key press JavaScript function that looks like this:
```
<input type=text onkeypress="return OnEnterKeyPress(event)" />
function OnEnterKeyPress(event) {
var keyNum = 0;
if (window.event) // IE
{
keyNum = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyNum = event.which;
}
else return true;
if (keyNum == 13) // Enter Key pressed, then start search, else do nothing.
{
OnButtonClick();
return false;
}
else
return true;
}
```
Strangly this doesn't work.
---
But if I pass the text field to the function :
```
<input type=text onkeypress="return OnEnterKeyPress(this,event);" />
function OnEnterKeyPress(thisForm,event) {
var keyNum = 0;
if (window.event) // IE
{
keyNum = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyNum = event.which;
}
else return true;
if (keyNum == 13) // Enter Key pressed, then start search, else do nothing.
{
OnButtonClick();
return false;
}
else
return true;
}
```
I am able to prevent the postback.
Can anyone confirm what is exactly happening here?
The HTML form has just one text box and a submit button.
The resultant output of the JavaScript function executed on submit is displayed in a HTML text area in a separate div. | Found out a work around for this issue.
i just found out that in IE, if,in a form, there is just one text field and one submit button, pressing enter results in form submit. However if there are more than one text boxes, IE doesn't auto postback the form on enter press, instead it fires the button's onclick event.
So i introduce a hidden text field in the form and everything works magically.
I donot even need to handle the onkeypress event for the text field.
```
<Form>
<input type="text" />
<input type="text" style="display:none"/>
<input type="submit" onClick="callPageMethod();return false;"/>
</Form>
```
This works perfectly for me!!
This is not an issue in FF, as pressing enter directly results in call to submit button's onclick event. | Hi you can also disable the default behavior.
```
jQuery('#yourInput').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
```
Cheers! | HTML form with single text field + preventing postback in Internet Explorer | [
"",
"javascript",
"internet-explorer",
"dom-events",
"autopostback",
""
] |
Where does Intel C++ Compiler store the vptr ( pointer to virtual function table ) in an Object ?
I believe MSVC puts it at the beginning of the object, gcc at the end. What is it for icpc ( Intel C++ Compiler )? | For Intel C++ compiler, for Linux, I found it to be the beginning of the object.
Code:
```
#include <cstdio>
class A
{
int a, b;
public:
A(int a1, int b1): a(a1), b(b1) {}
virtual void p(void) { printf("A\n"); }
};
class B: public A
{
public:
B(int a1, int b1): A(a1, b1) {}
void p(void){ printf("B\n"); }
};
int main(void)
{
A a(1, 2); int p=10; A a1(5, 6);
B b(3, 4); int q=11; B b2(7, 8);
a.p();
b.p();
int * x=(int*)&a;
printf("%d %d %d %d\n", x[0], x[1], x[2], x[3]);
x=(int*)&b;
printf("%d %d %d %d\n", x[0], x[1], x[2], x[3]);
}
``` | You can always look at where this and the first address in the derived class are located:
```
#include <stdio.h>
class foo
{
public:
virtual int do_foo()=0;
};
class bar : public foo
{
public:
int bar;
int do_foo() {printf ("%08x %08x\n", this, &bar);}
};
int main()
{
bar a_bar;
a_bar.do_foo();
}
```
On my linux box, the result is:
```
bfdbef3c bfdbef40
```
...which is exactly what you would expect: the first pointer, plus the size of a virtual function pointer, is the location of the second. | Where does Intel C++ Compiler store the vptr ( pointer to virtual function table ) in an Object? | [
"",
"c++",
"intel",
"icc",
""
] |
For example suppose I have a class Vehicle and I wish for a subclass ConvertibleVehicle which has extra methods such as foldRoof(), turboMode(), foldFrontSeats() etc. I wish to instantiate as follows
```
Vehicle convertible = new ConvertibleVehicle()
```
so I still have access to common method such as openDoor(), startEngine() etc. How do I designed such a solution?
To clarify my two initial solutions, neither of which I am happy with are:
1. Have dummy methods foldRoof(), turboMode(), foldFrontSeats() which I override in ConvertibleVehicle only, leaving them to do nothing in other subclasses
2. Have abstract methods foldRoof(), turboMode(), foldFrontSeats() and force each subclass to provide an implementation even if it will be blank in all instances other than ConvertibleVehicle
The above seem slightly convoluted since they both pollute the base class as I add an increasing number of subclasses each with their own unique functions
After reading some of the responses perhaps there is some type of fundamental flaw in my design. Suppose I have a class VehicleFleet which takes vehicles and instructs them to drive as follows:
```
public VehicleFleet(Vehicle[] myVehicles) {
for (int i=0; i < myVehicles.length; i++) {
myVehicles[i].drive();
}
}
```
Suppose this works for dozens of subclasses of Vehicle but for ConvertibleVehicle I also want to fold the roof before driving. To do so I subclass VehicleFleet as follows:
```
public ConvertibleVehicleFleet(Vehicle[] myVehicles) {
for (int i=0; i < myVehicles.length; i++) {
myVehicles[i].foldRoof();
myVehicles[i].drive();
}
}
```
This leaves me with a messy function foldRoof() stuck in the base class where it doesn't really belong which is overridden only in the case of ConvertibleVehicle and does nothing in all the other cases. The solution works but seems very inelegant. Does this problem lend itself to a better architecture?
I'm using Java although I would hope that a general solution could be found that will work in any object oriented language and that I will not need to rely upon language specific quirks | I've done this in similar situations.
Option A)
If the specialized operations are part of the same sequence as a base operation ( e.g. ConvertibleVehicle needs to be foldRoof before it can drive ) then just put the specialized operation inside the base operation.
```
class Vehicle {
public abstract void drive();
}
class ConvertibleVehicle {
public void drive() {
this.foldRoof();
.... // drive
}
private void foldRoof() {
....
}
}
```
So the effect of driving a fleet will be some of them will fold their roof before being driven.
```
for( Vehicle v : vehicleFleet ) {
v.drive();
}
```
The specialized method is not exposed in the object public interface but is called when needed.
Option B)
If the specialized operation are not part of the same sequence and must be called under certain "special" circumstances then let a specialized version of a client call those specialized operations. Warning, this is not so pure nor low coupling but when both objects ( the client and the service ) are created by the same "condition" or builder then most of the times is ok.
```
class Vehicle {
public void drive() {
....
}
}
class ConvertibleVehicle extends Vehicle {
// specialized version may override base operation or may not.
public void drive() {
...
}
public void foldRoof() { // specialized operation
...
}
}
```
Almost the same as the previous example, only in this case **foldRoof** is public also.
The difference is that I need an specialized client:
```
// Client ( base handler )
public class FleetHandler {
public void handle( Vehicle [] fleet ) {
for( Vehicle v : fleet ) {
v.drive();
}
}
}
// Specialized client ( sophisticate handler that is )
public class RoofAwareFleetHandler extends FleetHandler {
public void handle( Vehicle [] fleet ) {
for( Vehicle v : fleet ) {
// there are two options.
// either all vehicles are ConvertibleVehicles (risky) then
((ConvertibleVehicles)v).foldRoof();
v.drive();
// Or.. only some of them are ( safer ) .
if( v instenceOf ConvertibleVehicle ) {
((ConvertibleVehicles)v).foldRoof();
}
v.drive();
}
}
}
```
That **instaceof** look kind of ugly there, but it may be inlined by modern vm.
The point here is that only the specialized client knows and can invoke the specialized methods. That is, only **RoofAwareFleetHandler** can invoke **foldRoof()** on \*\* ConvertibleVehicle\*\*
The final code doesn't change ...
```
public class Main {
public static void main( String [] args ) {
FleetHandler fleetHandler = .....
Vehicles [] fleet = ....
fleetHandler.handle( fleet );
}
}
```
Of course, I always make sure the fleethandler and the array of Vehicles are compatible ( probably using abstrac factory or builder )
I hope this helps. | Any objects that use Vehicle shouldn't know about ConvertibleVehicle and its specialized methods. In proper loosely coupled object-oriented design Driver would only know about the Vehicle interface. Driver might call startEngine() on a Vehicle, but it's up to subclasses of Vehicle to override startEngine() to handle varying implementations such as turning a key versus pushing a button.
Consider reviewing the following two links which should help to explain this concept:
<http://en.wikipedia.org/wiki/Liskov_substitution_principle>
<http://en.wikipedia.org/wiki/Open/closed_principle>
Consider posting a real world problem that you feel leads to the dilemma you describe here and someone will be more than happy to demonstrate a better approach. | How do I design a sub class with features not available in the base class? | [
"",
"java",
"oop",
""
] |
This is a follow-up question to [Is there a difference between “throw” and “throw ex”](https://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex)?
is there a way to extract a new error handling method without resetting the stack trace?
**[EDIT]**
I will be trying both "inner method" and another [answer](https://stackoverflow.com/questions/730300/how-to-throw-exception-without-resetting-stack-trace/730385#730385) provided by Earwicker and see which one can work out better to mark an answer. | Not sure if you mean that, but my suggestion in your other question was addressing this.
If your handler returns a boolean whether the exception was handled or not, you can use this in your catch clause:
```
catch (Exception ex) {
if (!HandleException(ex)) {
throw;
}
}
``` | With .NET Framework 4.5 there is now an [ExceptionDispatchInfo](http://msdn.microsoft.com/en-us/library/system.runtime.exceptionservices.exceptiondispatchinfo.aspx) which supports this exact scenario. It allows capturing a complete exception and rethrowing it from somewhere else without overwriting the contained stack trace.
**code sample due to request in comment**
```
using System.Runtime.ExceptionServices;
class Test
{
private ExceptionDispatchInfo _exInfo;
public void DeleteNoThrow(string path)
{
try { File.Delete(path); }
catch(IOException ex)
{
// Capture exception (including stack trace) for later rethrow.
_exInfo = ExceptionDispatchInfo.Capture(ex);
}
}
public Exception GetFailure()
{
// You can access the captured exception without rethrowing.
return _exInfo != null ? _exInfo.SourceException : null;
}
public void ThrowIfFailed()
{
// This will rethrow the exception including the stack trace of the
// original DeleteNoThrow call.
_exInfo.Throw();
// Contrast with 'throw GetFailure()' which rethrows the exception but
// overwrites the stack trace to the current caller of ThrowIfFailed.
}
}
``` | How to throw exception without resetting stack trace? | [
"",
"c#",
".net",
"exception",
"error-handling",
"stack-trace",
""
] |
Suppose I have the following two classes in two different assemblies:
```
//in assembly A
public class TypeA {
// Constructor omitted
public void MethodA
{
try {
//do something
}
catch {
throw;
}
}
}
//in assembly B
public class TypeB {
public void MethodB
{
try {
TypeA a = new TypeA();
a.MethodA();
}
catch (Exception e)
//Handle exception
}
}
}
```
In this case, the try-catch in MethodA just elevates the exception but doesn't really handle it. Is there any advantage in using try-catch at all in MethodA? In other words, is there a difference between this kind of try-catch block and not using one at all? | In your example, there is no advantage to this. But there are cases where it is desirable to just bubble up a specific exception.
```
public void Foo()
{
try
{
// Some service adapter code
// A call to the service
}
catch (ServiceBoundaryException)
{
throw;
}
catch (Exception ex)
{
throw new AdapterBoundaryException("some message", ex);
}
}
```
This allows you to easily identify which boundary an exception occurred in. In this case, you would need to ensure your boundary exceptions are only thrown for code specific to the boundary. | With the code the way you've written it for MethodA, there is no difference. All it will do is eat up processor cycles. However there can be an advantage to writing code this way if there is a resource you must free. For example
```
Resource r = GetSomeResource();
try {
// Do Something
} catch {
FreeSomeResource();
throw;
}
FreeSomeResource();
```
However there is no real point in doing it this way. It would be **much** better to just use a finally block instead. | The difference between re-throwing parameter-less catch and not doing anything? | [
"",
"c#",
"exception",
"try-catch",
""
] |
I'm trying out SlickEdit and it says it can use a "tag file" for PHP. Does anyone know where I can find this tag file? | It supports the ability to create a tag file on PHP source code. You still need to point it in the direction of the PHP source code.
To create these tag files, go Tools | Tag Files... | Add Tag File...
Select PHP and then add the directories containing your source code. | Tag files are basically an index of names in your code project that are spread across files. This can be used for jumping between files and auto-completion. Some relevant information about the concept is here on Wikipedia: [Ctags](http://en.wikipedia.org/wiki/Ctags).
As for creating it in SlickEdit, check the section "Building and Managing Tag Files" in the help. You should be able to use the Tools -> Tag Files dialog to add files that you want to index. | Where can I find a PHP Tag File for SlickEdit? | [
"",
"php",
"text-editor",
"slickedit",
""
] |
It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)
I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: [WoA Map](http://woarl.com/map/turn_32_normal.html)
The background image for the map is located here: [Map background](http://woarl.com/map/images/theMap.jpg) and created in [Omnigraffle](http://www.omnigroup.com/applications/omnigraffle/). It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine.
The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using [PIL](http://www.pythonware.com/products/pil/), I have looked at incorporating it with [Blender](http://www.blender.org/), I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;)
I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass.
As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example.
Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time).
Edit 2:
Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order).
After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well.
I will be making an editor for this as suggested by [Adam Smith](https://stackoverflow.com/users/66634/adam-smith). I don't know that graphs will be relevant [Xynth](https://stackoverflow.com/users/62014/xynth) but I've not had a chance to look into them fully yet.
I really appreciate all those that answered my question, thanks. | I'd store a game map in code as a [graph](http://en.wikipedia.org/wiki/Graph_(mathematics)).
Each node would represent a country/city and each edge would represent adjacency. Once you have a map like that, I'm sure you can find many resources on AI (pathfinding, strategy, etc.) online.
If you want to be able to build an image of the map programattically, consider adding an (x, y) coordinate and an image for each node. That way you can display all of the images at the given coordinates to build up a map view. | The key thing to realize here is that you don't have to use just **one** map. You can use two maps:
* The one you already have which is drawn on screen
* A hidden map which isn't drawn but which is used for path finding, collision detection etc.
The natural next question then is where does this second map come from? Easy, you create your own tool which can load your first map, and display it. Your tool will then let you draw boundaries around you islands and place markers at your cities. These markers and boundaries (simple polygons e.g.) are stored as your second map and is used in your code to do path finding etc.
In fact you can have your tool emit python code which creates the graphs and polygons so that you don't have to load any data yourself.
I am just basically telling you to make a level editor. It isn't very hard to do. You just need some buttons to click on to define what you are adding. e.g. if you are adding a polygon. Then you can just add each mouse coordinate to an array each time you click on your mouse if you have toggled your add polygon button. You can have another button for adding cities so that each time you click on the map you will record that coordinate for the city and possibly a corresponding name that you can provide in a text box. | Game map from Code | [
"",
"python",
""
] |
Consider I have an Array,
```
int[] i = {1,2,3,4,5};
```
Here I have assigned values for it. But in my problem I get these values only at runtime.
How can I assign them to an array.
For example:
I get the max size of array from user and the values to them now how do I assign them to the array int [].
Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end? | Well, the easiest is to use `List<T>`:
```
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();
```
Otherwise, you need to allocate an array of suitable size, and set via the indexer.
```
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
```
This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a `List<T>` uses a doubling strategy to minimize the reallocations required. | You mean?
```
int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };
``` | How to assign array values at run time | [
"",
"c#",
""
] |
The overall structure of a given software system is model view controller.
The view (graphical interface) is a representation of the model (domain object models).
However, within the view (graphical interface) there are components (such as JTextComponent). These components too are arranged in Model View Controller. JTextComponent uses [Document](http://java.sun.com/javase/6/docs/api/javax/swing/text/Document.html) as its model.
The JTextComponent is meant to represent a specific part of a domain object model. But its model is actually the Document object.
This one piece of information, portrayed by the JTextComponent, is stored both in the JTextComponent Document and in the domain object model. This organisation results in this information of the model being duplicated. And thus the two models need to be kept synchronised. Violation of DRY.
Are there any elegant solutions for binding a JTextComponent (or any graphical Component) to a part of the domain object model, so there truly is one place for the data? | There are a couple of things going on here.
The Java framework is offering you a nice way updated your UI but constrains you to using a specific structure, Document.
On the other hand you have a adequate model that represents your data. By using Document directly in your model you also take the risks of tying your model to a specific framework. Which isn't a good idea.
The Java Document framework offers the ability to listen to changes you can leverage this into creating an [Adapter class](http://en.wikipedia.org/wiki/Adapter_pattern) between your model and Document. Basically when you setup the form you will make an instance of the adapter class. You will initialize with your model. The adapter will have a property returning a document. IN addition the Adapter will register itself as the listener for that document model. The adapter will be smart enough to know how to translate the chances to the document model to your model.
Goes something like this
1. UI is Created along with the
JTextDocument.
2. In the creation process it requests
your model from the View.
3. It create an instance of the Adapter
initializing it with your model.
4. The adapter also sets itself up as
the listener of the Document.
5. Assign the document to the
JTextDocument object.
6. Any interaction with the Document is
reported back to Adapter
7. The Adapter notifies the View
passing the translated data back.
8. The View changes the Model.
9. The View nofitifies the Adapter that
the model has change.
10. The Adapter translates the changes
into changes to the document.
Because the adapter is tied to the Java Framework is should be pushed as close to the UI as it can get. Likely the Adapter will implement a interface exposed by the View so that the View doesn't have to reference anything specific to the framework you are using. When you change framework all you have to do is make a new object that implements that interface and the View is none the wiser. | Make a `Document` object of your own, in your object model.
Then use the [**setDocument(d) method**](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/text/JTextComponent.html#setDocument(javax.swing.text.Document)). | Model View synchronisation (or avoiding synchronisation) | [
"",
"java",
"model-view-controller",
"design-patterns",
""
] |
I have a class with a static factory method on it. I want to call the factory to retrieve an instance of the class, and then do additional initialization, preferablly via c# object initializer syntax :
```
MyClass instance = MyClass.FactoryCreate()
{
someProperty = someValue;
}
```
vs
```
MyClass instance = MyClass.FactoryCreate();
instance.someProperty = someValue;
``` | Yes. You **can** use object initializer for already created instance with the following trick. You should create a simple object wrapper:
```
public struct ObjectIniter<TObject>
{
public ObjectIniter(TObject obj)
{
Obj = obj;
}
public TObject Obj { get; }
}
```
And now you can use it like this to initialize your objects:
```
new ObjectIniter<MyClass>(existingInstance)
{
Obj =
{
//Object initializer of MyClass:
Property1 = value1,
Property2 = value2,
//...
}
};
```
P.S. Related discussion in dotnet repository:
<https://github.com/dotnet/csharplang/issues/803> | No. Alternatively you could accept a lambda as an argument, which also gives you full control in which part of the "creation" process will be called. This way you can call it like:
```
MyClass instance = MyClass.FactoryCreate(c=>
{
c.SomeProperty = something;
c.AnotherProperty = somethingElse;
});
```
The create would look similar to:
```
public static MyClass FactoryCreate(Action<MyClass> initalizer)
{
MyClass myClass = new MyClass();
//do stuff
initializer( myClass );
//do more stuff
return myClass;
}
```
---
Another option is to return a builder instead (with an implicit cast operator to MyClass). Which you would call like:
```
MyClass instance = MyClass.FactoryCreate()
.WithSomeProperty(something)
.WithAnotherProperty(somethingElse);
```
Check [this](http://elegantcode.com/2008/04/26/test-data-builders-refined/) for the builder
Both of these versions are checked at compile time and have full intellisense support.
---
A third option that requires a default constructor:
```
//used like:
var data = MyClass.FactoryCreate(() => new Data
{
Desc = "something",
Id = 1
});
//Implemented as:
public static MyClass FactoryCreate(Expression<Func<MyClass>> initializer)
{
var myclass = new MyClass();
ApplyInitializer(myclass, (MemberInitExpression)initializer.Body);
return myclass ;
}
//using this:
static void ApplyInitializer(object instance, MemberInitExpression initalizer)
{
foreach (var bind in initalizer.Bindings.Cast<MemberAssignment>())
{
var prop = (PropertyInfo)bind.Member;
var value = ((ConstantExpression)bind.Expression).Value;
prop.SetValue(instance, value, null);
}
}
```
Its a middle between checked at compile time and not checked. It does need some work, as it is forcing constant expression on the assignments. I think that anything else are variations of the approaches already in the answers. Remember that you can also use the normal assignments, consider if you really need any of this. | Is it possible to use a c# object initializer with a factory method? | [
"",
"c#",
"object",
"factory",
"initializer",
""
] |
I found the text browser w3m which is the best so far in my opinion.
However, it is main problem is Javascript.
I cannot see comments at all in Stackoverflow when I use it.
I am not sure what is the restriction in letting Javascript to be in terminal.
**How can you enable at least some of JavaScript for Terminal** such that comments are visible? | Javascript requires a Javascript interpreter. If your user-agent doesn't understand a particular kind of scripting, it simply ignores it. To get a minimal level of support, try the **[w3m-js](http://abe.nwr.jp/w3m/w3m-js-en.html)** extension. | Unfortunately w3m doesn't support JavaScript at all. | How can you use Javascript in terminal for w3m? | [
"",
"javascript",
"unix",
"terminal",
"w3m",
""
] |
I have a PHP redirect page to track clicks on links. Basically it does:
```
- get url from $_GET
- connect to database
- create row for url, or update with 1 hit if it exists
- redirect browser to url using Location: header
```
I was wondering if it's possible to send the redirect to the client first, so it can get on with it's job, and then log the click. Would simply switching things around work? | You can do this:
1. get url from `$_GET`
2. send `Location:` header
3. call [`flush()`](https://www.php.net/flush)
4. connect to database
5. create row for url, or update with 1 hit if it exists
This will not necessarily cause the browser to go on its way immediately, since your connection is still being held open and what the browser does about that is up to it, but (barring conditions that cause `flush()` to not work) it will at least get the `Location:` header out to the browser so it can do the redirect if it likes.
If that's not good enough, I'd recommend dumping your data to per-minute or per-second files that a script then picks up for postprocessing into the database. If *that's* not good enough, you can play with [`pcntl_fork()`](https://www.php.net/pcntl_fork); this is an *extremely* hairy thing to do under Apache SAPI. | Most databases give you the ability to insert a query delayed, so it'll only process when the database is idle. You're most likely best doing that...so long as the data isn't critical (you'll lose the query if mysqld dies or the RAM is flushed).
<http://dev.mysql.com/doc/refman/5.1/en/insert-delayed.html> | redirect user, then log his visit using php and mysql | [
"",
"php",
"mysql",
"redirect",
"statistics",
"tracking",
""
] |
If you open a text file (.txt, .js, .css, ...) in your browser, it will get wrapped up in a nice DOM tree.
For example, open [this .txt file](http://www.ietf.org/rfc/rfc2549.txt) and enter
```
javascript:alert(document.documentElement.innerHTML);
```
into your address bar. Nice... every major browser supports DOM manipulation on this wrapped text files, which is a great thing for writing powerful bookmarklets or [user scripts](http://www.userscripts.org).
However, Firefox fails on *assigning* any element's innerHTML. For example,
```
javascript: document.body.innerHTML = document.body.innerHTML.replace(/(\d+\s+\w+(?=\s+\d+))/g, '<span style="color:red">$1</span>'); void 0;
```
will work in every browser but Firefox.
Is there a trick to work around this issue?
(No, I don't want to parse the innerHTML string manually, and no, it doesn't work with jQuery either.) | I think I found a working solution. First of all, let me give some more details on the question.
The problem is: Firefox creates something like
```
[some wrapper]
+---document
+---<html>[=documentElement]
+---<body>
+---<head/>
+---<pre>
+---[actual plain text contents]
```
but the wrapped document object does not support setting innerHTML properly. So, the basic idea is, create a new document object with full innerHTML support. Here's how it works:
```
var setInnerHTML = function(el, string) {
if (typeof window.supportsInnerHTML == 'undefined') {
var testParent = document.createElement('div');
testParent.innerHTML = '<br/>';
window.supportsInnerHTML = (testParent.firstChild.nodeType == 1);
}
if (window.supportsInnerHTML) {
el.innerHTML = string;
} else {
if (!window.cleanDocumentObject) {
/* this is where we get a 'clean' document object */
var f = document.createElement('iframe');
f.style.setProperty('display', 'none', 'important');
f.src = 'data:text/html,<!DOCTYPE html><html><title></title></html>';
document.body.appendChild(f); /* <- this is where FF creates f.contentDocument */
window.cleanDocumentObject = f.contentDocument;
document.body.removeChild(f);
}
/* let browser do the parsing */
var div = window.cleanDocumentObject.createElement('div');
div.innerHTML = string; /* this does work */
/* copy childNodes */
while(el.firstChild) {
el.removeChild(el.firstChild); /* cleanup */
}
for (var i = 0; i < div.childNodes.length; i++) {
el.appendChild(div.childNodes[i].cloneNode(true));
}
delete div;
}
}
```
---
edit:
This version is better and faster; using XSLTProcessor instead of iFrame.
```
var setInnerHTML = function(el, string) {
// element.innerHTML does not work on plain text files in FF; this restriction is similar to
// http://groups.google.com/group/mozilla.dev.extensions/t/55662db3ea44a198
var self = arguments.callee;
if (typeof self.supportsInnerHTML == 'undefined') {
var testParent = document.createElement('div');
testParent.innerHTML = '<p/>';
self.supportsInnerHTML = (testParent.firstChild.nodeType == 1);
}
if (self.supportsInnerHTML) {
el.innerHTML = string;
return el;
} else if (typeof XSLTProcessor == 'undefined') {
return undefined;
} else {
if (typeof self.cleanDocument == 'undefined')
self.cleanDocument = createHTMLDocument();
if (el.parentNode) {
var cleanEl = self.cleanDocument.importNode(el, false);
cleanEl.innerHTML = string;
el.parentNode.replaceChild(document.adoptNode(cleanEl), el);
} else {
var cleanEl = self.cleanDocument.adoptNode(el);
cleanEl.innerHTML = string;
el = document.adoptNode(cleanEl);
}
return el;
}
function createHTMLDocument() {
// Firefox does not support document.implementation.createHTMLDocument()
// cf. http://www.quirksmode.org/dom/w3c_html.html#t12
// the following is taken from http://gist.github.com/49453
var xmlDoc = document.implementation.createDocument('', 'fooblar', null);
var templ = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">'
+ '<xsl:output method="html"/><xsl:template match="/">'
+ '<html><title/><body/></html>'
+ '</xsl:template></xsl:stylesheet>';
var proc = new XSLTProcessor();
proc.importStylesheet(new DOMParser().parseFromString(templ,'text/xml'));
return proc.transformToDocument(xmlDoc);
}
};
``` | It is failing because there is no `body` - even the file you linked is just a text file without a body (perhaps you are looking at it in firebug?).
The best thing to do would be a regex replace since you are working with text. | How to use innerHTML on plain txt files in Firefox? | [
"",
"javascript",
"firefox",
"dom",
"innerhtml",
""
] |
my question is related to my previous question ([How to display data from txt file in specific format](https://stackoverflow.com/questions/731917/how-to-display-data-from-txt-file-in-specific-format)).
I was wondering if it is possible at the first place, to store data on txt file in specific format rather than store it first and then retreived it again and display it in specific format?
e.g. instead of store data on txt file like this
```
Jessica
Walking
20 minutes
Matthew
Run
10 minutes
```
I wanted to store it in txt file in this format
```
Jessica Walking 20 minutes
Matthew Run 10 minutes
``` | Regarding your comment to adeel's answer:
> Thanks adeel825, however I dont know where to put the "\t".. so far I use this method: new PrintStream(fout).println (name); new PrintStream(fout).println (exercise); new PrintStream(fout).println("10 minutes");
First, don't call "`new PrintStream(fout)`" everytime you print something. Do this:
```
PrintStream ps = new PrintStream(fout);
ps.print(name);
ps.print('\t');
ps.print(exercise);
ps.print('\t');
ps.print(time);
ps.println();
```
Or simply:
```
PrintStream ps = new PrintStream(fout);
ps.println(name + '\t' + exercise + '\t' + time);
```
**Edit**
In response to your comment:
> one more question...some of the name are too long and it requires more tab..I have put ps.print('\t','\t'); but it seems not working..
If this is a problem, it sounds like you are trying to store them in the manner you want to display them. I had assumed you were trying to store them in a way that would be easy to parse programmatically. If you want to store them displayed in columns, I'd suggest padding with spaces rather than tabs.
If you know that all the columns are going to be less than, say, 30 characters wide, you could do something like this with printf:
```
ps.printf("%30s%30s%30s%n", name, exercise, time);
```
That syntax can look quite byzantine if you're not used to it.. basiclly each "%30s" means pad the string argument so that it is at least 30 characters wide. Your result won't look right if any of the values are 30 or more characters wide. If you can't know ahead of time, you'll have to loop through the values in each column to determine how wide the columns need to be. | There is no problem with storing data this way. All you need to do is write out the values and delimit them with a tab character "\t" | Storing data in txt file in specific format | [
"",
"java",
"file",
"file-format",
"text-files",
""
] |
Linqpad, when coding in C#, will draw a vertical line between opening and closing curly braces.
Boy, oh boy, I sure do wish Visual Studio would do this. Does it? Is there anyway to make it do it? | [CodeRush Xpress for C#](http://msdn.microsoft.com/en-us/vcsharp/dd218053.aspx) will do that, and MS is providing it for free. | Get the [CodeRush tools](http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/) - they do what you want and more. | LinqPad Feature - Does VS do this? | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"linq",
"linqpad",
""
] |
I've been experimenting with using the `<canvas>` tag for drawing simple diagrams and charts, and so far it's pretty easy to work with. I have one issue thought. I can't figure out how to draw text on a `<canvas>` in Safari. In Firefox 3.0, I can do this:
```
Chart.prototype.drawTextCentered = function(context, text, x, y, font, color) {
if (context.mozDrawText) {
context.save();
context.fillStyle = color;
context.mozTextStyle = font;
x -= 0.5 * context.mozMeasureText(text);
context.translate(x, y);
context.mozDrawText(text);
context.restore();
}
}
```
I've seen reference to a `fillText()` method in Apple's Safari docs, but it doesn't appear to be supported in Safari 3.2. Is this just something that's currently missing, or is it some well-kept secret? | I don't believe that Safari 3.2 supports rendering text in the canvas.
According to [this blog](http://bottledtext.blogspot.com/2009/03/firefox-31b2-safari-4-beta-and-html-5.html), Safari 4 beta supports rending text to the canvas, based on the [HTML 5 canvas text APIs](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#text).
**edit**: I have confirmed that the following snippet works in Safari 4 beta:
```
<canvas id="canvas"></canvas>
<script>
var context = document.getElementById("canvas").getContext("2d");
context.fillText("Hello, world!", 10, 10);
</script>
``` | This isn't ideal, and it looks like you are fine waiting, but for reference, there's a library called [strokeText](http://www.netzgesta.de/dev/text/) that does its own font rendering. It works in Firefox 1.5+, Opera 9+, Safari (I don't know what versions) and IE6+ (using VML instead of canvas). | How do you draw text on a <canvas> tag in Safari | [
"",
"javascript",
"safari",
"canvas",
""
] |
I'm trying to come to terms with using IoC/Dependency Injection while at the same time programming to contracts rather than specific classes. The dilemma I'm having is the tension between:
1. **Do program to interfaces for IoC**: I started out with IoC relying heavily on interfaces. Judging by Spring's sample projects, interfaces are the way to go when programing to a contract with IoC.
2. ( **... although abstract classes generally preferred**: [the main drawback of interfaces is that they are much less flexible than classes when it comes to allowing for evolution of APIs](http://en.csharp-online.net/.NET_Type_Design_Guidelines%E2%80%94Choosing_Between_Class_and_Interface) )
3. **Do make class dependencies explicit via constructor**
My gut feeling is that it's good programming practice to pass dependencies in to a class's constructor. Indeed, this *is* dependency injection.
4. **... except you can't enforce constructor signature in interfaces/abstract clases**: Neither interfaces or nor abstract classes allow for defining a constructor signature [( easily / elegantly )](https://stackoverflow.com/questions/619856/interface-defining-a-constructor-signature).
See also [Framework Design Guidelines section 4.4:](http://msdn.microsoft.com/en-us/library/ms229047.aspx) **DO NOT** define public or protected internal constructors in abstract types. ... Constructors should be public only if users will need to create instances of the type.
This question is related to a previous stackoverflow question: [Interface defining a constructor signature?](https://stackoverflow.com/questions/619856/interface-defining-a-constructor-signature)
But my question is:
Since you can't define a constructor in a C# interface/abstract class, as the question above asks, on a practical level:
**How do you reconcile this with the sensible practice of [passing dependencies in via a constructor](http://msdn.microsoft.com/en-us/library/ms229060.aspx)**?
Edit: Thank you for the answers. I'm hoping for some insight on what I *should* do in this case. Just not use contructor args? Use some sort of Init() method that does take the dependencies?
Edit2: Thanks for the great answers, very helpful. | I always think this is easier to explain with a (made up) example...
Imagine you have an ICustomerRepository interface, an IShoppingCartRepository interface and an ICheckout interface. You have concrete implementations of those interfaces - CustomerRepository, ShoppingCartRepository, and CheckoutService.
Your CheckoutService concrete class has a constructor that takes an ICustomerRepository and an IShoppingCartRepository - e.g.
```
public CheckoutService(ICustomerRepository customerRepository, IShoppingCartRepository shoppingCartRepository)
{
// Set fields for use in some methods later...
_customerRepository = customerRepository;
_shoppingCartRepository = shoppingCartRepository;
}
```
Then, when you want an ICheckoutService implementation to do some work with, you tell your IoC container which concrete class it should use for each interface type and ask it to build you an ICheckoutService. Your IoC container will go and build your classes for you, injecting the correct concrete classes into the constructor of your CheckoutService. It will also build dependencies all the way down the class heirarchy here, so if, for example your ShoppingCartRepository takes an IDatabaseSession interface in the constructor, your IoC container will inject that dependency too, as long as you have told it which concrete class to use for your IDatabaseService.
Here's some code you might use when configuring (for example) [StructureMap](http://structuremap.sourceforge.net/Default.htm) as your IoC container (this code would typically be called during app startup):
```
public class AppRegistry : Registry
{
public AppRegistry()
{
ForRequestedType<ICheckoutService>().TheDefaultIsConcreteType<CheckoutService>();
ForRequestedType<ICustomerRepository>().TheDefaultIsConcreteType<CustomerRepository>();
// etc...
}
}
```
Then to get an instance of ICheckoutService built up and ready to go, with all the dependencies passed into the constructor for you, you would use something like:
```
var checkoutService = ObjectFactory.GetInstance<ICheckoutService>();
```
I hope that makes sense! | Your IoC container must construct an object from a concrete type, even though what you're passing around is an interface. Your constructor is not a behavior or state contract, so it does not belong in an interface or as a public member of your abstract class.
A constructor is an implementation detail, so you do not need to separate its definition from the concrete class. | Enforcing dependencies in IoC via a constructor? | [
"",
"c#",
"interface",
"dependency-injection",
"inversion-of-control",
"abstract-class",
""
] |
I'm using something like this in my template
```
<select multiple="multiple" name="services" id="services" size="5">
{% for service in services %}
<option value="{{service.id}}">{{service}}</option>
{% endfor %}
</select>
```
When I view the POST data in Firebug or the Django debug, I see it only sends one value. Am I doing something wrong or misunderstanding a concept? | ```
request.POST.getlist('services')
``` | Just FYI, I had to use:
```
list = request.POST.getlist("items[]")
```
because omitting the [] caused a blank list to be returned instead of the correct values. I'm using jQuery to fetch the values of a multiple select element, and jQuery appears to be adding the [] | Django: using <select multiple> and POST | [
"",
"python",
"django",
"http",
""
] |
What's the difference between the `WebConfigurationManager` and the `ConfigurationManager`?
When should I use one over the other?
**UPDATED**
I just looked at the `WebConfigurationManager`, and for some reason, you can't access the connection strings as you do in the `ConfigurationManager` (like an array). Can anyone tell me why MS made it like this? It seems to be a pain to get the connection string you need using the `WebConfigurationManager`.
**UPDATED AGAIN with CAVEAT!**
If you don't have a reference to the `System.Configuration` namespace added to your project, then Visual Studio will show an error when you try and access the `WebConfigurationManager.ConnectionStrings` like an array! | WebConfigurationManger knows how to deal with configuration inheritance within a web application. As you know, there could be several web.config files in one applicaion - one in the root of the site and any number in subdirectories. You can pass path to the GetSection() method to get possible overridden config.
If we'd looke at WebConfigurationManager with Reflector then things are clear:
```
public static object GetSection(string sectionName)
{
...
return ConfigurationManager.GetSection(sectionName);
}
public static object GetSection(string sectionName, string path)
{
...
return HttpConfigurationSystem.GetSection(sectionName, path);
}
``` | WebConfigurationManager is made specifically for ASP.NET applications.
WebConfigurationManager provides additional methods to load configuration files applicable to Web applications.
ConfigurationManager provides also methods to load configuration files applicable to ".exe" applications.
I’d suggest taking a look at WebConfigurationManager and see if it provides you with anything you simply cannot do with ConfigurationManager and use it instead, otherwise using ConfigurationManager will make it far easier to have your code be used seamlessly between web and desktop aps. | What's the difference between the WebConfigurationManager and the ConfigurationManager? | [
"",
"c#",
".net",
"asp.net",
"configurationmanager",
"webconfigurationmanager",
""
] |
I'm looking for a best way that is available for Java developers to implement REST services that will be communicating via JSON or XML. I'm looking for production-ready products.
I know that Spring 3.0 is coming, but it's not done yet - no luck.
Is Jersey the one?
My application is hosted by Tomcat, uses Spring, Jettison and XStream.
I'd like to use an open-source package that will allow me so have a similar development experience as WCF.NET, where I can declare the Url templates, map GET/POST and get an output either in XML or JSON. The accepted payload should be XML or JSON as well.
Any ideas out there? | Jersey, RESTEasy, and Restlet all claim to do what you're asking. I've only tried Restlet, and I thought it was pretty nasty.
Spring 3 hasn't reached final release yet, but the M2 build seems to be pretty solid, and has the REST stuff there. If I were building a new REST webapp, I'd probably take the risk with M2. | I tried with Restlet, RestEasy, Jersey, CXF, Spring. Here are my feedbacks:
1. Restlet: Kind of nasty with its own set of Annotations. And little confusing as well. Cant blame much though, as they stared implementing this even before JAX-RS was there.
2. RestEasy / Jersey / CXF : As easy as its name is. Simple and straight forward to start working on it. Good part for these 3 framework is that, as they are compliant with JAX-RS, anytime in future can quickly fall back to so other JAX-RS compliant framework if its performing better or suiting your needs even better
3. Spring: Spring 3 have started supporting REST APIs. But make a not that it is NOT JAX-RS compliant, for the very reason as that for Restlet.
So I would choose only from RestEasy / Jersey / CXF. | What is the best Java-way to create JSON/XML REST Web services that is similar to WCF? | [
"",
"java",
"spring",
"tomcat",
"jersey",
"xstream",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.